3a909b5db3194fa0dbf2efd70194472ba061c26e
[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   };
418 }
419
420
421 namespace {
422 /// This class is a DAGUpdateListener that removes any deleted
423 /// nodes from the worklist.
424 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
425   DAGCombiner &DC;
426 public:
427   explicit WorklistRemover(DAGCombiner &dc)
428     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
429
430   void NodeDeleted(SDNode *N, SDNode *E) override {
431     DC.removeFromWorklist(N);
432   }
433 };
434 }
435
436 //===----------------------------------------------------------------------===//
437 //  TargetLowering::DAGCombinerInfo implementation
438 //===----------------------------------------------------------------------===//
439
440 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
441   ((DAGCombiner*)DC)->AddToWorklist(N);
442 }
443
444 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
445   ((DAGCombiner*)DC)->removeFromWorklist(N);
446 }
447
448 SDValue TargetLowering::DAGCombinerInfo::
449 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
450   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
451 }
452
453 SDValue TargetLowering::DAGCombinerInfo::
454 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
455   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
456 }
457
458
459 SDValue TargetLowering::DAGCombinerInfo::
460 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
461   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
462 }
463
464 void TargetLowering::DAGCombinerInfo::
465 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
466   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
467 }
468
469 //===----------------------------------------------------------------------===//
470 // Helper Functions
471 //===----------------------------------------------------------------------===//
472
473 void DAGCombiner::deleteAndRecombine(SDNode *N) {
474   removeFromWorklist(N);
475
476   // If the operands of this node are only used by the node, they will now be
477   // dead. Make sure to re-visit them and recursively delete dead nodes.
478   for (const SDValue &Op : N->ops())
479     // For an operand generating multiple values, one of the values may
480     // become dead allowing further simplification (e.g. split index
481     // arithmetic from an indexed load).
482     if (Op->hasOneUse() || Op->getNumValues() > 1)
483       AddToWorklist(Op.getNode());
484
485   DAG.DeleteNode(N);
486 }
487
488 /// Return 1 if we can compute the negated form of the specified expression for
489 /// the same cost as the expression itself, or 2 if we can compute the negated
490 /// form more cheaply than the expression itself.
491 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
492                                const TargetLowering &TLI,
493                                const TargetOptions *Options,
494                                unsigned Depth = 0) {
495   // fneg is removable even if it has multiple uses.
496   if (Op.getOpcode() == ISD::FNEG) return 2;
497
498   // Don't allow anything with multiple uses.
499   if (!Op.hasOneUse()) return 0;
500
501   // Don't recurse exponentially.
502   if (Depth > 6) return 0;
503
504   switch (Op.getOpcode()) {
505   default: return false;
506   case ISD::ConstantFP:
507     // Don't invert constant FP values after legalize.  The negated constant
508     // isn't necessarily legal.
509     return LegalOperations ? 0 : 1;
510   case ISD::FADD:
511     // FIXME: determine better conditions for this xform.
512     if (!Options->UnsafeFPMath) return 0;
513
514     // After operation legalization, it might not be legal to create new FSUBs.
515     if (LegalOperations &&
516         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
517       return 0;
518
519     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
520     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
521                                     Options, Depth + 1))
522       return V;
523     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
524     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
525                               Depth + 1);
526   case ISD::FSUB:
527     // We can't turn -(A-B) into B-A when we honor signed zeros.
528     if (!Options->UnsafeFPMath) return 0;
529
530     // fold (fneg (fsub A, B)) -> (fsub B, A)
531     return 1;
532
533   case ISD::FMUL:
534   case ISD::FDIV:
535     if (Options->HonorSignDependentRoundingFPMath()) return 0;
536
537     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
538     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
539                                     Options, Depth + 1))
540       return V;
541
542     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
543                               Depth + 1);
544
545   case ISD::FP_EXTEND:
546   case ISD::FP_ROUND:
547   case ISD::FSIN:
548     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
549                               Depth + 1);
550   }
551 }
552
553 /// If isNegatibleForFree returns true, return the newly negated expression.
554 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
555                                     bool LegalOperations, unsigned Depth = 0) {
556   const TargetOptions &Options = DAG.getTarget().Options;
557   // fneg is removable even if it has multiple uses.
558   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
559
560   // Don't allow anything with multiple uses.
561   assert(Op.hasOneUse() && "Unknown reuse!");
562
563   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
564   switch (Op.getOpcode()) {
565   default: llvm_unreachable("Unknown code");
566   case ISD::ConstantFP: {
567     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
568     V.changeSign();
569     return DAG.getConstantFP(V, Op.getValueType());
570   }
571   case ISD::FADD:
572     // FIXME: determine better conditions for this xform.
573     assert(Options.UnsafeFPMath);
574
575     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
576     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
577                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
578       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
579                          GetNegatedExpression(Op.getOperand(0), DAG,
580                                               LegalOperations, Depth+1),
581                          Op.getOperand(1));
582     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
583     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
584                        GetNegatedExpression(Op.getOperand(1), DAG,
585                                             LegalOperations, Depth+1),
586                        Op.getOperand(0));
587   case ISD::FSUB:
588     // We can't turn -(A-B) into B-A when we honor signed zeros.
589     assert(Options.UnsafeFPMath);
590
591     // fold (fneg (fsub 0, B)) -> B
592     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
593       if (N0CFP->getValueAPF().isZero())
594         return Op.getOperand(1);
595
596     // fold (fneg (fsub A, B)) -> (fsub B, A)
597     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
598                        Op.getOperand(1), Op.getOperand(0));
599
600   case ISD::FMUL:
601   case ISD::FDIV:
602     assert(!Options.HonorSignDependentRoundingFPMath());
603
604     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
605     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
606                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
607       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
608                          GetNegatedExpression(Op.getOperand(0), DAG,
609                                               LegalOperations, Depth+1),
610                          Op.getOperand(1));
611
612     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
613     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
614                        Op.getOperand(0),
615                        GetNegatedExpression(Op.getOperand(1), DAG,
616                                             LegalOperations, Depth+1));
617
618   case ISD::FP_EXTEND:
619   case ISD::FSIN:
620     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
621                        GetNegatedExpression(Op.getOperand(0), DAG,
622                                             LegalOperations, Depth+1));
623   case ISD::FP_ROUND:
624       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
625                          GetNegatedExpression(Op.getOperand(0), DAG,
626                                               LegalOperations, Depth+1),
627                          Op.getOperand(1));
628   }
629 }
630
631 // Return true if this node is a setcc, or is a select_cc
632 // that selects between the target values used for true and false, making it
633 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
634 // the appropriate nodes based on the type of node we are checking. This
635 // simplifies life a bit for the callers.
636 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
637                                     SDValue &CC) const {
638   if (N.getOpcode() == ISD::SETCC) {
639     LHS = N.getOperand(0);
640     RHS = N.getOperand(1);
641     CC  = N.getOperand(2);
642     return true;
643   }
644
645   if (N.getOpcode() != ISD::SELECT_CC ||
646       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
647       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
648     return false;
649
650   if (TLI.getBooleanContents(N.getValueType()) ==
651       TargetLowering::UndefinedBooleanContent)
652     return false;
653
654   LHS = N.getOperand(0);
655   RHS = N.getOperand(1);
656   CC  = N.getOperand(4);
657   return true;
658 }
659
660 /// Return true if this is a SetCC-equivalent operation with only one use.
661 /// If this is true, it allows the users to invert the operation for free when
662 /// it is profitable to do so.
663 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
664   SDValue N0, N1, N2;
665   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
666     return true;
667   return false;
668 }
669
670 /// Returns true if N is a BUILD_VECTOR node whose
671 /// elements are all the same constant or undefined.
672 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
673   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
674   if (!C)
675     return false;
676
677   APInt SplatUndef;
678   unsigned SplatBitSize;
679   bool HasAnyUndefs;
680   EVT EltVT = N->getValueType(0).getVectorElementType();
681   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
682                              HasAnyUndefs) &&
683           EltVT.getSizeInBits() >= SplatBitSize);
684 }
685
686 // \brief Returns the SDNode if it is a constant BuildVector or constant.
687 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
688   if (isa<ConstantSDNode>(N))
689     return N.getNode();
690   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
691   if (BV && BV->isConstant())
692     return BV;
693   return nullptr;
694 }
695
696 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
697 // int.
698 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
699   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
700     return CN;
701
702   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
703     BitVector UndefElements;
704     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
705
706     // BuildVectors can truncate their operands. Ignore that case here.
707     // FIXME: We blindly ignore splats which include undef which is overly
708     // pessimistic.
709     if (CN && UndefElements.none() &&
710         CN->getValueType(0) == N.getValueType().getScalarType())
711       return CN;
712   }
713
714   return nullptr;
715 }
716
717 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
718 // float.
719 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
720   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
721     return CN;
722
723   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
724     BitVector UndefElements;
725     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
726
727     if (CN && UndefElements.none())
728       return CN;
729   }
730
731   return nullptr;
732 }
733
734 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
735                                     SDValue N0, SDValue N1) {
736   EVT VT = N0.getValueType();
737   if (N0.getOpcode() == Opc) {
738     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
739       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
740         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
741         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
742           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
743         return SDValue();
744       }
745       if (N0.hasOneUse()) {
746         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
747         // use
748         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
749         if (!OpNode.getNode())
750           return SDValue();
751         AddToWorklist(OpNode.getNode());
752         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
753       }
754     }
755   }
756
757   if (N1.getOpcode() == Opc) {
758     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
759       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
760         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
761         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
762           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
763         return SDValue();
764       }
765       if (N1.hasOneUse()) {
766         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
767         // use
768         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
769         if (!OpNode.getNode())
770           return SDValue();
771         AddToWorklist(OpNode.getNode());
772         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
773       }
774     }
775   }
776
777   return SDValue();
778 }
779
780 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
781                                bool AddTo) {
782   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
783   ++NodesCombined;
784   DEBUG(dbgs() << "\nReplacing.1 ";
785         N->dump(&DAG);
786         dbgs() << "\nWith: ";
787         To[0].getNode()->dump(&DAG);
788         dbgs() << " and " << NumTo-1 << " other values\n");
789   for (unsigned i = 0, e = NumTo; i != e; ++i)
790     assert((!To[i].getNode() ||
791             N->getValueType(i) == To[i].getValueType()) &&
792            "Cannot combine value to value of different type!");
793
794   WorklistRemover DeadNodes(*this);
795   DAG.ReplaceAllUsesWith(N, To);
796   if (AddTo) {
797     // Push the new nodes and any users onto the worklist
798     for (unsigned i = 0, e = NumTo; i != e; ++i) {
799       if (To[i].getNode()) {
800         AddToWorklist(To[i].getNode());
801         AddUsersToWorklist(To[i].getNode());
802       }
803     }
804   }
805
806   // Finally, if the node is now dead, remove it from the graph.  The node
807   // may not be dead if the replacement process recursively simplified to
808   // something else needing this node.
809   if (N->use_empty())
810     deleteAndRecombine(N);
811   return SDValue(N, 0);
812 }
813
814 void DAGCombiner::
815 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
816   // Replace all uses.  If any nodes become isomorphic to other nodes and
817   // are deleted, make sure to remove them from our worklist.
818   WorklistRemover DeadNodes(*this);
819   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
820
821   // Push the new node and any (possibly new) users onto the worklist.
822   AddToWorklist(TLO.New.getNode());
823   AddUsersToWorklist(TLO.New.getNode());
824
825   // Finally, if the node is now dead, remove it from the graph.  The node
826   // may not be dead if the replacement process recursively simplified to
827   // something else needing this node.
828   if (TLO.Old.getNode()->use_empty())
829     deleteAndRecombine(TLO.Old.getNode());
830 }
831
832 /// Check the specified integer node value to see if it can be simplified or if
833 /// things it uses can be simplified by bit propagation. If so, return true.
834 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
835   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
836   APInt KnownZero, KnownOne;
837   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
838     return false;
839
840   // Revisit the node.
841   AddToWorklist(Op.getNode());
842
843   // Replace the old value with the new one.
844   ++NodesCombined;
845   DEBUG(dbgs() << "\nReplacing.2 ";
846         TLO.Old.getNode()->dump(&DAG);
847         dbgs() << "\nWith: ";
848         TLO.New.getNode()->dump(&DAG);
849         dbgs() << '\n');
850
851   CommitTargetLoweringOpt(TLO);
852   return true;
853 }
854
855 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
856   SDLoc dl(Load);
857   EVT VT = Load->getValueType(0);
858   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
859
860   DEBUG(dbgs() << "\nReplacing.9 ";
861         Load->dump(&DAG);
862         dbgs() << "\nWith: ";
863         Trunc.getNode()->dump(&DAG);
864         dbgs() << '\n');
865   WorklistRemover DeadNodes(*this);
866   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
867   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
868   deleteAndRecombine(Load);
869   AddToWorklist(Trunc.getNode());
870 }
871
872 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
873   Replace = false;
874   SDLoc dl(Op);
875   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
876     EVT MemVT = LD->getMemoryVT();
877     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
878       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
879                                                        : ISD::EXTLOAD)
880       : LD->getExtensionType();
881     Replace = true;
882     return DAG.getExtLoad(ExtType, dl, PVT,
883                           LD->getChain(), LD->getBasePtr(),
884                           MemVT, LD->getMemOperand());
885   }
886
887   unsigned Opc = Op.getOpcode();
888   switch (Opc) {
889   default: break;
890   case ISD::AssertSext:
891     return DAG.getNode(ISD::AssertSext, dl, PVT,
892                        SExtPromoteOperand(Op.getOperand(0), PVT),
893                        Op.getOperand(1));
894   case ISD::AssertZext:
895     return DAG.getNode(ISD::AssertZext, dl, PVT,
896                        ZExtPromoteOperand(Op.getOperand(0), PVT),
897                        Op.getOperand(1));
898   case ISD::Constant: {
899     unsigned ExtOpc =
900       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
901     return DAG.getNode(ExtOpc, dl, PVT, Op);
902   }
903   }
904
905   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
906     return SDValue();
907   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
908 }
909
910 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
911   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
912     return SDValue();
913   EVT OldVT = Op.getValueType();
914   SDLoc dl(Op);
915   bool Replace = false;
916   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
917   if (!NewOp.getNode())
918     return SDValue();
919   AddToWorklist(NewOp.getNode());
920
921   if (Replace)
922     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
923   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
924                      DAG.getValueType(OldVT));
925 }
926
927 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
928   EVT OldVT = Op.getValueType();
929   SDLoc dl(Op);
930   bool Replace = false;
931   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
932   if (!NewOp.getNode())
933     return SDValue();
934   AddToWorklist(NewOp.getNode());
935
936   if (Replace)
937     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
938   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
939 }
940
941 /// Promote the specified integer binary operation if the target indicates it is
942 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
943 /// i32 since i16 instructions are longer.
944 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
945   if (!LegalOperations)
946     return SDValue();
947
948   EVT VT = Op.getValueType();
949   if (VT.isVector() || !VT.isInteger())
950     return SDValue();
951
952   // If operation type is 'undesirable', e.g. i16 on x86, consider
953   // promoting it.
954   unsigned Opc = Op.getOpcode();
955   if (TLI.isTypeDesirableForOp(Opc, VT))
956     return SDValue();
957
958   EVT PVT = VT;
959   // Consult target whether it is a good idea to promote this operation and
960   // what's the right type to promote it to.
961   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
962     assert(PVT != VT && "Don't know what type to promote to!");
963
964     bool Replace0 = false;
965     SDValue N0 = Op.getOperand(0);
966     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
967     if (!NN0.getNode())
968       return SDValue();
969
970     bool Replace1 = false;
971     SDValue N1 = Op.getOperand(1);
972     SDValue NN1;
973     if (N0 == N1)
974       NN1 = NN0;
975     else {
976       NN1 = PromoteOperand(N1, PVT, Replace1);
977       if (!NN1.getNode())
978         return SDValue();
979     }
980
981     AddToWorklist(NN0.getNode());
982     if (NN1.getNode())
983       AddToWorklist(NN1.getNode());
984
985     if (Replace0)
986       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
987     if (Replace1)
988       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
989
990     DEBUG(dbgs() << "\nPromoting ";
991           Op.getNode()->dump(&DAG));
992     SDLoc dl(Op);
993     return DAG.getNode(ISD::TRUNCATE, dl, VT,
994                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
995   }
996   return SDValue();
997 }
998
999 /// Promote the specified integer shift operation if the target indicates it is
1000 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1001 /// i32 since i16 instructions are longer.
1002 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1003   if (!LegalOperations)
1004     return SDValue();
1005
1006   EVT VT = Op.getValueType();
1007   if (VT.isVector() || !VT.isInteger())
1008     return SDValue();
1009
1010   // If operation type is 'undesirable', e.g. i16 on x86, consider
1011   // promoting it.
1012   unsigned Opc = Op.getOpcode();
1013   if (TLI.isTypeDesirableForOp(Opc, VT))
1014     return SDValue();
1015
1016   EVT PVT = VT;
1017   // Consult target whether it is a good idea to promote this operation and
1018   // what's the right type to promote it to.
1019   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1020     assert(PVT != VT && "Don't know what type to promote to!");
1021
1022     bool Replace = false;
1023     SDValue N0 = Op.getOperand(0);
1024     if (Opc == ISD::SRA)
1025       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1026     else if (Opc == ISD::SRL)
1027       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1028     else
1029       N0 = PromoteOperand(N0, PVT, Replace);
1030     if (!N0.getNode())
1031       return SDValue();
1032
1033     AddToWorklist(N0.getNode());
1034     if (Replace)
1035       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1036
1037     DEBUG(dbgs() << "\nPromoting ";
1038           Op.getNode()->dump(&DAG));
1039     SDLoc dl(Op);
1040     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1041                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1042   }
1043   return SDValue();
1044 }
1045
1046 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1047   if (!LegalOperations)
1048     return SDValue();
1049
1050   EVT VT = Op.getValueType();
1051   if (VT.isVector() || !VT.isInteger())
1052     return SDValue();
1053
1054   // If operation type is 'undesirable', e.g. i16 on x86, consider
1055   // promoting it.
1056   unsigned Opc = Op.getOpcode();
1057   if (TLI.isTypeDesirableForOp(Opc, VT))
1058     return SDValue();
1059
1060   EVT PVT = VT;
1061   // Consult target whether it is a good idea to promote this operation and
1062   // what's the right type to promote it to.
1063   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1064     assert(PVT != VT && "Don't know what type to promote to!");
1065     // fold (aext (aext x)) -> (aext x)
1066     // fold (aext (zext x)) -> (zext x)
1067     // fold (aext (sext x)) -> (sext x)
1068     DEBUG(dbgs() << "\nPromoting ";
1069           Op.getNode()->dump(&DAG));
1070     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1071   }
1072   return SDValue();
1073 }
1074
1075 bool DAGCombiner::PromoteLoad(SDValue Op) {
1076   if (!LegalOperations)
1077     return false;
1078
1079   EVT VT = Op.getValueType();
1080   if (VT.isVector() || !VT.isInteger())
1081     return false;
1082
1083   // If operation type is 'undesirable', e.g. i16 on x86, consider
1084   // promoting it.
1085   unsigned Opc = Op.getOpcode();
1086   if (TLI.isTypeDesirableForOp(Opc, VT))
1087     return false;
1088
1089   EVT PVT = VT;
1090   // Consult target whether it is a good idea to promote this operation and
1091   // what's the right type to promote it to.
1092   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1093     assert(PVT != VT && "Don't know what type to promote to!");
1094
1095     SDLoc dl(Op);
1096     SDNode *N = Op.getNode();
1097     LoadSDNode *LD = cast<LoadSDNode>(N);
1098     EVT MemVT = LD->getMemoryVT();
1099     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1100       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1101                                                        : ISD::EXTLOAD)
1102       : LD->getExtensionType();
1103     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1104                                    LD->getChain(), LD->getBasePtr(),
1105                                    MemVT, LD->getMemOperand());
1106     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1107
1108     DEBUG(dbgs() << "\nPromoting ";
1109           N->dump(&DAG);
1110           dbgs() << "\nTo: ";
1111           Result.getNode()->dump(&DAG);
1112           dbgs() << '\n');
1113     WorklistRemover DeadNodes(*this);
1114     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1115     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1116     deleteAndRecombine(N);
1117     AddToWorklist(Result.getNode());
1118     return true;
1119   }
1120   return false;
1121 }
1122
1123 /// \brief Recursively delete a node which has no uses and any operands for
1124 /// which it is the only use.
1125 ///
1126 /// Note that this both deletes the nodes and removes them from the worklist.
1127 /// It also adds any nodes who have had a user deleted to the worklist as they
1128 /// may now have only one use and subject to other combines.
1129 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1130   if (!N->use_empty())
1131     return false;
1132
1133   SmallSetVector<SDNode *, 16> Nodes;
1134   Nodes.insert(N);
1135   do {
1136     N = Nodes.pop_back_val();
1137     if (!N)
1138       continue;
1139
1140     if (N->use_empty()) {
1141       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1142         Nodes.insert(N->getOperand(i).getNode());
1143
1144       removeFromWorklist(N);
1145       DAG.DeleteNode(N);
1146     } else {
1147       AddToWorklist(N);
1148     }
1149   } while (!Nodes.empty());
1150   return true;
1151 }
1152
1153 //===----------------------------------------------------------------------===//
1154 //  Main DAG Combiner implementation
1155 //===----------------------------------------------------------------------===//
1156
1157 void DAGCombiner::Run(CombineLevel AtLevel) {
1158   // set the instance variables, so that the various visit routines may use it.
1159   Level = AtLevel;
1160   LegalOperations = Level >= AfterLegalizeVectorOps;
1161   LegalTypes = Level >= AfterLegalizeTypes;
1162
1163   // Early exit if this basic block is in an optnone function.
1164   AttributeSet FnAttrs =
1165     DAG.getMachineFunction().getFunction()->getAttributes();
1166   if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1167                            Attribute::OptimizeNone))
1168     return;
1169
1170   // Add all the dag nodes to the worklist.
1171   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1172        E = DAG.allnodes_end(); I != E; ++I)
1173     AddToWorklist(I);
1174
1175   // Create a dummy node (which is not added to allnodes), that adds a reference
1176   // to the root node, preventing it from being deleted, and tracking any
1177   // changes of the root.
1178   HandleSDNode Dummy(DAG.getRoot());
1179
1180   // while the worklist isn't empty, find a node and
1181   // try and combine it.
1182   while (!WorklistMap.empty()) {
1183     SDNode *N;
1184     // The Worklist holds the SDNodes in order, but it may contain null entries.
1185     do {
1186       N = Worklist.pop_back_val();
1187     } while (!N);
1188
1189     bool GoodWorklistEntry = WorklistMap.erase(N);
1190     (void)GoodWorklistEntry;
1191     assert(GoodWorklistEntry &&
1192            "Found a worklist entry without a corresponding map entry!");
1193
1194     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1195     // N is deleted from the DAG, since they too may now be dead or may have a
1196     // reduced number of uses, allowing other xforms.
1197     if (recursivelyDeleteUnusedNodes(N))
1198       continue;
1199
1200     WorklistRemover DeadNodes(*this);
1201
1202     // If this combine is running after legalizing the DAG, re-legalize any
1203     // nodes pulled off the worklist.
1204     if (Level == AfterLegalizeDAG) {
1205       SmallSetVector<SDNode *, 16> UpdatedNodes;
1206       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1207
1208       for (SDNode *LN : UpdatedNodes) {
1209         AddToWorklist(LN);
1210         AddUsersToWorklist(LN);
1211       }
1212       if (!NIsValid)
1213         continue;
1214     }
1215
1216     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1217
1218     // Add any operands of the new node which have not yet been combined to the
1219     // worklist as well. Because the worklist uniques things already, this
1220     // won't repeatedly process the same operand.
1221     CombinedNodes.insert(N);
1222     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1223       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1224         AddToWorklist(N->getOperand(i).getNode());
1225
1226     SDValue RV = combine(N);
1227
1228     if (!RV.getNode())
1229       continue;
1230
1231     ++NodesCombined;
1232
1233     // If we get back the same node we passed in, rather than a new node or
1234     // zero, we know that the node must have defined multiple values and
1235     // CombineTo was used.  Since CombineTo takes care of the worklist
1236     // mechanics for us, we have no work to do in this case.
1237     if (RV.getNode() == N)
1238       continue;
1239
1240     assert(N->getOpcode() != ISD::DELETED_NODE &&
1241            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1242            "Node was deleted but visit returned new node!");
1243
1244     DEBUG(dbgs() << " ... into: ";
1245           RV.getNode()->dump(&DAG));
1246
1247     // Transfer debug value.
1248     DAG.TransferDbgValues(SDValue(N, 0), RV);
1249     if (N->getNumValues() == RV.getNode()->getNumValues())
1250       DAG.ReplaceAllUsesWith(N, RV.getNode());
1251     else {
1252       assert(N->getValueType(0) == RV.getValueType() &&
1253              N->getNumValues() == 1 && "Type mismatch");
1254       SDValue OpV = RV;
1255       DAG.ReplaceAllUsesWith(N, &OpV);
1256     }
1257
1258     // Push the new node and any users onto the worklist
1259     AddToWorklist(RV.getNode());
1260     AddUsersToWorklist(RV.getNode());
1261
1262     // Finally, if the node is now dead, remove it from the graph.  The node
1263     // may not be dead if the replacement process recursively simplified to
1264     // something else needing this node. This will also take care of adding any
1265     // operands which have lost a user to the worklist.
1266     recursivelyDeleteUnusedNodes(N);
1267   }
1268
1269   // If the root changed (e.g. it was a dead load, update the root).
1270   DAG.setRoot(Dummy.getValue());
1271   DAG.RemoveDeadNodes();
1272 }
1273
1274 SDValue DAGCombiner::visit(SDNode *N) {
1275   switch (N->getOpcode()) {
1276   default: break;
1277   case ISD::TokenFactor:        return visitTokenFactor(N);
1278   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1279   case ISD::ADD:                return visitADD(N);
1280   case ISD::SUB:                return visitSUB(N);
1281   case ISD::ADDC:               return visitADDC(N);
1282   case ISD::SUBC:               return visitSUBC(N);
1283   case ISD::ADDE:               return visitADDE(N);
1284   case ISD::SUBE:               return visitSUBE(N);
1285   case ISD::MUL:                return visitMUL(N);
1286   case ISD::SDIV:               return visitSDIV(N);
1287   case ISD::UDIV:               return visitUDIV(N);
1288   case ISD::SREM:               return visitSREM(N);
1289   case ISD::UREM:               return visitUREM(N);
1290   case ISD::MULHU:              return visitMULHU(N);
1291   case ISD::MULHS:              return visitMULHS(N);
1292   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1293   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1294   case ISD::SMULO:              return visitSMULO(N);
1295   case ISD::UMULO:              return visitUMULO(N);
1296   case ISD::SDIVREM:            return visitSDIVREM(N);
1297   case ISD::UDIVREM:            return visitUDIVREM(N);
1298   case ISD::AND:                return visitAND(N);
1299   case ISD::OR:                 return visitOR(N);
1300   case ISD::XOR:                return visitXOR(N);
1301   case ISD::SHL:                return visitSHL(N);
1302   case ISD::SRA:                return visitSRA(N);
1303   case ISD::SRL:                return visitSRL(N);
1304   case ISD::ROTR:
1305   case ISD::ROTL:               return visitRotate(N);
1306   case ISD::CTLZ:               return visitCTLZ(N);
1307   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1308   case ISD::CTTZ:               return visitCTTZ(N);
1309   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1310   case ISD::CTPOP:              return visitCTPOP(N);
1311   case ISD::SELECT:             return visitSELECT(N);
1312   case ISD::VSELECT:            return visitVSELECT(N);
1313   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1314   case ISD::SETCC:              return visitSETCC(N);
1315   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1316   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1317   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1318   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1319   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1320   case ISD::BITCAST:            return visitBITCAST(N);
1321   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1322   case ISD::FADD:               return visitFADD(N);
1323   case ISD::FSUB:               return visitFSUB(N);
1324   case ISD::FMUL:               return visitFMUL(N);
1325   case ISD::FMA:                return visitFMA(N);
1326   case ISD::FDIV:               return visitFDIV(N);
1327   case ISD::FREM:               return visitFREM(N);
1328   case ISD::FSQRT:              return visitFSQRT(N);
1329   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1330   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1331   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1332   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1333   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1334   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1335   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1336   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1337   case ISD::FNEG:               return visitFNEG(N);
1338   case ISD::FABS:               return visitFABS(N);
1339   case ISD::FFLOOR:             return visitFFLOOR(N);
1340   case ISD::FMINNUM:            return visitFMINNUM(N);
1341   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1342   case ISD::FCEIL:              return visitFCEIL(N);
1343   case ISD::FTRUNC:             return visitFTRUNC(N);
1344   case ISD::BRCOND:             return visitBRCOND(N);
1345   case ISD::BR_CC:              return visitBR_CC(N);
1346   case ISD::LOAD:               return visitLOAD(N);
1347   case ISD::STORE:              return visitSTORE(N);
1348   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1349   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1350   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1351   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1352   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1353   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1354   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1355   case ISD::MLOAD:              return visitMLOAD(N);
1356   case ISD::MSTORE:             return visitMSTORE(N);
1357   }
1358   return SDValue();
1359 }
1360
1361 SDValue DAGCombiner::combine(SDNode *N) {
1362   SDValue RV = visit(N);
1363
1364   // If nothing happened, try a target-specific DAG combine.
1365   if (!RV.getNode()) {
1366     assert(N->getOpcode() != ISD::DELETED_NODE &&
1367            "Node was deleted but visit returned NULL!");
1368
1369     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1370         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1371
1372       // Expose the DAG combiner to the target combiner impls.
1373       TargetLowering::DAGCombinerInfo
1374         DagCombineInfo(DAG, Level, false, this);
1375
1376       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1377     }
1378   }
1379
1380   // If nothing happened still, try promoting the operation.
1381   if (!RV.getNode()) {
1382     switch (N->getOpcode()) {
1383     default: break;
1384     case ISD::ADD:
1385     case ISD::SUB:
1386     case ISD::MUL:
1387     case ISD::AND:
1388     case ISD::OR:
1389     case ISD::XOR:
1390       RV = PromoteIntBinOp(SDValue(N, 0));
1391       break;
1392     case ISD::SHL:
1393     case ISD::SRA:
1394     case ISD::SRL:
1395       RV = PromoteIntShiftOp(SDValue(N, 0));
1396       break;
1397     case ISD::SIGN_EXTEND:
1398     case ISD::ZERO_EXTEND:
1399     case ISD::ANY_EXTEND:
1400       RV = PromoteExtend(SDValue(N, 0));
1401       break;
1402     case ISD::LOAD:
1403       if (PromoteLoad(SDValue(N, 0)))
1404         RV = SDValue(N, 0);
1405       break;
1406     }
1407   }
1408
1409   // If N is a commutative binary node, try commuting it to enable more
1410   // sdisel CSE.
1411   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1412       N->getNumValues() == 1) {
1413     SDValue N0 = N->getOperand(0);
1414     SDValue N1 = N->getOperand(1);
1415
1416     // Constant operands are canonicalized to RHS.
1417     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1418       SDValue Ops[] = {N1, N0};
1419       SDNode *CSENode;
1420       if (const BinaryWithFlagsSDNode *BinNode =
1421               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1422         CSENode = DAG.getNodeIfExists(
1423             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1424             BinNode->hasNoSignedWrap(), BinNode->isExact());
1425       } else {
1426         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1427       }
1428       if (CSENode)
1429         return SDValue(CSENode, 0);
1430     }
1431   }
1432
1433   return RV;
1434 }
1435
1436 /// Given a node, return its input chain if it has one, otherwise return a null
1437 /// sd operand.
1438 static SDValue getInputChainForNode(SDNode *N) {
1439   if (unsigned NumOps = N->getNumOperands()) {
1440     if (N->getOperand(0).getValueType() == MVT::Other)
1441       return N->getOperand(0);
1442     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1443       return N->getOperand(NumOps-1);
1444     for (unsigned i = 1; i < NumOps-1; ++i)
1445       if (N->getOperand(i).getValueType() == MVT::Other)
1446         return N->getOperand(i);
1447   }
1448   return SDValue();
1449 }
1450
1451 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1452   // If N has two operands, where one has an input chain equal to the other,
1453   // the 'other' chain is redundant.
1454   if (N->getNumOperands() == 2) {
1455     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1456       return N->getOperand(0);
1457     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1458       return N->getOperand(1);
1459   }
1460
1461   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1462   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1463   SmallPtrSet<SDNode*, 16> SeenOps;
1464   bool Changed = false;             // If we should replace this token factor.
1465
1466   // Start out with this token factor.
1467   TFs.push_back(N);
1468
1469   // Iterate through token factors.  The TFs grows when new token factors are
1470   // encountered.
1471   for (unsigned i = 0; i < TFs.size(); ++i) {
1472     SDNode *TF = TFs[i];
1473
1474     // Check each of the operands.
1475     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1476       SDValue Op = TF->getOperand(i);
1477
1478       switch (Op.getOpcode()) {
1479       case ISD::EntryToken:
1480         // Entry tokens don't need to be added to the list. They are
1481         // rededundant.
1482         Changed = true;
1483         break;
1484
1485       case ISD::TokenFactor:
1486         if (Op.hasOneUse() &&
1487             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1488           // Queue up for processing.
1489           TFs.push_back(Op.getNode());
1490           // Clean up in case the token factor is removed.
1491           AddToWorklist(Op.getNode());
1492           Changed = true;
1493           break;
1494         }
1495         // Fall thru
1496
1497       default:
1498         // Only add if it isn't already in the list.
1499         if (SeenOps.insert(Op.getNode()).second)
1500           Ops.push_back(Op);
1501         else
1502           Changed = true;
1503         break;
1504       }
1505     }
1506   }
1507
1508   SDValue Result;
1509
1510   // If we've change things around then replace token factor.
1511   if (Changed) {
1512     if (Ops.empty()) {
1513       // The entry token is the only possible outcome.
1514       Result = DAG.getEntryNode();
1515     } else {
1516       // New and improved token factor.
1517       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1518     }
1519
1520     // Don't add users to work list.
1521     return CombineTo(N, Result, false);
1522   }
1523
1524   return Result;
1525 }
1526
1527 /// MERGE_VALUES can always be eliminated.
1528 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1529   WorklistRemover DeadNodes(*this);
1530   // Replacing results may cause a different MERGE_VALUES to suddenly
1531   // be CSE'd with N, and carry its uses with it. Iterate until no
1532   // uses remain, to ensure that the node can be safely deleted.
1533   // First add the users of this node to the work list so that they
1534   // can be tried again once they have new operands.
1535   AddUsersToWorklist(N);
1536   do {
1537     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1538       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1539   } while (!N->use_empty());
1540   deleteAndRecombine(N);
1541   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1542 }
1543
1544 SDValue DAGCombiner::visitADD(SDNode *N) {
1545   SDValue N0 = N->getOperand(0);
1546   SDValue N1 = N->getOperand(1);
1547   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1548   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1549   EVT VT = N0.getValueType();
1550
1551   // fold vector ops
1552   if (VT.isVector()) {
1553     SDValue FoldedVOp = SimplifyVBinOp(N);
1554     if (FoldedVOp.getNode()) return FoldedVOp;
1555
1556     // fold (add x, 0) -> x, vector edition
1557     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1558       return N0;
1559     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1560       return N1;
1561   }
1562
1563   // fold (add x, undef) -> undef
1564   if (N0.getOpcode() == ISD::UNDEF)
1565     return N0;
1566   if (N1.getOpcode() == ISD::UNDEF)
1567     return N1;
1568   // fold (add c1, c2) -> c1+c2
1569   if (N0C && N1C)
1570     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1571   // canonicalize constant to RHS
1572   if (N0C && !N1C)
1573     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1574   // fold (add x, 0) -> x
1575   if (N1C && N1C->isNullValue())
1576     return N0;
1577   // fold (add Sym, c) -> Sym+c
1578   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1579     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1580         GA->getOpcode() == ISD::GlobalAddress)
1581       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1582                                   GA->getOffset() +
1583                                     (uint64_t)N1C->getSExtValue());
1584   // fold ((c1-A)+c2) -> (c1+c2)-A
1585   if (N1C && N0.getOpcode() == ISD::SUB)
1586     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1587       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1588                          DAG.getConstant(N1C->getAPIntValue()+
1589                                          N0C->getAPIntValue(), VT),
1590                          N0.getOperand(1));
1591   // reassociate add
1592   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1593   if (RADD.getNode())
1594     return RADD;
1595   // fold ((0-A) + B) -> B-A
1596   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1597       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1598     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1599   // fold (A + (0-B)) -> A-B
1600   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1601       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1602     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1603   // fold (A+(B-A)) -> B
1604   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1605     return N1.getOperand(0);
1606   // fold ((B-A)+A) -> B
1607   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1608     return N0.getOperand(0);
1609   // fold (A+(B-(A+C))) to (B-C)
1610   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1611       N0 == N1.getOperand(1).getOperand(0))
1612     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1613                        N1.getOperand(1).getOperand(1));
1614   // fold (A+(B-(C+A))) to (B-C)
1615   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1616       N0 == N1.getOperand(1).getOperand(1))
1617     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1618                        N1.getOperand(1).getOperand(0));
1619   // fold (A+((B-A)+or-C)) to (B+or-C)
1620   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1621       N1.getOperand(0).getOpcode() == ISD::SUB &&
1622       N0 == N1.getOperand(0).getOperand(1))
1623     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1624                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1625
1626   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1627   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1628     SDValue N00 = N0.getOperand(0);
1629     SDValue N01 = N0.getOperand(1);
1630     SDValue N10 = N1.getOperand(0);
1631     SDValue N11 = N1.getOperand(1);
1632
1633     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1634       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1635                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1636                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1637   }
1638
1639   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1640     return SDValue(N, 0);
1641
1642   // fold (a+b) -> (a|b) iff a and b share no bits.
1643   if (VT.isInteger() && !VT.isVector()) {
1644     APInt LHSZero, LHSOne;
1645     APInt RHSZero, RHSOne;
1646     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1647
1648     if (LHSZero.getBoolValue()) {
1649       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1650
1651       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1652       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1653       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1654         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1655           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1656       }
1657     }
1658   }
1659
1660   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1661   if (N1.getOpcode() == ISD::SHL &&
1662       N1.getOperand(0).getOpcode() == ISD::SUB)
1663     if (ConstantSDNode *C =
1664           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1665       if (C->getAPIntValue() == 0)
1666         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1667                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1668                                        N1.getOperand(0).getOperand(1),
1669                                        N1.getOperand(1)));
1670   if (N0.getOpcode() == ISD::SHL &&
1671       N0.getOperand(0).getOpcode() == ISD::SUB)
1672     if (ConstantSDNode *C =
1673           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1674       if (C->getAPIntValue() == 0)
1675         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1676                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1677                                        N0.getOperand(0).getOperand(1),
1678                                        N0.getOperand(1)));
1679
1680   if (N1.getOpcode() == ISD::AND) {
1681     SDValue AndOp0 = N1.getOperand(0);
1682     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1683     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1684     unsigned DestBits = VT.getScalarType().getSizeInBits();
1685
1686     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1687     // and similar xforms where the inner op is either ~0 or 0.
1688     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1689       SDLoc DL(N);
1690       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1691     }
1692   }
1693
1694   // add (sext i1), X -> sub X, (zext i1)
1695   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1696       N0.getOperand(0).getValueType() == MVT::i1 &&
1697       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1698     SDLoc DL(N);
1699     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1700     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1701   }
1702
1703   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1704   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1705     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1706     if (TN->getVT() == MVT::i1) {
1707       SDLoc DL(N);
1708       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1709                                  DAG.getConstant(1, VT));
1710       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1711     }
1712   }
1713
1714   return SDValue();
1715 }
1716
1717 SDValue DAGCombiner::visitADDC(SDNode *N) {
1718   SDValue N0 = N->getOperand(0);
1719   SDValue N1 = N->getOperand(1);
1720   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1721   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1722   EVT VT = N0.getValueType();
1723
1724   // If the flag result is dead, turn this into an ADD.
1725   if (!N->hasAnyUseOfValue(1))
1726     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1727                      DAG.getNode(ISD::CARRY_FALSE,
1728                                  SDLoc(N), MVT::Glue));
1729
1730   // canonicalize constant to RHS.
1731   if (N0C && !N1C)
1732     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1733
1734   // fold (addc x, 0) -> x + no carry out
1735   if (N1C && N1C->isNullValue())
1736     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1737                                         SDLoc(N), MVT::Glue));
1738
1739   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1740   APInt LHSZero, LHSOne;
1741   APInt RHSZero, RHSOne;
1742   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1743
1744   if (LHSZero.getBoolValue()) {
1745     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1746
1747     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1748     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1749     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1750       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1751                        DAG.getNode(ISD::CARRY_FALSE,
1752                                    SDLoc(N), MVT::Glue));
1753   }
1754
1755   return SDValue();
1756 }
1757
1758 SDValue DAGCombiner::visitADDE(SDNode *N) {
1759   SDValue N0 = N->getOperand(0);
1760   SDValue N1 = N->getOperand(1);
1761   SDValue CarryIn = N->getOperand(2);
1762   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1763   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1764
1765   // canonicalize constant to RHS
1766   if (N0C && !N1C)
1767     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1768                        N1, N0, CarryIn);
1769
1770   // fold (adde x, y, false) -> (addc x, y)
1771   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1772     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1773
1774   return SDValue();
1775 }
1776
1777 // Since it may not be valid to emit a fold to zero for vector initializers
1778 // check if we can before folding.
1779 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1780                              SelectionDAG &DAG,
1781                              bool LegalOperations, bool LegalTypes) {
1782   if (!VT.isVector())
1783     return DAG.getConstant(0, VT);
1784   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1785     return DAG.getConstant(0, VT);
1786   return SDValue();
1787 }
1788
1789 SDValue DAGCombiner::visitSUB(SDNode *N) {
1790   SDValue N0 = N->getOperand(0);
1791   SDValue N1 = N->getOperand(1);
1792   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1793   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1794   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1795     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1796   EVT VT = N0.getValueType();
1797
1798   // fold vector ops
1799   if (VT.isVector()) {
1800     SDValue FoldedVOp = SimplifyVBinOp(N);
1801     if (FoldedVOp.getNode()) return FoldedVOp;
1802
1803     // fold (sub x, 0) -> x, vector edition
1804     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1805       return N0;
1806   }
1807
1808   // fold (sub x, x) -> 0
1809   // FIXME: Refactor this and xor and other similar operations together.
1810   if (N0 == N1)
1811     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1812   // fold (sub c1, c2) -> c1-c2
1813   if (N0C && N1C)
1814     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1815   // fold (sub x, c) -> (add x, -c)
1816   if (N1C)
1817     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1818                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1819   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1820   if (N0C && N0C->isAllOnesValue())
1821     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1822   // fold A-(A-B) -> B
1823   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1824     return N1.getOperand(1);
1825   // fold (A+B)-A -> B
1826   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1827     return N0.getOperand(1);
1828   // fold (A+B)-B -> A
1829   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1830     return N0.getOperand(0);
1831   // fold C2-(A+C1) -> (C2-C1)-A
1832   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1833     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1834                                    VT);
1835     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1836                        N1.getOperand(0));
1837   }
1838   // fold ((A+(B+or-C))-B) -> A+or-C
1839   if (N0.getOpcode() == ISD::ADD &&
1840       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1841        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1842       N0.getOperand(1).getOperand(0) == N1)
1843     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1844                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1845   // fold ((A+(C+B))-B) -> A+C
1846   if (N0.getOpcode() == ISD::ADD &&
1847       N0.getOperand(1).getOpcode() == ISD::ADD &&
1848       N0.getOperand(1).getOperand(1) == N1)
1849     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1850                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1851   // fold ((A-(B-C))-C) -> A-B
1852   if (N0.getOpcode() == ISD::SUB &&
1853       N0.getOperand(1).getOpcode() == ISD::SUB &&
1854       N0.getOperand(1).getOperand(1) == N1)
1855     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1856                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1857
1858   // If either operand of a sub is undef, the result is undef
1859   if (N0.getOpcode() == ISD::UNDEF)
1860     return N0;
1861   if (N1.getOpcode() == ISD::UNDEF)
1862     return N1;
1863
1864   // If the relocation model supports it, consider symbol offsets.
1865   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1866     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1867       // fold (sub Sym, c) -> Sym-c
1868       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1869         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1870                                     GA->getOffset() -
1871                                       (uint64_t)N1C->getSExtValue());
1872       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1873       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1874         if (GA->getGlobal() == GB->getGlobal())
1875           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1876                                  VT);
1877     }
1878
1879   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1880   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1881     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1882     if (TN->getVT() == MVT::i1) {
1883       SDLoc DL(N);
1884       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1885                                  DAG.getConstant(1, VT));
1886       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1887     }
1888   }
1889
1890   return SDValue();
1891 }
1892
1893 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1894   SDValue N0 = N->getOperand(0);
1895   SDValue N1 = N->getOperand(1);
1896   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1897   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1898   EVT VT = N0.getValueType();
1899
1900   // If the flag result is dead, turn this into an SUB.
1901   if (!N->hasAnyUseOfValue(1))
1902     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1903                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1904                                  MVT::Glue));
1905
1906   // fold (subc x, x) -> 0 + no borrow
1907   if (N0 == N1)
1908     return CombineTo(N, DAG.getConstant(0, VT),
1909                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1910                                  MVT::Glue));
1911
1912   // fold (subc x, 0) -> x + no borrow
1913   if (N1C && N1C->isNullValue())
1914     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1915                                         MVT::Glue));
1916
1917   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1918   if (N0C && N0C->isAllOnesValue())
1919     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1920                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1921                                  MVT::Glue));
1922
1923   return SDValue();
1924 }
1925
1926 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1927   SDValue N0 = N->getOperand(0);
1928   SDValue N1 = N->getOperand(1);
1929   SDValue CarryIn = N->getOperand(2);
1930
1931   // fold (sube x, y, false) -> (subc x, y)
1932   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1933     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1934
1935   return SDValue();
1936 }
1937
1938 SDValue DAGCombiner::visitMUL(SDNode *N) {
1939   SDValue N0 = N->getOperand(0);
1940   SDValue N1 = N->getOperand(1);
1941   EVT VT = N0.getValueType();
1942
1943   // fold (mul x, undef) -> 0
1944   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1945     return DAG.getConstant(0, VT);
1946
1947   bool N0IsConst = false;
1948   bool N1IsConst = false;
1949   APInt ConstValue0, ConstValue1;
1950   // fold vector ops
1951   if (VT.isVector()) {
1952     SDValue FoldedVOp = SimplifyVBinOp(N);
1953     if (FoldedVOp.getNode()) return FoldedVOp;
1954
1955     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1956     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1957   } else {
1958     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1959     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1960                             : APInt();
1961     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1962     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1963                             : APInt();
1964   }
1965
1966   // fold (mul c1, c2) -> c1*c2
1967   if (N0IsConst && N1IsConst)
1968     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1969
1970   // canonicalize constant to RHS
1971   if (N0IsConst && !N1IsConst)
1972     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1973   // fold (mul x, 0) -> 0
1974   if (N1IsConst && ConstValue1 == 0)
1975     return N1;
1976   // We require a splat of the entire scalar bit width for non-contiguous
1977   // bit patterns.
1978   bool IsFullSplat =
1979     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1980   // fold (mul x, 1) -> x
1981   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1982     return N0;
1983   // fold (mul x, -1) -> 0-x
1984   if (N1IsConst && ConstValue1.isAllOnesValue())
1985     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1986                        DAG.getConstant(0, VT), N0);
1987   // fold (mul x, (1 << c)) -> x << c
1988   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1989     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1990                        DAG.getConstant(ConstValue1.logBase2(),
1991                                        getShiftAmountTy(N0.getValueType())));
1992   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1993   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1994     unsigned Log2Val = (-ConstValue1).logBase2();
1995     // FIXME: If the input is something that is easily negated (e.g. a
1996     // single-use add), we should put the negate there.
1997     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1998                        DAG.getConstant(0, VT),
1999                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2000                             DAG.getConstant(Log2Val,
2001                                       getShiftAmountTy(N0.getValueType()))));
2002   }
2003
2004   APInt Val;
2005   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2006   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2007       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2008                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2009     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2010                              N1, N0.getOperand(1));
2011     AddToWorklist(C3.getNode());
2012     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2013                        N0.getOperand(0), C3);
2014   }
2015
2016   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2017   // use.
2018   {
2019     SDValue Sh(nullptr,0), Y(nullptr,0);
2020     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2021     if (N0.getOpcode() == ISD::SHL &&
2022         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2023                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2024         N0.getNode()->hasOneUse()) {
2025       Sh = N0; Y = N1;
2026     } else if (N1.getOpcode() == ISD::SHL &&
2027                isa<ConstantSDNode>(N1.getOperand(1)) &&
2028                N1.getNode()->hasOneUse()) {
2029       Sh = N1; Y = N0;
2030     }
2031
2032     if (Sh.getNode()) {
2033       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2034                                 Sh.getOperand(0), Y);
2035       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2036                          Mul, Sh.getOperand(1));
2037     }
2038   }
2039
2040   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2041   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2042       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2043                      isa<ConstantSDNode>(N0.getOperand(1))))
2044     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2045                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2046                                    N0.getOperand(0), N1),
2047                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2048                                    N0.getOperand(1), N1));
2049
2050   // reassociate mul
2051   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2052   if (RMUL.getNode())
2053     return RMUL;
2054
2055   return SDValue();
2056 }
2057
2058 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2059   SDValue N0 = N->getOperand(0);
2060   SDValue N1 = N->getOperand(1);
2061   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2062   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2063   EVT VT = N->getValueType(0);
2064
2065   // fold vector ops
2066   if (VT.isVector()) {
2067     SDValue FoldedVOp = SimplifyVBinOp(N);
2068     if (FoldedVOp.getNode()) return FoldedVOp;
2069   }
2070
2071   // fold (sdiv c1, c2) -> c1/c2
2072   if (N0C && N1C && !N1C->isNullValue())
2073     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2074   // fold (sdiv X, 1) -> X
2075   if (N1C && N1C->getAPIntValue() == 1LL)
2076     return N0;
2077   // fold (sdiv X, -1) -> 0-X
2078   if (N1C && N1C->isAllOnesValue())
2079     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2080                        DAG.getConstant(0, VT), N0);
2081   // If we know the sign bits of both operands are zero, strength reduce to a
2082   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2083   if (!VT.isVector()) {
2084     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2085       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2086                          N0, N1);
2087   }
2088
2089   // fold (sdiv X, pow2) -> simple ops after legalize
2090   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2091                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2092     // If dividing by powers of two is cheap, then don't perform the following
2093     // fold.
2094     if (TLI.isPow2SDivCheap())
2095       return SDValue();
2096
2097     // Target-specific implementation of sdiv x, pow2.
2098     SDValue Res = BuildSDIVPow2(N);
2099     if (Res.getNode())
2100       return Res;
2101
2102     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2103
2104     // Splat the sign bit into the register
2105     SDValue SGN =
2106         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2107                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2108                                     getShiftAmountTy(N0.getValueType())));
2109     AddToWorklist(SGN.getNode());
2110
2111     // Add (N0 < 0) ? abs2 - 1 : 0;
2112     SDValue SRL =
2113         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2114                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2115                                     getShiftAmountTy(SGN.getValueType())));
2116     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2117     AddToWorklist(SRL.getNode());
2118     AddToWorklist(ADD.getNode());    // Divide by pow2
2119     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2120                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2121
2122     // If we're dividing by a positive value, we're done.  Otherwise, we must
2123     // negate the result.
2124     if (N1C->getAPIntValue().isNonNegative())
2125       return SRA;
2126
2127     AddToWorklist(SRA.getNode());
2128     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2129   }
2130
2131   // if integer divide is expensive and we satisfy the requirements, emit an
2132   // alternate sequence.
2133   if (N1C && !TLI.isIntDivCheap()) {
2134     SDValue Op = BuildSDIV(N);
2135     if (Op.getNode()) return Op;
2136   }
2137
2138   // undef / X -> 0
2139   if (N0.getOpcode() == ISD::UNDEF)
2140     return DAG.getConstant(0, VT);
2141   // X / undef -> undef
2142   if (N1.getOpcode() == ISD::UNDEF)
2143     return N1;
2144
2145   return SDValue();
2146 }
2147
2148 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2149   SDValue N0 = N->getOperand(0);
2150   SDValue N1 = N->getOperand(1);
2151   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2152   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2153   EVT VT = N->getValueType(0);
2154
2155   // fold vector ops
2156   if (VT.isVector()) {
2157     SDValue FoldedVOp = SimplifyVBinOp(N);
2158     if (FoldedVOp.getNode()) return FoldedVOp;
2159   }
2160
2161   // fold (udiv c1, c2) -> c1/c2
2162   if (N0C && N1C && !N1C->isNullValue())
2163     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2164   // fold (udiv x, (1 << c)) -> x >>u c
2165   if (N1C && N1C->getAPIntValue().isPowerOf2())
2166     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2167                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2168                                        getShiftAmountTy(N0.getValueType())));
2169   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2170   if (N1.getOpcode() == ISD::SHL) {
2171     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2172       if (SHC->getAPIntValue().isPowerOf2()) {
2173         EVT ADDVT = N1.getOperand(1).getValueType();
2174         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2175                                   N1.getOperand(1),
2176                                   DAG.getConstant(SHC->getAPIntValue()
2177                                                                   .logBase2(),
2178                                                   ADDVT));
2179         AddToWorklist(Add.getNode());
2180         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2181       }
2182     }
2183   }
2184   // fold (udiv x, c) -> alternate
2185   if (N1C && !TLI.isIntDivCheap()) {
2186     SDValue Op = BuildUDIV(N);
2187     if (Op.getNode()) return Op;
2188   }
2189
2190   // undef / X -> 0
2191   if (N0.getOpcode() == ISD::UNDEF)
2192     return DAG.getConstant(0, VT);
2193   // X / undef -> undef
2194   if (N1.getOpcode() == ISD::UNDEF)
2195     return N1;
2196
2197   return SDValue();
2198 }
2199
2200 SDValue DAGCombiner::visitSREM(SDNode *N) {
2201   SDValue N0 = N->getOperand(0);
2202   SDValue N1 = N->getOperand(1);
2203   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2204   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2205   EVT VT = N->getValueType(0);
2206
2207   // fold (srem c1, c2) -> c1%c2
2208   if (N0C && N1C && !N1C->isNullValue())
2209     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2210   // If we know the sign bits of both operands are zero, strength reduce to a
2211   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2212   if (!VT.isVector()) {
2213     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2214       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2215   }
2216
2217   // If X/C can be simplified by the division-by-constant logic, lower
2218   // X%C to the equivalent of X-X/C*C.
2219   if (N1C && !N1C->isNullValue()) {
2220     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2221     AddToWorklist(Div.getNode());
2222     SDValue OptimizedDiv = combine(Div.getNode());
2223     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2224       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2225                                 OptimizedDiv, N1);
2226       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2227       AddToWorklist(Mul.getNode());
2228       return Sub;
2229     }
2230   }
2231
2232   // undef % X -> 0
2233   if (N0.getOpcode() == ISD::UNDEF)
2234     return DAG.getConstant(0, VT);
2235   // X % undef -> undef
2236   if (N1.getOpcode() == ISD::UNDEF)
2237     return N1;
2238
2239   return SDValue();
2240 }
2241
2242 SDValue DAGCombiner::visitUREM(SDNode *N) {
2243   SDValue N0 = N->getOperand(0);
2244   SDValue N1 = N->getOperand(1);
2245   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2246   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2247   EVT VT = N->getValueType(0);
2248
2249   // fold (urem c1, c2) -> c1%c2
2250   if (N0C && N1C && !N1C->isNullValue())
2251     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2252   // fold (urem x, pow2) -> (and x, pow2-1)
2253   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2254     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2255                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2256   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2257   if (N1.getOpcode() == ISD::SHL) {
2258     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2259       if (SHC->getAPIntValue().isPowerOf2()) {
2260         SDValue Add =
2261           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2262                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2263                                  VT));
2264         AddToWorklist(Add.getNode());
2265         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2266       }
2267     }
2268   }
2269
2270   // If X/C can be simplified by the division-by-constant logic, lower
2271   // X%C to the equivalent of X-X/C*C.
2272   if (N1C && !N1C->isNullValue()) {
2273     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2274     AddToWorklist(Div.getNode());
2275     SDValue OptimizedDiv = combine(Div.getNode());
2276     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2277       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2278                                 OptimizedDiv, N1);
2279       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2280       AddToWorklist(Mul.getNode());
2281       return Sub;
2282     }
2283   }
2284
2285   // undef % X -> 0
2286   if (N0.getOpcode() == ISD::UNDEF)
2287     return DAG.getConstant(0, VT);
2288   // X % undef -> undef
2289   if (N1.getOpcode() == ISD::UNDEF)
2290     return N1;
2291
2292   return SDValue();
2293 }
2294
2295 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2296   SDValue N0 = N->getOperand(0);
2297   SDValue N1 = N->getOperand(1);
2298   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2299   EVT VT = N->getValueType(0);
2300   SDLoc DL(N);
2301
2302   // fold (mulhs x, 0) -> 0
2303   if (N1C && N1C->isNullValue())
2304     return N1;
2305   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2306   if (N1C && N1C->getAPIntValue() == 1)
2307     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2308                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2309                                        getShiftAmountTy(N0.getValueType())));
2310   // fold (mulhs x, undef) -> 0
2311   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2312     return DAG.getConstant(0, VT);
2313
2314   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2315   // plus a shift.
2316   if (VT.isSimple() && !VT.isVector()) {
2317     MVT Simple = VT.getSimpleVT();
2318     unsigned SimpleSize = Simple.getSizeInBits();
2319     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2320     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2321       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2322       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2323       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2324       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2325             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2326       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2327     }
2328   }
2329
2330   return SDValue();
2331 }
2332
2333 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2334   SDValue N0 = N->getOperand(0);
2335   SDValue N1 = N->getOperand(1);
2336   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2337   EVT VT = N->getValueType(0);
2338   SDLoc DL(N);
2339
2340   // fold (mulhu x, 0) -> 0
2341   if (N1C && N1C->isNullValue())
2342     return N1;
2343   // fold (mulhu x, 1) -> 0
2344   if (N1C && N1C->getAPIntValue() == 1)
2345     return DAG.getConstant(0, N0.getValueType());
2346   // fold (mulhu x, undef) -> 0
2347   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2348     return DAG.getConstant(0, VT);
2349
2350   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2351   // plus a shift.
2352   if (VT.isSimple() && !VT.isVector()) {
2353     MVT Simple = VT.getSimpleVT();
2354     unsigned SimpleSize = Simple.getSizeInBits();
2355     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2356     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2357       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2358       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2359       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2360       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2361             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2362       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2363     }
2364   }
2365
2366   return SDValue();
2367 }
2368
2369 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2370 /// give the opcodes for the two computations that are being performed. Return
2371 /// true if a simplification was made.
2372 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2373                                                 unsigned HiOp) {
2374   // If the high half is not needed, just compute the low half.
2375   bool HiExists = N->hasAnyUseOfValue(1);
2376   if (!HiExists &&
2377       (!LegalOperations ||
2378        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2379     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2380     return CombineTo(N, Res, Res);
2381   }
2382
2383   // If the low half is not needed, just compute the high half.
2384   bool LoExists = N->hasAnyUseOfValue(0);
2385   if (!LoExists &&
2386       (!LegalOperations ||
2387        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2388     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2389     return CombineTo(N, Res, Res);
2390   }
2391
2392   // If both halves are used, return as it is.
2393   if (LoExists && HiExists)
2394     return SDValue();
2395
2396   // If the two computed results can be simplified separately, separate them.
2397   if (LoExists) {
2398     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2399     AddToWorklist(Lo.getNode());
2400     SDValue LoOpt = combine(Lo.getNode());
2401     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2402         (!LegalOperations ||
2403          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2404       return CombineTo(N, LoOpt, LoOpt);
2405   }
2406
2407   if (HiExists) {
2408     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2409     AddToWorklist(Hi.getNode());
2410     SDValue HiOpt = combine(Hi.getNode());
2411     if (HiOpt.getNode() && HiOpt != Hi &&
2412         (!LegalOperations ||
2413          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2414       return CombineTo(N, HiOpt, HiOpt);
2415   }
2416
2417   return SDValue();
2418 }
2419
2420 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2421   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2422   if (Res.getNode()) return Res;
2423
2424   EVT VT = N->getValueType(0);
2425   SDLoc DL(N);
2426
2427   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2428   // plus a shift.
2429   if (VT.isSimple() && !VT.isVector()) {
2430     MVT Simple = VT.getSimpleVT();
2431     unsigned SimpleSize = Simple.getSizeInBits();
2432     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2433     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2434       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2435       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2436       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2437       // Compute the high part as N1.
2438       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2439             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2440       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2441       // Compute the low part as N0.
2442       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2443       return CombineTo(N, Lo, Hi);
2444     }
2445   }
2446
2447   return SDValue();
2448 }
2449
2450 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2451   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2452   if (Res.getNode()) return Res;
2453
2454   EVT VT = N->getValueType(0);
2455   SDLoc DL(N);
2456
2457   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2458   // plus a shift.
2459   if (VT.isSimple() && !VT.isVector()) {
2460     MVT Simple = VT.getSimpleVT();
2461     unsigned SimpleSize = Simple.getSizeInBits();
2462     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2463     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2464       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2465       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2466       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2467       // Compute the high part as N1.
2468       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2469             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2470       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2471       // Compute the low part as N0.
2472       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2473       return CombineTo(N, Lo, Hi);
2474     }
2475   }
2476
2477   return SDValue();
2478 }
2479
2480 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2481   // (smulo x, 2) -> (saddo x, x)
2482   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2483     if (C2->getAPIntValue() == 2)
2484       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2485                          N->getOperand(0), N->getOperand(0));
2486
2487   return SDValue();
2488 }
2489
2490 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2491   // (umulo x, 2) -> (uaddo x, x)
2492   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2493     if (C2->getAPIntValue() == 2)
2494       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2495                          N->getOperand(0), N->getOperand(0));
2496
2497   return SDValue();
2498 }
2499
2500 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2501   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2502   if (Res.getNode()) return Res;
2503
2504   return SDValue();
2505 }
2506
2507 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2508   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2509   if (Res.getNode()) return Res;
2510
2511   return SDValue();
2512 }
2513
2514 /// If this is a binary operator with two operands of the same opcode, try to
2515 /// simplify it.
2516 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2517   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2518   EVT VT = N0.getValueType();
2519   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2520
2521   // Bail early if none of these transforms apply.
2522   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2523
2524   // For each of OP in AND/OR/XOR:
2525   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2526   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2527   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2528   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2529   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2530   //
2531   // do not sink logical op inside of a vector extend, since it may combine
2532   // into a vsetcc.
2533   EVT Op0VT = N0.getOperand(0).getValueType();
2534   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2535        N0.getOpcode() == ISD::SIGN_EXTEND ||
2536        N0.getOpcode() == ISD::BSWAP ||
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->getValueType(0),
2802                                                     Load->getMemoryVT());
2803
2804     // Resize the constant to the same size as the original memory access before
2805     // extension. If it is still the AllOnesValue then this AND is completely
2806     // unneeded.
2807     Constant =
2808       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2809
2810     bool B;
2811     switch (Load->getExtensionType()) {
2812     default: B = false; break;
2813     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2814     case ISD::ZEXTLOAD:
2815     case ISD::NON_EXTLOAD: B = true; break;
2816     }
2817
2818     if (B && Constant.isAllOnesValue()) {
2819       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2820       // preserve semantics once we get rid of the AND.
2821       SDValue NewLoad(Load, 0);
2822       if (Load->getExtensionType() == ISD::EXTLOAD) {
2823         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2824                               Load->getValueType(0), SDLoc(Load),
2825                               Load->getChain(), Load->getBasePtr(),
2826                               Load->getOffset(), Load->getMemoryVT(),
2827                               Load->getMemOperand());
2828         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2829         if (Load->getNumValues() == 3) {
2830           // PRE/POST_INC loads have 3 values.
2831           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2832                            NewLoad.getValue(2) };
2833           CombineTo(Load, To, 3, true);
2834         } else {
2835           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2836         }
2837       }
2838
2839       // Fold the AND away, taking care not to fold to the old load node if we
2840       // replaced it.
2841       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2842
2843       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2844     }
2845   }
2846   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2847   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2848     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2849     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2850
2851     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2852         LL.getValueType().isInteger()) {
2853       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2854       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2855         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2856                                      LR.getValueType(), LL, RL);
2857         AddToWorklist(ORNode.getNode());
2858         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2859       }
2860       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2861       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2862         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2863                                       LR.getValueType(), LL, RL);
2864         AddToWorklist(ANDNode.getNode());
2865         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2866       }
2867       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2868       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2869         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2870                                      LR.getValueType(), LL, RL);
2871         AddToWorklist(ORNode.getNode());
2872         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2873       }
2874     }
2875     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2876     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2877         Op0 == Op1 && LL.getValueType().isInteger() &&
2878       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2879                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2880                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2881                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2882       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2883                                     LL, DAG.getConstant(1, LL.getValueType()));
2884       AddToWorklist(ADDNode.getNode());
2885       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2886                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2887     }
2888     // canonicalize equivalent to ll == rl
2889     if (LL == RR && LR == RL) {
2890       Op1 = ISD::getSetCCSwappedOperands(Op1);
2891       std::swap(RL, RR);
2892     }
2893     if (LL == RL && LR == RR) {
2894       bool isInteger = LL.getValueType().isInteger();
2895       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2896       if (Result != ISD::SETCC_INVALID &&
2897           (!LegalOperations ||
2898            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2899             TLI.isOperationLegal(ISD::SETCC,
2900                             getSetCCResultType(N0.getSimpleValueType())))))
2901         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2902                             LL, LR, Result);
2903     }
2904   }
2905
2906   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2907   if (N0.getOpcode() == N1.getOpcode()) {
2908     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2909     if (Tmp.getNode()) return Tmp;
2910   }
2911
2912   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2913   // fold (and (sra)) -> (and (srl)) when possible.
2914   if (!VT.isVector() &&
2915       SimplifyDemandedBits(SDValue(N, 0)))
2916     return SDValue(N, 0);
2917
2918   // fold (zext_inreg (extload x)) -> (zextload x)
2919   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2920     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2921     EVT MemVT = LN0->getMemoryVT();
2922     // If we zero all the possible extended bits, then we can turn this into
2923     // a zextload if we are running before legalize or the operation is legal.
2924     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2925     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2926                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2927         ((!LegalOperations && !LN0->isVolatile()) ||
2928          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2929       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2930                                        LN0->getChain(), LN0->getBasePtr(),
2931                                        MemVT, LN0->getMemOperand());
2932       AddToWorklist(N);
2933       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2934       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2935     }
2936   }
2937   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2938   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2939       N0.hasOneUse()) {
2940     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2941     EVT MemVT = LN0->getMemoryVT();
2942     // If we zero all the possible extended bits, then we can turn this into
2943     // a zextload if we are running before legalize or the operation is legal.
2944     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2945     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2946                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2947         ((!LegalOperations && !LN0->isVolatile()) ||
2948          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2949       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2950                                        LN0->getChain(), LN0->getBasePtr(),
2951                                        MemVT, LN0->getMemOperand());
2952       AddToWorklist(N);
2953       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2954       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2955     }
2956   }
2957
2958   // fold (and (load x), 255) -> (zextload x, i8)
2959   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2960   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2961   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2962               (N0.getOpcode() == ISD::ANY_EXTEND &&
2963                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2964     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2965     LoadSDNode *LN0 = HasAnyExt
2966       ? cast<LoadSDNode>(N0.getOperand(0))
2967       : cast<LoadSDNode>(N0);
2968     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2969         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2970       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2971       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2972         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2973         EVT LoadedVT = LN0->getMemoryVT();
2974         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2975
2976         if (ExtVT == LoadedVT &&
2977             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2978                                                     ExtVT))) {
2979
2980           SDValue NewLoad =
2981             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2982                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2983                            LN0->getMemOperand());
2984           AddToWorklist(N);
2985           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2986           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2987         }
2988
2989         // Do not change the width of a volatile load.
2990         // Do not generate loads of non-round integer types since these can
2991         // be expensive (and would be wrong if the type is not byte sized).
2992         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2993             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2994                                                     ExtVT))) {
2995           EVT PtrType = LN0->getOperand(1).getValueType();
2996
2997           unsigned Alignment = LN0->getAlignment();
2998           SDValue NewPtr = LN0->getBasePtr();
2999
3000           // For big endian targets, we need to add an offset to the pointer
3001           // to load the correct bytes.  For little endian systems, we merely
3002           // need to read fewer bytes from the same pointer.
3003           if (TLI.isBigEndian()) {
3004             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3005             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3006             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3007             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3008                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3009             Alignment = MinAlign(Alignment, PtrOff);
3010           }
3011
3012           AddToWorklist(NewPtr.getNode());
3013
3014           SDValue Load =
3015             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3016                            LN0->getChain(), NewPtr,
3017                            LN0->getPointerInfo(),
3018                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3019                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3020           AddToWorklist(N);
3021           CombineTo(LN0, Load, Load.getValue(1));
3022           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3023         }
3024       }
3025     }
3026   }
3027
3028   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3029       VT.getSizeInBits() <= 64) {
3030     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3031       APInt ADDC = ADDI->getAPIntValue();
3032       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3033         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3034         // immediate for an add, but it is legal if its top c2 bits are set,
3035         // transform the ADD so the immediate doesn't need to be materialized
3036         // in a register.
3037         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3038           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3039                                              SRLI->getZExtValue());
3040           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3041             ADDC |= Mask;
3042             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3043               SDValue NewAdd =
3044                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3045                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3046               CombineTo(N0.getNode(), NewAdd);
3047               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3048             }
3049           }
3050         }
3051       }
3052     }
3053   }
3054
3055   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3056   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3057     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3058                                        N0.getOperand(1), false);
3059     if (BSwap.getNode())
3060       return BSwap;
3061   }
3062
3063   return SDValue();
3064 }
3065
3066 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3067 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3068                                         bool DemandHighBits) {
3069   if (!LegalOperations)
3070     return SDValue();
3071
3072   EVT VT = N->getValueType(0);
3073   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3074     return SDValue();
3075   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3076     return SDValue();
3077
3078   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3079   bool LookPassAnd0 = false;
3080   bool LookPassAnd1 = false;
3081   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3082       std::swap(N0, N1);
3083   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3084       std::swap(N0, N1);
3085   if (N0.getOpcode() == ISD::AND) {
3086     if (!N0.getNode()->hasOneUse())
3087       return SDValue();
3088     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3089     if (!N01C || N01C->getZExtValue() != 0xFF00)
3090       return SDValue();
3091     N0 = N0.getOperand(0);
3092     LookPassAnd0 = true;
3093   }
3094
3095   if (N1.getOpcode() == ISD::AND) {
3096     if (!N1.getNode()->hasOneUse())
3097       return SDValue();
3098     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3099     if (!N11C || N11C->getZExtValue() != 0xFF)
3100       return SDValue();
3101     N1 = N1.getOperand(0);
3102     LookPassAnd1 = true;
3103   }
3104
3105   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3106     std::swap(N0, N1);
3107   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3108     return SDValue();
3109   if (!N0.getNode()->hasOneUse() ||
3110       !N1.getNode()->hasOneUse())
3111     return SDValue();
3112
3113   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3114   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3115   if (!N01C || !N11C)
3116     return SDValue();
3117   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3118     return SDValue();
3119
3120   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3121   SDValue N00 = N0->getOperand(0);
3122   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3123     if (!N00.getNode()->hasOneUse())
3124       return SDValue();
3125     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3126     if (!N001C || N001C->getZExtValue() != 0xFF)
3127       return SDValue();
3128     N00 = N00.getOperand(0);
3129     LookPassAnd0 = true;
3130   }
3131
3132   SDValue N10 = N1->getOperand(0);
3133   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3134     if (!N10.getNode()->hasOneUse())
3135       return SDValue();
3136     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3137     if (!N101C || N101C->getZExtValue() != 0xFF00)
3138       return SDValue();
3139     N10 = N10.getOperand(0);
3140     LookPassAnd1 = true;
3141   }
3142
3143   if (N00 != N10)
3144     return SDValue();
3145
3146   // Make sure everything beyond the low halfword gets set to zero since the SRL
3147   // 16 will clear the top bits.
3148   unsigned OpSizeInBits = VT.getSizeInBits();
3149   if (DemandHighBits && OpSizeInBits > 16) {
3150     // If the left-shift isn't masked out then the only way this is a bswap is
3151     // if all bits beyond the low 8 are 0. In that case the entire pattern
3152     // reduces to a left shift anyway: leave it for other parts of the combiner.
3153     if (!LookPassAnd0)
3154       return SDValue();
3155
3156     // However, if the right shift isn't masked out then it might be because
3157     // it's not needed. See if we can spot that too.
3158     if (!LookPassAnd1 &&
3159         !DAG.MaskedValueIsZero(
3160             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3161       return SDValue();
3162   }
3163
3164   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3165   if (OpSizeInBits > 16)
3166     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3167                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3168   return Res;
3169 }
3170
3171 /// Return true if the specified node is an element that makes up a 32-bit
3172 /// packed halfword byteswap.
3173 /// ((x & 0x000000ff) << 8) |
3174 /// ((x & 0x0000ff00) >> 8) |
3175 /// ((x & 0x00ff0000) << 8) |
3176 /// ((x & 0xff000000) >> 8)
3177 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3178   if (!N.getNode()->hasOneUse())
3179     return false;
3180
3181   unsigned Opc = N.getOpcode();
3182   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3183     return false;
3184
3185   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3186   if (!N1C)
3187     return false;
3188
3189   unsigned Num;
3190   switch (N1C->getZExtValue()) {
3191   default:
3192     return false;
3193   case 0xFF:       Num = 0; break;
3194   case 0xFF00:     Num = 1; break;
3195   case 0xFF0000:   Num = 2; break;
3196   case 0xFF000000: Num = 3; break;
3197   }
3198
3199   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3200   SDValue N0 = N.getOperand(0);
3201   if (Opc == ISD::AND) {
3202     if (Num == 0 || Num == 2) {
3203       // (x >> 8) & 0xff
3204       // (x >> 8) & 0xff0000
3205       if (N0.getOpcode() != ISD::SRL)
3206         return false;
3207       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3208       if (!C || C->getZExtValue() != 8)
3209         return false;
3210     } else {
3211       // (x << 8) & 0xff00
3212       // (x << 8) & 0xff000000
3213       if (N0.getOpcode() != ISD::SHL)
3214         return false;
3215       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3216       if (!C || C->getZExtValue() != 8)
3217         return false;
3218     }
3219   } else if (Opc == ISD::SHL) {
3220     // (x & 0xff) << 8
3221     // (x & 0xff0000) << 8
3222     if (Num != 0 && Num != 2)
3223       return false;
3224     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3225     if (!C || C->getZExtValue() != 8)
3226       return false;
3227   } else { // Opc == ISD::SRL
3228     // (x & 0xff00) >> 8
3229     // (x & 0xff000000) >> 8
3230     if (Num != 1 && Num != 3)
3231       return false;
3232     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3233     if (!C || C->getZExtValue() != 8)
3234       return false;
3235   }
3236
3237   if (Parts[Num])
3238     return false;
3239
3240   Parts[Num] = N0.getOperand(0).getNode();
3241   return true;
3242 }
3243
3244 /// Match a 32-bit packed halfword bswap. That is
3245 /// ((x & 0x000000ff) << 8) |
3246 /// ((x & 0x0000ff00) >> 8) |
3247 /// ((x & 0x00ff0000) << 8) |
3248 /// ((x & 0xff000000) >> 8)
3249 /// => (rotl (bswap x), 16)
3250 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3251   if (!LegalOperations)
3252     return SDValue();
3253
3254   EVT VT = N->getValueType(0);
3255   if (VT != MVT::i32)
3256     return SDValue();
3257   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3258     return SDValue();
3259
3260   // Look for either
3261   // (or (or (and), (and)), (or (and), (and)))
3262   // (or (or (or (and), (and)), (and)), (and))
3263   if (N0.getOpcode() != ISD::OR)
3264     return SDValue();
3265   SDValue N00 = N0.getOperand(0);
3266   SDValue N01 = N0.getOperand(1);
3267   SDNode *Parts[4] = {};
3268
3269   if (N1.getOpcode() == ISD::OR &&
3270       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3271     // (or (or (and), (and)), (or (and), (and)))
3272     SDValue N000 = N00.getOperand(0);
3273     if (!isBSwapHWordElement(N000, Parts))
3274       return SDValue();
3275
3276     SDValue N001 = N00.getOperand(1);
3277     if (!isBSwapHWordElement(N001, Parts))
3278       return SDValue();
3279     SDValue N010 = N01.getOperand(0);
3280     if (!isBSwapHWordElement(N010, Parts))
3281       return SDValue();
3282     SDValue N011 = N01.getOperand(1);
3283     if (!isBSwapHWordElement(N011, Parts))
3284       return SDValue();
3285   } else {
3286     // (or (or (or (and), (and)), (and)), (and))
3287     if (!isBSwapHWordElement(N1, Parts))
3288       return SDValue();
3289     if (!isBSwapHWordElement(N01, Parts))
3290       return SDValue();
3291     if (N00.getOpcode() != ISD::OR)
3292       return SDValue();
3293     SDValue N000 = N00.getOperand(0);
3294     if (!isBSwapHWordElement(N000, Parts))
3295       return SDValue();
3296     SDValue N001 = N00.getOperand(1);
3297     if (!isBSwapHWordElement(N001, Parts))
3298       return SDValue();
3299   }
3300
3301   // Make sure the parts are all coming from the same node.
3302   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3303     return SDValue();
3304
3305   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3306                               SDValue(Parts[0],0));
3307
3308   // Result of the bswap should be rotated by 16. If it's not legal, then
3309   // do  (x << 16) | (x >> 16).
3310   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3311   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3312     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3313   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3314     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3315   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3316                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3317                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3318 }
3319
3320 SDValue DAGCombiner::visitOR(SDNode *N) {
3321   SDValue N0 = N->getOperand(0);
3322   SDValue N1 = N->getOperand(1);
3323   SDValue LL, LR, RL, RR, CC0, CC1;
3324   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3325   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3326   EVT VT = N1.getValueType();
3327
3328   // fold vector ops
3329   if (VT.isVector()) {
3330     SDValue FoldedVOp = SimplifyVBinOp(N);
3331     if (FoldedVOp.getNode()) return FoldedVOp;
3332
3333     // fold (or x, 0) -> x, vector edition
3334     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3335       return N1;
3336     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3337       return N0;
3338
3339     // fold (or x, -1) -> -1, vector edition
3340     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3341       // do not return N0, because undef node may exist in N0
3342       return DAG.getConstant(
3343           APInt::getAllOnesValue(
3344               N0.getValueType().getScalarType().getSizeInBits()),
3345           N0.getValueType());
3346     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3347       // do not return N1, because undef node may exist in N1
3348       return DAG.getConstant(
3349           APInt::getAllOnesValue(
3350               N1.getValueType().getScalarType().getSizeInBits()),
3351           N1.getValueType());
3352
3353     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3354     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3355     // Do this only if the resulting shuffle is legal.
3356     if (isa<ShuffleVectorSDNode>(N0) &&
3357         isa<ShuffleVectorSDNode>(N1) &&
3358         // Avoid folding a node with illegal type.
3359         TLI.isTypeLegal(VT) &&
3360         N0->getOperand(1) == N1->getOperand(1) &&
3361         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3362       bool CanFold = true;
3363       unsigned NumElts = VT.getVectorNumElements();
3364       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3365       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3366       // We construct two shuffle masks:
3367       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3368       // and N1 as the second operand.
3369       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3370       // and N0 as the second operand.
3371       // We do this because OR is commutable and therefore there might be
3372       // two ways to fold this node into a shuffle.
3373       SmallVector<int,4> Mask1;
3374       SmallVector<int,4> Mask2;
3375
3376       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3377         int M0 = SV0->getMaskElt(i);
3378         int M1 = SV1->getMaskElt(i);
3379
3380         // Both shuffle indexes are undef. Propagate Undef.
3381         if (M0 < 0 && M1 < 0) {
3382           Mask1.push_back(M0);
3383           Mask2.push_back(M0);
3384           continue;
3385         }
3386
3387         if (M0 < 0 || M1 < 0 ||
3388             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3389             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3390           CanFold = false;
3391           break;
3392         }
3393
3394         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3395         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3396       }
3397
3398       if (CanFold) {
3399         // Fold this sequence only if the resulting shuffle is 'legal'.
3400         if (TLI.isShuffleMaskLegal(Mask1, VT))
3401           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3402                                       N1->getOperand(0), &Mask1[0]);
3403         if (TLI.isShuffleMaskLegal(Mask2, VT))
3404           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3405                                       N0->getOperand(0), &Mask2[0]);
3406       }
3407     }
3408   }
3409
3410   // fold (or x, undef) -> -1
3411   if (!LegalOperations &&
3412       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3413     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3414     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3415   }
3416   // fold (or c1, c2) -> c1|c2
3417   if (N0C && N1C)
3418     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3419   // canonicalize constant to RHS
3420   if (N0C && !N1C)
3421     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3422   // fold (or x, 0) -> x
3423   if (N1C && N1C->isNullValue())
3424     return N0;
3425   // fold (or x, -1) -> -1
3426   if (N1C && N1C->isAllOnesValue())
3427     return N1;
3428   // fold (or x, c) -> c iff (x & ~c) == 0
3429   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3430     return N1;
3431
3432   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3433   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3434   if (BSwap.getNode())
3435     return BSwap;
3436   BSwap = MatchBSwapHWordLow(N, N0, N1);
3437   if (BSwap.getNode())
3438     return BSwap;
3439
3440   // reassociate or
3441   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3442   if (ROR.getNode())
3443     return ROR;
3444   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3445   // iff (c1 & c2) == 0.
3446   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3447              isa<ConstantSDNode>(N0.getOperand(1))) {
3448     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3449     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3450       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3451         return DAG.getNode(
3452             ISD::AND, SDLoc(N), VT,
3453             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3454       return SDValue();
3455     }
3456   }
3457   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3458   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3459     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3460     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3461
3462     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3463         LL.getValueType().isInteger()) {
3464       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3465       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3466       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3467           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3468         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3469                                      LR.getValueType(), LL, RL);
3470         AddToWorklist(ORNode.getNode());
3471         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3472       }
3473       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3474       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3475       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3476           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3477         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3478                                       LR.getValueType(), LL, RL);
3479         AddToWorklist(ANDNode.getNode());
3480         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3481       }
3482     }
3483     // canonicalize equivalent to ll == rl
3484     if (LL == RR && LR == RL) {
3485       Op1 = ISD::getSetCCSwappedOperands(Op1);
3486       std::swap(RL, RR);
3487     }
3488     if (LL == RL && LR == RR) {
3489       bool isInteger = LL.getValueType().isInteger();
3490       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3491       if (Result != ISD::SETCC_INVALID &&
3492           (!LegalOperations ||
3493            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3494             TLI.isOperationLegal(ISD::SETCC,
3495               getSetCCResultType(N0.getValueType())))))
3496         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3497                             LL, LR, Result);
3498     }
3499   }
3500
3501   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3502   if (N0.getOpcode() == N1.getOpcode()) {
3503     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3504     if (Tmp.getNode()) return Tmp;
3505   }
3506
3507   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3508   if (N0.getOpcode() == ISD::AND &&
3509       N1.getOpcode() == ISD::AND &&
3510       N0.getOperand(1).getOpcode() == ISD::Constant &&
3511       N1.getOperand(1).getOpcode() == ISD::Constant &&
3512       // Don't increase # computations.
3513       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3514     // We can only do this xform if we know that bits from X that are set in C2
3515     // but not in C1 are already zero.  Likewise for Y.
3516     const APInt &LHSMask =
3517       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3518     const APInt &RHSMask =
3519       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3520
3521     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3522         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3523       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3524                               N0.getOperand(0), N1.getOperand(0));
3525       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3526                          DAG.getConstant(LHSMask | RHSMask, VT));
3527     }
3528   }
3529
3530   // See if this is some rotate idiom.
3531   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3532     return SDValue(Rot, 0);
3533
3534   // Simplify the operands using demanded-bits information.
3535   if (!VT.isVector() &&
3536       SimplifyDemandedBits(SDValue(N, 0)))
3537     return SDValue(N, 0);
3538
3539   return SDValue();
3540 }
3541
3542 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3543 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3544   if (Op.getOpcode() == ISD::AND) {
3545     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3546       Mask = Op.getOperand(1);
3547       Op = Op.getOperand(0);
3548     } else {
3549       return false;
3550     }
3551   }
3552
3553   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3554     Shift = Op;
3555     return true;
3556   }
3557
3558   return false;
3559 }
3560
3561 // Return true if we can prove that, whenever Neg and Pos are both in the
3562 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3563 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3564 //
3565 //     (or (shift1 X, Neg), (shift2 X, Pos))
3566 //
3567 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3568 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3569 // to consider shift amounts with defined behavior.
3570 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3571   // If OpSize is a power of 2 then:
3572   //
3573   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3574   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3575   //
3576   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3577   // for the stronger condition:
3578   //
3579   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3580   //
3581   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3582   // we can just replace Neg with Neg' for the rest of the function.
3583   //
3584   // In other cases we check for the even stronger condition:
3585   //
3586   //     Neg == OpSize - Pos                                    [B]
3587   //
3588   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3589   // behavior if Pos == 0 (and consequently Neg == OpSize).
3590   //
3591   // We could actually use [A] whenever OpSize is a power of 2, but the
3592   // only extra cases that it would match are those uninteresting ones
3593   // where Neg and Pos are never in range at the same time.  E.g. for
3594   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3595   // as well as (sub 32, Pos), but:
3596   //
3597   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3598   //
3599   // always invokes undefined behavior for 32-bit X.
3600   //
3601   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3602   unsigned MaskLoBits = 0;
3603   if (Neg.getOpcode() == ISD::AND &&
3604       isPowerOf2_64(OpSize) &&
3605       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3606       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3607     Neg = Neg.getOperand(0);
3608     MaskLoBits = Log2_64(OpSize);
3609   }
3610
3611   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3612   if (Neg.getOpcode() != ISD::SUB)
3613     return 0;
3614   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3615   if (!NegC)
3616     return 0;
3617   SDValue NegOp1 = Neg.getOperand(1);
3618
3619   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3620   // Pos'.  The truncation is redundant for the purpose of the equality.
3621   if (MaskLoBits &&
3622       Pos.getOpcode() == ISD::AND &&
3623       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3624       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3625     Pos = Pos.getOperand(0);
3626
3627   // The condition we need is now:
3628   //
3629   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3630   //
3631   // If NegOp1 == Pos then we need:
3632   //
3633   //              OpSize & Mask == NegC & Mask
3634   //
3635   // (because "x & Mask" is a truncation and distributes through subtraction).
3636   APInt Width;
3637   if (Pos == NegOp1)
3638     Width = NegC->getAPIntValue();
3639   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3640   // Then the condition we want to prove becomes:
3641   //
3642   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3643   //
3644   // which, again because "x & Mask" is a truncation, becomes:
3645   //
3646   //                NegC & Mask == (OpSize - PosC) & Mask
3647   //              OpSize & Mask == (NegC + PosC) & Mask
3648   else if (Pos.getOpcode() == ISD::ADD &&
3649            Pos.getOperand(0) == NegOp1 &&
3650            Pos.getOperand(1).getOpcode() == ISD::Constant)
3651     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3652              NegC->getAPIntValue());
3653   else
3654     return false;
3655
3656   // Now we just need to check that OpSize & Mask == Width & Mask.
3657   if (MaskLoBits)
3658     // Opsize & Mask is 0 since Mask is Opsize - 1.
3659     return Width.getLoBits(MaskLoBits) == 0;
3660   return Width == OpSize;
3661 }
3662
3663 // A subroutine of MatchRotate used once we have found an OR of two opposite
3664 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3665 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3666 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3667 // Neg with outer conversions stripped away.
3668 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3669                                        SDValue Neg, SDValue InnerPos,
3670                                        SDValue InnerNeg, unsigned PosOpcode,
3671                                        unsigned NegOpcode, SDLoc DL) {
3672   // fold (or (shl x, (*ext y)),
3673   //          (srl x, (*ext (sub 32, y)))) ->
3674   //   (rotl x, y) or (rotr x, (sub 32, y))
3675   //
3676   // fold (or (shl x, (*ext (sub 32, y))),
3677   //          (srl x, (*ext y))) ->
3678   //   (rotr x, y) or (rotl x, (sub 32, y))
3679   EVT VT = Shifted.getValueType();
3680   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3681     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3682     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3683                        HasPos ? Pos : Neg).getNode();
3684   }
3685
3686   return nullptr;
3687 }
3688
3689 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3690 // idioms for rotate, and if the target supports rotation instructions, generate
3691 // a rot[lr].
3692 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3693   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3694   EVT VT = LHS.getValueType();
3695   if (!TLI.isTypeLegal(VT)) return nullptr;
3696
3697   // The target must have at least one rotate flavor.
3698   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3699   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3700   if (!HasROTL && !HasROTR) return nullptr;
3701
3702   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3703   SDValue LHSShift;   // The shift.
3704   SDValue LHSMask;    // AND value if any.
3705   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3706     return nullptr; // Not part of a rotate.
3707
3708   SDValue RHSShift;   // The shift.
3709   SDValue RHSMask;    // AND value if any.
3710   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3711     return nullptr; // Not part of a rotate.
3712
3713   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3714     return nullptr;   // Not shifting the same value.
3715
3716   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3717     return nullptr;   // Shifts must disagree.
3718
3719   // Canonicalize shl to left side in a shl/srl pair.
3720   if (RHSShift.getOpcode() == ISD::SHL) {
3721     std::swap(LHS, RHS);
3722     std::swap(LHSShift, RHSShift);
3723     std::swap(LHSMask , RHSMask );
3724   }
3725
3726   unsigned OpSizeInBits = VT.getSizeInBits();
3727   SDValue LHSShiftArg = LHSShift.getOperand(0);
3728   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3729   SDValue RHSShiftArg = RHSShift.getOperand(0);
3730   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3731
3732   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3733   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3734   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3735       RHSShiftAmt.getOpcode() == ISD::Constant) {
3736     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3737     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3738     if ((LShVal + RShVal) != OpSizeInBits)
3739       return nullptr;
3740
3741     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3742                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3743
3744     // If there is an AND of either shifted operand, apply it to the result.
3745     if (LHSMask.getNode() || RHSMask.getNode()) {
3746       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3747
3748       if (LHSMask.getNode()) {
3749         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3750         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3751       }
3752       if (RHSMask.getNode()) {
3753         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3754         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3755       }
3756
3757       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3758     }
3759
3760     return Rot.getNode();
3761   }
3762
3763   // If there is a mask here, and we have a variable shift, we can't be sure
3764   // that we're masking out the right stuff.
3765   if (LHSMask.getNode() || RHSMask.getNode())
3766     return nullptr;
3767
3768   // If the shift amount is sign/zext/any-extended just peel it off.
3769   SDValue LExtOp0 = LHSShiftAmt;
3770   SDValue RExtOp0 = RHSShiftAmt;
3771   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3772        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3773        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3774        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3775       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3776        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3777        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3778        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3779     LExtOp0 = LHSShiftAmt.getOperand(0);
3780     RExtOp0 = RHSShiftAmt.getOperand(0);
3781   }
3782
3783   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3784                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3785   if (TryL)
3786     return TryL;
3787
3788   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3789                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3790   if (TryR)
3791     return TryR;
3792
3793   return nullptr;
3794 }
3795
3796 SDValue DAGCombiner::visitXOR(SDNode *N) {
3797   SDValue N0 = N->getOperand(0);
3798   SDValue N1 = N->getOperand(1);
3799   SDValue LHS, RHS, CC;
3800   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3801   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3802   EVT VT = N0.getValueType();
3803
3804   // fold vector ops
3805   if (VT.isVector()) {
3806     SDValue FoldedVOp = SimplifyVBinOp(N);
3807     if (FoldedVOp.getNode()) return FoldedVOp;
3808
3809     // fold (xor x, 0) -> x, vector edition
3810     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3811       return N1;
3812     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3813       return N0;
3814   }
3815
3816   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3817   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3818     return DAG.getConstant(0, VT);
3819   // fold (xor x, undef) -> undef
3820   if (N0.getOpcode() == ISD::UNDEF)
3821     return N0;
3822   if (N1.getOpcode() == ISD::UNDEF)
3823     return N1;
3824   // fold (xor c1, c2) -> c1^c2
3825   if (N0C && N1C)
3826     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3827   // canonicalize constant to RHS
3828   if (N0C && !N1C)
3829     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3830   // fold (xor x, 0) -> x
3831   if (N1C && N1C->isNullValue())
3832     return N0;
3833   // reassociate xor
3834   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3835   if (RXOR.getNode())
3836     return RXOR;
3837
3838   // fold !(x cc y) -> (x !cc y)
3839   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3840     bool isInt = LHS.getValueType().isInteger();
3841     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3842                                                isInt);
3843
3844     if (!LegalOperations ||
3845         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3846       switch (N0.getOpcode()) {
3847       default:
3848         llvm_unreachable("Unhandled SetCC Equivalent!");
3849       case ISD::SETCC:
3850         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3851       case ISD::SELECT_CC:
3852         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3853                                N0.getOperand(3), NotCC);
3854       }
3855     }
3856   }
3857
3858   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3859   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3860       N0.getNode()->hasOneUse() &&
3861       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3862     SDValue V = N0.getOperand(0);
3863     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3864                     DAG.getConstant(1, V.getValueType()));
3865     AddToWorklist(V.getNode());
3866     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3867   }
3868
3869   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3870   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3871       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3872     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3873     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3874       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3875       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3876       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3877       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3878       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3879     }
3880   }
3881   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3882   if (N1C && N1C->isAllOnesValue() &&
3883       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3884     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3885     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3886       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3887       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3888       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3889       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3890       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3891     }
3892   }
3893   // fold (xor (and x, y), y) -> (and (not x), y)
3894   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3895       N0->getOperand(1) == N1) {
3896     SDValue X = N0->getOperand(0);
3897     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3898     AddToWorklist(NotX.getNode());
3899     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3900   }
3901   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3902   if (N1C && N0.getOpcode() == ISD::XOR) {
3903     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3904     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3905     if (N00C)
3906       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3907                          DAG.getConstant(N1C->getAPIntValue() ^
3908                                          N00C->getAPIntValue(), VT));
3909     if (N01C)
3910       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3911                          DAG.getConstant(N1C->getAPIntValue() ^
3912                                          N01C->getAPIntValue(), VT));
3913   }
3914   // fold (xor x, x) -> 0
3915   if (N0 == N1)
3916     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3917
3918   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3919   if (N0.getOpcode() == N1.getOpcode()) {
3920     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3921     if (Tmp.getNode()) return Tmp;
3922   }
3923
3924   // Simplify the expression using non-local knowledge.
3925   if (!VT.isVector() &&
3926       SimplifyDemandedBits(SDValue(N, 0)))
3927     return SDValue(N, 0);
3928
3929   return SDValue();
3930 }
3931
3932 /// Handle transforms common to the three shifts, when the shift amount is a
3933 /// constant.
3934 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3935   // We can't and shouldn't fold opaque constants.
3936   if (Amt->isOpaque())
3937     return SDValue();
3938
3939   SDNode *LHS = N->getOperand(0).getNode();
3940   if (!LHS->hasOneUse()) return SDValue();
3941
3942   // We want to pull some binops through shifts, so that we have (and (shift))
3943   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3944   // thing happens with address calculations, so it's important to canonicalize
3945   // it.
3946   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3947
3948   switch (LHS->getOpcode()) {
3949   default: return SDValue();
3950   case ISD::OR:
3951   case ISD::XOR:
3952     HighBitSet = false; // We can only transform sra if the high bit is clear.
3953     break;
3954   case ISD::AND:
3955     HighBitSet = true;  // We can only transform sra if the high bit is set.
3956     break;
3957   case ISD::ADD:
3958     if (N->getOpcode() != ISD::SHL)
3959       return SDValue(); // only shl(add) not sr[al](add).
3960     HighBitSet = false; // We can only transform sra if the high bit is clear.
3961     break;
3962   }
3963
3964   // We require the RHS of the binop to be a constant and not opaque as well.
3965   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3966   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3967
3968   // FIXME: disable this unless the input to the binop is a shift by a constant.
3969   // If it is not a shift, it pessimizes some common cases like:
3970   //
3971   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3972   //    int bar(int *X, int i) { return X[i & 255]; }
3973   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3974   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3975        BinOpLHSVal->getOpcode() != ISD::SRA &&
3976        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3977       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3978     return SDValue();
3979
3980   EVT VT = N->getValueType(0);
3981
3982   // If this is a signed shift right, and the high bit is modified by the
3983   // logical operation, do not perform the transformation. The highBitSet
3984   // boolean indicates the value of the high bit of the constant which would
3985   // cause it to be modified for this operation.
3986   if (N->getOpcode() == ISD::SRA) {
3987     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3988     if (BinOpRHSSignSet != HighBitSet)
3989       return SDValue();
3990   }
3991
3992   if (!TLI.isDesirableToCommuteWithShift(LHS))
3993     return SDValue();
3994
3995   // Fold the constants, shifting the binop RHS by the shift amount.
3996   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3997                                N->getValueType(0),
3998                                LHS->getOperand(1), N->getOperand(1));
3999   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4000
4001   // Create the new shift.
4002   SDValue NewShift = DAG.getNode(N->getOpcode(),
4003                                  SDLoc(LHS->getOperand(0)),
4004                                  VT, LHS->getOperand(0), N->getOperand(1));
4005
4006   // Create the new binop.
4007   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4008 }
4009
4010 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4011   assert(N->getOpcode() == ISD::TRUNCATE);
4012   assert(N->getOperand(0).getOpcode() == ISD::AND);
4013
4014   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4015   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4016     SDValue N01 = N->getOperand(0).getOperand(1);
4017
4018     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4019       EVT TruncVT = N->getValueType(0);
4020       SDValue N00 = N->getOperand(0).getOperand(0);
4021       APInt TruncC = N01C->getAPIntValue();
4022       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4023
4024       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4025                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4026                          DAG.getConstant(TruncC, TruncVT));
4027     }
4028   }
4029
4030   return SDValue();
4031 }
4032
4033 SDValue DAGCombiner::visitRotate(SDNode *N) {
4034   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4035   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4036       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4037     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4038     if (NewOp1.getNode())
4039       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4040                          N->getOperand(0), NewOp1);
4041   }
4042   return SDValue();
4043 }
4044
4045 SDValue DAGCombiner::visitSHL(SDNode *N) {
4046   SDValue N0 = N->getOperand(0);
4047   SDValue N1 = N->getOperand(1);
4048   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4049   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4050   EVT VT = N0.getValueType();
4051   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4052
4053   // fold vector ops
4054   if (VT.isVector()) {
4055     SDValue FoldedVOp = SimplifyVBinOp(N);
4056     if (FoldedVOp.getNode()) return FoldedVOp;
4057
4058     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4059     // If setcc produces all-one true value then:
4060     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4061     if (N1CV && N1CV->isConstant()) {
4062       if (N0.getOpcode() == ISD::AND) {
4063         SDValue N00 = N0->getOperand(0);
4064         SDValue N01 = N0->getOperand(1);
4065         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4066
4067         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4068             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4069                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4070           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
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
4617 /// \brief Generate Min/Max node
4618 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4619                                    SDValue True, SDValue False,
4620                                    ISD::CondCode CC, const TargetLowering &TLI,
4621                                    SelectionDAG &DAG) {
4622   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4623     return SDValue();
4624
4625   switch (CC) {
4626   case ISD::SETOLT:
4627   case ISD::SETOLE:
4628   case ISD::SETLT:
4629   case ISD::SETLE:
4630   case ISD::SETULT:
4631   case ISD::SETULE: {
4632     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4633     if (TLI.isOperationLegal(Opcode, VT))
4634       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4635     return SDValue();
4636   }
4637   case ISD::SETOGT:
4638   case ISD::SETOGE:
4639   case ISD::SETGT:
4640   case ISD::SETGE:
4641   case ISD::SETUGT:
4642   case ISD::SETUGE: {
4643     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4644     if (TLI.isOperationLegal(Opcode, VT))
4645       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4646     return SDValue();
4647   }
4648   default:
4649     return SDValue();
4650   }
4651 }
4652
4653 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4654   SDValue N0 = N->getOperand(0);
4655   SDValue N1 = N->getOperand(1);
4656   SDValue N2 = N->getOperand(2);
4657   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4658   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4659   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4660   EVT VT = N->getValueType(0);
4661   EVT VT0 = N0.getValueType();
4662
4663   // fold (select C, X, X) -> X
4664   if (N1 == N2)
4665     return N1;
4666   // fold (select true, X, Y) -> X
4667   if (N0C && !N0C->isNullValue())
4668     return N1;
4669   // fold (select false, X, Y) -> Y
4670   if (N0C && N0C->isNullValue())
4671     return N2;
4672   // fold (select C, 1, X) -> (or C, X)
4673   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4674     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4675   // fold (select C, 0, 1) -> (xor C, 1)
4676   // We can't do this reliably if integer based booleans have different contents
4677   // to floating point based booleans. This is because we can't tell whether we
4678   // have an integer-based boolean or a floating-point-based boolean unless we
4679   // can find the SETCC that produced it and inspect its operands. This is
4680   // fairly easy if C is the SETCC node, but it can potentially be
4681   // undiscoverable (or not reasonably discoverable). For example, it could be
4682   // in another basic block or it could require searching a complicated
4683   // expression.
4684   if (VT.isInteger() &&
4685       (VT0 == MVT::i1 || (VT0.isInteger() &&
4686                           TLI.getBooleanContents(false, false) ==
4687                               TLI.getBooleanContents(false, true) &&
4688                           TLI.getBooleanContents(false, false) ==
4689                               TargetLowering::ZeroOrOneBooleanContent)) &&
4690       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4691     SDValue XORNode;
4692     if (VT == VT0)
4693       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4694                          N0, DAG.getConstant(1, VT0));
4695     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4696                           N0, DAG.getConstant(1, VT0));
4697     AddToWorklist(XORNode.getNode());
4698     if (VT.bitsGT(VT0))
4699       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4700     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4701   }
4702   // fold (select C, 0, X) -> (and (not C), X)
4703   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4704     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4705     AddToWorklist(NOTNode.getNode());
4706     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4707   }
4708   // fold (select C, X, 1) -> (or (not C), X)
4709   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4710     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4711     AddToWorklist(NOTNode.getNode());
4712     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4713   }
4714   // fold (select C, X, 0) -> (and C, X)
4715   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4716     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4717   // fold (select X, X, Y) -> (or X, Y)
4718   // fold (select X, 1, Y) -> (or X, Y)
4719   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4720     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4721   // fold (select X, Y, X) -> (and X, Y)
4722   // fold (select X, Y, 0) -> (and X, Y)
4723   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4724     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4725
4726   // If we can fold this based on the true/false value, do so.
4727   if (SimplifySelectOps(N, N1, N2))
4728     return SDValue(N, 0);  // Don't revisit N.
4729
4730   // fold selects based on a setcc into other things, such as min/max/abs
4731   if (N0.getOpcode() == ISD::SETCC) {
4732     // select x, y (fcmp lt x, y) -> fminnum x, y
4733     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4734     //
4735     // This is OK if we don't care about what happens if either operand is a
4736     // NaN.
4737     //
4738
4739     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4740     // no signed zeros as well as no nans.
4741     const TargetOptions &Options = DAG.getTarget().Options;
4742     if (Options.UnsafeFPMath &&
4743         VT.isFloatingPoint() && N0.hasOneUse() &&
4744         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4745       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4746
4747       SDValue FMinMax =
4748           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4749                               N1, N2, CC, TLI, DAG);
4750       if (FMinMax)
4751         return FMinMax;
4752     }
4753
4754     if ((!LegalOperations &&
4755          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4756         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4757       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4758                          N0.getOperand(0), N0.getOperand(1),
4759                          N1, N2, N0.getOperand(2));
4760     return SimplifySelect(SDLoc(N), N0, N1, N2);
4761   }
4762
4763   return SDValue();
4764 }
4765
4766 static
4767 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4768   SDLoc DL(N);
4769   EVT LoVT, HiVT;
4770   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4771
4772   // Split the inputs.
4773   SDValue Lo, Hi, LL, LH, RL, RH;
4774   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4775   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4776
4777   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4778   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4779
4780   return std::make_pair(Lo, Hi);
4781 }
4782
4783 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4784 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4785 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4786   SDLoc dl(N);
4787   SDValue Cond = N->getOperand(0);
4788   SDValue LHS = N->getOperand(1);
4789   SDValue RHS = N->getOperand(2);
4790   EVT VT = N->getValueType(0);
4791   int NumElems = VT.getVectorNumElements();
4792   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4793          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4794          Cond.getOpcode() == ISD::BUILD_VECTOR);
4795
4796   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4797   // binary ones here.
4798   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4799     return SDValue();
4800
4801   // We're sure we have an even number of elements due to the
4802   // concat_vectors we have as arguments to vselect.
4803   // Skip BV elements until we find one that's not an UNDEF
4804   // After we find an UNDEF element, keep looping until we get to half the
4805   // length of the BV and see if all the non-undef nodes are the same.
4806   ConstantSDNode *BottomHalf = nullptr;
4807   for (int i = 0; i < NumElems / 2; ++i) {
4808     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4809       continue;
4810
4811     if (BottomHalf == nullptr)
4812       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4813     else if (Cond->getOperand(i).getNode() != BottomHalf)
4814       return SDValue();
4815   }
4816
4817   // Do the same for the second half of the BuildVector
4818   ConstantSDNode *TopHalf = nullptr;
4819   for (int i = NumElems / 2; i < NumElems; ++i) {
4820     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4821       continue;
4822
4823     if (TopHalf == nullptr)
4824       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4825     else if (Cond->getOperand(i).getNode() != TopHalf)
4826       return SDValue();
4827   }
4828
4829   assert(TopHalf && BottomHalf &&
4830          "One half of the selector was all UNDEFs and the other was all the "
4831          "same value. This should have been addressed before this function.");
4832   return DAG.getNode(
4833       ISD::CONCAT_VECTORS, dl, VT,
4834       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4835       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4836 }
4837
4838 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4839
4840   if (Level >= AfterLegalizeTypes)
4841     return SDValue();
4842
4843   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4844   SDValue Mask = MST->getMask();
4845   SDValue Data  = MST->getData();
4846   SDLoc DL(N);
4847
4848   // If the MSTORE data type requires splitting and the mask is provided by a
4849   // SETCC, then split both nodes and its operands before legalization. This
4850   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4851   // and enables future optimizations (e.g. min/max pattern matching on X86).
4852   if (Mask.getOpcode() == ISD::SETCC) {
4853
4854     // Check if any splitting is required.
4855     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4856         TargetLowering::TypeSplitVector)
4857       return SDValue();
4858
4859     SDValue MaskLo, MaskHi, Lo, Hi;
4860     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4861
4862     EVT LoVT, HiVT;
4863     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4864
4865     SDValue Chain = MST->getChain();
4866     SDValue Ptr   = MST->getBasePtr();
4867
4868     EVT MemoryVT = MST->getMemoryVT();
4869     unsigned Alignment = MST->getOriginalAlignment();
4870
4871     // if Alignment is equal to the vector size,
4872     // take the half of it for the second part
4873     unsigned SecondHalfAlignment =
4874       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4875          Alignment/2 : Alignment;
4876
4877     EVT LoMemVT, HiMemVT;
4878     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4879
4880     SDValue DataLo, DataHi;
4881     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4882
4883     MachineMemOperand *MMO = DAG.getMachineFunction().
4884       getMachineMemOperand(MST->getPointerInfo(), 
4885                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
4886                            Alignment, MST->getAAInfo(), MST->getRanges());
4887
4888     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4889
4890     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4891     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4892                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4893
4894     MMO = DAG.getMachineFunction().
4895       getMachineMemOperand(MST->getPointerInfo(), 
4896                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
4897                            SecondHalfAlignment, MST->getAAInfo(),
4898                            MST->getRanges());
4899
4900     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4901
4902     AddToWorklist(Lo.getNode());
4903     AddToWorklist(Hi.getNode());
4904
4905     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4906   }
4907   return SDValue();
4908 }
4909
4910 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4911
4912   if (Level >= AfterLegalizeTypes)
4913     return SDValue();
4914
4915   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4916   SDValue Mask = MLD->getMask();
4917   SDLoc DL(N);
4918
4919   // If the MLOAD result requires splitting and the mask is provided by a
4920   // SETCC, then split both nodes and its operands before legalization. This
4921   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4922   // and enables future optimizations (e.g. min/max pattern matching on X86).
4923
4924   if (Mask.getOpcode() == ISD::SETCC) {
4925     EVT VT = N->getValueType(0);
4926
4927     // Check if any splitting is required.
4928     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4929         TargetLowering::TypeSplitVector)
4930       return SDValue();
4931
4932     SDValue MaskLo, MaskHi, Lo, Hi;
4933     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4934
4935     SDValue Src0 = MLD->getSrc0();
4936     SDValue Src0Lo, Src0Hi;
4937     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4938
4939     EVT LoVT, HiVT;
4940     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4941
4942     SDValue Chain = MLD->getChain();
4943     SDValue Ptr   = MLD->getBasePtr();
4944     EVT MemoryVT = MLD->getMemoryVT();
4945     unsigned Alignment = MLD->getOriginalAlignment();
4946
4947     // if Alignment is equal to the vector size,
4948     // take the half of it for the second part
4949     unsigned SecondHalfAlignment =
4950       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4951          Alignment/2 : Alignment;
4952
4953     EVT LoMemVT, HiMemVT;
4954     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4955
4956     MachineMemOperand *MMO = DAG.getMachineFunction().
4957     getMachineMemOperand(MLD->getPointerInfo(), 
4958                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
4959                          Alignment, MLD->getAAInfo(), MLD->getRanges());
4960
4961     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4962
4963     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4964     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4965                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4966
4967     MMO = DAG.getMachineFunction().
4968     getMachineMemOperand(MLD->getPointerInfo(), 
4969                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
4970                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4971
4972     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4973
4974     AddToWorklist(Lo.getNode());
4975     AddToWorklist(Hi.getNode());
4976
4977     // Build a factor node to remember that this load is independent of the
4978     // other one.
4979     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4980                         Hi.getValue(1));
4981
4982     // Legalized the chain result - switch anything that used the old chain to
4983     // use the new one.
4984     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4985
4986     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4987
4988     SDValue RetOps[] = { LoadRes, Chain };
4989     return DAG.getMergeValues(RetOps, DL);
4990   }
4991   return SDValue();
4992 }
4993
4994 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4995   SDValue N0 = N->getOperand(0);
4996   SDValue N1 = N->getOperand(1);
4997   SDValue N2 = N->getOperand(2);
4998   SDLoc DL(N);
4999
5000   // Canonicalize integer abs.
5001   // vselect (setg[te] X,  0),  X, -X ->
5002   // vselect (setgt    X, -1),  X, -X ->
5003   // vselect (setl[te] X,  0), -X,  X ->
5004   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5005   if (N0.getOpcode() == ISD::SETCC) {
5006     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5007     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5008     bool isAbs = false;
5009     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5010
5011     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5012          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5013         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5014       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5015     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5016              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5017       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5018
5019     if (isAbs) {
5020       EVT VT = LHS.getValueType();
5021       SDValue Shift = DAG.getNode(
5022           ISD::SRA, DL, VT, LHS,
5023           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5024       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5025       AddToWorklist(Shift.getNode());
5026       AddToWorklist(Add.getNode());
5027       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5028     }
5029   }
5030
5031   // If the VSELECT result requires splitting and the mask is provided by a
5032   // SETCC, then split both nodes and its operands before legalization. This
5033   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5034   // and enables future optimizations (e.g. min/max pattern matching on X86).
5035   if (N0.getOpcode() == ISD::SETCC) {
5036     EVT VT = N->getValueType(0);
5037
5038     // Check if any splitting is required.
5039     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5040         TargetLowering::TypeSplitVector)
5041       return SDValue();
5042
5043     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5044     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5045     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5046     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5047
5048     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5049     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5050
5051     // Add the new VSELECT nodes to the work list in case they need to be split
5052     // again.
5053     AddToWorklist(Lo.getNode());
5054     AddToWorklist(Hi.getNode());
5055
5056     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5057   }
5058
5059   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5060   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5061     return N1;
5062   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5063   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5064     return N2;
5065
5066   // The ConvertSelectToConcatVector function is assuming both the above
5067   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5068   // and addressed.
5069   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5070       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5071       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5072     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5073     if (CV.getNode())
5074       return CV;
5075   }
5076
5077   return SDValue();
5078 }
5079
5080 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5081   SDValue N0 = N->getOperand(0);
5082   SDValue N1 = N->getOperand(1);
5083   SDValue N2 = N->getOperand(2);
5084   SDValue N3 = N->getOperand(3);
5085   SDValue N4 = N->getOperand(4);
5086   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5087
5088   // fold select_cc lhs, rhs, x, x, cc -> x
5089   if (N2 == N3)
5090     return N2;
5091
5092   // Determine if the condition we're dealing with is constant
5093   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5094                               N0, N1, CC, SDLoc(N), false);
5095   if (SCC.getNode()) {
5096     AddToWorklist(SCC.getNode());
5097
5098     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5099       if (!SCCC->isNullValue())
5100         return N2;    // cond always true -> true val
5101       else
5102         return N3;    // cond always false -> false val
5103     }
5104
5105     // Fold to a simpler select_cc
5106     if (SCC.getOpcode() == ISD::SETCC)
5107       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5108                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5109                          SCC.getOperand(2));
5110   }
5111
5112   // If we can fold this based on the true/false value, do so.
5113   if (SimplifySelectOps(N, N2, N3))
5114     return SDValue(N, 0);  // Don't revisit N.
5115
5116   // fold select_cc into other things, such as min/max/abs
5117   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5118 }
5119
5120 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5121   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5122                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5123                        SDLoc(N));
5124 }
5125
5126 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5127 // dag node into a ConstantSDNode or a build_vector of constants.
5128 // This function is called by the DAGCombiner when visiting sext/zext/aext
5129 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5130 // Vector extends are not folded if operations are legal; this is to
5131 // avoid introducing illegal build_vector dag nodes.
5132 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5133                                          SelectionDAG &DAG, bool LegalTypes,
5134                                          bool LegalOperations) {
5135   unsigned Opcode = N->getOpcode();
5136   SDValue N0 = N->getOperand(0);
5137   EVT VT = N->getValueType(0);
5138
5139   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5140          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5141
5142   // fold (sext c1) -> c1
5143   // fold (zext c1) -> c1
5144   // fold (aext c1) -> c1
5145   if (isa<ConstantSDNode>(N0))
5146     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5147
5148   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5149   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5150   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5151   EVT SVT = VT.getScalarType();
5152   if (!(VT.isVector() &&
5153       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5154       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5155     return nullptr;
5156
5157   // We can fold this node into a build_vector.
5158   unsigned VTBits = SVT.getSizeInBits();
5159   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5160   unsigned ShAmt = VTBits - EVTBits;
5161   SmallVector<SDValue, 8> Elts;
5162   unsigned NumElts = N0->getNumOperands();
5163   SDLoc DL(N);
5164
5165   for (unsigned i=0; i != NumElts; ++i) {
5166     SDValue Op = N0->getOperand(i);
5167     if (Op->getOpcode() == ISD::UNDEF) {
5168       Elts.push_back(DAG.getUNDEF(SVT));
5169       continue;
5170     }
5171
5172     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5173     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5174     if (Opcode == ISD::SIGN_EXTEND)
5175       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5176                                      SVT));
5177     else
5178       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5179                                      SVT));
5180   }
5181
5182   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5183 }
5184
5185 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5186 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5187 // transformation. Returns true if extension are possible and the above
5188 // mentioned transformation is profitable.
5189 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5190                                     unsigned ExtOpc,
5191                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5192                                     const TargetLowering &TLI) {
5193   bool HasCopyToRegUses = false;
5194   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5195   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5196                             UE = N0.getNode()->use_end();
5197        UI != UE; ++UI) {
5198     SDNode *User = *UI;
5199     if (User == N)
5200       continue;
5201     if (UI.getUse().getResNo() != N0.getResNo())
5202       continue;
5203     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5204     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5205       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5206       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5207         // Sign bits will be lost after a zext.
5208         return false;
5209       bool Add = false;
5210       for (unsigned i = 0; i != 2; ++i) {
5211         SDValue UseOp = User->getOperand(i);
5212         if (UseOp == N0)
5213           continue;
5214         if (!isa<ConstantSDNode>(UseOp))
5215           return false;
5216         Add = true;
5217       }
5218       if (Add)
5219         ExtendNodes.push_back(User);
5220       continue;
5221     }
5222     // If truncates aren't free and there are users we can't
5223     // extend, it isn't worthwhile.
5224     if (!isTruncFree)
5225       return false;
5226     // Remember if this value is live-out.
5227     if (User->getOpcode() == ISD::CopyToReg)
5228       HasCopyToRegUses = true;
5229   }
5230
5231   if (HasCopyToRegUses) {
5232     bool BothLiveOut = false;
5233     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5234          UI != UE; ++UI) {
5235       SDUse &Use = UI.getUse();
5236       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5237         BothLiveOut = true;
5238         break;
5239       }
5240     }
5241     if (BothLiveOut)
5242       // Both unextended and extended values are live out. There had better be
5243       // a good reason for the transformation.
5244       return ExtendNodes.size();
5245   }
5246   return true;
5247 }
5248
5249 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5250                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5251                                   ISD::NodeType ExtType) {
5252   // Extend SetCC uses if necessary.
5253   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5254     SDNode *SetCC = SetCCs[i];
5255     SmallVector<SDValue, 4> Ops;
5256
5257     for (unsigned j = 0; j != 2; ++j) {
5258       SDValue SOp = SetCC->getOperand(j);
5259       if (SOp == Trunc)
5260         Ops.push_back(ExtLoad);
5261       else
5262         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5263     }
5264
5265     Ops.push_back(SetCC->getOperand(2));
5266     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5267   }
5268 }
5269
5270 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5271   SDValue N0 = N->getOperand(0);
5272   EVT VT = N->getValueType(0);
5273
5274   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5275                                               LegalOperations))
5276     return SDValue(Res, 0);
5277
5278   // fold (sext (sext x)) -> (sext x)
5279   // fold (sext (aext x)) -> (sext x)
5280   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5281     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5282                        N0.getOperand(0));
5283
5284   if (N0.getOpcode() == ISD::TRUNCATE) {
5285     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5286     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5287     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5288     if (NarrowLoad.getNode()) {
5289       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5290       if (NarrowLoad.getNode() != N0.getNode()) {
5291         CombineTo(N0.getNode(), NarrowLoad);
5292         // CombineTo deleted the truncate, if needed, but not what's under it.
5293         AddToWorklist(oye);
5294       }
5295       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5296     }
5297
5298     // See if the value being truncated is already sign extended.  If so, just
5299     // eliminate the trunc/sext pair.
5300     SDValue Op = N0.getOperand(0);
5301     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5302     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5303     unsigned DestBits = VT.getScalarType().getSizeInBits();
5304     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5305
5306     if (OpBits == DestBits) {
5307       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5308       // bits, it is already ready.
5309       if (NumSignBits > DestBits-MidBits)
5310         return Op;
5311     } else if (OpBits < DestBits) {
5312       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5313       // bits, just sext from i32.
5314       if (NumSignBits > OpBits-MidBits)
5315         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5316     } else {
5317       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5318       // bits, just truncate to i32.
5319       if (NumSignBits > OpBits-MidBits)
5320         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5321     }
5322
5323     // fold (sext (truncate x)) -> (sextinreg x).
5324     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5325                                                  N0.getValueType())) {
5326       if (OpBits < DestBits)
5327         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5328       else if (OpBits > DestBits)
5329         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5330       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5331                          DAG.getValueType(N0.getValueType()));
5332     }
5333   }
5334
5335   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5336   // None of the supported targets knows how to perform load and sign extend
5337   // on vectors in one instruction.  We only perform this transformation on
5338   // scalars.
5339   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5340       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5341       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5342        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5343     bool DoXform = true;
5344     SmallVector<SDNode*, 4> SetCCs;
5345     if (!N0.hasOneUse())
5346       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5347     if (DoXform) {
5348       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5349       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5350                                        LN0->getChain(),
5351                                        LN0->getBasePtr(), N0.getValueType(),
5352                                        LN0->getMemOperand());
5353       CombineTo(N, ExtLoad);
5354       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5355                                   N0.getValueType(), ExtLoad);
5356       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5357       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5358                       ISD::SIGN_EXTEND);
5359       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5360     }
5361   }
5362
5363   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5364   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5365   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5366       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5367     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5368     EVT MemVT = LN0->getMemoryVT();
5369     if ((!LegalOperations && !LN0->isVolatile()) ||
5370         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5371       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5372                                        LN0->getChain(),
5373                                        LN0->getBasePtr(), MemVT,
5374                                        LN0->getMemOperand());
5375       CombineTo(N, ExtLoad);
5376       CombineTo(N0.getNode(),
5377                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5378                             N0.getValueType(), ExtLoad),
5379                 ExtLoad.getValue(1));
5380       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5381     }
5382   }
5383
5384   // fold (sext (and/or/xor (load x), cst)) ->
5385   //      (and/or/xor (sextload x), (sext cst))
5386   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5387        N0.getOpcode() == ISD::XOR) &&
5388       isa<LoadSDNode>(N0.getOperand(0)) &&
5389       N0.getOperand(1).getOpcode() == ISD::Constant &&
5390       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5391       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5392     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5393     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5394       bool DoXform = true;
5395       SmallVector<SDNode*, 4> SetCCs;
5396       if (!N0.hasOneUse())
5397         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5398                                           SetCCs, TLI);
5399       if (DoXform) {
5400         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5401                                          LN0->getChain(), LN0->getBasePtr(),
5402                                          LN0->getMemoryVT(),
5403                                          LN0->getMemOperand());
5404         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5405         Mask = Mask.sext(VT.getSizeInBits());
5406         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5407                                   ExtLoad, DAG.getConstant(Mask, VT));
5408         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5409                                     SDLoc(N0.getOperand(0)),
5410                                     N0.getOperand(0).getValueType(), ExtLoad);
5411         CombineTo(N, And);
5412         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5413         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5414                         ISD::SIGN_EXTEND);
5415         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5416       }
5417     }
5418   }
5419
5420   if (N0.getOpcode() == ISD::SETCC) {
5421     EVT N0VT = N0.getOperand(0).getValueType();
5422     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5423     // Only do this before legalize for now.
5424     if (VT.isVector() && !LegalOperations &&
5425         TLI.getBooleanContents(N0VT) ==
5426             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5427       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5428       // of the same size as the compared operands. Only optimize sext(setcc())
5429       // if this is the case.
5430       EVT SVT = getSetCCResultType(N0VT);
5431
5432       // We know that the # elements of the results is the same as the
5433       // # elements of the compare (and the # elements of the compare result
5434       // for that matter).  Check to see that they are the same size.  If so,
5435       // we know that the element size of the sext'd result matches the
5436       // element size of the compare operands.
5437       if (VT.getSizeInBits() == SVT.getSizeInBits())
5438         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5439                              N0.getOperand(1),
5440                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5441
5442       // If the desired elements are smaller or larger than the source
5443       // elements we can use a matching integer vector type and then
5444       // truncate/sign extend
5445       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5446       if (SVT == MatchingVectorType) {
5447         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5448                                N0.getOperand(0), N0.getOperand(1),
5449                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5450         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5451       }
5452     }
5453
5454     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5455     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5456     SDValue NegOne =
5457       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5458     SDValue SCC =
5459       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5460                        NegOne, DAG.getConstant(0, VT),
5461                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5462     if (SCC.getNode()) return SCC;
5463
5464     if (!VT.isVector()) {
5465       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5466       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5467         SDLoc DL(N);
5468         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5469         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5470                                      N0.getOperand(0), N0.getOperand(1), CC);
5471         return DAG.getSelect(DL, VT, SetCC,
5472                              NegOne, DAG.getConstant(0, VT));
5473       }
5474     }
5475   }
5476
5477   // fold (sext x) -> (zext x) if the sign bit is known zero.
5478   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5479       DAG.SignBitIsZero(N0))
5480     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5481
5482   return SDValue();
5483 }
5484
5485 // isTruncateOf - If N is a truncate of some other value, return true, record
5486 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5487 // This function computes KnownZero to avoid a duplicated call to
5488 // computeKnownBits in the caller.
5489 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5490                          APInt &KnownZero) {
5491   APInt KnownOne;
5492   if (N->getOpcode() == ISD::TRUNCATE) {
5493     Op = N->getOperand(0);
5494     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5495     return true;
5496   }
5497
5498   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5499       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5500     return false;
5501
5502   SDValue Op0 = N->getOperand(0);
5503   SDValue Op1 = N->getOperand(1);
5504   assert(Op0.getValueType() == Op1.getValueType());
5505
5506   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5507   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5508   if (COp0 && COp0->isNullValue())
5509     Op = Op1;
5510   else if (COp1 && COp1->isNullValue())
5511     Op = Op0;
5512   else
5513     return false;
5514
5515   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5516
5517   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5518     return false;
5519
5520   return true;
5521 }
5522
5523 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5524   SDValue N0 = N->getOperand(0);
5525   EVT VT = N->getValueType(0);
5526
5527   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5528                                               LegalOperations))
5529     return SDValue(Res, 0);
5530
5531   // fold (zext (zext x)) -> (zext x)
5532   // fold (zext (aext x)) -> (zext x)
5533   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5534     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5535                        N0.getOperand(0));
5536
5537   // fold (zext (truncate x)) -> (zext x) or
5538   //      (zext (truncate x)) -> (truncate x)
5539   // This is valid when the truncated bits of x are already zero.
5540   // FIXME: We should extend this to work for vectors too.
5541   SDValue Op;
5542   APInt KnownZero;
5543   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5544     APInt TruncatedBits =
5545       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5546       APInt(Op.getValueSizeInBits(), 0) :
5547       APInt::getBitsSet(Op.getValueSizeInBits(),
5548                         N0.getValueSizeInBits(),
5549                         std::min(Op.getValueSizeInBits(),
5550                                  VT.getSizeInBits()));
5551     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5552       if (VT.bitsGT(Op.getValueType()))
5553         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5554       if (VT.bitsLT(Op.getValueType()))
5555         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5556
5557       return Op;
5558     }
5559   }
5560
5561   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5562   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5563   if (N0.getOpcode() == ISD::TRUNCATE) {
5564     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5565     if (NarrowLoad.getNode()) {
5566       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5567       if (NarrowLoad.getNode() != N0.getNode()) {
5568         CombineTo(N0.getNode(), NarrowLoad);
5569         // CombineTo deleted the truncate, if needed, but not what's under it.
5570         AddToWorklist(oye);
5571       }
5572       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5573     }
5574   }
5575
5576   // fold (zext (truncate x)) -> (and x, mask)
5577   if (N0.getOpcode() == ISD::TRUNCATE &&
5578       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5579
5580     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5581     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5582     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5583     if (NarrowLoad.getNode()) {
5584       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5585       if (NarrowLoad.getNode() != N0.getNode()) {
5586         CombineTo(N0.getNode(), NarrowLoad);
5587         // CombineTo deleted the truncate, if needed, but not what's under it.
5588         AddToWorklist(oye);
5589       }
5590       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5591     }
5592
5593     SDValue Op = N0.getOperand(0);
5594     if (Op.getValueType().bitsLT(VT)) {
5595       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5596       AddToWorklist(Op.getNode());
5597     } else if (Op.getValueType().bitsGT(VT)) {
5598       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5599       AddToWorklist(Op.getNode());
5600     }
5601     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5602                                   N0.getValueType().getScalarType());
5603   }
5604
5605   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5606   // if either of the casts is not free.
5607   if (N0.getOpcode() == ISD::AND &&
5608       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5609       N0.getOperand(1).getOpcode() == ISD::Constant &&
5610       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5611                            N0.getValueType()) ||
5612        !TLI.isZExtFree(N0.getValueType(), VT))) {
5613     SDValue X = N0.getOperand(0).getOperand(0);
5614     if (X.getValueType().bitsLT(VT)) {
5615       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5616     } else if (X.getValueType().bitsGT(VT)) {
5617       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5618     }
5619     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5620     Mask = Mask.zext(VT.getSizeInBits());
5621     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5622                        X, DAG.getConstant(Mask, VT));
5623   }
5624
5625   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5626   // None of the supported targets knows how to perform load and vector_zext
5627   // on vectors in one instruction.  We only perform this transformation on
5628   // scalars.
5629   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5630       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5631       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5632        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5633     bool DoXform = true;
5634     SmallVector<SDNode*, 4> SetCCs;
5635     if (!N0.hasOneUse())
5636       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5637     if (DoXform) {
5638       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5639       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5640                                        LN0->getChain(),
5641                                        LN0->getBasePtr(), N0.getValueType(),
5642                                        LN0->getMemOperand());
5643       CombineTo(N, ExtLoad);
5644       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5645                                   N0.getValueType(), ExtLoad);
5646       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5647
5648       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5649                       ISD::ZERO_EXTEND);
5650       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5651     }
5652   }
5653
5654   // fold (zext (and/or/xor (load x), cst)) ->
5655   //      (and/or/xor (zextload x), (zext cst))
5656   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5657        N0.getOpcode() == ISD::XOR) &&
5658       isa<LoadSDNode>(N0.getOperand(0)) &&
5659       N0.getOperand(1).getOpcode() == ISD::Constant &&
5660       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5661       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5662     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5663     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5664       bool DoXform = true;
5665       SmallVector<SDNode*, 4> SetCCs;
5666       if (!N0.hasOneUse())
5667         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5668                                           SetCCs, TLI);
5669       if (DoXform) {
5670         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5671                                          LN0->getChain(), LN0->getBasePtr(),
5672                                          LN0->getMemoryVT(),
5673                                          LN0->getMemOperand());
5674         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5675         Mask = Mask.zext(VT.getSizeInBits());
5676         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5677                                   ExtLoad, DAG.getConstant(Mask, VT));
5678         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5679                                     SDLoc(N0.getOperand(0)),
5680                                     N0.getOperand(0).getValueType(), ExtLoad);
5681         CombineTo(N, And);
5682         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5683         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5684                         ISD::ZERO_EXTEND);
5685         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5686       }
5687     }
5688   }
5689
5690   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5691   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5692   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5693       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5694     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5695     EVT MemVT = LN0->getMemoryVT();
5696     if ((!LegalOperations && !LN0->isVolatile()) ||
5697         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5698       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5699                                        LN0->getChain(),
5700                                        LN0->getBasePtr(), MemVT,
5701                                        LN0->getMemOperand());
5702       CombineTo(N, ExtLoad);
5703       CombineTo(N0.getNode(),
5704                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5705                             ExtLoad),
5706                 ExtLoad.getValue(1));
5707       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5708     }
5709   }
5710
5711   if (N0.getOpcode() == ISD::SETCC) {
5712     if (!LegalOperations && VT.isVector() &&
5713         N0.getValueType().getVectorElementType() == MVT::i1) {
5714       EVT N0VT = N0.getOperand(0).getValueType();
5715       if (getSetCCResultType(N0VT) == N0.getValueType())
5716         return SDValue();
5717
5718       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5719       // Only do this before legalize for now.
5720       EVT EltVT = VT.getVectorElementType();
5721       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5722                                     DAG.getConstant(1, EltVT));
5723       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5724         // We know that the # elements of the results is the same as the
5725         // # elements of the compare (and the # elements of the compare result
5726         // for that matter).  Check to see that they are the same size.  If so,
5727         // we know that the element size of the sext'd result matches the
5728         // element size of the compare operands.
5729         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5730                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5731                                          N0.getOperand(1),
5732                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5733                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5734                                        OneOps));
5735
5736       // If the desired elements are smaller or larger than the source
5737       // elements we can use a matching integer vector type and then
5738       // truncate/sign extend
5739       EVT MatchingElementType =
5740         EVT::getIntegerVT(*DAG.getContext(),
5741                           N0VT.getScalarType().getSizeInBits());
5742       EVT MatchingVectorType =
5743         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5744                          N0VT.getVectorNumElements());
5745       SDValue VsetCC =
5746         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5747                       N0.getOperand(1),
5748                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5749       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5750                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5751                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5752     }
5753
5754     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5755     SDValue SCC =
5756       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5757                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5758                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5759     if (SCC.getNode()) return SCC;
5760   }
5761
5762   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5763   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5764       isa<ConstantSDNode>(N0.getOperand(1)) &&
5765       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5766       N0.hasOneUse()) {
5767     SDValue ShAmt = N0.getOperand(1);
5768     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5769     if (N0.getOpcode() == ISD::SHL) {
5770       SDValue InnerZExt = N0.getOperand(0);
5771       // If the original shl may be shifting out bits, do not perform this
5772       // transformation.
5773       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5774         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5775       if (ShAmtVal > KnownZeroBits)
5776         return SDValue();
5777     }
5778
5779     SDLoc DL(N);
5780
5781     // Ensure that the shift amount is wide enough for the shifted value.
5782     if (VT.getSizeInBits() >= 256)
5783       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5784
5785     return DAG.getNode(N0.getOpcode(), DL, VT,
5786                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5787                        ShAmt);
5788   }
5789
5790   return SDValue();
5791 }
5792
5793 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5794   SDValue N0 = N->getOperand(0);
5795   EVT VT = N->getValueType(0);
5796
5797   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5798                                               LegalOperations))
5799     return SDValue(Res, 0);
5800
5801   // fold (aext (aext x)) -> (aext x)
5802   // fold (aext (zext x)) -> (zext x)
5803   // fold (aext (sext x)) -> (sext x)
5804   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5805       N0.getOpcode() == ISD::ZERO_EXTEND ||
5806       N0.getOpcode() == ISD::SIGN_EXTEND)
5807     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5808
5809   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5810   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5811   if (N0.getOpcode() == ISD::TRUNCATE) {
5812     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5813     if (NarrowLoad.getNode()) {
5814       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5815       if (NarrowLoad.getNode() != N0.getNode()) {
5816         CombineTo(N0.getNode(), NarrowLoad);
5817         // CombineTo deleted the truncate, if needed, but not what's under it.
5818         AddToWorklist(oye);
5819       }
5820       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5821     }
5822   }
5823
5824   // fold (aext (truncate x))
5825   if (N0.getOpcode() == ISD::TRUNCATE) {
5826     SDValue TruncOp = N0.getOperand(0);
5827     if (TruncOp.getValueType() == VT)
5828       return TruncOp; // x iff x size == zext size.
5829     if (TruncOp.getValueType().bitsGT(VT))
5830       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5831     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5832   }
5833
5834   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5835   // if the trunc is not free.
5836   if (N0.getOpcode() == ISD::AND &&
5837       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5838       N0.getOperand(1).getOpcode() == ISD::Constant &&
5839       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5840                           N0.getValueType())) {
5841     SDValue X = N0.getOperand(0).getOperand(0);
5842     if (X.getValueType().bitsLT(VT)) {
5843       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5844     } else if (X.getValueType().bitsGT(VT)) {
5845       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5846     }
5847     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5848     Mask = Mask.zext(VT.getSizeInBits());
5849     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5850                        X, DAG.getConstant(Mask, VT));
5851   }
5852
5853   // fold (aext (load x)) -> (aext (truncate (extload x)))
5854   // None of the supported targets knows how to perform load and any_ext
5855   // on vectors in one instruction.  We only perform this transformation on
5856   // scalars.
5857   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5858       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5859       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
5860     bool DoXform = true;
5861     SmallVector<SDNode*, 4> SetCCs;
5862     if (!N0.hasOneUse())
5863       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5864     if (DoXform) {
5865       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5866       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5867                                        LN0->getChain(),
5868                                        LN0->getBasePtr(), N0.getValueType(),
5869                                        LN0->getMemOperand());
5870       CombineTo(N, ExtLoad);
5871       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5872                                   N0.getValueType(), ExtLoad);
5873       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5874       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5875                       ISD::ANY_EXTEND);
5876       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5877     }
5878   }
5879
5880   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5881   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5882   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5883   if (N0.getOpcode() == ISD::LOAD &&
5884       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5885       N0.hasOneUse()) {
5886     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5887     ISD::LoadExtType ExtType = LN0->getExtensionType();
5888     EVT MemVT = LN0->getMemoryVT();
5889     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
5890       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5891                                        VT, LN0->getChain(), LN0->getBasePtr(),
5892                                        MemVT, LN0->getMemOperand());
5893       CombineTo(N, ExtLoad);
5894       CombineTo(N0.getNode(),
5895                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5896                             N0.getValueType(), ExtLoad),
5897                 ExtLoad.getValue(1));
5898       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5899     }
5900   }
5901
5902   if (N0.getOpcode() == ISD::SETCC) {
5903     // For vectors:
5904     // aext(setcc) -> vsetcc
5905     // aext(setcc) -> truncate(vsetcc)
5906     // aext(setcc) -> aext(vsetcc)
5907     // Only do this before legalize for now.
5908     if (VT.isVector() && !LegalOperations) {
5909       EVT N0VT = N0.getOperand(0).getValueType();
5910         // We know that the # elements of the results is the same as the
5911         // # elements of the compare (and the # elements of the compare result
5912         // for that matter).  Check to see that they are the same size.  If so,
5913         // we know that the element size of the sext'd result matches the
5914         // element size of the compare operands.
5915       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5916         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5917                              N0.getOperand(1),
5918                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5919       // If the desired elements are smaller or larger than the source
5920       // elements we can use a matching integer vector type and then
5921       // truncate/any extend
5922       else {
5923         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5924         SDValue VsetCC =
5925           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5926                         N0.getOperand(1),
5927                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5928         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5929       }
5930     }
5931
5932     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5933     SDValue SCC =
5934       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5935                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5936                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5937     if (SCC.getNode())
5938       return SCC;
5939   }
5940
5941   return SDValue();
5942 }
5943
5944 /// See if the specified operand can be simplified with the knowledge that only
5945 /// the bits specified by Mask are used.  If so, return the simpler operand,
5946 /// otherwise return a null SDValue.
5947 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5948   switch (V.getOpcode()) {
5949   default: break;
5950   case ISD::Constant: {
5951     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5952     assert(CV && "Const value should be ConstSDNode.");
5953     const APInt &CVal = CV->getAPIntValue();
5954     APInt NewVal = CVal & Mask;
5955     if (NewVal != CVal)
5956       return DAG.getConstant(NewVal, V.getValueType());
5957     break;
5958   }
5959   case ISD::OR:
5960   case ISD::XOR:
5961     // If the LHS or RHS don't contribute bits to the or, drop them.
5962     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5963       return V.getOperand(1);
5964     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5965       return V.getOperand(0);
5966     break;
5967   case ISD::SRL:
5968     // Only look at single-use SRLs.
5969     if (!V.getNode()->hasOneUse())
5970       break;
5971     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5972       // See if we can recursively simplify the LHS.
5973       unsigned Amt = RHSC->getZExtValue();
5974
5975       // Watch out for shift count overflow though.
5976       if (Amt >= Mask.getBitWidth()) break;
5977       APInt NewMask = Mask << Amt;
5978       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5979       if (SimplifyLHS.getNode())
5980         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5981                            SimplifyLHS, V.getOperand(1));
5982     }
5983   }
5984   return SDValue();
5985 }
5986
5987 /// If the result of a wider load is shifted to right of N  bits and then
5988 /// truncated to a narrower type and where N is a multiple of number of bits of
5989 /// the narrower type, transform it to a narrower load from address + N / num of
5990 /// bits of new type. If the result is to be extended, also fold the extension
5991 /// to form a extending load.
5992 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5993   unsigned Opc = N->getOpcode();
5994
5995   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5996   SDValue N0 = N->getOperand(0);
5997   EVT VT = N->getValueType(0);
5998   EVT ExtVT = VT;
5999
6000   // This transformation isn't valid for vector loads.
6001   if (VT.isVector())
6002     return SDValue();
6003
6004   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6005   // extended to VT.
6006   if (Opc == ISD::SIGN_EXTEND_INREG) {
6007     ExtType = ISD::SEXTLOAD;
6008     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6009   } else if (Opc == ISD::SRL) {
6010     // Another special-case: SRL is basically zero-extending a narrower value.
6011     ExtType = ISD::ZEXTLOAD;
6012     N0 = SDValue(N, 0);
6013     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6014     if (!N01) return SDValue();
6015     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6016                               VT.getSizeInBits() - N01->getZExtValue());
6017   }
6018   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6019     return SDValue();
6020
6021   unsigned EVTBits = ExtVT.getSizeInBits();
6022
6023   // Do not generate loads of non-round integer types since these can
6024   // be expensive (and would be wrong if the type is not byte sized).
6025   if (!ExtVT.isRound())
6026     return SDValue();
6027
6028   unsigned ShAmt = 0;
6029   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6030     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6031       ShAmt = N01->getZExtValue();
6032       // Is the shift amount a multiple of size of VT?
6033       if ((ShAmt & (EVTBits-1)) == 0) {
6034         N0 = N0.getOperand(0);
6035         // Is the load width a multiple of size of VT?
6036         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6037           return SDValue();
6038       }
6039
6040       // At this point, we must have a load or else we can't do the transform.
6041       if (!isa<LoadSDNode>(N0)) return SDValue();
6042
6043       // Because a SRL must be assumed to *need* to zero-extend the high bits
6044       // (as opposed to anyext the high bits), we can't combine the zextload
6045       // lowering of SRL and an sextload.
6046       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6047         return SDValue();
6048
6049       // If the shift amount is larger than the input type then we're not
6050       // accessing any of the loaded bytes.  If the load was a zextload/extload
6051       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6052       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6053         return SDValue();
6054     }
6055   }
6056
6057   // If the load is shifted left (and the result isn't shifted back right),
6058   // we can fold the truncate through the shift.
6059   unsigned ShLeftAmt = 0;
6060   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6061       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6062     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6063       ShLeftAmt = N01->getZExtValue();
6064       N0 = N0.getOperand(0);
6065     }
6066   }
6067
6068   // If we haven't found a load, we can't narrow it.  Don't transform one with
6069   // multiple uses, this would require adding a new load.
6070   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6071     return SDValue();
6072
6073   // Don't change the width of a volatile load.
6074   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6075   if (LN0->isVolatile())
6076     return SDValue();
6077
6078   // Verify that we are actually reducing a load width here.
6079   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6080     return SDValue();
6081
6082   // For the transform to be legal, the load must produce only two values
6083   // (the value loaded and the chain).  Don't transform a pre-increment
6084   // load, for example, which produces an extra value.  Otherwise the
6085   // transformation is not equivalent, and the downstream logic to replace
6086   // uses gets things wrong.
6087   if (LN0->getNumValues() > 2)
6088     return SDValue();
6089
6090   // If the load that we're shrinking is an extload and we're not just
6091   // discarding the extension we can't simply shrink the load. Bail.
6092   // TODO: It would be possible to merge the extensions in some cases.
6093   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6094       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6095     return SDValue();
6096
6097   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6098     return SDValue();
6099
6100   EVT PtrType = N0.getOperand(1).getValueType();
6101
6102   if (PtrType == MVT::Untyped || PtrType.isExtended())
6103     // It's not possible to generate a constant of extended or untyped type.
6104     return SDValue();
6105
6106   // For big endian targets, we need to adjust the offset to the pointer to
6107   // load the correct bytes.
6108   if (TLI.isBigEndian()) {
6109     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6110     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6111     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6112   }
6113
6114   uint64_t PtrOff = ShAmt / 8;
6115   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6116   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6117                                PtrType, LN0->getBasePtr(),
6118                                DAG.getConstant(PtrOff, PtrType));
6119   AddToWorklist(NewPtr.getNode());
6120
6121   SDValue Load;
6122   if (ExtType == ISD::NON_EXTLOAD)
6123     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6124                         LN0->getPointerInfo().getWithOffset(PtrOff),
6125                         LN0->isVolatile(), LN0->isNonTemporal(),
6126                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6127   else
6128     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6129                           LN0->getPointerInfo().getWithOffset(PtrOff),
6130                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6131                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6132
6133   // Replace the old load's chain with the new load's chain.
6134   WorklistRemover DeadNodes(*this);
6135   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6136
6137   // Shift the result left, if we've swallowed a left shift.
6138   SDValue Result = Load;
6139   if (ShLeftAmt != 0) {
6140     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6141     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6142       ShImmTy = VT;
6143     // If the shift amount is as large as the result size (but, presumably,
6144     // no larger than the source) then the useful bits of the result are
6145     // zero; we can't simply return the shortened shift, because the result
6146     // of that operation is undefined.
6147     if (ShLeftAmt >= VT.getSizeInBits())
6148       Result = DAG.getConstant(0, VT);
6149     else
6150       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6151                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6152   }
6153
6154   // Return the new loaded value.
6155   return Result;
6156 }
6157
6158 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6159   SDValue N0 = N->getOperand(0);
6160   SDValue N1 = N->getOperand(1);
6161   EVT VT = N->getValueType(0);
6162   EVT EVT = cast<VTSDNode>(N1)->getVT();
6163   unsigned VTBits = VT.getScalarType().getSizeInBits();
6164   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6165
6166   // fold (sext_in_reg c1) -> c1
6167   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6168     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6169
6170   // If the input is already sign extended, just drop the extension.
6171   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6172     return N0;
6173
6174   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6175   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6176       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6177     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6178                        N0.getOperand(0), N1);
6179
6180   // fold (sext_in_reg (sext x)) -> (sext x)
6181   // fold (sext_in_reg (aext x)) -> (sext x)
6182   // if x is small enough.
6183   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6184     SDValue N00 = N0.getOperand(0);
6185     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6186         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6187       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6188   }
6189
6190   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6191   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6192     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6193
6194   // fold operands of sext_in_reg based on knowledge that the top bits are not
6195   // demanded.
6196   if (SimplifyDemandedBits(SDValue(N, 0)))
6197     return SDValue(N, 0);
6198
6199   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6200   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6201   SDValue NarrowLoad = ReduceLoadWidth(N);
6202   if (NarrowLoad.getNode())
6203     return NarrowLoad;
6204
6205   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6206   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6207   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6208   if (N0.getOpcode() == ISD::SRL) {
6209     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6210       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6211         // We can turn this into an SRA iff the input to the SRL is already sign
6212         // extended enough.
6213         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6214         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6215           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6216                              N0.getOperand(0), N0.getOperand(1));
6217       }
6218   }
6219
6220   // fold (sext_inreg (extload x)) -> (sextload x)
6221   if (ISD::isEXTLoad(N0.getNode()) &&
6222       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6223       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6224       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6225        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6226     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6227     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6228                                      LN0->getChain(),
6229                                      LN0->getBasePtr(), EVT,
6230                                      LN0->getMemOperand());
6231     CombineTo(N, ExtLoad);
6232     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6233     AddToWorklist(ExtLoad.getNode());
6234     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6235   }
6236   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6237   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6238       N0.hasOneUse() &&
6239       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6240       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6241        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6242     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6243     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6244                                      LN0->getChain(),
6245                                      LN0->getBasePtr(), EVT,
6246                                      LN0->getMemOperand());
6247     CombineTo(N, ExtLoad);
6248     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6249     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6250   }
6251
6252   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6253   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6254     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6255                                        N0.getOperand(1), false);
6256     if (BSwap.getNode())
6257       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6258                          BSwap, N1);
6259   }
6260
6261   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6262   // into a build_vector.
6263   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6264     SmallVector<SDValue, 8> Elts;
6265     unsigned NumElts = N0->getNumOperands();
6266     unsigned ShAmt = VTBits - EVTBits;
6267
6268     for (unsigned i = 0; i != NumElts; ++i) {
6269       SDValue Op = N0->getOperand(i);
6270       if (Op->getOpcode() == ISD::UNDEF) {
6271         Elts.push_back(Op);
6272         continue;
6273       }
6274
6275       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6276       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6277       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6278                                      Op.getValueType()));
6279     }
6280
6281     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6282   }
6283
6284   return SDValue();
6285 }
6286
6287 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6288   SDValue N0 = N->getOperand(0);
6289   EVT VT = N->getValueType(0);
6290   bool isLE = TLI.isLittleEndian();
6291
6292   // noop truncate
6293   if (N0.getValueType() == N->getValueType(0))
6294     return N0;
6295   // fold (truncate c1) -> c1
6296   if (isa<ConstantSDNode>(N0))
6297     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6298   // fold (truncate (truncate x)) -> (truncate x)
6299   if (N0.getOpcode() == ISD::TRUNCATE)
6300     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6301   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6302   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6303       N0.getOpcode() == ISD::SIGN_EXTEND ||
6304       N0.getOpcode() == ISD::ANY_EXTEND) {
6305     if (N0.getOperand(0).getValueType().bitsLT(VT))
6306       // if the source is smaller than the dest, we still need an extend
6307       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6308                          N0.getOperand(0));
6309     if (N0.getOperand(0).getValueType().bitsGT(VT))
6310       // if the source is larger than the dest, than we just need the truncate
6311       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6312     // if the source and dest are the same type, we can drop both the extend
6313     // and the truncate.
6314     return N0.getOperand(0);
6315   }
6316
6317   // Fold extract-and-trunc into a narrow extract. For example:
6318   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6319   //   i32 y = TRUNCATE(i64 x)
6320   //        -- becomes --
6321   //   v16i8 b = BITCAST (v2i64 val)
6322   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6323   //
6324   // Note: We only run this optimization after type legalization (which often
6325   // creates this pattern) and before operation legalization after which
6326   // we need to be more careful about the vector instructions that we generate.
6327   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6328       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6329
6330     EVT VecTy = N0.getOperand(0).getValueType();
6331     EVT ExTy = N0.getValueType();
6332     EVT TrTy = N->getValueType(0);
6333
6334     unsigned NumElem = VecTy.getVectorNumElements();
6335     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6336
6337     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6338     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6339
6340     SDValue EltNo = N0->getOperand(1);
6341     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6342       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6343       EVT IndexTy = TLI.getVectorIdxTy();
6344       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6345
6346       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6347                               NVT, N0.getOperand(0));
6348
6349       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6350                          SDLoc(N), TrTy, V,
6351                          DAG.getConstant(Index, IndexTy));
6352     }
6353   }
6354
6355   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6356   if (N0.getOpcode() == ISD::SELECT) {
6357     EVT SrcVT = N0.getValueType();
6358     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6359         TLI.isTruncateFree(SrcVT, VT)) {
6360       SDLoc SL(N0);
6361       SDValue Cond = N0.getOperand(0);
6362       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6363       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6364       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6365     }
6366   }
6367
6368   // Fold a series of buildvector, bitcast, and truncate if possible.
6369   // For example fold
6370   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6371   //   (2xi32 (buildvector x, y)).
6372   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6373       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6374       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6375       N0.getOperand(0).hasOneUse()) {
6376
6377     SDValue BuildVect = N0.getOperand(0);
6378     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6379     EVT TruncVecEltTy = VT.getVectorElementType();
6380
6381     // Check that the element types match.
6382     if (BuildVectEltTy == TruncVecEltTy) {
6383       // Now we only need to compute the offset of the truncated elements.
6384       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6385       unsigned TruncVecNumElts = VT.getVectorNumElements();
6386       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6387
6388       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6389              "Invalid number of elements");
6390
6391       SmallVector<SDValue, 8> Opnds;
6392       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6393         Opnds.push_back(BuildVect.getOperand(i));
6394
6395       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6396     }
6397   }
6398
6399   // See if we can simplify the input to this truncate through knowledge that
6400   // only the low bits are being used.
6401   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6402   // Currently we only perform this optimization on scalars because vectors
6403   // may have different active low bits.
6404   if (!VT.isVector()) {
6405     SDValue Shorter =
6406       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6407                                                VT.getSizeInBits()));
6408     if (Shorter.getNode())
6409       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6410   }
6411   // fold (truncate (load x)) -> (smaller load x)
6412   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6413   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6414     SDValue Reduced = ReduceLoadWidth(N);
6415     if (Reduced.getNode())
6416       return Reduced;
6417     // Handle the case where the load remains an extending load even
6418     // after truncation.
6419     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6420       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6421       if (!LN0->isVolatile() &&
6422           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6423         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6424                                          VT, LN0->getChain(), LN0->getBasePtr(),
6425                                          LN0->getMemoryVT(),
6426                                          LN0->getMemOperand());
6427         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6428         return NewLoad;
6429       }
6430     }
6431   }
6432   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6433   // where ... are all 'undef'.
6434   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6435     SmallVector<EVT, 8> VTs;
6436     SDValue V;
6437     unsigned Idx = 0;
6438     unsigned NumDefs = 0;
6439
6440     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6441       SDValue X = N0.getOperand(i);
6442       if (X.getOpcode() != ISD::UNDEF) {
6443         V = X;
6444         Idx = i;
6445         NumDefs++;
6446       }
6447       // Stop if more than one members are non-undef.
6448       if (NumDefs > 1)
6449         break;
6450       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6451                                      VT.getVectorElementType(),
6452                                      X.getValueType().getVectorNumElements()));
6453     }
6454
6455     if (NumDefs == 0)
6456       return DAG.getUNDEF(VT);
6457
6458     if (NumDefs == 1) {
6459       assert(V.getNode() && "The single defined operand is empty!");
6460       SmallVector<SDValue, 8> Opnds;
6461       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6462         if (i != Idx) {
6463           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6464           continue;
6465         }
6466         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6467         AddToWorklist(NV.getNode());
6468         Opnds.push_back(NV);
6469       }
6470       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6471     }
6472   }
6473
6474   // Simplify the operands using demanded-bits information.
6475   if (!VT.isVector() &&
6476       SimplifyDemandedBits(SDValue(N, 0)))
6477     return SDValue(N, 0);
6478
6479   return SDValue();
6480 }
6481
6482 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6483   SDValue Elt = N->getOperand(i);
6484   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6485     return Elt.getNode();
6486   return Elt.getOperand(Elt.getResNo()).getNode();
6487 }
6488
6489 /// build_pair (load, load) -> load
6490 /// if load locations are consecutive.
6491 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6492   assert(N->getOpcode() == ISD::BUILD_PAIR);
6493
6494   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6495   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6496   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6497       LD1->getAddressSpace() != LD2->getAddressSpace())
6498     return SDValue();
6499   EVT LD1VT = LD1->getValueType(0);
6500
6501   if (ISD::isNON_EXTLoad(LD2) &&
6502       LD2->hasOneUse() &&
6503       // If both are volatile this would reduce the number of volatile loads.
6504       // If one is volatile it might be ok, but play conservative and bail out.
6505       !LD1->isVolatile() &&
6506       !LD2->isVolatile() &&
6507       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6508     unsigned Align = LD1->getAlignment();
6509     unsigned NewAlign = TLI.getDataLayout()->
6510       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6511
6512     if (NewAlign <= Align &&
6513         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6514       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6515                          LD1->getBasePtr(), LD1->getPointerInfo(),
6516                          false, false, false, Align);
6517   }
6518
6519   return SDValue();
6520 }
6521
6522 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6523   SDValue N0 = N->getOperand(0);
6524   EVT VT = N->getValueType(0);
6525
6526   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6527   // Only do this before legalize, since afterward the target may be depending
6528   // on the bitconvert.
6529   // First check to see if this is all constant.
6530   if (!LegalTypes &&
6531       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6532       VT.isVector()) {
6533     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6534
6535     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6536     assert(!DestEltVT.isVector() &&
6537            "Element type of vector ValueType must not be vector!");
6538     if (isSimple)
6539       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6540   }
6541
6542   // If the input is a constant, let getNode fold it.
6543   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6544     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6545     if (Res.getNode() != N) {
6546       if (!LegalOperations ||
6547           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6548         return Res;
6549
6550       // Folding it resulted in an illegal node, and it's too late to
6551       // do that. Clean up the old node and forego the transformation.
6552       // Ideally this won't happen very often, because instcombine
6553       // and the earlier dagcombine runs (where illegal nodes are
6554       // permitted) should have folded most of them already.
6555       deleteAndRecombine(Res.getNode());
6556     }
6557   }
6558
6559   // (conv (conv x, t1), t2) -> (conv x, t2)
6560   if (N0.getOpcode() == ISD::BITCAST)
6561     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6562                        N0.getOperand(0));
6563
6564   // fold (conv (load x)) -> (load (conv*)x)
6565   // If the resultant load doesn't need a higher alignment than the original!
6566   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6567       // Do not change the width of a volatile load.
6568       !cast<LoadSDNode>(N0)->isVolatile() &&
6569       // Do not remove the cast if the types differ in endian layout.
6570       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6571       TLI.hasBigEndianPartOrdering(VT) &&
6572       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6573       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6574     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6575     unsigned Align = TLI.getDataLayout()->
6576       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6577     unsigned OrigAlign = LN0->getAlignment();
6578
6579     if (Align <= OrigAlign) {
6580       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6581                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6582                                  LN0->isVolatile(), LN0->isNonTemporal(),
6583                                  LN0->isInvariant(), OrigAlign,
6584                                  LN0->getAAInfo());
6585       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6586       return Load;
6587     }
6588   }
6589
6590   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6591   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6592   // This often reduces constant pool loads.
6593   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6594        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6595       N0.getNode()->hasOneUse() && VT.isInteger() &&
6596       !VT.isVector() && !N0.getValueType().isVector()) {
6597     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6598                                   N0.getOperand(0));
6599     AddToWorklist(NewConv.getNode());
6600
6601     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6602     if (N0.getOpcode() == ISD::FNEG)
6603       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6604                          NewConv, DAG.getConstant(SignBit, VT));
6605     assert(N0.getOpcode() == ISD::FABS);
6606     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6607                        NewConv, DAG.getConstant(~SignBit, VT));
6608   }
6609
6610   // fold (bitconvert (fcopysign cst, x)) ->
6611   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6612   // Note that we don't handle (copysign x, cst) because this can always be
6613   // folded to an fneg or fabs.
6614   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6615       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6616       VT.isInteger() && !VT.isVector()) {
6617     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6618     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6619     if (isTypeLegal(IntXVT)) {
6620       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6621                               IntXVT, N0.getOperand(1));
6622       AddToWorklist(X.getNode());
6623
6624       // If X has a different width than the result/lhs, sext it or truncate it.
6625       unsigned VTWidth = VT.getSizeInBits();
6626       if (OrigXWidth < VTWidth) {
6627         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6628         AddToWorklist(X.getNode());
6629       } else if (OrigXWidth > VTWidth) {
6630         // To get the sign bit in the right place, we have to shift it right
6631         // before truncating.
6632         X = DAG.getNode(ISD::SRL, SDLoc(X),
6633                         X.getValueType(), X,
6634                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6635         AddToWorklist(X.getNode());
6636         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6637         AddToWorklist(X.getNode());
6638       }
6639
6640       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6641       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6642                       X, DAG.getConstant(SignBit, VT));
6643       AddToWorklist(X.getNode());
6644
6645       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6646                                 VT, N0.getOperand(0));
6647       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6648                         Cst, DAG.getConstant(~SignBit, VT));
6649       AddToWorklist(Cst.getNode());
6650
6651       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6652     }
6653   }
6654
6655   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6656   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6657     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6658     if (CombineLD.getNode())
6659       return CombineLD;
6660   }
6661
6662   return SDValue();
6663 }
6664
6665 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6666   EVT VT = N->getValueType(0);
6667   return CombineConsecutiveLoads(N, VT);
6668 }
6669
6670 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6671 /// operands. DstEltVT indicates the destination element value type.
6672 SDValue DAGCombiner::
6673 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6674   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6675
6676   // If this is already the right type, we're done.
6677   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6678
6679   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6680   unsigned DstBitSize = DstEltVT.getSizeInBits();
6681
6682   // If this is a conversion of N elements of one type to N elements of another
6683   // type, convert each element.  This handles FP<->INT cases.
6684   if (SrcBitSize == DstBitSize) {
6685     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6686                               BV->getValueType(0).getVectorNumElements());
6687
6688     // Due to the FP element handling below calling this routine recursively,
6689     // we can end up with a scalar-to-vector node here.
6690     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6691       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6692                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6693                                      DstEltVT, BV->getOperand(0)));
6694
6695     SmallVector<SDValue, 8> Ops;
6696     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6697       SDValue Op = BV->getOperand(i);
6698       // If the vector element type is not legal, the BUILD_VECTOR operands
6699       // are promoted and implicitly truncated.  Make that explicit here.
6700       if (Op.getValueType() != SrcEltVT)
6701         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6702       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6703                                 DstEltVT, Op));
6704       AddToWorklist(Ops.back().getNode());
6705     }
6706     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6707   }
6708
6709   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6710   // handle annoying details of growing/shrinking FP values, we convert them to
6711   // int first.
6712   if (SrcEltVT.isFloatingPoint()) {
6713     // Convert the input float vector to a int vector where the elements are the
6714     // same sizes.
6715     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6716     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6717     SrcEltVT = IntVT;
6718   }
6719
6720   // Now we know the input is an integer vector.  If the output is a FP type,
6721   // convert to integer first, then to FP of the right size.
6722   if (DstEltVT.isFloatingPoint()) {
6723     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6724     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6725
6726     // Next, convert to FP elements of the same size.
6727     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6728   }
6729
6730   // Okay, we know the src/dst types are both integers of differing types.
6731   // Handling growing first.
6732   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6733   if (SrcBitSize < DstBitSize) {
6734     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6735
6736     SmallVector<SDValue, 8> Ops;
6737     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6738          i += NumInputsPerOutput) {
6739       bool isLE = TLI.isLittleEndian();
6740       APInt NewBits = APInt(DstBitSize, 0);
6741       bool EltIsUndef = true;
6742       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6743         // Shift the previously computed bits over.
6744         NewBits <<= SrcBitSize;
6745         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6746         if (Op.getOpcode() == ISD::UNDEF) continue;
6747         EltIsUndef = false;
6748
6749         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6750                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6751       }
6752
6753       if (EltIsUndef)
6754         Ops.push_back(DAG.getUNDEF(DstEltVT));
6755       else
6756         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6757     }
6758
6759     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6760     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6761   }
6762
6763   // Finally, this must be the case where we are shrinking elements: each input
6764   // turns into multiple outputs.
6765   bool isS2V = ISD::isScalarToVector(BV);
6766   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6767   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6768                             NumOutputsPerInput*BV->getNumOperands());
6769   SmallVector<SDValue, 8> Ops;
6770
6771   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6772     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6773       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6774         Ops.push_back(DAG.getUNDEF(DstEltVT));
6775       continue;
6776     }
6777
6778     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6779                   getAPIntValue().zextOrTrunc(SrcBitSize);
6780
6781     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6782       APInt ThisVal = OpVal.trunc(DstBitSize);
6783       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6784       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6785         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6786         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6787                            Ops[0]);
6788       OpVal = OpVal.lshr(DstBitSize);
6789     }
6790
6791     // For big endian targets, swap the order of the pieces of each element.
6792     if (TLI.isBigEndian())
6793       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6794   }
6795
6796   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6797 }
6798
6799 SDValue DAGCombiner::visitFADD(SDNode *N) {
6800   SDValue N0 = N->getOperand(0);
6801   SDValue N1 = N->getOperand(1);
6802   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6803   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6804   EVT VT = N->getValueType(0);
6805   const TargetOptions &Options = DAG.getTarget().Options;
6806
6807   // fold vector ops
6808   if (VT.isVector()) {
6809     SDValue FoldedVOp = SimplifyVBinOp(N);
6810     if (FoldedVOp.getNode()) return FoldedVOp;
6811   }
6812
6813   // fold (fadd c1, c2) -> c1 + c2
6814   if (N0CFP && N1CFP)
6815     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6816
6817   // canonicalize constant to RHS
6818   if (N0CFP && !N1CFP)
6819     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6820
6821   // fold (fadd A, (fneg B)) -> (fsub A, B)
6822   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6823       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6824     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6825                        GetNegatedExpression(N1, DAG, LegalOperations));
6826
6827   // fold (fadd (fneg A), B) -> (fsub B, A)
6828   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6829       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6830     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6831                        GetNegatedExpression(N0, DAG, LegalOperations));
6832
6833   // If 'unsafe math' is enabled, fold lots of things.
6834   if (Options.UnsafeFPMath) {
6835     // No FP constant should be created after legalization as Instruction
6836     // Selection pass has a hard time dealing with FP constants.
6837     bool AllowNewConst = (Level < AfterLegalizeDAG);
6838
6839     // fold (fadd A, 0) -> A
6840     if (N1CFP && N1CFP->getValueAPF().isZero())
6841       return N0;
6842
6843     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6844     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6845         isa<ConstantFPSDNode>(N0.getOperand(1)))
6846       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6847                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6848                                      N0.getOperand(1), N1));
6849
6850     // If allowed, fold (fadd (fneg x), x) -> 0.0
6851     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6852       return DAG.getConstantFP(0.0, VT);
6853
6854     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6855     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6856       return DAG.getConstantFP(0.0, VT);
6857
6858     // We can fold chains of FADD's of the same value into multiplications.
6859     // This transform is not safe in general because we are reducing the number
6860     // of rounding steps.
6861     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6862       if (N0.getOpcode() == ISD::FMUL) {
6863         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6864         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6865
6866         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6867         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6868           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6869                                        SDValue(CFP01, 0),
6870                                        DAG.getConstantFP(1.0, VT));
6871           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6872         }
6873
6874         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6875         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6876             N1.getOperand(0) == N1.getOperand(1) &&
6877             N0.getOperand(0) == N1.getOperand(0)) {
6878           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6879                                        SDValue(CFP01, 0),
6880                                        DAG.getConstantFP(2.0, VT));
6881           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6882                              N0.getOperand(0), NewCFP);
6883         }
6884       }
6885
6886       if (N1.getOpcode() == ISD::FMUL) {
6887         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6888         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6889
6890         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6891         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6892           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6893                                        SDValue(CFP11, 0),
6894                                        DAG.getConstantFP(1.0, VT));
6895           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6896         }
6897
6898         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6899         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6900             N0.getOperand(0) == N0.getOperand(1) &&
6901             N1.getOperand(0) == N0.getOperand(0)) {
6902           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6903                                        SDValue(CFP11, 0),
6904                                        DAG.getConstantFP(2.0, VT));
6905           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6906         }
6907       }
6908
6909       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6910         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6911         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6912         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6913             (N0.getOperand(0) == N1))
6914           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6915                              N1, DAG.getConstantFP(3.0, VT));
6916       }
6917
6918       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6919         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6920         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6921         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6922             N1.getOperand(0) == N0)
6923           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6924                              N0, DAG.getConstantFP(3.0, VT));
6925       }
6926
6927       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6928       if (AllowNewConst &&
6929           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6930           N0.getOperand(0) == N0.getOperand(1) &&
6931           N1.getOperand(0) == N1.getOperand(1) &&
6932           N0.getOperand(0) == N1.getOperand(0))
6933         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6934                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6935     }
6936   } // enable-unsafe-fp-math
6937
6938   // FADD -> FMA combines:
6939   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6940       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6941       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6942
6943     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6944     if (N0.getOpcode() == ISD::FMUL &&
6945         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6946       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6947                          N0.getOperand(0), N0.getOperand(1), N1);
6948
6949     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6950     // Note: Commutes FADD operands.
6951     if (N1.getOpcode() == ISD::FMUL &&
6952         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6953       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6954                          N1.getOperand(0), N1.getOperand(1), N0);
6955
6956     // When FP_EXTEND nodes are free on the target, and there is an opportunity
6957     // to combine into FMA, arrange such nodes accordingly.
6958     if (TLI.isFPExtFree(VT)) {
6959
6960       // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
6961       if (N0.getOpcode() == ISD::FP_EXTEND) {
6962         SDValue N00 = N0.getOperand(0);
6963         if (N00.getOpcode() == ISD::FMUL)
6964           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6965                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6966                                          N00.getOperand(0)),
6967                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6968                                          N00.getOperand(1)), N1);
6969       }
6970
6971       // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
6972       // Note: Commutes FADD operands.
6973       if (N1.getOpcode() == ISD::FP_EXTEND) {
6974         SDValue N10 = N1.getOperand(0);
6975         if (N10.getOpcode() == ISD::FMUL)
6976           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6977                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6978                                          N10.getOperand(0)),
6979                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6980                                          N10.getOperand(1)), N0);
6981       }
6982     }
6983
6984     // More folding opportunities when target permits.
6985     if (TLI.enableAggressiveFMAFusion(VT)) {
6986
6987       // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
6988       if (N0.getOpcode() == ISD::FMA &&
6989           N0.getOperand(2).getOpcode() == ISD::FMUL)
6990         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6991                            N0.getOperand(0), N0.getOperand(1),
6992                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
6993                                        N0.getOperand(2).getOperand(0),
6994                                        N0.getOperand(2).getOperand(1),
6995                                        N1));
6996
6997       // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
6998       if (N1->getOpcode() == ISD::FMA &&
6999           N1.getOperand(2).getOpcode() == ISD::FMUL)
7000         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7001                            N1.getOperand(0), N1.getOperand(1),
7002                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7003                                        N1.getOperand(2).getOperand(0),
7004                                        N1.getOperand(2).getOperand(1),
7005                                        N0));
7006     }
7007   }
7008
7009   return SDValue();
7010 }
7011
7012 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7013   SDValue N0 = N->getOperand(0);
7014   SDValue N1 = N->getOperand(1);
7015   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7016   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7017   EVT VT = N->getValueType(0);
7018   SDLoc dl(N);
7019   const TargetOptions &Options = DAG.getTarget().Options;
7020
7021   // fold vector ops
7022   if (VT.isVector()) {
7023     SDValue FoldedVOp = SimplifyVBinOp(N);
7024     if (FoldedVOp.getNode()) return FoldedVOp;
7025   }
7026
7027   // fold (fsub c1, c2) -> c1-c2
7028   if (N0CFP && N1CFP)
7029     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7030
7031   // fold (fsub A, (fneg B)) -> (fadd A, B)
7032   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7033     return DAG.getNode(ISD::FADD, dl, VT, N0,
7034                        GetNegatedExpression(N1, DAG, LegalOperations));
7035
7036   // If 'unsafe math' is enabled, fold lots of things.
7037   if (Options.UnsafeFPMath) {
7038     // (fsub A, 0) -> A
7039     if (N1CFP && N1CFP->getValueAPF().isZero())
7040       return N0;
7041
7042     // (fsub 0, B) -> -B
7043     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7044       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7045         return GetNegatedExpression(N1, DAG, LegalOperations);
7046       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7047         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7048     }
7049
7050     // (fsub x, x) -> 0.0
7051     if (N0 == N1)
7052       return DAG.getConstantFP(0.0f, VT);
7053
7054     // (fsub x, (fadd x, y)) -> (fneg y)
7055     // (fsub x, (fadd y, x)) -> (fneg y)
7056     if (N1.getOpcode() == ISD::FADD) {
7057       SDValue N10 = N1->getOperand(0);
7058       SDValue N11 = N1->getOperand(1);
7059
7060       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7061         return GetNegatedExpression(N11, DAG, LegalOperations);
7062
7063       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7064         return GetNegatedExpression(N10, DAG, LegalOperations);
7065     }
7066   }
7067
7068   // FSUB -> FMA combines:
7069   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7070       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7071       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7072
7073     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7074     if (N0.getOpcode() == ISD::FMUL &&
7075         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7076       return DAG.getNode(ISD::FMA, dl, VT,
7077                          N0.getOperand(0), N0.getOperand(1),
7078                          DAG.getNode(ISD::FNEG, dl, VT, N1));
7079
7080     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7081     // Note: Commutes FSUB operands.
7082     if (N1.getOpcode() == ISD::FMUL &&
7083         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7084       return DAG.getNode(ISD::FMA, dl, VT,
7085                          DAG.getNode(ISD::FNEG, dl, VT,
7086                          N1.getOperand(0)),
7087                          N1.getOperand(1), N0);
7088
7089     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7090     if (N0.getOpcode() == ISD::FNEG &&
7091         N0.getOperand(0).getOpcode() == ISD::FMUL &&
7092         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
7093             TLI.enableAggressiveFMAFusion(VT))) {
7094       SDValue N00 = N0.getOperand(0).getOperand(0);
7095       SDValue N01 = N0.getOperand(0).getOperand(1);
7096       return DAG.getNode(ISD::FMA, dl, VT,
7097                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
7098                          DAG.getNode(ISD::FNEG, dl, VT, N1));
7099     }
7100
7101     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7102     // to combine into FMA, arrange such nodes accordingly.
7103     if (TLI.isFPExtFree(VT)) {
7104
7105       // fold (fsub (fpext (fmul x, y)), z)
7106       //   -> (fma (fpext x), (fpext y), (fneg z))
7107       if (N0.getOpcode() == ISD::FP_EXTEND) {
7108         SDValue N00 = N0.getOperand(0);
7109         if (N00.getOpcode() == ISD::FMUL)
7110           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7111                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7112                                          N00.getOperand(0)),
7113                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7114                                          N00.getOperand(1)),
7115                              DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7116       }
7117
7118       // fold (fsub x, (fpext (fmul y, z)))
7119       //   -> (fma (fneg (fpext y)), (fpext z), x)
7120       // Note: Commutes FSUB operands.
7121       if (N1.getOpcode() == ISD::FP_EXTEND) {
7122         SDValue N10 = N1.getOperand(0);
7123         if (N10.getOpcode() == ISD::FMUL)
7124           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7125                              DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7126                                          DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7127                                                      VT, N10.getOperand(0))),
7128                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7129                                          N10.getOperand(1)),
7130                              N0);
7131       }
7132
7133       // fold (fsub (fpext (fneg (fmul, x, y))), z)
7134       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7135       if (N0.getOpcode() == ISD::FP_EXTEND) {
7136         SDValue N00 = N0.getOperand(0);
7137         if (N00.getOpcode() == ISD::FNEG) {
7138           SDValue N000 = N00.getOperand(0);
7139           if (N000.getOpcode() == ISD::FMUL) {
7140             return DAG.getNode(ISD::FMA, dl, VT,
7141                                DAG.getNode(ISD::FNEG, dl, VT,
7142                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7143                                                        VT, N000.getOperand(0))),
7144                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7145                                            N000.getOperand(1)),
7146                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7147           }
7148         }
7149       }
7150
7151       // fold (fsub (fneg (fpext (fmul, x, y))), z)
7152       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7153       if (N0.getOpcode() == ISD::FNEG) {
7154         SDValue N00 = N0.getOperand(0);
7155         if (N00.getOpcode() == ISD::FP_EXTEND) {
7156           SDValue N000 = N00.getOperand(0);
7157           if (N000.getOpcode() == ISD::FMUL) {
7158             return DAG.getNode(ISD::FMA, dl, VT,
7159                                DAG.getNode(ISD::FNEG, dl, VT,
7160                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7161                                            VT, N000.getOperand(0))),
7162                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7163                                            N000.getOperand(1)),
7164                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7165           }
7166         }
7167       }
7168     }
7169
7170     // More folding opportunities when target permits.
7171     if (TLI.enableAggressiveFMAFusion(VT)) {
7172
7173       // fold (fsub (fma x, y, (fmul u, v)), z)
7174       //   -> (fma x, y (fma u, v, (fneg z)))
7175       if (N0.getOpcode() == ISD::FMA &&
7176           N0.getOperand(2).getOpcode() == ISD::FMUL)
7177         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7178                            N0.getOperand(0), N0.getOperand(1),
7179                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7180                                        N0.getOperand(2).getOperand(0),
7181                                        N0.getOperand(2).getOperand(1),
7182                                        DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7183                                                    N1)));
7184
7185       // fold (fsub x, (fma y, z, (fmul u, v)))
7186       //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7187       if (N1.getOpcode() == ISD::FMA &&
7188           N1.getOperand(2).getOpcode() == ISD::FMUL) {
7189         SDValue N20 = N1.getOperand(2).getOperand(0);
7190         SDValue N21 = N1.getOperand(2).getOperand(1);
7191         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7192                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7193                                        N1.getOperand(0)),
7194                            N1.getOperand(1),
7195                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7196                                        DAG.getNode(ISD::FNEG, SDLoc(N),  VT,
7197                                                    N20),
7198                                        N21, N0));
7199       }
7200     }
7201   }
7202
7203   return SDValue();
7204 }
7205
7206 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7207   SDValue N0 = N->getOperand(0);
7208   SDValue N1 = N->getOperand(1);
7209   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7210   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7211   EVT VT = N->getValueType(0);
7212   const TargetOptions &Options = DAG.getTarget().Options;
7213
7214   // fold vector ops
7215   if (VT.isVector()) {
7216     // This just handles C1 * C2 for vectors. Other vector folds are below.
7217     SDValue FoldedVOp = SimplifyVBinOp(N);
7218     if (FoldedVOp.getNode())
7219       return FoldedVOp;
7220     // Canonicalize vector constant to RHS.
7221     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7222         N1.getOpcode() != ISD::BUILD_VECTOR)
7223       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7224         if (BV0->isConstant())
7225           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7226   }
7227
7228   // fold (fmul c1, c2) -> c1*c2
7229   if (N0CFP && N1CFP)
7230     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7231
7232   // canonicalize constant to RHS
7233   if (N0CFP && !N1CFP)
7234     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7235
7236   // fold (fmul A, 1.0) -> A
7237   if (N1CFP && N1CFP->isExactlyValue(1.0))
7238     return N0;
7239
7240   if (Options.UnsafeFPMath) {
7241     // fold (fmul A, 0) -> 0
7242     if (N1CFP && N1CFP->getValueAPF().isZero())
7243       return N1;
7244
7245     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7246     if (N0.getOpcode() == ISD::FMUL) {
7247       // Fold scalars or any vector constants (not just splats).
7248       // This fold is done in general by InstCombine, but extra fmul insts
7249       // may have been generated during lowering.
7250       SDValue N01 = N0.getOperand(1);
7251       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7252       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7253       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7254           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7255         SDLoc SL(N);
7256         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7257         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7258       }
7259     }
7260
7261     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7262     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7263     // during an early run of DAGCombiner can prevent folding with fmuls
7264     // inserted during lowering.
7265     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7266       SDLoc SL(N);
7267       const SDValue Two = DAG.getConstantFP(2.0, VT);
7268       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7269       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7270     }
7271   }
7272
7273   // fold (fmul X, 2.0) -> (fadd X, X)
7274   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7275     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7276
7277   // fold (fmul X, -1.0) -> (fneg X)
7278   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7279     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7280       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7281
7282   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7283   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7284     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7285       // Both can be negated for free, check to see if at least one is cheaper
7286       // negated.
7287       if (LHSNeg == 2 || RHSNeg == 2)
7288         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7289                            GetNegatedExpression(N0, DAG, LegalOperations),
7290                            GetNegatedExpression(N1, DAG, LegalOperations));
7291     }
7292   }
7293
7294   return SDValue();
7295 }
7296
7297 SDValue DAGCombiner::visitFMA(SDNode *N) {
7298   SDValue N0 = N->getOperand(0);
7299   SDValue N1 = N->getOperand(1);
7300   SDValue N2 = N->getOperand(2);
7301   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7302   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7303   EVT VT = N->getValueType(0);
7304   SDLoc dl(N);
7305   const TargetOptions &Options = DAG.getTarget().Options;
7306
7307   // Constant fold FMA.
7308   if (isa<ConstantFPSDNode>(N0) &&
7309       isa<ConstantFPSDNode>(N1) &&
7310       isa<ConstantFPSDNode>(N2)) {
7311     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7312   }
7313
7314   if (Options.UnsafeFPMath) {
7315     if (N0CFP && N0CFP->isZero())
7316       return N2;
7317     if (N1CFP && N1CFP->isZero())
7318       return N2;
7319   }
7320   if (N0CFP && N0CFP->isExactlyValue(1.0))
7321     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7322   if (N1CFP && N1CFP->isExactlyValue(1.0))
7323     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7324
7325   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7326   if (N0CFP && !N1CFP)
7327     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7328
7329   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7330   if (Options.UnsafeFPMath && N1CFP &&
7331       N2.getOpcode() == ISD::FMUL &&
7332       N0 == N2.getOperand(0) &&
7333       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7334     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7335                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7336   }
7337
7338
7339   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7340   if (Options.UnsafeFPMath &&
7341       N0.getOpcode() == ISD::FMUL && N1CFP &&
7342       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7343     return DAG.getNode(ISD::FMA, dl, VT,
7344                        N0.getOperand(0),
7345                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7346                        N2);
7347   }
7348
7349   // (fma x, 1, y) -> (fadd x, y)
7350   // (fma x, -1, y) -> (fadd (fneg x), y)
7351   if (N1CFP) {
7352     if (N1CFP->isExactlyValue(1.0))
7353       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7354
7355     if (N1CFP->isExactlyValue(-1.0) &&
7356         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7357       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7358       AddToWorklist(RHSNeg.getNode());
7359       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7360     }
7361   }
7362
7363   // (fma x, c, x) -> (fmul x, (c+1))
7364   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7365     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7366                        DAG.getNode(ISD::FADD, dl, VT,
7367                                    N1, DAG.getConstantFP(1.0, VT)));
7368
7369   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7370   if (Options.UnsafeFPMath && N1CFP &&
7371       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7372     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7373                        DAG.getNode(ISD::FADD, dl, VT,
7374                                    N1, DAG.getConstantFP(-1.0, VT)));
7375
7376
7377   return SDValue();
7378 }
7379
7380 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7381   SDValue N0 = N->getOperand(0);
7382   SDValue N1 = N->getOperand(1);
7383   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7384   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7385   EVT VT = N->getValueType(0);
7386   SDLoc DL(N);
7387   const TargetOptions &Options = DAG.getTarget().Options;
7388
7389   // fold vector ops
7390   if (VT.isVector()) {
7391     SDValue FoldedVOp = SimplifyVBinOp(N);
7392     if (FoldedVOp.getNode()) return FoldedVOp;
7393   }
7394
7395   // fold (fdiv c1, c2) -> c1/c2
7396   if (N0CFP && N1CFP)
7397     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7398
7399   if (Options.UnsafeFPMath) {
7400     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7401     if (N1CFP) {
7402       // Compute the reciprocal 1.0 / c2.
7403       APFloat N1APF = N1CFP->getValueAPF();
7404       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7405       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7406       // Only do the transform if the reciprocal is a legal fp immediate that
7407       // isn't too nasty (eg NaN, denormal, ...).
7408       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7409           (!LegalOperations ||
7410            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7411            // backend)... we should handle this gracefully after Legalize.
7412            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7413            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7414            TLI.isFPImmLegal(Recip, VT)))
7415         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7416                            DAG.getConstantFP(Recip, VT));
7417     }
7418
7419     // If this FDIV is part of a reciprocal square root, it may be folded
7420     // into a target-specific square root estimate instruction.
7421     if (N1.getOpcode() == ISD::FSQRT) {
7422       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7423         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7424       }
7425     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7426                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7427       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7428         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7429         AddToWorklist(RV.getNode());
7430         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7431       }
7432     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7433                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7434       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7435         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7436         AddToWorklist(RV.getNode());
7437         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7438       }
7439     } else if (N1.getOpcode() == ISD::FMUL) {
7440       // Look through an FMUL. Even though this won't remove the FDIV directly,
7441       // it's still worthwhile to get rid of the FSQRT if possible.
7442       SDValue SqrtOp;
7443       SDValue OtherOp;
7444       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7445         SqrtOp = N1.getOperand(0);
7446         OtherOp = N1.getOperand(1);
7447       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7448         SqrtOp = N1.getOperand(1);
7449         OtherOp = N1.getOperand(0);
7450       }
7451       if (SqrtOp.getNode()) {
7452         // We found a FSQRT, so try to make this fold:
7453         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7454         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7455           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7456           AddToWorklist(RV.getNode());
7457           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7458         }
7459       }
7460     }
7461
7462     // Fold into a reciprocal estimate and multiply instead of a real divide.
7463     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7464       AddToWorklist(RV.getNode());
7465       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7466     }
7467   }
7468
7469   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7470   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7471     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7472       // Both can be negated for free, check to see if at least one is cheaper
7473       // negated.
7474       if (LHSNeg == 2 || RHSNeg == 2)
7475         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7476                            GetNegatedExpression(N0, DAG, LegalOperations),
7477                            GetNegatedExpression(N1, DAG, LegalOperations));
7478     }
7479   }
7480
7481   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7482   // reciprocal.
7483   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7484   // Notice that this is not always beneficial. One reason is different target
7485   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7486   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7487   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7488   if (Options.UnsafeFPMath) {
7489     // Skip if current node is a reciprocal.
7490     if (N0CFP && N0CFP->isExactlyValue(1.0))
7491       return SDValue();
7492
7493     SmallVector<SDNode *, 4> Users;
7494     // Find all FDIV users of the same divisor.
7495     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7496                               UE = N1.getNode()->use_end();
7497          UI != UE; ++UI) {
7498       SDNode *User = UI.getUse().getUser();
7499       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7500         Users.push_back(User);
7501     }
7502
7503     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7504       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7505       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7506
7507       // Dividend / Divisor -> Dividend * Reciprocal
7508       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7509         if ((*I)->getOperand(0) != FPOne) {
7510           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7511                                         (*I)->getOperand(0), Reciprocal);
7512           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7513         }
7514       }
7515       return SDValue();
7516     }
7517   }
7518
7519   return SDValue();
7520 }
7521
7522 SDValue DAGCombiner::visitFREM(SDNode *N) {
7523   SDValue N0 = N->getOperand(0);
7524   SDValue N1 = N->getOperand(1);
7525   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7526   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7527   EVT VT = N->getValueType(0);
7528
7529   // fold (frem c1, c2) -> fmod(c1,c2)
7530   if (N0CFP && N1CFP)
7531     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7532
7533   return SDValue();
7534 }
7535
7536 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7537   if (DAG.getTarget().Options.UnsafeFPMath &&
7538       !TLI.isFsqrtCheap()) {
7539     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7540     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7541       EVT VT = RV.getValueType();
7542       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7543       AddToWorklist(RV.getNode());
7544
7545       // Unfortunately, RV is now NaN if the input was exactly 0.
7546       // Select out this case and force the answer to 0.
7547       SDValue Zero = DAG.getConstantFP(0.0, VT);
7548       SDValue ZeroCmp =
7549         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7550                      N->getOperand(0), Zero, ISD::SETEQ);
7551       AddToWorklist(ZeroCmp.getNode());
7552       AddToWorklist(RV.getNode());
7553
7554       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7555                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7556       return RV;
7557     }
7558   }
7559   return SDValue();
7560 }
7561
7562 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7563   SDValue N0 = N->getOperand(0);
7564   SDValue N1 = N->getOperand(1);
7565   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7566   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7567   EVT VT = N->getValueType(0);
7568
7569   if (N0CFP && N1CFP)  // Constant fold
7570     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7571
7572   if (N1CFP) {
7573     const APFloat& V = N1CFP->getValueAPF();
7574     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7575     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7576     if (!V.isNegative()) {
7577       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7578         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7579     } else {
7580       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7581         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7582                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7583     }
7584   }
7585
7586   // copysign(fabs(x), y) -> copysign(x, y)
7587   // copysign(fneg(x), y) -> copysign(x, y)
7588   // copysign(copysign(x,z), y) -> copysign(x, y)
7589   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7590       N0.getOpcode() == ISD::FCOPYSIGN)
7591     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7592                        N0.getOperand(0), N1);
7593
7594   // copysign(x, abs(y)) -> abs(x)
7595   if (N1.getOpcode() == ISD::FABS)
7596     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7597
7598   // copysign(x, copysign(y,z)) -> copysign(x, z)
7599   if (N1.getOpcode() == ISD::FCOPYSIGN)
7600     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7601                        N0, N1.getOperand(1));
7602
7603   // copysign(x, fp_extend(y)) -> copysign(x, y)
7604   // copysign(x, fp_round(y)) -> copysign(x, y)
7605   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7606     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7607                        N0, N1.getOperand(0));
7608
7609   return SDValue();
7610 }
7611
7612 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7613   SDValue N0 = N->getOperand(0);
7614   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7615   EVT VT = N->getValueType(0);
7616   EVT OpVT = N0.getValueType();
7617
7618   // fold (sint_to_fp c1) -> c1fp
7619   if (N0C &&
7620       // ...but only if the target supports immediate floating-point values
7621       (!LegalOperations ||
7622        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7623     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7624
7625   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7626   // but UINT_TO_FP is legal on this target, try to convert.
7627   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7628       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7629     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7630     if (DAG.SignBitIsZero(N0))
7631       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7632   }
7633
7634   // The next optimizations are desirable only if SELECT_CC can be lowered.
7635   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7636     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7637     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7638         !VT.isVector() &&
7639         (!LegalOperations ||
7640          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7641       SDValue Ops[] =
7642         { N0.getOperand(0), N0.getOperand(1),
7643           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7644           N0.getOperand(2) };
7645       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7646     }
7647
7648     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7649     //      (select_cc x, y, 1.0, 0.0,, cc)
7650     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7651         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7652         (!LegalOperations ||
7653          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7654       SDValue Ops[] =
7655         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7656           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7657           N0.getOperand(0).getOperand(2) };
7658       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7659     }
7660   }
7661
7662   return SDValue();
7663 }
7664
7665 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7666   SDValue N0 = N->getOperand(0);
7667   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7668   EVT VT = N->getValueType(0);
7669   EVT OpVT = N0.getValueType();
7670
7671   // fold (uint_to_fp c1) -> c1fp
7672   if (N0C &&
7673       // ...but only if the target supports immediate floating-point values
7674       (!LegalOperations ||
7675        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7676     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7677
7678   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7679   // but SINT_TO_FP is legal on this target, try to convert.
7680   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7681       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7682     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7683     if (DAG.SignBitIsZero(N0))
7684       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7685   }
7686
7687   // The next optimizations are desirable only if SELECT_CC can be lowered.
7688   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7689     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7690
7691     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7692         (!LegalOperations ||
7693          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7694       SDValue Ops[] =
7695         { N0.getOperand(0), N0.getOperand(1),
7696           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7697           N0.getOperand(2) };
7698       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7699     }
7700   }
7701
7702   return SDValue();
7703 }
7704
7705 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7706   SDValue N0 = N->getOperand(0);
7707   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7708   EVT VT = N->getValueType(0);
7709
7710   // fold (fp_to_sint c1fp) -> c1
7711   if (N0CFP)
7712     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7713
7714   return SDValue();
7715 }
7716
7717 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7718   SDValue N0 = N->getOperand(0);
7719   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7720   EVT VT = N->getValueType(0);
7721
7722   // fold (fp_to_uint c1fp) -> c1
7723   if (N0CFP)
7724     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7725
7726   return SDValue();
7727 }
7728
7729 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7730   SDValue N0 = N->getOperand(0);
7731   SDValue N1 = N->getOperand(1);
7732   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7733   EVT VT = N->getValueType(0);
7734
7735   // fold (fp_round c1fp) -> c1fp
7736   if (N0CFP)
7737     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7738
7739   // fold (fp_round (fp_extend x)) -> x
7740   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7741     return N0.getOperand(0);
7742
7743   // fold (fp_round (fp_round x)) -> (fp_round x)
7744   if (N0.getOpcode() == ISD::FP_ROUND) {
7745     // This is a value preserving truncation if both round's are.
7746     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7747                    N0.getNode()->getConstantOperandVal(1) == 1;
7748     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7749                        DAG.getIntPtrConstant(IsTrunc));
7750   }
7751
7752   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7753   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7754     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7755                               N0.getOperand(0), N1);
7756     AddToWorklist(Tmp.getNode());
7757     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7758                        Tmp, N0.getOperand(1));
7759   }
7760
7761   return SDValue();
7762 }
7763
7764 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7765   SDValue N0 = N->getOperand(0);
7766   EVT VT = N->getValueType(0);
7767   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7768   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7769
7770   // fold (fp_round_inreg c1fp) -> c1fp
7771   if (N0CFP && isTypeLegal(EVT)) {
7772     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7773     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7774   }
7775
7776   return SDValue();
7777 }
7778
7779 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7780   SDValue N0 = N->getOperand(0);
7781   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7782   EVT VT = N->getValueType(0);
7783
7784   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7785   if (N->hasOneUse() &&
7786       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7787     return SDValue();
7788
7789   // fold (fp_extend c1fp) -> c1fp
7790   if (N0CFP)
7791     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7792
7793   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7794   // value of X.
7795   if (N0.getOpcode() == ISD::FP_ROUND
7796       && N0.getNode()->getConstantOperandVal(1) == 1) {
7797     SDValue In = N0.getOperand(0);
7798     if (In.getValueType() == VT) return In;
7799     if (VT.bitsLT(In.getValueType()))
7800       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7801                          In, N0.getOperand(1));
7802     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7803   }
7804
7805   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7806   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7807        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7808     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7809     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7810                                      LN0->getChain(),
7811                                      LN0->getBasePtr(), N0.getValueType(),
7812                                      LN0->getMemOperand());
7813     CombineTo(N, ExtLoad);
7814     CombineTo(N0.getNode(),
7815               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7816                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7817               ExtLoad.getValue(1));
7818     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7819   }
7820
7821   return SDValue();
7822 }
7823
7824 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7825   SDValue N0 = N->getOperand(0);
7826   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7827   EVT VT = N->getValueType(0);
7828
7829   // fold (fceil c1) -> fceil(c1)
7830   if (N0CFP)
7831     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7832
7833   return SDValue();
7834 }
7835
7836 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7837   SDValue N0 = N->getOperand(0);
7838   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7839   EVT VT = N->getValueType(0);
7840
7841   // fold (ftrunc c1) -> ftrunc(c1)
7842   if (N0CFP)
7843     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7844
7845   return SDValue();
7846 }
7847
7848 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7849   SDValue N0 = N->getOperand(0);
7850   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7851   EVT VT = N->getValueType(0);
7852
7853   // fold (ffloor c1) -> ffloor(c1)
7854   if (N0CFP)
7855     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7856
7857   return SDValue();
7858 }
7859
7860 // FIXME: FNEG and FABS have a lot in common; refactor.
7861 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7862   SDValue N0 = N->getOperand(0);
7863   EVT VT = N->getValueType(0);
7864
7865   if (VT.isVector()) {
7866     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7867     if (FoldedVOp.getNode()) return FoldedVOp;
7868   }
7869
7870   // Constant fold FNEG.
7871   if (isa<ConstantFPSDNode>(N0))
7872     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7873
7874   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7875                          &DAG.getTarget().Options))
7876     return GetNegatedExpression(N0, DAG, LegalOperations);
7877
7878   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7879   // constant pool values.
7880   if (!TLI.isFNegFree(VT) &&
7881       N0.getOpcode() == ISD::BITCAST &&
7882       N0.getNode()->hasOneUse()) {
7883     SDValue Int = N0.getOperand(0);
7884     EVT IntVT = Int.getValueType();
7885     if (IntVT.isInteger() && !IntVT.isVector()) {
7886       APInt SignMask;
7887       if (N0.getValueType().isVector()) {
7888         // For a vector, get a mask such as 0x80... per scalar element
7889         // and splat it.
7890         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7891         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7892       } else {
7893         // For a scalar, just generate 0x80...
7894         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7895       }
7896       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7897                         DAG.getConstant(SignMask, IntVT));
7898       AddToWorklist(Int.getNode());
7899       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7900     }
7901   }
7902
7903   // (fneg (fmul c, x)) -> (fmul -c, x)
7904   if (N0.getOpcode() == ISD::FMUL) {
7905     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7906     if (CFP1) {
7907       APFloat CVal = CFP1->getValueAPF();
7908       CVal.changeSign();
7909       if (Level >= AfterLegalizeDAG &&
7910           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7911            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7912         return DAG.getNode(
7913             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7914             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7915     }
7916   }
7917
7918   return SDValue();
7919 }
7920
7921 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7922   SDValue N0 = N->getOperand(0);
7923   SDValue N1 = N->getOperand(1);
7924   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7925   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7926
7927   if (N0CFP && N1CFP) {
7928     const APFloat &C0 = N0CFP->getValueAPF();
7929     const APFloat &C1 = N1CFP->getValueAPF();
7930     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7931   }
7932
7933   if (N0CFP) {
7934     EVT VT = N->getValueType(0);
7935     // Canonicalize to constant on RHS.
7936     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7937   }
7938
7939   return SDValue();
7940 }
7941
7942 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7943   SDValue N0 = N->getOperand(0);
7944   SDValue N1 = N->getOperand(1);
7945   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7946   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7947
7948   if (N0CFP && N1CFP) {
7949     const APFloat &C0 = N0CFP->getValueAPF();
7950     const APFloat &C1 = N1CFP->getValueAPF();
7951     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7952   }
7953
7954   if (N0CFP) {
7955     EVT VT = N->getValueType(0);
7956     // Canonicalize to constant on RHS.
7957     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7958   }
7959
7960   return SDValue();
7961 }
7962
7963 SDValue DAGCombiner::visitFABS(SDNode *N) {
7964   SDValue N0 = N->getOperand(0);
7965   EVT VT = N->getValueType(0);
7966
7967   if (VT.isVector()) {
7968     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7969     if (FoldedVOp.getNode()) return FoldedVOp;
7970   }
7971
7972   // fold (fabs c1) -> fabs(c1)
7973   if (isa<ConstantFPSDNode>(N0))
7974     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7975
7976   // fold (fabs (fabs x)) -> (fabs x)
7977   if (N0.getOpcode() == ISD::FABS)
7978     return N->getOperand(0);
7979
7980   // fold (fabs (fneg x)) -> (fabs x)
7981   // fold (fabs (fcopysign x, y)) -> (fabs x)
7982   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7983     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7984
7985   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7986   // constant pool values.
7987   if (!TLI.isFAbsFree(VT) &&
7988       N0.getOpcode() == ISD::BITCAST &&
7989       N0.getNode()->hasOneUse()) {
7990     SDValue Int = N0.getOperand(0);
7991     EVT IntVT = Int.getValueType();
7992     if (IntVT.isInteger() && !IntVT.isVector()) {
7993       APInt SignMask;
7994       if (N0.getValueType().isVector()) {
7995         // For a vector, get a mask such as 0x7f... per scalar element
7996         // and splat it.
7997         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7998         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7999       } else {
8000         // For a scalar, just generate 0x7f...
8001         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8002       }
8003       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8004                         DAG.getConstant(SignMask, IntVT));
8005       AddToWorklist(Int.getNode());
8006       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8007     }
8008   }
8009
8010   return SDValue();
8011 }
8012
8013 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8014   SDValue Chain = N->getOperand(0);
8015   SDValue N1 = N->getOperand(1);
8016   SDValue N2 = N->getOperand(2);
8017
8018   // If N is a constant we could fold this into a fallthrough or unconditional
8019   // branch. However that doesn't happen very often in normal code, because
8020   // Instcombine/SimplifyCFG should have handled the available opportunities.
8021   // If we did this folding here, it would be necessary to update the
8022   // MachineBasicBlock CFG, which is awkward.
8023
8024   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8025   // on the target.
8026   if (N1.getOpcode() == ISD::SETCC &&
8027       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8028                                    N1.getOperand(0).getValueType())) {
8029     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8030                        Chain, N1.getOperand(2),
8031                        N1.getOperand(0), N1.getOperand(1), N2);
8032   }
8033
8034   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8035       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8036        (N1.getOperand(0).hasOneUse() &&
8037         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8038     SDNode *Trunc = nullptr;
8039     if (N1.getOpcode() == ISD::TRUNCATE) {
8040       // Look pass the truncate.
8041       Trunc = N1.getNode();
8042       N1 = N1.getOperand(0);
8043     }
8044
8045     // Match this pattern so that we can generate simpler code:
8046     //
8047     //   %a = ...
8048     //   %b = and i32 %a, 2
8049     //   %c = srl i32 %b, 1
8050     //   brcond i32 %c ...
8051     //
8052     // into
8053     //
8054     //   %a = ...
8055     //   %b = and i32 %a, 2
8056     //   %c = setcc eq %b, 0
8057     //   brcond %c ...
8058     //
8059     // This applies only when the AND constant value has one bit set and the
8060     // SRL constant is equal to the log2 of the AND constant. The back-end is
8061     // smart enough to convert the result into a TEST/JMP sequence.
8062     SDValue Op0 = N1.getOperand(0);
8063     SDValue Op1 = N1.getOperand(1);
8064
8065     if (Op0.getOpcode() == ISD::AND &&
8066         Op1.getOpcode() == ISD::Constant) {
8067       SDValue AndOp1 = Op0.getOperand(1);
8068
8069       if (AndOp1.getOpcode() == ISD::Constant) {
8070         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8071
8072         if (AndConst.isPowerOf2() &&
8073             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8074           SDValue SetCC =
8075             DAG.getSetCC(SDLoc(N),
8076                          getSetCCResultType(Op0.getValueType()),
8077                          Op0, DAG.getConstant(0, Op0.getValueType()),
8078                          ISD::SETNE);
8079
8080           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8081                                           MVT::Other, Chain, SetCC, N2);
8082           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8083           // will convert it back to (X & C1) >> C2.
8084           CombineTo(N, NewBRCond, false);
8085           // Truncate is dead.
8086           if (Trunc)
8087             deleteAndRecombine(Trunc);
8088           // Replace the uses of SRL with SETCC
8089           WorklistRemover DeadNodes(*this);
8090           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8091           deleteAndRecombine(N1.getNode());
8092           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8093         }
8094       }
8095     }
8096
8097     if (Trunc)
8098       // Restore N1 if the above transformation doesn't match.
8099       N1 = N->getOperand(1);
8100   }
8101
8102   // Transform br(xor(x, y)) -> br(x != y)
8103   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8104   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8105     SDNode *TheXor = N1.getNode();
8106     SDValue Op0 = TheXor->getOperand(0);
8107     SDValue Op1 = TheXor->getOperand(1);
8108     if (Op0.getOpcode() == Op1.getOpcode()) {
8109       // Avoid missing important xor optimizations.
8110       SDValue Tmp = visitXOR(TheXor);
8111       if (Tmp.getNode()) {
8112         if (Tmp.getNode() != TheXor) {
8113           DEBUG(dbgs() << "\nReplacing.8 ";
8114                 TheXor->dump(&DAG);
8115                 dbgs() << "\nWith: ";
8116                 Tmp.getNode()->dump(&DAG);
8117                 dbgs() << '\n');
8118           WorklistRemover DeadNodes(*this);
8119           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8120           deleteAndRecombine(TheXor);
8121           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8122                              MVT::Other, Chain, Tmp, N2);
8123         }
8124
8125         // visitXOR has changed XOR's operands or replaced the XOR completely,
8126         // bail out.
8127         return SDValue(N, 0);
8128       }
8129     }
8130
8131     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8132       bool Equal = false;
8133       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8134         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8135             Op0.getOpcode() == ISD::XOR) {
8136           TheXor = Op0.getNode();
8137           Equal = true;
8138         }
8139
8140       EVT SetCCVT = N1.getValueType();
8141       if (LegalTypes)
8142         SetCCVT = getSetCCResultType(SetCCVT);
8143       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8144                                    SetCCVT,
8145                                    Op0, Op1,
8146                                    Equal ? ISD::SETEQ : ISD::SETNE);
8147       // Replace the uses of XOR with SETCC
8148       WorklistRemover DeadNodes(*this);
8149       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8150       deleteAndRecombine(N1.getNode());
8151       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8152                          MVT::Other, Chain, SetCC, N2);
8153     }
8154   }
8155
8156   return SDValue();
8157 }
8158
8159 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8160 //
8161 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8162   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8163   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8164
8165   // If N is a constant we could fold this into a fallthrough or unconditional
8166   // branch. However that doesn't happen very often in normal code, because
8167   // Instcombine/SimplifyCFG should have handled the available opportunities.
8168   // If we did this folding here, it would be necessary to update the
8169   // MachineBasicBlock CFG, which is awkward.
8170
8171   // Use SimplifySetCC to simplify SETCC's.
8172   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8173                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8174                                false);
8175   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8176
8177   // fold to a simpler setcc
8178   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8179     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8180                        N->getOperand(0), Simp.getOperand(2),
8181                        Simp.getOperand(0), Simp.getOperand(1),
8182                        N->getOperand(4));
8183
8184   return SDValue();
8185 }
8186
8187 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8188 /// and that N may be folded in the load / store addressing mode.
8189 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8190                                     SelectionDAG &DAG,
8191                                     const TargetLowering &TLI) {
8192   EVT VT;
8193   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8194     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8195       return false;
8196     VT = Use->getValueType(0);
8197   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8198     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8199       return false;
8200     VT = ST->getValue().getValueType();
8201   } else
8202     return false;
8203
8204   TargetLowering::AddrMode AM;
8205   if (N->getOpcode() == ISD::ADD) {
8206     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8207     if (Offset)
8208       // [reg +/- imm]
8209       AM.BaseOffs = Offset->getSExtValue();
8210     else
8211       // [reg +/- reg]
8212       AM.Scale = 1;
8213   } else if (N->getOpcode() == ISD::SUB) {
8214     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8215     if (Offset)
8216       // [reg +/- imm]
8217       AM.BaseOffs = -Offset->getSExtValue();
8218     else
8219       // [reg +/- reg]
8220       AM.Scale = 1;
8221   } else
8222     return false;
8223
8224   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8225 }
8226
8227 /// Try turning a load/store into a pre-indexed load/store when the base
8228 /// pointer is an add or subtract and it has other uses besides the load/store.
8229 /// After the transformation, the new indexed load/store has effectively folded
8230 /// the add/subtract in and all of its other uses are redirected to the
8231 /// new load/store.
8232 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8233   if (Level < AfterLegalizeDAG)
8234     return false;
8235
8236   bool isLoad = true;
8237   SDValue Ptr;
8238   EVT VT;
8239   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8240     if (LD->isIndexed())
8241       return false;
8242     VT = LD->getMemoryVT();
8243     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8244         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8245       return false;
8246     Ptr = LD->getBasePtr();
8247   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8248     if (ST->isIndexed())
8249       return false;
8250     VT = ST->getMemoryVT();
8251     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8252         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8253       return false;
8254     Ptr = ST->getBasePtr();
8255     isLoad = false;
8256   } else {
8257     return false;
8258   }
8259
8260   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8261   // out.  There is no reason to make this a preinc/predec.
8262   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8263       Ptr.getNode()->hasOneUse())
8264     return false;
8265
8266   // Ask the target to do addressing mode selection.
8267   SDValue BasePtr;
8268   SDValue Offset;
8269   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8270   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8271     return false;
8272
8273   // Backends without true r+i pre-indexed forms may need to pass a
8274   // constant base with a variable offset so that constant coercion
8275   // will work with the patterns in canonical form.
8276   bool Swapped = false;
8277   if (isa<ConstantSDNode>(BasePtr)) {
8278     std::swap(BasePtr, Offset);
8279     Swapped = true;
8280   }
8281
8282   // Don't create a indexed load / store with zero offset.
8283   if (isa<ConstantSDNode>(Offset) &&
8284       cast<ConstantSDNode>(Offset)->isNullValue())
8285     return false;
8286
8287   // Try turning it into a pre-indexed load / store except when:
8288   // 1) The new base ptr is a frame index.
8289   // 2) If N is a store and the new base ptr is either the same as or is a
8290   //    predecessor of the value being stored.
8291   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8292   //    that would create a cycle.
8293   // 4) All uses are load / store ops that use it as old base ptr.
8294
8295   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8296   // (plus the implicit offset) to a register to preinc anyway.
8297   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8298     return false;
8299
8300   // Check #2.
8301   if (!isLoad) {
8302     SDValue Val = cast<StoreSDNode>(N)->getValue();
8303     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8304       return false;
8305   }
8306
8307   // If the offset is a constant, there may be other adds of constants that
8308   // can be folded with this one. We should do this to avoid having to keep
8309   // a copy of the original base pointer.
8310   SmallVector<SDNode *, 16> OtherUses;
8311   if (isa<ConstantSDNode>(Offset))
8312     for (SDNode *Use : BasePtr.getNode()->uses()) {
8313       if (Use == Ptr.getNode())
8314         continue;
8315
8316       if (Use->isPredecessorOf(N))
8317         continue;
8318
8319       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8320         OtherUses.clear();
8321         break;
8322       }
8323
8324       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8325       if (Op1.getNode() == BasePtr.getNode())
8326         std::swap(Op0, Op1);
8327       assert(Op0.getNode() == BasePtr.getNode() &&
8328              "Use of ADD/SUB but not an operand");
8329
8330       if (!isa<ConstantSDNode>(Op1)) {
8331         OtherUses.clear();
8332         break;
8333       }
8334
8335       // FIXME: In some cases, we can be smarter about this.
8336       if (Op1.getValueType() != Offset.getValueType()) {
8337         OtherUses.clear();
8338         break;
8339       }
8340
8341       OtherUses.push_back(Use);
8342     }
8343
8344   if (Swapped)
8345     std::swap(BasePtr, Offset);
8346
8347   // Now check for #3 and #4.
8348   bool RealUse = false;
8349
8350   // Caches for hasPredecessorHelper
8351   SmallPtrSet<const SDNode *, 32> Visited;
8352   SmallVector<const SDNode *, 16> Worklist;
8353
8354   for (SDNode *Use : Ptr.getNode()->uses()) {
8355     if (Use == N)
8356       continue;
8357     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8358       return false;
8359
8360     // If Ptr may be folded in addressing mode of other use, then it's
8361     // not profitable to do this transformation.
8362     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8363       RealUse = true;
8364   }
8365
8366   if (!RealUse)
8367     return false;
8368
8369   SDValue Result;
8370   if (isLoad)
8371     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8372                                 BasePtr, Offset, AM);
8373   else
8374     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8375                                  BasePtr, Offset, AM);
8376   ++PreIndexedNodes;
8377   ++NodesCombined;
8378   DEBUG(dbgs() << "\nReplacing.4 ";
8379         N->dump(&DAG);
8380         dbgs() << "\nWith: ";
8381         Result.getNode()->dump(&DAG);
8382         dbgs() << '\n');
8383   WorklistRemover DeadNodes(*this);
8384   if (isLoad) {
8385     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8386     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8387   } else {
8388     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8389   }
8390
8391   // Finally, since the node is now dead, remove it from the graph.
8392   deleteAndRecombine(N);
8393
8394   if (Swapped)
8395     std::swap(BasePtr, Offset);
8396
8397   // Replace other uses of BasePtr that can be updated to use Ptr
8398   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8399     unsigned OffsetIdx = 1;
8400     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8401       OffsetIdx = 0;
8402     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8403            BasePtr.getNode() && "Expected BasePtr operand");
8404
8405     // We need to replace ptr0 in the following expression:
8406     //   x0 * offset0 + y0 * ptr0 = t0
8407     // knowing that
8408     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8409     //
8410     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8411     // indexed load/store and the expresion that needs to be re-written.
8412     //
8413     // Therefore, we have:
8414     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8415
8416     ConstantSDNode *CN =
8417       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8418     int X0, X1, Y0, Y1;
8419     APInt Offset0 = CN->getAPIntValue();
8420     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8421
8422     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8423     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8424     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8425     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8426
8427     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8428
8429     APInt CNV = Offset0;
8430     if (X0 < 0) CNV = -CNV;
8431     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8432     else CNV = CNV - Offset1;
8433
8434     // We can now generate the new expression.
8435     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8436     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8437
8438     SDValue NewUse = DAG.getNode(Opcode,
8439                                  SDLoc(OtherUses[i]),
8440                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8441     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8442     deleteAndRecombine(OtherUses[i]);
8443   }
8444
8445   // Replace the uses of Ptr with uses of the updated base value.
8446   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8447   deleteAndRecombine(Ptr.getNode());
8448
8449   return true;
8450 }
8451
8452 /// Try to combine a load/store with a add/sub of the base pointer node into a
8453 /// post-indexed load/store. The transformation folded the add/subtract into the
8454 /// new indexed load/store effectively and all of its uses are redirected to the
8455 /// new load/store.
8456 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8457   if (Level < AfterLegalizeDAG)
8458     return false;
8459
8460   bool isLoad = true;
8461   SDValue Ptr;
8462   EVT VT;
8463   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8464     if (LD->isIndexed())
8465       return false;
8466     VT = LD->getMemoryVT();
8467     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8468         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8469       return false;
8470     Ptr = LD->getBasePtr();
8471   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8472     if (ST->isIndexed())
8473       return false;
8474     VT = ST->getMemoryVT();
8475     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8476         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8477       return false;
8478     Ptr = ST->getBasePtr();
8479     isLoad = false;
8480   } else {
8481     return false;
8482   }
8483
8484   if (Ptr.getNode()->hasOneUse())
8485     return false;
8486
8487   for (SDNode *Op : Ptr.getNode()->uses()) {
8488     if (Op == N ||
8489         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8490       continue;
8491
8492     SDValue BasePtr;
8493     SDValue Offset;
8494     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8495     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8496       // Don't create a indexed load / store with zero offset.
8497       if (isa<ConstantSDNode>(Offset) &&
8498           cast<ConstantSDNode>(Offset)->isNullValue())
8499         continue;
8500
8501       // Try turning it into a post-indexed load / store except when
8502       // 1) All uses are load / store ops that use it as base ptr (and
8503       //    it may be folded as addressing mmode).
8504       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8505       //    nor a successor of N. Otherwise, if Op is folded that would
8506       //    create a cycle.
8507
8508       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8509         continue;
8510
8511       // Check for #1.
8512       bool TryNext = false;
8513       for (SDNode *Use : BasePtr.getNode()->uses()) {
8514         if (Use == Ptr.getNode())
8515           continue;
8516
8517         // If all the uses are load / store addresses, then don't do the
8518         // transformation.
8519         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8520           bool RealUse = false;
8521           for (SDNode *UseUse : Use->uses()) {
8522             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8523               RealUse = true;
8524           }
8525
8526           if (!RealUse) {
8527             TryNext = true;
8528             break;
8529           }
8530         }
8531       }
8532
8533       if (TryNext)
8534         continue;
8535
8536       // Check for #2
8537       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8538         SDValue Result = isLoad
8539           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8540                                BasePtr, Offset, AM)
8541           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8542                                 BasePtr, Offset, AM);
8543         ++PostIndexedNodes;
8544         ++NodesCombined;
8545         DEBUG(dbgs() << "\nReplacing.5 ";
8546               N->dump(&DAG);
8547               dbgs() << "\nWith: ";
8548               Result.getNode()->dump(&DAG);
8549               dbgs() << '\n');
8550         WorklistRemover DeadNodes(*this);
8551         if (isLoad) {
8552           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8553           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8554         } else {
8555           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8556         }
8557
8558         // Finally, since the node is now dead, remove it from the graph.
8559         deleteAndRecombine(N);
8560
8561         // Replace the uses of Use with uses of the updated base value.
8562         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8563                                       Result.getValue(isLoad ? 1 : 0));
8564         deleteAndRecombine(Op);
8565         return true;
8566       }
8567     }
8568   }
8569
8570   return false;
8571 }
8572
8573 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8574 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8575   ISD::MemIndexedMode AM = LD->getAddressingMode();
8576   assert(AM != ISD::UNINDEXED);
8577   SDValue BP = LD->getOperand(1);
8578   SDValue Inc = LD->getOperand(2);
8579
8580   // Some backends use TargetConstants for load offsets, but don't expect
8581   // TargetConstants in general ADD nodes. We can convert these constants into
8582   // regular Constants (if the constant is not opaque).
8583   assert((Inc.getOpcode() != ISD::TargetConstant ||
8584           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8585          "Cannot split out indexing using opaque target constants");
8586   if (Inc.getOpcode() == ISD::TargetConstant) {
8587     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8588     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8589                           ConstInc->getValueType(0));
8590   }
8591
8592   unsigned Opc =
8593       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8594   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8595 }
8596
8597 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8598   LoadSDNode *LD  = cast<LoadSDNode>(N);
8599   SDValue Chain = LD->getChain();
8600   SDValue Ptr   = LD->getBasePtr();
8601
8602   // If load is not volatile and there are no uses of the loaded value (and
8603   // the updated indexed value in case of indexed loads), change uses of the
8604   // chain value into uses of the chain input (i.e. delete the dead load).
8605   if (!LD->isVolatile()) {
8606     if (N->getValueType(1) == MVT::Other) {
8607       // Unindexed loads.
8608       if (!N->hasAnyUseOfValue(0)) {
8609         // It's not safe to use the two value CombineTo variant here. e.g.
8610         // v1, chain2 = load chain1, loc
8611         // v2, chain3 = load chain2, loc
8612         // v3         = add v2, c
8613         // Now we replace use of chain2 with chain1.  This makes the second load
8614         // isomorphic to the one we are deleting, and thus makes this load live.
8615         DEBUG(dbgs() << "\nReplacing.6 ";
8616               N->dump(&DAG);
8617               dbgs() << "\nWith chain: ";
8618               Chain.getNode()->dump(&DAG);
8619               dbgs() << "\n");
8620         WorklistRemover DeadNodes(*this);
8621         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8622
8623         if (N->use_empty())
8624           deleteAndRecombine(N);
8625
8626         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8627       }
8628     } else {
8629       // Indexed loads.
8630       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8631
8632       // If this load has an opaque TargetConstant offset, then we cannot split
8633       // the indexing into an add/sub directly (that TargetConstant may not be
8634       // valid for a different type of node, and we cannot convert an opaque
8635       // target constant into a regular constant).
8636       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8637                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8638
8639       if (!N->hasAnyUseOfValue(0) &&
8640           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8641         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8642         SDValue Index;
8643         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8644           Index = SplitIndexingFromLoad(LD);
8645           // Try to fold the base pointer arithmetic into subsequent loads and
8646           // stores.
8647           AddUsersToWorklist(N);
8648         } else
8649           Index = DAG.getUNDEF(N->getValueType(1));
8650         DEBUG(dbgs() << "\nReplacing.7 ";
8651               N->dump(&DAG);
8652               dbgs() << "\nWith: ";
8653               Undef.getNode()->dump(&DAG);
8654               dbgs() << " and 2 other values\n");
8655         WorklistRemover DeadNodes(*this);
8656         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8657         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8658         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8659         deleteAndRecombine(N);
8660         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8661       }
8662     }
8663   }
8664
8665   // If this load is directly stored, replace the load value with the stored
8666   // value.
8667   // TODO: Handle store large -> read small portion.
8668   // TODO: Handle TRUNCSTORE/LOADEXT
8669   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8670     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8671       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8672       if (PrevST->getBasePtr() == Ptr &&
8673           PrevST->getValue().getValueType() == N->getValueType(0))
8674       return CombineTo(N, Chain.getOperand(1), Chain);
8675     }
8676   }
8677
8678   // Try to infer better alignment information than the load already has.
8679   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8680     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8681       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8682         SDValue NewLoad =
8683                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8684                               LD->getValueType(0),
8685                               Chain, Ptr, LD->getPointerInfo(),
8686                               LD->getMemoryVT(),
8687                               LD->isVolatile(), LD->isNonTemporal(),
8688                               LD->isInvariant(), Align, LD->getAAInfo());
8689         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8690       }
8691     }
8692   }
8693
8694   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8695                                                   : DAG.getSubtarget().useAA();
8696 #ifndef NDEBUG
8697   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8698       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8699     UseAA = false;
8700 #endif
8701   if (UseAA && LD->isUnindexed()) {
8702     // Walk up chain skipping non-aliasing memory nodes.
8703     SDValue BetterChain = FindBetterChain(N, Chain);
8704
8705     // If there is a better chain.
8706     if (Chain != BetterChain) {
8707       SDValue ReplLoad;
8708
8709       // Replace the chain to void dependency.
8710       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8711         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8712                                BetterChain, Ptr, LD->getMemOperand());
8713       } else {
8714         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8715                                   LD->getValueType(0),
8716                                   BetterChain, Ptr, LD->getMemoryVT(),
8717                                   LD->getMemOperand());
8718       }
8719
8720       // Create token factor to keep old chain connected.
8721       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8722                                   MVT::Other, Chain, ReplLoad.getValue(1));
8723
8724       // Make sure the new and old chains are cleaned up.
8725       AddToWorklist(Token.getNode());
8726
8727       // Replace uses with load result and token factor. Don't add users
8728       // to work list.
8729       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8730     }
8731   }
8732
8733   // Try transforming N to an indexed load.
8734   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8735     return SDValue(N, 0);
8736
8737   // Try to slice up N to more direct loads if the slices are mapped to
8738   // different register banks or pairing can take place.
8739   if (SliceUpLoad(N))
8740     return SDValue(N, 0);
8741
8742   return SDValue();
8743 }
8744
8745 namespace {
8746 /// \brief Helper structure used to slice a load in smaller loads.
8747 /// Basically a slice is obtained from the following sequence:
8748 /// Origin = load Ty1, Base
8749 /// Shift = srl Ty1 Origin, CstTy Amount
8750 /// Inst = trunc Shift to Ty2
8751 ///
8752 /// Then, it will be rewriten into:
8753 /// Slice = load SliceTy, Base + SliceOffset
8754 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8755 ///
8756 /// SliceTy is deduced from the number of bits that are actually used to
8757 /// build Inst.
8758 struct LoadedSlice {
8759   /// \brief Helper structure used to compute the cost of a slice.
8760   struct Cost {
8761     /// Are we optimizing for code size.
8762     bool ForCodeSize;
8763     /// Various cost.
8764     unsigned Loads;
8765     unsigned Truncates;
8766     unsigned CrossRegisterBanksCopies;
8767     unsigned ZExts;
8768     unsigned Shift;
8769
8770     Cost(bool ForCodeSize = false)
8771         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8772           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8773
8774     /// \brief Get the cost of one isolated slice.
8775     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8776         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8777           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8778       EVT TruncType = LS.Inst->getValueType(0);
8779       EVT LoadedType = LS.getLoadedType();
8780       if (TruncType != LoadedType &&
8781           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8782         ZExts = 1;
8783     }
8784
8785     /// \brief Account for slicing gain in the current cost.
8786     /// Slicing provide a few gains like removing a shift or a
8787     /// truncate. This method allows to grow the cost of the original
8788     /// load with the gain from this slice.
8789     void addSliceGain(const LoadedSlice &LS) {
8790       // Each slice saves a truncate.
8791       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8792       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8793                               LS.Inst->getOperand(0).getValueType()))
8794         ++Truncates;
8795       // If there is a shift amount, this slice gets rid of it.
8796       if (LS.Shift)
8797         ++Shift;
8798       // If this slice can merge a cross register bank copy, account for it.
8799       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8800         ++CrossRegisterBanksCopies;
8801     }
8802
8803     Cost &operator+=(const Cost &RHS) {
8804       Loads += RHS.Loads;
8805       Truncates += RHS.Truncates;
8806       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8807       ZExts += RHS.ZExts;
8808       Shift += RHS.Shift;
8809       return *this;
8810     }
8811
8812     bool operator==(const Cost &RHS) const {
8813       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8814              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8815              ZExts == RHS.ZExts && Shift == RHS.Shift;
8816     }
8817
8818     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8819
8820     bool operator<(const Cost &RHS) const {
8821       // Assume cross register banks copies are as expensive as loads.
8822       // FIXME: Do we want some more target hooks?
8823       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8824       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8825       // Unless we are optimizing for code size, consider the
8826       // expensive operation first.
8827       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8828         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8829       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8830              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8831     }
8832
8833     bool operator>(const Cost &RHS) const { return RHS < *this; }
8834
8835     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8836
8837     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8838   };
8839   // The last instruction that represent the slice. This should be a
8840   // truncate instruction.
8841   SDNode *Inst;
8842   // The original load instruction.
8843   LoadSDNode *Origin;
8844   // The right shift amount in bits from the original load.
8845   unsigned Shift;
8846   // The DAG from which Origin came from.
8847   // This is used to get some contextual information about legal types, etc.
8848   SelectionDAG *DAG;
8849
8850   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8851               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8852       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8853
8854   LoadedSlice(const LoadedSlice &LS)
8855       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8856
8857   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8858   /// \return Result is \p BitWidth and has used bits set to 1 and
8859   ///         not used bits set to 0.
8860   APInt getUsedBits() const {
8861     // Reproduce the trunc(lshr) sequence:
8862     // - Start from the truncated value.
8863     // - Zero extend to the desired bit width.
8864     // - Shift left.
8865     assert(Origin && "No original load to compare against.");
8866     unsigned BitWidth = Origin->getValueSizeInBits(0);
8867     assert(Inst && "This slice is not bound to an instruction");
8868     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8869            "Extracted slice is bigger than the whole type!");
8870     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8871     UsedBits.setAllBits();
8872     UsedBits = UsedBits.zext(BitWidth);
8873     UsedBits <<= Shift;
8874     return UsedBits;
8875   }
8876
8877   /// \brief Get the size of the slice to be loaded in bytes.
8878   unsigned getLoadedSize() const {
8879     unsigned SliceSize = getUsedBits().countPopulation();
8880     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8881     return SliceSize / 8;
8882   }
8883
8884   /// \brief Get the type that will be loaded for this slice.
8885   /// Note: This may not be the final type for the slice.
8886   EVT getLoadedType() const {
8887     assert(DAG && "Missing context");
8888     LLVMContext &Ctxt = *DAG->getContext();
8889     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8890   }
8891
8892   /// \brief Get the alignment of the load used for this slice.
8893   unsigned getAlignment() const {
8894     unsigned Alignment = Origin->getAlignment();
8895     unsigned Offset = getOffsetFromBase();
8896     if (Offset != 0)
8897       Alignment = MinAlign(Alignment, Alignment + Offset);
8898     return Alignment;
8899   }
8900
8901   /// \brief Check if this slice can be rewritten with legal operations.
8902   bool isLegal() const {
8903     // An invalid slice is not legal.
8904     if (!Origin || !Inst || !DAG)
8905       return false;
8906
8907     // Offsets are for indexed load only, we do not handle that.
8908     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8909       return false;
8910
8911     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8912
8913     // Check that the type is legal.
8914     EVT SliceType = getLoadedType();
8915     if (!TLI.isTypeLegal(SliceType))
8916       return false;
8917
8918     // Check that the load is legal for this type.
8919     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8920       return false;
8921
8922     // Check that the offset can be computed.
8923     // 1. Check its type.
8924     EVT PtrType = Origin->getBasePtr().getValueType();
8925     if (PtrType == MVT::Untyped || PtrType.isExtended())
8926       return false;
8927
8928     // 2. Check that it fits in the immediate.
8929     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8930       return false;
8931
8932     // 3. Check that the computation is legal.
8933     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8934       return false;
8935
8936     // Check that the zext is legal if it needs one.
8937     EVT TruncateType = Inst->getValueType(0);
8938     if (TruncateType != SliceType &&
8939         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8940       return false;
8941
8942     return true;
8943   }
8944
8945   /// \brief Get the offset in bytes of this slice in the original chunk of
8946   /// bits.
8947   /// \pre DAG != nullptr.
8948   uint64_t getOffsetFromBase() const {
8949     assert(DAG && "Missing context.");
8950     bool IsBigEndian =
8951         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8952     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8953     uint64_t Offset = Shift / 8;
8954     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8955     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8956            "The size of the original loaded type is not a multiple of a"
8957            " byte.");
8958     // If Offset is bigger than TySizeInBytes, it means we are loading all
8959     // zeros. This should have been optimized before in the process.
8960     assert(TySizeInBytes > Offset &&
8961            "Invalid shift amount for given loaded size");
8962     if (IsBigEndian)
8963       Offset = TySizeInBytes - Offset - getLoadedSize();
8964     return Offset;
8965   }
8966
8967   /// \brief Generate the sequence of instructions to load the slice
8968   /// represented by this object and redirect the uses of this slice to
8969   /// this new sequence of instructions.
8970   /// \pre this->Inst && this->Origin are valid Instructions and this
8971   /// object passed the legal check: LoadedSlice::isLegal returned true.
8972   /// \return The last instruction of the sequence used to load the slice.
8973   SDValue loadSlice() const {
8974     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8975     const SDValue &OldBaseAddr = Origin->getBasePtr();
8976     SDValue BaseAddr = OldBaseAddr;
8977     // Get the offset in that chunk of bytes w.r.t. the endianess.
8978     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8979     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8980     if (Offset) {
8981       // BaseAddr = BaseAddr + Offset.
8982       EVT ArithType = BaseAddr.getValueType();
8983       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8984                               DAG->getConstant(Offset, ArithType));
8985     }
8986
8987     // Create the type of the loaded slice according to its size.
8988     EVT SliceType = getLoadedType();
8989
8990     // Create the load for the slice.
8991     SDValue LastInst = DAG->getLoad(
8992         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8993         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8994         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8995     // If the final type is not the same as the loaded type, this means that
8996     // we have to pad with zero. Create a zero extend for that.
8997     EVT FinalType = Inst->getValueType(0);
8998     if (SliceType != FinalType)
8999       LastInst =
9000           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9001     return LastInst;
9002   }
9003
9004   /// \brief Check if this slice can be merged with an expensive cross register
9005   /// bank copy. E.g.,
9006   /// i = load i32
9007   /// f = bitcast i32 i to float
9008   bool canMergeExpensiveCrossRegisterBankCopy() const {
9009     if (!Inst || !Inst->hasOneUse())
9010       return false;
9011     SDNode *Use = *Inst->use_begin();
9012     if (Use->getOpcode() != ISD::BITCAST)
9013       return false;
9014     assert(DAG && "Missing context");
9015     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9016     EVT ResVT = Use->getValueType(0);
9017     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9018     const TargetRegisterClass *ArgRC =
9019         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9020     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9021       return false;
9022
9023     // At this point, we know that we perform a cross-register-bank copy.
9024     // Check if it is expensive.
9025     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9026     // Assume bitcasts are cheap, unless both register classes do not
9027     // explicitly share a common sub class.
9028     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9029       return false;
9030
9031     // Check if it will be merged with the load.
9032     // 1. Check the alignment constraint.
9033     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9034         ResVT.getTypeForEVT(*DAG->getContext()));
9035
9036     if (RequiredAlignment > getAlignment())
9037       return false;
9038
9039     // 2. Check that the load is a legal operation for that type.
9040     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9041       return false;
9042
9043     // 3. Check that we do not have a zext in the way.
9044     if (Inst->getValueType(0) != getLoadedType())
9045       return false;
9046
9047     return true;
9048   }
9049 };
9050 }
9051
9052 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9053 /// \p UsedBits looks like 0..0 1..1 0..0.
9054 static bool areUsedBitsDense(const APInt &UsedBits) {
9055   // If all the bits are one, this is dense!
9056   if (UsedBits.isAllOnesValue())
9057     return true;
9058
9059   // Get rid of the unused bits on the right.
9060   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9061   // Get rid of the unused bits on the left.
9062   if (NarrowedUsedBits.countLeadingZeros())
9063     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9064   // Check that the chunk of bits is completely used.
9065   return NarrowedUsedBits.isAllOnesValue();
9066 }
9067
9068 /// \brief Check whether or not \p First and \p Second are next to each other
9069 /// in memory. This means that there is no hole between the bits loaded
9070 /// by \p First and the bits loaded by \p Second.
9071 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9072                                      const LoadedSlice &Second) {
9073   assert(First.Origin == Second.Origin && First.Origin &&
9074          "Unable to match different memory origins.");
9075   APInt UsedBits = First.getUsedBits();
9076   assert((UsedBits & Second.getUsedBits()) == 0 &&
9077          "Slices are not supposed to overlap.");
9078   UsedBits |= Second.getUsedBits();
9079   return areUsedBitsDense(UsedBits);
9080 }
9081
9082 /// \brief Adjust the \p GlobalLSCost according to the target
9083 /// paring capabilities and the layout of the slices.
9084 /// \pre \p GlobalLSCost should account for at least as many loads as
9085 /// there is in the slices in \p LoadedSlices.
9086 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9087                                  LoadedSlice::Cost &GlobalLSCost) {
9088   unsigned NumberOfSlices = LoadedSlices.size();
9089   // If there is less than 2 elements, no pairing is possible.
9090   if (NumberOfSlices < 2)
9091     return;
9092
9093   // Sort the slices so that elements that are likely to be next to each
9094   // other in memory are next to each other in the list.
9095   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9096             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9097     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9098     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9099   });
9100   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9101   // First (resp. Second) is the first (resp. Second) potentially candidate
9102   // to be placed in a paired load.
9103   const LoadedSlice *First = nullptr;
9104   const LoadedSlice *Second = nullptr;
9105   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9106                 // Set the beginning of the pair.
9107                                                            First = Second) {
9108
9109     Second = &LoadedSlices[CurrSlice];
9110
9111     // If First is NULL, it means we start a new pair.
9112     // Get to the next slice.
9113     if (!First)
9114       continue;
9115
9116     EVT LoadedType = First->getLoadedType();
9117
9118     // If the types of the slices are different, we cannot pair them.
9119     if (LoadedType != Second->getLoadedType())
9120       continue;
9121
9122     // Check if the target supplies paired loads for this type.
9123     unsigned RequiredAlignment = 0;
9124     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9125       // move to the next pair, this type is hopeless.
9126       Second = nullptr;
9127       continue;
9128     }
9129     // Check if we meet the alignment requirement.
9130     if (RequiredAlignment > First->getAlignment())
9131       continue;
9132
9133     // Check that both loads are next to each other in memory.
9134     if (!areSlicesNextToEachOther(*First, *Second))
9135       continue;
9136
9137     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9138     --GlobalLSCost.Loads;
9139     // Move to the next pair.
9140     Second = nullptr;
9141   }
9142 }
9143
9144 /// \brief Check the profitability of all involved LoadedSlice.
9145 /// Currently, it is considered profitable if there is exactly two
9146 /// involved slices (1) which are (2) next to each other in memory, and
9147 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9148 ///
9149 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9150 /// the elements themselves.
9151 ///
9152 /// FIXME: When the cost model will be mature enough, we can relax
9153 /// constraints (1) and (2).
9154 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9155                                 const APInt &UsedBits, bool ForCodeSize) {
9156   unsigned NumberOfSlices = LoadedSlices.size();
9157   if (StressLoadSlicing)
9158     return NumberOfSlices > 1;
9159
9160   // Check (1).
9161   if (NumberOfSlices != 2)
9162     return false;
9163
9164   // Check (2).
9165   if (!areUsedBitsDense(UsedBits))
9166     return false;
9167
9168   // Check (3).
9169   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9170   // The original code has one big load.
9171   OrigCost.Loads = 1;
9172   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9173     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9174     // Accumulate the cost of all the slices.
9175     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9176     GlobalSlicingCost += SliceCost;
9177
9178     // Account as cost in the original configuration the gain obtained
9179     // with the current slices.
9180     OrigCost.addSliceGain(LS);
9181   }
9182
9183   // If the target supports paired load, adjust the cost accordingly.
9184   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9185   return OrigCost > GlobalSlicingCost;
9186 }
9187
9188 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9189 /// operations, split it in the various pieces being extracted.
9190 ///
9191 /// This sort of thing is introduced by SROA.
9192 /// This slicing takes care not to insert overlapping loads.
9193 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9194 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9195   if (Level < AfterLegalizeDAG)
9196     return false;
9197
9198   LoadSDNode *LD = cast<LoadSDNode>(N);
9199   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9200       !LD->getValueType(0).isInteger())
9201     return false;
9202
9203   // Keep track of already used bits to detect overlapping values.
9204   // In that case, we will just abort the transformation.
9205   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9206
9207   SmallVector<LoadedSlice, 4> LoadedSlices;
9208
9209   // Check if this load is used as several smaller chunks of bits.
9210   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9211   // of computation for each trunc.
9212   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9213        UI != UIEnd; ++UI) {
9214     // Skip the uses of the chain.
9215     if (UI.getUse().getResNo() != 0)
9216       continue;
9217
9218     SDNode *User = *UI;
9219     unsigned Shift = 0;
9220
9221     // Check if this is a trunc(lshr).
9222     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9223         isa<ConstantSDNode>(User->getOperand(1))) {
9224       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9225       User = *User->use_begin();
9226     }
9227
9228     // At this point, User is a Truncate, iff we encountered, trunc or
9229     // trunc(lshr).
9230     if (User->getOpcode() != ISD::TRUNCATE)
9231       return false;
9232
9233     // The width of the type must be a power of 2 and greater than 8-bits.
9234     // Otherwise the load cannot be represented in LLVM IR.
9235     // Moreover, if we shifted with a non-8-bits multiple, the slice
9236     // will be across several bytes. We do not support that.
9237     unsigned Width = User->getValueSizeInBits(0);
9238     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9239       return 0;
9240
9241     // Build the slice for this chain of computations.
9242     LoadedSlice LS(User, LD, Shift, &DAG);
9243     APInt CurrentUsedBits = LS.getUsedBits();
9244
9245     // Check if this slice overlaps with another.
9246     if ((CurrentUsedBits & UsedBits) != 0)
9247       return false;
9248     // Update the bits used globally.
9249     UsedBits |= CurrentUsedBits;
9250
9251     // Check if the new slice would be legal.
9252     if (!LS.isLegal())
9253       return false;
9254
9255     // Record the slice.
9256     LoadedSlices.push_back(LS);
9257   }
9258
9259   // Abort slicing if it does not seem to be profitable.
9260   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9261     return false;
9262
9263   ++SlicedLoads;
9264
9265   // Rewrite each chain to use an independent load.
9266   // By construction, each chain can be represented by a unique load.
9267
9268   // Prepare the argument for the new token factor for all the slices.
9269   SmallVector<SDValue, 8> ArgChains;
9270   for (SmallVectorImpl<LoadedSlice>::const_iterator
9271            LSIt = LoadedSlices.begin(),
9272            LSItEnd = LoadedSlices.end();
9273        LSIt != LSItEnd; ++LSIt) {
9274     SDValue SliceInst = LSIt->loadSlice();
9275     CombineTo(LSIt->Inst, SliceInst, true);
9276     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9277       SliceInst = SliceInst.getOperand(0);
9278     assert(SliceInst->getOpcode() == ISD::LOAD &&
9279            "It takes more than a zext to get to the loaded slice!!");
9280     ArgChains.push_back(SliceInst.getValue(1));
9281   }
9282
9283   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9284                               ArgChains);
9285   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9286   return true;
9287 }
9288
9289 /// Check to see if V is (and load (ptr), imm), where the load is having
9290 /// specific bytes cleared out.  If so, return the byte size being masked out
9291 /// and the shift amount.
9292 static std::pair<unsigned, unsigned>
9293 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9294   std::pair<unsigned, unsigned> Result(0, 0);
9295
9296   // Check for the structure we're looking for.
9297   if (V->getOpcode() != ISD::AND ||
9298       !isa<ConstantSDNode>(V->getOperand(1)) ||
9299       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9300     return Result;
9301
9302   // Check the chain and pointer.
9303   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9304   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9305
9306   // The store should be chained directly to the load or be an operand of a
9307   // tokenfactor.
9308   if (LD == Chain.getNode())
9309     ; // ok.
9310   else if (Chain->getOpcode() != ISD::TokenFactor)
9311     return Result; // Fail.
9312   else {
9313     bool isOk = false;
9314     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9315       if (Chain->getOperand(i).getNode() == LD) {
9316         isOk = true;
9317         break;
9318       }
9319     if (!isOk) return Result;
9320   }
9321
9322   // This only handles simple types.
9323   if (V.getValueType() != MVT::i16 &&
9324       V.getValueType() != MVT::i32 &&
9325       V.getValueType() != MVT::i64)
9326     return Result;
9327
9328   // Check the constant mask.  Invert it so that the bits being masked out are
9329   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9330   // follow the sign bit for uniformity.
9331   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9332   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9333   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9334   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9335   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9336   if (NotMaskLZ == 64) return Result;  // All zero mask.
9337
9338   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9339   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9340     return Result;
9341
9342   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9343   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9344     NotMaskLZ -= 64-V.getValueSizeInBits();
9345
9346   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9347   switch (MaskedBytes) {
9348   case 1:
9349   case 2:
9350   case 4: break;
9351   default: return Result; // All one mask, or 5-byte mask.
9352   }
9353
9354   // Verify that the first bit starts at a multiple of mask so that the access
9355   // is aligned the same as the access width.
9356   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9357
9358   Result.first = MaskedBytes;
9359   Result.second = NotMaskTZ/8;
9360   return Result;
9361 }
9362
9363
9364 /// Check to see if IVal is something that provides a value as specified by
9365 /// MaskInfo. If so, replace the specified store with a narrower store of
9366 /// truncated IVal.
9367 static SDNode *
9368 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9369                                 SDValue IVal, StoreSDNode *St,
9370                                 DAGCombiner *DC) {
9371   unsigned NumBytes = MaskInfo.first;
9372   unsigned ByteShift = MaskInfo.second;
9373   SelectionDAG &DAG = DC->getDAG();
9374
9375   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9376   // that uses this.  If not, this is not a replacement.
9377   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9378                                   ByteShift*8, (ByteShift+NumBytes)*8);
9379   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9380
9381   // Check that it is legal on the target to do this.  It is legal if the new
9382   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9383   // legalization.
9384   MVT VT = MVT::getIntegerVT(NumBytes*8);
9385   if (!DC->isTypeLegal(VT))
9386     return nullptr;
9387
9388   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9389   // shifted by ByteShift and truncated down to NumBytes.
9390   if (ByteShift)
9391     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9392                        DAG.getConstant(ByteShift*8,
9393                                     DC->getShiftAmountTy(IVal.getValueType())));
9394
9395   // Figure out the offset for the store and the alignment of the access.
9396   unsigned StOffset;
9397   unsigned NewAlign = St->getAlignment();
9398
9399   if (DAG.getTargetLoweringInfo().isLittleEndian())
9400     StOffset = ByteShift;
9401   else
9402     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9403
9404   SDValue Ptr = St->getBasePtr();
9405   if (StOffset) {
9406     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9407                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9408     NewAlign = MinAlign(NewAlign, StOffset);
9409   }
9410
9411   // Truncate down to the new size.
9412   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9413
9414   ++OpsNarrowed;
9415   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9416                       St->getPointerInfo().getWithOffset(StOffset),
9417                       false, false, NewAlign).getNode();
9418 }
9419
9420
9421 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9422 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9423 /// narrowing the load and store if it would end up being a win for performance
9424 /// or code size.
9425 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9426   StoreSDNode *ST  = cast<StoreSDNode>(N);
9427   if (ST->isVolatile())
9428     return SDValue();
9429
9430   SDValue Chain = ST->getChain();
9431   SDValue Value = ST->getValue();
9432   SDValue Ptr   = ST->getBasePtr();
9433   EVT VT = Value.getValueType();
9434
9435   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9436     return SDValue();
9437
9438   unsigned Opc = Value.getOpcode();
9439
9440   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9441   // is a byte mask indicating a consecutive number of bytes, check to see if
9442   // Y is known to provide just those bytes.  If so, we try to replace the
9443   // load + replace + store sequence with a single (narrower) store, which makes
9444   // the load dead.
9445   if (Opc == ISD::OR) {
9446     std::pair<unsigned, unsigned> MaskedLoad;
9447     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9448     if (MaskedLoad.first)
9449       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9450                                                   Value.getOperand(1), ST,this))
9451         return SDValue(NewST, 0);
9452
9453     // Or is commutative, so try swapping X and Y.
9454     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9455     if (MaskedLoad.first)
9456       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9457                                                   Value.getOperand(0), ST,this))
9458         return SDValue(NewST, 0);
9459   }
9460
9461   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9462       Value.getOperand(1).getOpcode() != ISD::Constant)
9463     return SDValue();
9464
9465   SDValue N0 = Value.getOperand(0);
9466   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9467       Chain == SDValue(N0.getNode(), 1)) {
9468     LoadSDNode *LD = cast<LoadSDNode>(N0);
9469     if (LD->getBasePtr() != Ptr ||
9470         LD->getPointerInfo().getAddrSpace() !=
9471         ST->getPointerInfo().getAddrSpace())
9472       return SDValue();
9473
9474     // Find the type to narrow it the load / op / store to.
9475     SDValue N1 = Value.getOperand(1);
9476     unsigned BitWidth = N1.getValueSizeInBits();
9477     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9478     if (Opc == ISD::AND)
9479       Imm ^= APInt::getAllOnesValue(BitWidth);
9480     if (Imm == 0 || Imm.isAllOnesValue())
9481       return SDValue();
9482     unsigned ShAmt = Imm.countTrailingZeros();
9483     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9484     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9485     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9486     while (NewBW < BitWidth &&
9487            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9488              TLI.isNarrowingProfitable(VT, NewVT))) {
9489       NewBW = NextPowerOf2(NewBW);
9490       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9491     }
9492     if (NewBW >= BitWidth)
9493       return SDValue();
9494
9495     // If the lsb changed does not start at the type bitwidth boundary,
9496     // start at the previous one.
9497     if (ShAmt % NewBW)
9498       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9499     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9500                                    std::min(BitWidth, ShAmt + NewBW));
9501     if ((Imm & Mask) == Imm) {
9502       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9503       if (Opc == ISD::AND)
9504         NewImm ^= APInt::getAllOnesValue(NewBW);
9505       uint64_t PtrOff = ShAmt / 8;
9506       // For big endian targets, we need to adjust the offset to the pointer to
9507       // load the correct bytes.
9508       if (TLI.isBigEndian())
9509         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9510
9511       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9512       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9513       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9514         return SDValue();
9515
9516       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9517                                    Ptr.getValueType(), Ptr,
9518                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9519       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9520                                   LD->getChain(), NewPtr,
9521                                   LD->getPointerInfo().getWithOffset(PtrOff),
9522                                   LD->isVolatile(), LD->isNonTemporal(),
9523                                   LD->isInvariant(), NewAlign,
9524                                   LD->getAAInfo());
9525       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9526                                    DAG.getConstant(NewImm, NewVT));
9527       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9528                                    NewVal, NewPtr,
9529                                    ST->getPointerInfo().getWithOffset(PtrOff),
9530                                    false, false, NewAlign);
9531
9532       AddToWorklist(NewPtr.getNode());
9533       AddToWorklist(NewLD.getNode());
9534       AddToWorklist(NewVal.getNode());
9535       WorklistRemover DeadNodes(*this);
9536       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9537       ++OpsNarrowed;
9538       return NewST;
9539     }
9540   }
9541
9542   return SDValue();
9543 }
9544
9545 /// For a given floating point load / store pair, if the load value isn't used
9546 /// by any other operations, then consider transforming the pair to integer
9547 /// load / store operations if the target deems the transformation profitable.
9548 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9549   StoreSDNode *ST  = cast<StoreSDNode>(N);
9550   SDValue Chain = ST->getChain();
9551   SDValue Value = ST->getValue();
9552   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9553       Value.hasOneUse() &&
9554       Chain == SDValue(Value.getNode(), 1)) {
9555     LoadSDNode *LD = cast<LoadSDNode>(Value);
9556     EVT VT = LD->getMemoryVT();
9557     if (!VT.isFloatingPoint() ||
9558         VT != ST->getMemoryVT() ||
9559         LD->isNonTemporal() ||
9560         ST->isNonTemporal() ||
9561         LD->getPointerInfo().getAddrSpace() != 0 ||
9562         ST->getPointerInfo().getAddrSpace() != 0)
9563       return SDValue();
9564
9565     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9566     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9567         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9568         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9569         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9570       return SDValue();
9571
9572     unsigned LDAlign = LD->getAlignment();
9573     unsigned STAlign = ST->getAlignment();
9574     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9575     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9576     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9577       return SDValue();
9578
9579     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9580                                 LD->getChain(), LD->getBasePtr(),
9581                                 LD->getPointerInfo(),
9582                                 false, false, false, LDAlign);
9583
9584     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9585                                  NewLD, ST->getBasePtr(),
9586                                  ST->getPointerInfo(),
9587                                  false, false, STAlign);
9588
9589     AddToWorklist(NewLD.getNode());
9590     AddToWorklist(NewST.getNode());
9591     WorklistRemover DeadNodes(*this);
9592     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9593     ++LdStFP2Int;
9594     return NewST;
9595   }
9596
9597   return SDValue();
9598 }
9599
9600 /// Helper struct to parse and store a memory address as base + index + offset.
9601 /// We ignore sign extensions when it is safe to do so.
9602 /// The following two expressions are not equivalent. To differentiate we need
9603 /// to store whether there was a sign extension involved in the index
9604 /// computation.
9605 ///  (load (i64 add (i64 copyfromreg %c)
9606 ///                 (i64 signextend (add (i8 load %index)
9607 ///                                      (i8 1))))
9608 /// vs
9609 ///
9610 /// (load (i64 add (i64 copyfromreg %c)
9611 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9612 ///                                         (i32 1)))))
9613 struct BaseIndexOffset {
9614   SDValue Base;
9615   SDValue Index;
9616   int64_t Offset;
9617   bool IsIndexSignExt;
9618
9619   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9620
9621   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9622                   bool IsIndexSignExt) :
9623     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9624
9625   bool equalBaseIndex(const BaseIndexOffset &Other) {
9626     return Other.Base == Base && Other.Index == Index &&
9627       Other.IsIndexSignExt == IsIndexSignExt;
9628   }
9629
9630   /// Parses tree in Ptr for base, index, offset addresses.
9631   static BaseIndexOffset match(SDValue Ptr) {
9632     bool IsIndexSignExt = false;
9633
9634     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9635     // instruction, then it could be just the BASE or everything else we don't
9636     // know how to handle. Just use Ptr as BASE and give up.
9637     if (Ptr->getOpcode() != ISD::ADD)
9638       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9639
9640     // We know that we have at least an ADD instruction. Try to pattern match
9641     // the simple case of BASE + OFFSET.
9642     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9643       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9644       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9645                               IsIndexSignExt);
9646     }
9647
9648     // Inside a loop the current BASE pointer is calculated using an ADD and a
9649     // MUL instruction. In this case Ptr is the actual BASE pointer.
9650     // (i64 add (i64 %array_ptr)
9651     //          (i64 mul (i64 %induction_var)
9652     //                   (i64 %element_size)))
9653     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9654       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9655
9656     // Look at Base + Index + Offset cases.
9657     SDValue Base = Ptr->getOperand(0);
9658     SDValue IndexOffset = Ptr->getOperand(1);
9659
9660     // Skip signextends.
9661     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9662       IndexOffset = IndexOffset->getOperand(0);
9663       IsIndexSignExt = true;
9664     }
9665
9666     // Either the case of Base + Index (no offset) or something else.
9667     if (IndexOffset->getOpcode() != ISD::ADD)
9668       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9669
9670     // Now we have the case of Base + Index + offset.
9671     SDValue Index = IndexOffset->getOperand(0);
9672     SDValue Offset = IndexOffset->getOperand(1);
9673
9674     if (!isa<ConstantSDNode>(Offset))
9675       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9676
9677     // Ignore signextends.
9678     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9679       Index = Index->getOperand(0);
9680       IsIndexSignExt = true;
9681     } else IsIndexSignExt = false;
9682
9683     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9684     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9685   }
9686 };
9687
9688 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9689 /// is located in a sequence of memory operations connected by a chain.
9690 struct MemOpLink {
9691   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9692     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9693   // Ptr to the mem node.
9694   LSBaseSDNode *MemNode;
9695   // Offset from the base ptr.
9696   int64_t OffsetFromBase;
9697   // What is the sequence number of this mem node.
9698   // Lowest mem operand in the DAG starts at zero.
9699   unsigned SequenceNum;
9700 };
9701
9702 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9703   EVT MemVT = St->getMemoryVT();
9704   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9705   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9706     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9707
9708   // Don't merge vectors into wider inputs.
9709   if (MemVT.isVector() || !MemVT.isSimple())
9710     return false;
9711
9712   // Perform an early exit check. Do not bother looking at stored values that
9713   // are not constants or loads.
9714   SDValue StoredVal = St->getValue();
9715   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9716   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9717       !IsLoadSrc)
9718     return false;
9719
9720   // Only look at ends of store sequences.
9721   SDValue Chain = SDValue(St, 0);
9722   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9723     return false;
9724
9725   // This holds the base pointer, index, and the offset in bytes from the base
9726   // pointer.
9727   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9728
9729   // We must have a base and an offset.
9730   if (!BasePtr.Base.getNode())
9731     return false;
9732
9733   // Do not handle stores to undef base pointers.
9734   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9735     return false;
9736
9737   // Save the LoadSDNodes that we find in the chain.
9738   // We need to make sure that these nodes do not interfere with
9739   // any of the store nodes.
9740   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9741
9742   // Save the StoreSDNodes that we find in the chain.
9743   SmallVector<MemOpLink, 8> StoreNodes;
9744
9745   // Walk up the chain and look for nodes with offsets from the same
9746   // base pointer. Stop when reaching an instruction with a different kind
9747   // or instruction which has a different base pointer.
9748   unsigned Seq = 0;
9749   StoreSDNode *Index = St;
9750   while (Index) {
9751     // If the chain has more than one use, then we can't reorder the mem ops.
9752     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9753       break;
9754
9755     // Find the base pointer and offset for this memory node.
9756     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9757
9758     // Check that the base pointer is the same as the original one.
9759     if (!Ptr.equalBaseIndex(BasePtr))
9760       break;
9761
9762     // Check that the alignment is the same.
9763     if (Index->getAlignment() != St->getAlignment())
9764       break;
9765
9766     // The memory operands must not be volatile.
9767     if (Index->isVolatile() || Index->isIndexed())
9768       break;
9769
9770     // No truncation.
9771     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9772       if (St->isTruncatingStore())
9773         break;
9774
9775     // The stored memory type must be the same.
9776     if (Index->getMemoryVT() != MemVT)
9777       break;
9778
9779     // We do not allow unaligned stores because we want to prevent overriding
9780     // stores.
9781     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9782       break;
9783
9784     // We found a potential memory operand to merge.
9785     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9786
9787     // Find the next memory operand in the chain. If the next operand in the
9788     // chain is a store then move up and continue the scan with the next
9789     // memory operand. If the next operand is a load save it and use alias
9790     // information to check if it interferes with anything.
9791     SDNode *NextInChain = Index->getChain().getNode();
9792     while (1) {
9793       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9794         // We found a store node. Use it for the next iteration.
9795         Index = STn;
9796         break;
9797       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9798         if (Ldn->isVolatile()) {
9799           Index = nullptr;
9800           break;
9801         }
9802
9803         // Save the load node for later. Continue the scan.
9804         AliasLoadNodes.push_back(Ldn);
9805         NextInChain = Ldn->getChain().getNode();
9806         continue;
9807       } else {
9808         Index = nullptr;
9809         break;
9810       }
9811     }
9812   }
9813
9814   // Check if there is anything to merge.
9815   if (StoreNodes.size() < 2)
9816     return false;
9817
9818   // Sort the memory operands according to their distance from the base pointer.
9819   std::sort(StoreNodes.begin(), StoreNodes.end(),
9820             [](MemOpLink LHS, MemOpLink RHS) {
9821     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9822            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9823             LHS.SequenceNum > RHS.SequenceNum);
9824   });
9825
9826   // Scan the memory operations on the chain and find the first non-consecutive
9827   // store memory address.
9828   unsigned LastConsecutiveStore = 0;
9829   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9830   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9831
9832     // Check that the addresses are consecutive starting from the second
9833     // element in the list of stores.
9834     if (i > 0) {
9835       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9836       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9837         break;
9838     }
9839
9840     bool Alias = false;
9841     // Check if this store interferes with any of the loads that we found.
9842     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9843       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9844         Alias = true;
9845         break;
9846       }
9847     // We found a load that alias with this store. Stop the sequence.
9848     if (Alias)
9849       break;
9850
9851     // Mark this node as useful.
9852     LastConsecutiveStore = i;
9853   }
9854
9855   // The node with the lowest store address.
9856   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9857
9858   // Store the constants into memory as one consecutive store.
9859   if (!IsLoadSrc) {
9860     unsigned LastLegalType = 0;
9861     unsigned LastLegalVectorType = 0;
9862     bool NonZero = false;
9863     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9864       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9865       SDValue StoredVal = St->getValue();
9866
9867       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9868         NonZero |= !C->isNullValue();
9869       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9870         NonZero |= !C->getConstantFPValue()->isNullValue();
9871       } else {
9872         // Non-constant.
9873         break;
9874       }
9875
9876       // Find a legal type for the constant store.
9877       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9878       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9879       if (TLI.isTypeLegal(StoreTy))
9880         LastLegalType = i+1;
9881       // Or check whether a truncstore is legal.
9882       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9883                TargetLowering::TypePromoteInteger) {
9884         EVT LegalizedStoredValueTy =
9885           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9886         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9887           LastLegalType = i+1;
9888       }
9889
9890       // Find a legal type for the vector store.
9891       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9892       if (TLI.isTypeLegal(Ty))
9893         LastLegalVectorType = i + 1;
9894     }
9895
9896     // We only use vectors if the constant is known to be zero and the
9897     // function is not marked with the noimplicitfloat attribute.
9898     if (NonZero || NoVectors)
9899       LastLegalVectorType = 0;
9900
9901     // Check if we found a legal integer type to store.
9902     if (LastLegalType == 0 && LastLegalVectorType == 0)
9903       return false;
9904
9905     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9906     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9907
9908     // Make sure we have something to merge.
9909     if (NumElem < 2)
9910       return false;
9911
9912     unsigned EarliestNodeUsed = 0;
9913     for (unsigned i=0; i < NumElem; ++i) {
9914       // Find a chain for the new wide-store operand. Notice that some
9915       // of the store nodes that we found may not be selected for inclusion
9916       // in the wide store. The chain we use needs to be the chain of the
9917       // earliest store node which is *used* and replaced by the wide store.
9918       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9919         EarliestNodeUsed = i;
9920     }
9921
9922     // The earliest Node in the DAG.
9923     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9924     SDLoc DL(StoreNodes[0].MemNode);
9925
9926     SDValue StoredVal;
9927     if (UseVector) {
9928       // Find a legal type for the vector store.
9929       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9930       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9931       StoredVal = DAG.getConstant(0, Ty);
9932     } else {
9933       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9934       APInt StoreInt(StoreBW, 0);
9935
9936       // Construct a single integer constant which is made of the smaller
9937       // constant inputs.
9938       bool IsLE = TLI.isLittleEndian();
9939       for (unsigned i = 0; i < NumElem ; ++i) {
9940         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9941         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9942         SDValue Val = St->getValue();
9943         StoreInt<<=ElementSizeBytes*8;
9944         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9945           StoreInt|=C->getAPIntValue().zext(StoreBW);
9946         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9947           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9948         } else {
9949           llvm_unreachable("Invalid constant element type");
9950         }
9951       }
9952
9953       // Create the new Load and Store operations.
9954       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9955       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9956     }
9957
9958     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9959                                     FirstInChain->getBasePtr(),
9960                                     FirstInChain->getPointerInfo(),
9961                                     false, false,
9962                                     FirstInChain->getAlignment());
9963
9964     // Replace the first store with the new store
9965     CombineTo(EarliestOp, NewStore);
9966     // Erase all other stores.
9967     for (unsigned i = 0; i < NumElem ; ++i) {
9968       if (StoreNodes[i].MemNode == EarliestOp)
9969         continue;
9970       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9971       // ReplaceAllUsesWith will replace all uses that existed when it was
9972       // called, but graph optimizations may cause new ones to appear. For
9973       // example, the case in pr14333 looks like
9974       //
9975       //  St's chain -> St -> another store -> X
9976       //
9977       // And the only difference from St to the other store is the chain.
9978       // When we change it's chain to be St's chain they become identical,
9979       // get CSEed and the net result is that X is now a use of St.
9980       // Since we know that St is redundant, just iterate.
9981       while (!St->use_empty())
9982         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9983       deleteAndRecombine(St);
9984     }
9985
9986     return true;
9987   }
9988
9989   // Below we handle the case of multiple consecutive stores that
9990   // come from multiple consecutive loads. We merge them into a single
9991   // wide load and a single wide store.
9992
9993   // Look for load nodes which are used by the stored values.
9994   SmallVector<MemOpLink, 8> LoadNodes;
9995
9996   // Find acceptable loads. Loads need to have the same chain (token factor),
9997   // must not be zext, volatile, indexed, and they must be consecutive.
9998   BaseIndexOffset LdBasePtr;
9999   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10000     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10001     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10002     if (!Ld) break;
10003
10004     // Loads must only have one use.
10005     if (!Ld->hasNUsesOfValue(1, 0))
10006       break;
10007
10008     // Check that the alignment is the same as the stores.
10009     if (Ld->getAlignment() != St->getAlignment())
10010       break;
10011
10012     // The memory operands must not be volatile.
10013     if (Ld->isVolatile() || Ld->isIndexed())
10014       break;
10015
10016     // We do not accept ext loads.
10017     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10018       break;
10019
10020     // The stored memory type must be the same.
10021     if (Ld->getMemoryVT() != MemVT)
10022       break;
10023
10024     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10025     // If this is not the first ptr that we check.
10026     if (LdBasePtr.Base.getNode()) {
10027       // The base ptr must be the same.
10028       if (!LdPtr.equalBaseIndex(LdBasePtr))
10029         break;
10030     } else {
10031       // Check that all other base pointers are the same as this one.
10032       LdBasePtr = LdPtr;
10033     }
10034
10035     // We found a potential memory operand to merge.
10036     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10037   }
10038
10039   if (LoadNodes.size() < 2)
10040     return false;
10041
10042   // If we have load/store pair instructions and we only have two values,
10043   // don't bother.
10044   unsigned RequiredAlignment;
10045   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10046       St->getAlignment() >= RequiredAlignment)
10047     return false;
10048
10049   // Scan the memory operations on the chain and find the first non-consecutive
10050   // load memory address. These variables hold the index in the store node
10051   // array.
10052   unsigned LastConsecutiveLoad = 0;
10053   // This variable refers to the size and not index in the array.
10054   unsigned LastLegalVectorType = 0;
10055   unsigned LastLegalIntegerType = 0;
10056   StartAddress = LoadNodes[0].OffsetFromBase;
10057   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10058   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10059     // All loads much share the same chain.
10060     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10061       break;
10062
10063     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10064     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10065       break;
10066     LastConsecutiveLoad = i;
10067
10068     // Find a legal type for the vector store.
10069     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10070     if (TLI.isTypeLegal(StoreTy))
10071       LastLegalVectorType = i + 1;
10072
10073     // Find a legal type for the integer store.
10074     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10075     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10076     if (TLI.isTypeLegal(StoreTy))
10077       LastLegalIntegerType = i + 1;
10078     // Or check whether a truncstore and extload is legal.
10079     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10080              TargetLowering::TypePromoteInteger) {
10081       EVT LegalizedStoredValueTy =
10082         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10083       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10084           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10085           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10086           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10087         LastLegalIntegerType = i+1;
10088     }
10089   }
10090
10091   // Only use vector types if the vector type is larger than the integer type.
10092   // If they are the same, use integers.
10093   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10094   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10095
10096   // We add +1 here because the LastXXX variables refer to location while
10097   // the NumElem refers to array/index size.
10098   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10099   NumElem = std::min(LastLegalType, NumElem);
10100
10101   if (NumElem < 2)
10102     return false;
10103
10104   // The earliest Node in the DAG.
10105   unsigned EarliestNodeUsed = 0;
10106   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10107   for (unsigned i=1; i<NumElem; ++i) {
10108     // Find a chain for the new wide-store operand. Notice that some
10109     // of the store nodes that we found may not be selected for inclusion
10110     // in the wide store. The chain we use needs to be the chain of the
10111     // earliest store node which is *used* and replaced by the wide store.
10112     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10113       EarliestNodeUsed = i;
10114   }
10115
10116   // Find if it is better to use vectors or integers to load and store
10117   // to memory.
10118   EVT JointMemOpVT;
10119   if (UseVectorTy) {
10120     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10121   } else {
10122     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10123     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10124   }
10125
10126   SDLoc LoadDL(LoadNodes[0].MemNode);
10127   SDLoc StoreDL(StoreNodes[0].MemNode);
10128
10129   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10130   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10131                                 FirstLoad->getChain(),
10132                                 FirstLoad->getBasePtr(),
10133                                 FirstLoad->getPointerInfo(),
10134                                 false, false, false,
10135                                 FirstLoad->getAlignment());
10136
10137   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10138                                   FirstInChain->getBasePtr(),
10139                                   FirstInChain->getPointerInfo(), false, false,
10140                                   FirstInChain->getAlignment());
10141
10142   // Replace one of the loads with the new load.
10143   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10144   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10145                                 SDValue(NewLoad.getNode(), 1));
10146
10147   // Remove the rest of the load chains.
10148   for (unsigned i = 1; i < NumElem ; ++i) {
10149     // Replace all chain users of the old load nodes with the chain of the new
10150     // load node.
10151     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10152     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10153   }
10154
10155   // Replace the first store with the new store.
10156   CombineTo(EarliestOp, NewStore);
10157   // Erase all other stores.
10158   for (unsigned i = 0; i < NumElem ; ++i) {
10159     // Remove all Store nodes.
10160     if (StoreNodes[i].MemNode == EarliestOp)
10161       continue;
10162     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10163     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10164     deleteAndRecombine(St);
10165   }
10166
10167   return true;
10168 }
10169
10170 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10171   StoreSDNode *ST  = cast<StoreSDNode>(N);
10172   SDValue Chain = ST->getChain();
10173   SDValue Value = ST->getValue();
10174   SDValue Ptr   = ST->getBasePtr();
10175
10176   // If this is a store of a bit convert, store the input value if the
10177   // resultant store does not need a higher alignment than the original.
10178   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10179       ST->isUnindexed()) {
10180     unsigned OrigAlign = ST->getAlignment();
10181     EVT SVT = Value.getOperand(0).getValueType();
10182     unsigned Align = TLI.getDataLayout()->
10183       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10184     if (Align <= OrigAlign &&
10185         ((!LegalOperations && !ST->isVolatile()) ||
10186          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10187       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10188                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10189                           ST->isNonTemporal(), OrigAlign,
10190                           ST->getAAInfo());
10191   }
10192
10193   // Turn 'store undef, Ptr' -> nothing.
10194   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10195     return Chain;
10196
10197   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10198   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10199     // NOTE: If the original store is volatile, this transform must not increase
10200     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10201     // processor operation but an i64 (which is not legal) requires two.  So the
10202     // transform should not be done in this case.
10203     if (Value.getOpcode() != ISD::TargetConstantFP) {
10204       SDValue Tmp;
10205       switch (CFP->getSimpleValueType(0).SimpleTy) {
10206       default: llvm_unreachable("Unknown FP type");
10207       case MVT::f16:    // We don't do this for these yet.
10208       case MVT::f80:
10209       case MVT::f128:
10210       case MVT::ppcf128:
10211         break;
10212       case MVT::f32:
10213         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10214             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10215           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10216                               bitcastToAPInt().getZExtValue(), MVT::i32);
10217           return DAG.getStore(Chain, SDLoc(N), Tmp,
10218                               Ptr, ST->getMemOperand());
10219         }
10220         break;
10221       case MVT::f64:
10222         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10223              !ST->isVolatile()) ||
10224             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10225           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10226                                 getZExtValue(), MVT::i64);
10227           return DAG.getStore(Chain, SDLoc(N), Tmp,
10228                               Ptr, ST->getMemOperand());
10229         }
10230
10231         if (!ST->isVolatile() &&
10232             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10233           // Many FP stores are not made apparent until after legalize, e.g. for
10234           // argument passing.  Since this is so common, custom legalize the
10235           // 64-bit integer store into two 32-bit stores.
10236           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10237           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10238           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10239           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10240
10241           unsigned Alignment = ST->getAlignment();
10242           bool isVolatile = ST->isVolatile();
10243           bool isNonTemporal = ST->isNonTemporal();
10244           AAMDNodes AAInfo = ST->getAAInfo();
10245
10246           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10247                                      Ptr, ST->getPointerInfo(),
10248                                      isVolatile, isNonTemporal,
10249                                      ST->getAlignment(), AAInfo);
10250           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10251                             DAG.getConstant(4, Ptr.getValueType()));
10252           Alignment = MinAlign(Alignment, 4U);
10253           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10254                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10255                                      isVolatile, isNonTemporal,
10256                                      Alignment, AAInfo);
10257           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10258                              St0, St1);
10259         }
10260
10261         break;
10262       }
10263     }
10264   }
10265
10266   // Try to infer better alignment information than the store already has.
10267   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10268     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10269       if (Align > ST->getAlignment())
10270         return DAG.getTruncStore(Chain, SDLoc(N), Value,
10271                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10272                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10273                                  ST->getAAInfo());
10274     }
10275   }
10276
10277   // Try transforming a pair floating point load / store ops to integer
10278   // load / store ops.
10279   SDValue NewST = TransformFPLoadStorePair(N);
10280   if (NewST.getNode())
10281     return NewST;
10282
10283   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10284                                                   : DAG.getSubtarget().useAA();
10285 #ifndef NDEBUG
10286   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10287       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10288     UseAA = false;
10289 #endif
10290   if (UseAA && ST->isUnindexed()) {
10291     // Walk up chain skipping non-aliasing memory nodes.
10292     SDValue BetterChain = FindBetterChain(N, Chain);
10293
10294     // If there is a better chain.
10295     if (Chain != BetterChain) {
10296       SDValue ReplStore;
10297
10298       // Replace the chain to avoid dependency.
10299       if (ST->isTruncatingStore()) {
10300         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10301                                       ST->getMemoryVT(), ST->getMemOperand());
10302       } else {
10303         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10304                                  ST->getMemOperand());
10305       }
10306
10307       // Create token to keep both nodes around.
10308       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10309                                   MVT::Other, Chain, ReplStore);
10310
10311       // Make sure the new and old chains are cleaned up.
10312       AddToWorklist(Token.getNode());
10313
10314       // Don't add users to work list.
10315       return CombineTo(N, Token, false);
10316     }
10317   }
10318
10319   // Try transforming N to an indexed store.
10320   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10321     return SDValue(N, 0);
10322
10323   // FIXME: is there such a thing as a truncating indexed store?
10324   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10325       Value.getValueType().isInteger()) {
10326     // See if we can simplify the input to this truncstore with knowledge that
10327     // only the low bits are being used.  For example:
10328     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10329     SDValue Shorter =
10330       GetDemandedBits(Value,
10331                       APInt::getLowBitsSet(
10332                         Value.getValueType().getScalarType().getSizeInBits(),
10333                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10334     AddToWorklist(Value.getNode());
10335     if (Shorter.getNode())
10336       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10337                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10338
10339     // Otherwise, see if we can simplify the operation with
10340     // SimplifyDemandedBits, which only works if the value has a single use.
10341     if (SimplifyDemandedBits(Value,
10342                         APInt::getLowBitsSet(
10343                           Value.getValueType().getScalarType().getSizeInBits(),
10344                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10345       return SDValue(N, 0);
10346   }
10347
10348   // If this is a load followed by a store to the same location, then the store
10349   // is dead/noop.
10350   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10351     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10352         ST->isUnindexed() && !ST->isVolatile() &&
10353         // There can't be any side effects between the load and store, such as
10354         // a call or store.
10355         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10356       // The store is dead, remove it.
10357       return Chain;
10358     }
10359   }
10360
10361   // If this is a store followed by a store with the same value to the same
10362   // location, then the store is dead/noop.
10363   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10364     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10365         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10366         ST1->isUnindexed() && !ST1->isVolatile()) {
10367       // The store is dead, remove it.
10368       return Chain;
10369     }
10370   }
10371
10372   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10373   // truncating store.  We can do this even if this is already a truncstore.
10374   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10375       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10376       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10377                             ST->getMemoryVT())) {
10378     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10379                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10380   }
10381
10382   // Only perform this optimization before the types are legal, because we
10383   // don't want to perform this optimization on every DAGCombine invocation.
10384   if (!LegalTypes) {
10385     bool EverChanged = false;
10386
10387     do {
10388       // There can be multiple store sequences on the same chain.
10389       // Keep trying to merge store sequences until we are unable to do so
10390       // or until we merge the last store on the chain.
10391       bool Changed = MergeConsecutiveStores(ST);
10392       EverChanged |= Changed;
10393       if (!Changed) break;
10394     } while (ST->getOpcode() != ISD::DELETED_NODE);
10395
10396     if (EverChanged)
10397       return SDValue(N, 0);
10398   }
10399
10400   return ReduceLoadOpStoreWidth(N);
10401 }
10402
10403 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10404   SDValue InVec = N->getOperand(0);
10405   SDValue InVal = N->getOperand(1);
10406   SDValue EltNo = N->getOperand(2);
10407   SDLoc dl(N);
10408
10409   // If the inserted element is an UNDEF, just use the input vector.
10410   if (InVal.getOpcode() == ISD::UNDEF)
10411     return InVec;
10412
10413   EVT VT = InVec.getValueType();
10414
10415   // If we can't generate a legal BUILD_VECTOR, exit
10416   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10417     return SDValue();
10418
10419   // Check that we know which element is being inserted
10420   if (!isa<ConstantSDNode>(EltNo))
10421     return SDValue();
10422   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10423
10424   // Canonicalize insert_vector_elt dag nodes.
10425   // Example:
10426   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10427   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10428   //
10429   // Do this only if the child insert_vector node has one use; also
10430   // do this only if indices are both constants and Idx1 < Idx0.
10431   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10432       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10433     unsigned OtherElt =
10434       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10435     if (Elt < OtherElt) {
10436       // Swap nodes.
10437       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10438                                   InVec.getOperand(0), InVal, EltNo);
10439       AddToWorklist(NewOp.getNode());
10440       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10441                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10442     }
10443   }
10444
10445   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10446   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10447   // vector elements.
10448   SmallVector<SDValue, 8> Ops;
10449   // Do not combine these two vectors if the output vector will not replace
10450   // the input vector.
10451   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10452     Ops.append(InVec.getNode()->op_begin(),
10453                InVec.getNode()->op_end());
10454   } else if (InVec.getOpcode() == ISD::UNDEF) {
10455     unsigned NElts = VT.getVectorNumElements();
10456     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10457   } else {
10458     return SDValue();
10459   }
10460
10461   // Insert the element
10462   if (Elt < Ops.size()) {
10463     // All the operands of BUILD_VECTOR must have the same type;
10464     // we enforce that here.
10465     EVT OpVT = Ops[0].getValueType();
10466     if (InVal.getValueType() != OpVT)
10467       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10468                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10469                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10470     Ops[Elt] = InVal;
10471   }
10472
10473   // Return the new vector
10474   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10475 }
10476
10477 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10478     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10479   EVT ResultVT = EVE->getValueType(0);
10480   EVT VecEltVT = InVecVT.getVectorElementType();
10481   unsigned Align = OriginalLoad->getAlignment();
10482   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10483       VecEltVT.getTypeForEVT(*DAG.getContext()));
10484
10485   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10486     return SDValue();
10487
10488   Align = NewAlign;
10489
10490   SDValue NewPtr = OriginalLoad->getBasePtr();
10491   SDValue Offset;
10492   EVT PtrType = NewPtr.getValueType();
10493   MachinePointerInfo MPI;
10494   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10495     int Elt = ConstEltNo->getZExtValue();
10496     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10497     if (TLI.isBigEndian())
10498       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10499     Offset = DAG.getConstant(PtrOff, PtrType);
10500     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10501   } else {
10502     Offset = DAG.getNode(
10503         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10504         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10505     if (TLI.isBigEndian())
10506       Offset = DAG.getNode(
10507           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10508           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10509     MPI = OriginalLoad->getPointerInfo();
10510   }
10511   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10512
10513   // The replacement we need to do here is a little tricky: we need to
10514   // replace an extractelement of a load with a load.
10515   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10516   // Note that this replacement assumes that the extractvalue is the only
10517   // use of the load; that's okay because we don't want to perform this
10518   // transformation in other cases anyway.
10519   SDValue Load;
10520   SDValue Chain;
10521   if (ResultVT.bitsGT(VecEltVT)) {
10522     // If the result type of vextract is wider than the load, then issue an
10523     // extending load instead.
10524     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10525                                                   VecEltVT)
10526                                    ? ISD::ZEXTLOAD
10527                                    : ISD::EXTLOAD;
10528     Load = DAG.getExtLoad(
10529         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10530         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10531         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10532     Chain = Load.getValue(1);
10533   } else {
10534     Load = DAG.getLoad(
10535         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10536         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10537         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10538     Chain = Load.getValue(1);
10539     if (ResultVT.bitsLT(VecEltVT))
10540       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10541     else
10542       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10543   }
10544   WorklistRemover DeadNodes(*this);
10545   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10546   SDValue To[] = { Load, Chain };
10547   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10548   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10549   // worklist explicitly as well.
10550   AddToWorklist(Load.getNode());
10551   AddUsersToWorklist(Load.getNode()); // Add users too
10552   // Make sure to revisit this node to clean it up; it will usually be dead.
10553   AddToWorklist(EVE);
10554   ++OpsNarrowed;
10555   return SDValue(EVE, 0);
10556 }
10557
10558 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10559   // (vextract (scalar_to_vector val, 0) -> val
10560   SDValue InVec = N->getOperand(0);
10561   EVT VT = InVec.getValueType();
10562   EVT NVT = N->getValueType(0);
10563
10564   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10565     // Check if the result type doesn't match the inserted element type. A
10566     // SCALAR_TO_VECTOR may truncate the inserted element and the
10567     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10568     SDValue InOp = InVec.getOperand(0);
10569     if (InOp.getValueType() != NVT) {
10570       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10571       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10572     }
10573     return InOp;
10574   }
10575
10576   SDValue EltNo = N->getOperand(1);
10577   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10578
10579   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10580   // We only perform this optimization before the op legalization phase because
10581   // we may introduce new vector instructions which are not backed by TD
10582   // patterns. For example on AVX, extracting elements from a wide vector
10583   // without using extract_subvector. However, if we can find an underlying
10584   // scalar value, then we can always use that.
10585   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10586       && ConstEltNo) {
10587     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10588     int NumElem = VT.getVectorNumElements();
10589     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10590     // Find the new index to extract from.
10591     int OrigElt = SVOp->getMaskElt(Elt);
10592
10593     // Extracting an undef index is undef.
10594     if (OrigElt == -1)
10595       return DAG.getUNDEF(NVT);
10596
10597     // Select the right vector half to extract from.
10598     SDValue SVInVec;
10599     if (OrigElt < NumElem) {
10600       SVInVec = InVec->getOperand(0);
10601     } else {
10602       SVInVec = InVec->getOperand(1);
10603       OrigElt -= NumElem;
10604     }
10605
10606     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10607       SDValue InOp = SVInVec.getOperand(OrigElt);
10608       if (InOp.getValueType() != NVT) {
10609         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10610         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10611       }
10612
10613       return InOp;
10614     }
10615
10616     // FIXME: We should handle recursing on other vector shuffles and
10617     // scalar_to_vector here as well.
10618
10619     if (!LegalOperations) {
10620       EVT IndexTy = TLI.getVectorIdxTy();
10621       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10622                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10623     }
10624   }
10625
10626   bool BCNumEltsChanged = false;
10627   EVT ExtVT = VT.getVectorElementType();
10628   EVT LVT = ExtVT;
10629
10630   // If the result of load has to be truncated, then it's not necessarily
10631   // profitable.
10632   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10633     return SDValue();
10634
10635   if (InVec.getOpcode() == ISD::BITCAST) {
10636     // Don't duplicate a load with other uses.
10637     if (!InVec.hasOneUse())
10638       return SDValue();
10639
10640     EVT BCVT = InVec.getOperand(0).getValueType();
10641     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10642       return SDValue();
10643     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10644       BCNumEltsChanged = true;
10645     InVec = InVec.getOperand(0);
10646     ExtVT = BCVT.getVectorElementType();
10647   }
10648
10649   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10650   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10651       ISD::isNormalLoad(InVec.getNode()) &&
10652       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10653     SDValue Index = N->getOperand(1);
10654     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10655       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10656                                                            OrigLoad);
10657   }
10658
10659   // Perform only after legalization to ensure build_vector / vector_shuffle
10660   // optimizations have already been done.
10661   if (!LegalOperations) return SDValue();
10662
10663   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10664   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10665   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10666
10667   if (ConstEltNo) {
10668     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10669
10670     LoadSDNode *LN0 = nullptr;
10671     const ShuffleVectorSDNode *SVN = nullptr;
10672     if (ISD::isNormalLoad(InVec.getNode())) {
10673       LN0 = cast<LoadSDNode>(InVec);
10674     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10675                InVec.getOperand(0).getValueType() == ExtVT &&
10676                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10677       // Don't duplicate a load with other uses.
10678       if (!InVec.hasOneUse())
10679         return SDValue();
10680
10681       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10682     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10683       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10684       // =>
10685       // (load $addr+1*size)
10686
10687       // Don't duplicate a load with other uses.
10688       if (!InVec.hasOneUse())
10689         return SDValue();
10690
10691       // If the bit convert changed the number of elements, it is unsafe
10692       // to examine the mask.
10693       if (BCNumEltsChanged)
10694         return SDValue();
10695
10696       // Select the input vector, guarding against out of range extract vector.
10697       unsigned NumElems = VT.getVectorNumElements();
10698       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10699       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10700
10701       if (InVec.getOpcode() == ISD::BITCAST) {
10702         // Don't duplicate a load with other uses.
10703         if (!InVec.hasOneUse())
10704           return SDValue();
10705
10706         InVec = InVec.getOperand(0);
10707       }
10708       if (ISD::isNormalLoad(InVec.getNode())) {
10709         LN0 = cast<LoadSDNode>(InVec);
10710         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10711         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10712       }
10713     }
10714
10715     // Make sure we found a non-volatile load and the extractelement is
10716     // the only use.
10717     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10718       return SDValue();
10719
10720     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10721     if (Elt == -1)
10722       return DAG.getUNDEF(LVT);
10723
10724     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10725   }
10726
10727   return SDValue();
10728 }
10729
10730 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10731 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10732   // We perform this optimization post type-legalization because
10733   // the type-legalizer often scalarizes integer-promoted vectors.
10734   // Performing this optimization before may create bit-casts which
10735   // will be type-legalized to complex code sequences.
10736   // We perform this optimization only before the operation legalizer because we
10737   // may introduce illegal operations.
10738   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10739     return SDValue();
10740
10741   unsigned NumInScalars = N->getNumOperands();
10742   SDLoc dl(N);
10743   EVT VT = N->getValueType(0);
10744
10745   // Check to see if this is a BUILD_VECTOR of a bunch of values
10746   // which come from any_extend or zero_extend nodes. If so, we can create
10747   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10748   // optimizations. We do not handle sign-extend because we can't fill the sign
10749   // using shuffles.
10750   EVT SourceType = MVT::Other;
10751   bool AllAnyExt = true;
10752
10753   for (unsigned i = 0; i != NumInScalars; ++i) {
10754     SDValue In = N->getOperand(i);
10755     // Ignore undef inputs.
10756     if (In.getOpcode() == ISD::UNDEF) continue;
10757
10758     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10759     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10760
10761     // Abort if the element is not an extension.
10762     if (!ZeroExt && !AnyExt) {
10763       SourceType = MVT::Other;
10764       break;
10765     }
10766
10767     // The input is a ZeroExt or AnyExt. Check the original type.
10768     EVT InTy = In.getOperand(0).getValueType();
10769
10770     // Check that all of the widened source types are the same.
10771     if (SourceType == MVT::Other)
10772       // First time.
10773       SourceType = InTy;
10774     else if (InTy != SourceType) {
10775       // Multiple income types. Abort.
10776       SourceType = MVT::Other;
10777       break;
10778     }
10779
10780     // Check if all of the extends are ANY_EXTENDs.
10781     AllAnyExt &= AnyExt;
10782   }
10783
10784   // In order to have valid types, all of the inputs must be extended from the
10785   // same source type and all of the inputs must be any or zero extend.
10786   // Scalar sizes must be a power of two.
10787   EVT OutScalarTy = VT.getScalarType();
10788   bool ValidTypes = SourceType != MVT::Other &&
10789                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10790                  isPowerOf2_32(SourceType.getSizeInBits());
10791
10792   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10793   // turn into a single shuffle instruction.
10794   if (!ValidTypes)
10795     return SDValue();
10796
10797   bool isLE = TLI.isLittleEndian();
10798   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10799   assert(ElemRatio > 1 && "Invalid element size ratio");
10800   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10801                                DAG.getConstant(0, SourceType);
10802
10803   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10804   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10805
10806   // Populate the new build_vector
10807   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10808     SDValue Cast = N->getOperand(i);
10809     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10810             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10811             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10812     SDValue In;
10813     if (Cast.getOpcode() == ISD::UNDEF)
10814       In = DAG.getUNDEF(SourceType);
10815     else
10816       In = Cast->getOperand(0);
10817     unsigned Index = isLE ? (i * ElemRatio) :
10818                             (i * ElemRatio + (ElemRatio - 1));
10819
10820     assert(Index < Ops.size() && "Invalid index");
10821     Ops[Index] = In;
10822   }
10823
10824   // The type of the new BUILD_VECTOR node.
10825   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10826   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10827          "Invalid vector size");
10828   // Check if the new vector type is legal.
10829   if (!isTypeLegal(VecVT)) return SDValue();
10830
10831   // Make the new BUILD_VECTOR.
10832   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10833
10834   // The new BUILD_VECTOR node has the potential to be further optimized.
10835   AddToWorklist(BV.getNode());
10836   // Bitcast to the desired type.
10837   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10838 }
10839
10840 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10841   EVT VT = N->getValueType(0);
10842
10843   unsigned NumInScalars = N->getNumOperands();
10844   SDLoc dl(N);
10845
10846   EVT SrcVT = MVT::Other;
10847   unsigned Opcode = ISD::DELETED_NODE;
10848   unsigned NumDefs = 0;
10849
10850   for (unsigned i = 0; i != NumInScalars; ++i) {
10851     SDValue In = N->getOperand(i);
10852     unsigned Opc = In.getOpcode();
10853
10854     if (Opc == ISD::UNDEF)
10855       continue;
10856
10857     // If all scalar values are floats and converted from integers.
10858     if (Opcode == ISD::DELETED_NODE &&
10859         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10860       Opcode = Opc;
10861     }
10862
10863     if (Opc != Opcode)
10864       return SDValue();
10865
10866     EVT InVT = In.getOperand(0).getValueType();
10867
10868     // If all scalar values are typed differently, bail out. It's chosen to
10869     // simplify BUILD_VECTOR of integer types.
10870     if (SrcVT == MVT::Other)
10871       SrcVT = InVT;
10872     if (SrcVT != InVT)
10873       return SDValue();
10874     NumDefs++;
10875   }
10876
10877   // If the vector has just one element defined, it's not worth to fold it into
10878   // a vectorized one.
10879   if (NumDefs < 2)
10880     return SDValue();
10881
10882   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10883          && "Should only handle conversion from integer to float.");
10884   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10885
10886   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10887
10888   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10889     return SDValue();
10890
10891   SmallVector<SDValue, 8> Opnds;
10892   for (unsigned i = 0; i != NumInScalars; ++i) {
10893     SDValue In = N->getOperand(i);
10894
10895     if (In.getOpcode() == ISD::UNDEF)
10896       Opnds.push_back(DAG.getUNDEF(SrcVT));
10897     else
10898       Opnds.push_back(In.getOperand(0));
10899   }
10900   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10901   AddToWorklist(BV.getNode());
10902
10903   return DAG.getNode(Opcode, dl, VT, BV);
10904 }
10905
10906 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10907   unsigned NumInScalars = N->getNumOperands();
10908   SDLoc dl(N);
10909   EVT VT = N->getValueType(0);
10910
10911   // A vector built entirely of undefs is undef.
10912   if (ISD::allOperandsUndef(N))
10913     return DAG.getUNDEF(VT);
10914
10915   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10916   if (V.getNode())
10917     return V;
10918
10919   V = reduceBuildVecConvertToConvertBuildVec(N);
10920   if (V.getNode())
10921     return V;
10922
10923   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10924   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10925   // at most two distinct vectors, turn this into a shuffle node.
10926
10927   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10928   if (!isTypeLegal(VT))
10929     return SDValue();
10930
10931   // May only combine to shuffle after legalize if shuffle is legal.
10932   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10933     return SDValue();
10934
10935   SDValue VecIn1, VecIn2;
10936   bool UsesZeroVector = false;
10937   for (unsigned i = 0; i != NumInScalars; ++i) {
10938     SDValue Op = N->getOperand(i);
10939     // Ignore undef inputs.
10940     if (Op.getOpcode() == ISD::UNDEF) continue;
10941
10942     // See if we can combine this build_vector into a blend with a zero vector.
10943     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10944         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10945         (Op.getOpcode() == ISD::ConstantFP &&
10946         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10947       UsesZeroVector = true;
10948       continue;
10949     }
10950
10951     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10952     // constant index, bail out.
10953     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10954         !isa<ConstantSDNode>(Op.getOperand(1))) {
10955       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10956       break;
10957     }
10958
10959     // We allow up to two distinct input vectors.
10960     SDValue ExtractedFromVec = Op.getOperand(0);
10961     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10962       continue;
10963
10964     if (!VecIn1.getNode()) {
10965       VecIn1 = ExtractedFromVec;
10966     } else if (!VecIn2.getNode() && !UsesZeroVector) {
10967       VecIn2 = ExtractedFromVec;
10968     } else {
10969       // Too many inputs.
10970       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10971       break;
10972     }
10973   }
10974
10975   // If everything is good, we can make a shuffle operation.
10976   if (VecIn1.getNode()) {
10977     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
10978     SmallVector<int, 8> Mask;
10979     for (unsigned i = 0; i != NumInScalars; ++i) {
10980       unsigned Opcode = N->getOperand(i).getOpcode();
10981       if (Opcode == ISD::UNDEF) {
10982         Mask.push_back(-1);
10983         continue;
10984       }
10985
10986       // Operands can also be zero.
10987       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
10988         assert(UsesZeroVector &&
10989                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
10990                "Unexpected node found!");
10991         Mask.push_back(NumInScalars+i);
10992         continue;
10993       }
10994
10995       // If extracting from the first vector, just use the index directly.
10996       SDValue Extract = N->getOperand(i);
10997       SDValue ExtVal = Extract.getOperand(1);
10998       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10999       if (Extract.getOperand(0) == VecIn1) {
11000         Mask.push_back(ExtIndex);
11001         continue;
11002       }
11003
11004       // Otherwise, use InIdx + InputVecSize
11005       Mask.push_back(InNumElements + ExtIndex);
11006     }
11007
11008     // Avoid introducing illegal shuffles with zero.
11009     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11010       return SDValue();
11011
11012     // We can't generate a shuffle node with mismatched input and output types.
11013     // Attempt to transform a single input vector to the correct type.
11014     if ((VT != VecIn1.getValueType())) {
11015       // If the input vector type has a different base type to the output
11016       // vector type, bail out.
11017       EVT VTElemType = VT.getVectorElementType();
11018       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11019           (VecIn2.getNode() &&
11020            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11021         return SDValue();
11022
11023       // If the input vector is too small, widen it.
11024       // We only support widening of vectors which are half the size of the
11025       // output registers. For example XMM->YMM widening on X86 with AVX.
11026       EVT VecInT = VecIn1.getValueType();
11027       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11028         // If we only have one small input, widen it by adding undef values.
11029         if (!VecIn2.getNode())
11030           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11031                                DAG.getUNDEF(VecIn1.getValueType()));
11032         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11033           // If we have two small inputs of the same type, try to concat them.
11034           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11035           VecIn2 = SDValue(nullptr, 0);
11036         } else
11037           return SDValue();
11038       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11039         // If the input vector is too large, try to split it.
11040         // We don't support having two input vectors that are too large.
11041         if (VecIn2.getNode())
11042           return SDValue();
11043
11044         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11045           return SDValue();
11046         
11047         // Try to replace VecIn1 with two extract_subvectors
11048         // No need to update the masks, they should still be correct.
11049         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 
11050           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11051         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11052           DAG.getConstant(0, TLI.getVectorIdxTy()));
11053         UsesZeroVector = false;
11054       } else
11055         return SDValue();
11056     }
11057
11058     if (UsesZeroVector)
11059       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11060                                 DAG.getConstantFP(0.0, VT);
11061     else
11062       // If VecIn2 is unused then change it to undef.
11063       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11064
11065     // Check that we were able to transform all incoming values to the same
11066     // type.
11067     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11068         VecIn1.getValueType() != VT)
11069           return SDValue();
11070
11071     // Return the new VECTOR_SHUFFLE node.
11072     SDValue Ops[2];
11073     Ops[0] = VecIn1;
11074     Ops[1] = VecIn2;
11075     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11076   }
11077
11078   return SDValue();
11079 }
11080
11081 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11082   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11083   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11084   // inputs come from at most two distinct vectors, turn this into a shuffle
11085   // node.
11086
11087   // If we only have one input vector, we don't need to do any concatenation.
11088   if (N->getNumOperands() == 1)
11089     return N->getOperand(0);
11090
11091   // Check if all of the operands are undefs.
11092   EVT VT = N->getValueType(0);
11093   if (ISD::allOperandsUndef(N))
11094     return DAG.getUNDEF(VT);
11095
11096   // Optimize concat_vectors where one of the vectors is undef.
11097   if (N->getNumOperands() == 2 &&
11098       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11099     SDValue In = N->getOperand(0);
11100     assert(In.getValueType().isVector() && "Must concat vectors");
11101
11102     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11103     if (In->getOpcode() == ISD::BITCAST &&
11104         !In->getOperand(0)->getValueType(0).isVector()) {
11105       SDValue Scalar = In->getOperand(0);
11106       EVT SclTy = Scalar->getValueType(0);
11107
11108       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11109         return SDValue();
11110
11111       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11112                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11113       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11114         return SDValue();
11115
11116       SDLoc dl = SDLoc(N);
11117       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11118       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11119     }
11120   }
11121
11122   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11123   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11124   if (N->getNumOperands() == 2 &&
11125       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
11126       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
11127     EVT VT = N->getValueType(0);
11128     SDValue N0 = N->getOperand(0);
11129     SDValue N1 = N->getOperand(1);
11130     SmallVector<SDValue, 8> Opnds;
11131     unsigned BuildVecNumElts =  N0.getNumOperands();
11132
11133     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
11134     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
11135     if (SclTy0.isFloatingPoint()) {
11136       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11137         Opnds.push_back(N0.getOperand(i));
11138       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11139         Opnds.push_back(N1.getOperand(i));
11140     } else {
11141       // If BUILD_VECTOR are from built from integer, they may have different
11142       // operand types. Get the smaller type and truncate all operands to it.
11143       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
11144       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11145         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11146                         N0.getOperand(i)));
11147       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11148         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11149                         N1.getOperand(i)));
11150     }
11151
11152     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11153   }
11154
11155   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11156   // nodes often generate nop CONCAT_VECTOR nodes.
11157   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11158   // place the incoming vectors at the exact same location.
11159   SDValue SingleSource = SDValue();
11160   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11161
11162   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11163     SDValue Op = N->getOperand(i);
11164
11165     if (Op.getOpcode() == ISD::UNDEF)
11166       continue;
11167
11168     // Check if this is the identity extract:
11169     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11170       return SDValue();
11171
11172     // Find the single incoming vector for the extract_subvector.
11173     if (SingleSource.getNode()) {
11174       if (Op.getOperand(0) != SingleSource)
11175         return SDValue();
11176     } else {
11177       SingleSource = Op.getOperand(0);
11178
11179       // Check the source type is the same as the type of the result.
11180       // If not, this concat may extend the vector, so we can not
11181       // optimize it away.
11182       if (SingleSource.getValueType() != N->getValueType(0))
11183         return SDValue();
11184     }
11185
11186     unsigned IdentityIndex = i * PartNumElem;
11187     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11188     // The extract index must be constant.
11189     if (!CS)
11190       return SDValue();
11191
11192     // Check that we are reading from the identity index.
11193     if (CS->getZExtValue() != IdentityIndex)
11194       return SDValue();
11195   }
11196
11197   if (SingleSource.getNode())
11198     return SingleSource;
11199
11200   return SDValue();
11201 }
11202
11203 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11204   EVT NVT = N->getValueType(0);
11205   SDValue V = N->getOperand(0);
11206
11207   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11208     // Combine:
11209     //    (extract_subvec (concat V1, V2, ...), i)
11210     // Into:
11211     //    Vi if possible
11212     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11213     // type.
11214     if (V->getOperand(0).getValueType() != NVT)
11215       return SDValue();
11216     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11217     unsigned NumElems = NVT.getVectorNumElements();
11218     assert((Idx % NumElems) == 0 &&
11219            "IDX in concat is not a multiple of the result vector length.");
11220     return V->getOperand(Idx / NumElems);
11221   }
11222
11223   // Skip bitcasting
11224   if (V->getOpcode() == ISD::BITCAST)
11225     V = V.getOperand(0);
11226
11227   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11228     SDLoc dl(N);
11229     // Handle only simple case where vector being inserted and vector
11230     // being extracted are of same type, and are half size of larger vectors.
11231     EVT BigVT = V->getOperand(0).getValueType();
11232     EVT SmallVT = V->getOperand(1).getValueType();
11233     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11234       return SDValue();
11235
11236     // Only handle cases where both indexes are constants with the same type.
11237     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11238     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11239
11240     if (InsIdx && ExtIdx &&
11241         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11242         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11243       // Combine:
11244       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11245       // Into:
11246       //    indices are equal or bit offsets are equal => V1
11247       //    otherwise => (extract_subvec V1, ExtIdx)
11248       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11249           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11250         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11251       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11252                          DAG.getNode(ISD::BITCAST, dl,
11253                                      N->getOperand(0).getValueType(),
11254                                      V->getOperand(0)), N->getOperand(1));
11255     }
11256   }
11257
11258   return SDValue();
11259 }
11260
11261 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11262                                                  SDValue V, SelectionDAG &DAG) {
11263   SDLoc DL(V);
11264   EVT VT = V.getValueType();
11265
11266   switch (V.getOpcode()) {
11267   default:
11268     return V;
11269
11270   case ISD::CONCAT_VECTORS: {
11271     EVT OpVT = V->getOperand(0).getValueType();
11272     int OpSize = OpVT.getVectorNumElements();
11273     SmallBitVector OpUsedElements(OpSize, false);
11274     bool FoundSimplification = false;
11275     SmallVector<SDValue, 4> NewOps;
11276     NewOps.reserve(V->getNumOperands());
11277     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11278       SDValue Op = V->getOperand(i);
11279       bool OpUsed = false;
11280       for (int j = 0; j < OpSize; ++j)
11281         if (UsedElements[i * OpSize + j]) {
11282           OpUsedElements[j] = true;
11283           OpUsed = true;
11284         }
11285       NewOps.push_back(
11286           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11287                  : DAG.getUNDEF(OpVT));
11288       FoundSimplification |= Op == NewOps.back();
11289       OpUsedElements.reset();
11290     }
11291     if (FoundSimplification)
11292       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11293     return V;
11294   }
11295
11296   case ISD::INSERT_SUBVECTOR: {
11297     SDValue BaseV = V->getOperand(0);
11298     SDValue SubV = V->getOperand(1);
11299     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11300     if (!IdxN)
11301       return V;
11302
11303     int SubSize = SubV.getValueType().getVectorNumElements();
11304     int Idx = IdxN->getZExtValue();
11305     bool SubVectorUsed = false;
11306     SmallBitVector SubUsedElements(SubSize, false);
11307     for (int i = 0; i < SubSize; ++i)
11308       if (UsedElements[i + Idx]) {
11309         SubVectorUsed = true;
11310         SubUsedElements[i] = true;
11311         UsedElements[i + Idx] = false;
11312       }
11313
11314     // Now recurse on both the base and sub vectors.
11315     SDValue SimplifiedSubV =
11316         SubVectorUsed
11317             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11318             : DAG.getUNDEF(SubV.getValueType());
11319     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11320     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11321       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11322                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11323     return V;
11324   }
11325   }
11326 }
11327
11328 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11329                                        SDValue N1, SelectionDAG &DAG) {
11330   EVT VT = SVN->getValueType(0);
11331   int NumElts = VT.getVectorNumElements();
11332   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11333   for (int M : SVN->getMask())
11334     if (M >= 0 && M < NumElts)
11335       N0UsedElements[M] = true;
11336     else if (M >= NumElts)
11337       N1UsedElements[M - NumElts] = true;
11338
11339   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11340   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11341   if (S0 == N0 && S1 == N1)
11342     return SDValue();
11343
11344   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11345 }
11346
11347 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
11348 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11349   EVT VT = N->getValueType(0);
11350   unsigned NumElts = VT.getVectorNumElements();
11351
11352   SDValue N0 = N->getOperand(0);
11353   SDValue N1 = N->getOperand(1);
11354   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11355
11356   SmallVector<SDValue, 4> Ops;
11357   EVT ConcatVT = N0.getOperand(0).getValueType();
11358   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11359   unsigned NumConcats = NumElts / NumElemsPerConcat;
11360
11361   // Look at every vector that's inserted. We're looking for exact
11362   // subvector-sized copies from a concatenated vector
11363   for (unsigned I = 0; I != NumConcats; ++I) {
11364     // Make sure we're dealing with a copy.
11365     unsigned Begin = I * NumElemsPerConcat;
11366     bool AllUndef = true, NoUndef = true;
11367     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11368       if (SVN->getMaskElt(J) >= 0)
11369         AllUndef = false;
11370       else
11371         NoUndef = false;
11372     }
11373
11374     if (NoUndef) {
11375       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11376         return SDValue();
11377
11378       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11379         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11380           return SDValue();
11381
11382       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11383       if (FirstElt < N0.getNumOperands())
11384         Ops.push_back(N0.getOperand(FirstElt));
11385       else
11386         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11387
11388     } else if (AllUndef) {
11389       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11390     } else { // Mixed with general masks and undefs, can't do optimization.
11391       return SDValue();
11392     }
11393   }
11394
11395   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11396 }
11397
11398 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11399   EVT VT = N->getValueType(0);
11400   unsigned NumElts = VT.getVectorNumElements();
11401
11402   SDValue N0 = N->getOperand(0);
11403   SDValue N1 = N->getOperand(1);
11404
11405   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11406
11407   // Canonicalize shuffle undef, undef -> undef
11408   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11409     return DAG.getUNDEF(VT);
11410
11411   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11412
11413   // Canonicalize shuffle v, v -> v, undef
11414   if (N0 == N1) {
11415     SmallVector<int, 8> NewMask;
11416     for (unsigned i = 0; i != NumElts; ++i) {
11417       int Idx = SVN->getMaskElt(i);
11418       if (Idx >= (int)NumElts) Idx -= NumElts;
11419       NewMask.push_back(Idx);
11420     }
11421     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11422                                 &NewMask[0]);
11423   }
11424
11425   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11426   if (N0.getOpcode() == ISD::UNDEF) {
11427     SmallVector<int, 8> NewMask;
11428     for (unsigned i = 0; i != NumElts; ++i) {
11429       int Idx = SVN->getMaskElt(i);
11430       if (Idx >= 0) {
11431         if (Idx >= (int)NumElts)
11432           Idx -= NumElts;
11433         else
11434           Idx = -1; // remove reference to lhs
11435       }
11436       NewMask.push_back(Idx);
11437     }
11438     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11439                                 &NewMask[0]);
11440   }
11441
11442   // Remove references to rhs if it is undef
11443   if (N1.getOpcode() == ISD::UNDEF) {
11444     bool Changed = false;
11445     SmallVector<int, 8> NewMask;
11446     for (unsigned i = 0; i != NumElts; ++i) {
11447       int Idx = SVN->getMaskElt(i);
11448       if (Idx >= (int)NumElts) {
11449         Idx = -1;
11450         Changed = true;
11451       }
11452       NewMask.push_back(Idx);
11453     }
11454     if (Changed)
11455       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11456   }
11457
11458   // If it is a splat, check if the argument vector is another splat or a
11459   // build_vector with all scalar elements the same.
11460   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11461     SDNode *V = N0.getNode();
11462
11463     // If this is a bit convert that changes the element type of the vector but
11464     // not the number of vector elements, look through it.  Be careful not to
11465     // look though conversions that change things like v4f32 to v2f64.
11466     if (V->getOpcode() == ISD::BITCAST) {
11467       SDValue ConvInput = V->getOperand(0);
11468       if (ConvInput.getValueType().isVector() &&
11469           ConvInput.getValueType().getVectorNumElements() == NumElts)
11470         V = ConvInput.getNode();
11471     }
11472
11473     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11474       assert(V->getNumOperands() == NumElts &&
11475              "BUILD_VECTOR has wrong number of operands");
11476       SDValue Base;
11477       bool AllSame = true;
11478       for (unsigned i = 0; i != NumElts; ++i) {
11479         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11480           Base = V->getOperand(i);
11481           break;
11482         }
11483       }
11484       // Splat of <u, u, u, u>, return <u, u, u, u>
11485       if (!Base.getNode())
11486         return N0;
11487       for (unsigned i = 0; i != NumElts; ++i) {
11488         if (V->getOperand(i) != Base) {
11489           AllSame = false;
11490           break;
11491         }
11492       }
11493       // Splat of <x, x, x, x>, return <x, x, x, x>
11494       if (AllSame)
11495         return N0;
11496     }
11497   }
11498
11499   // There are various patterns used to build up a vector from smaller vectors,
11500   // subvectors, or elements. Scan chains of these and replace unused insertions
11501   // or components with undef.
11502   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11503     return S;
11504
11505   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11506       Level < AfterLegalizeVectorOps &&
11507       (N1.getOpcode() == ISD::UNDEF ||
11508       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11509        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11510     SDValue V = partitionShuffleOfConcats(N, DAG);
11511
11512     if (V.getNode())
11513       return V;
11514   }
11515
11516   // Canonicalize shuffles according to rules:
11517   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11518   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11519   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11520   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11521       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11522       TLI.isTypeLegal(VT)) {
11523     // The incoming shuffle must be of the same type as the result of the
11524     // current shuffle.
11525     assert(N1->getOperand(0).getValueType() == VT &&
11526            "Shuffle types don't match");
11527
11528     SDValue SV0 = N1->getOperand(0);
11529     SDValue SV1 = N1->getOperand(1);
11530     bool HasSameOp0 = N0 == SV0;
11531     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11532     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11533       // Commute the operands of this shuffle so that next rule
11534       // will trigger.
11535       return DAG.getCommutedVectorShuffle(*SVN);
11536   }
11537
11538   // Try to fold according to rules:
11539   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11540   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11541   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11542   // Don't try to fold shuffles with illegal type.
11543   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11544       TLI.isTypeLegal(VT)) {
11545     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11546
11547     // The incoming shuffle must be of the same type as the result of the
11548     // current shuffle.
11549     assert(OtherSV->getOperand(0).getValueType() == VT &&
11550            "Shuffle types don't match");
11551
11552     SDValue SV0, SV1;
11553     SmallVector<int, 4> Mask;
11554     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11555     // operand, and SV1 as the second operand.
11556     for (unsigned i = 0; i != NumElts; ++i) {
11557       int Idx = SVN->getMaskElt(i);
11558       if (Idx < 0) {
11559         // Propagate Undef.
11560         Mask.push_back(Idx);
11561         continue;
11562       }
11563
11564       SDValue CurrentVec;
11565       if (Idx < (int)NumElts) {
11566         // This shuffle index refers to the inner shuffle N0. Lookup the inner
11567         // shuffle mask to identify which vector is actually referenced.
11568         Idx = OtherSV->getMaskElt(Idx);
11569         if (Idx < 0) {
11570           // Propagate Undef.
11571           Mask.push_back(Idx);
11572           continue;
11573         }
11574
11575         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11576                                            : OtherSV->getOperand(1);
11577       } else {
11578         // This shuffle index references an element within N1.
11579         CurrentVec = N1;
11580       }
11581
11582       // Simple case where 'CurrentVec' is UNDEF.
11583       if (CurrentVec.getOpcode() == ISD::UNDEF) {
11584         Mask.push_back(-1);
11585         continue;
11586       }
11587
11588       // Canonicalize the shuffle index. We don't know yet if CurrentVec
11589       // will be the first or second operand of the combined shuffle.
11590       Idx = Idx % NumElts;
11591       if (!SV0.getNode() || SV0 == CurrentVec) {
11592         // Ok. CurrentVec is the left hand side.
11593         // Update the mask accordingly.
11594         SV0 = CurrentVec;
11595         Mask.push_back(Idx);
11596         continue;
11597       }
11598
11599       // Bail out if we cannot convert the shuffle pair into a single shuffle.
11600       if (SV1.getNode() && SV1 != CurrentVec)
11601         return SDValue();
11602
11603       // Ok. CurrentVec is the right hand side.
11604       // Update the mask accordingly.
11605       SV1 = CurrentVec;
11606       Mask.push_back(Idx + NumElts);
11607     }
11608
11609     // Check if all indices in Mask are Undef. In case, propagate Undef.
11610     bool isUndefMask = true;
11611     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11612       isUndefMask &= Mask[i] < 0;
11613
11614     if (isUndefMask)
11615       return DAG.getUNDEF(VT);
11616
11617     if (!SV0.getNode())
11618       SV0 = DAG.getUNDEF(VT);
11619     if (!SV1.getNode())
11620       SV1 = DAG.getUNDEF(VT);
11621
11622     // Avoid introducing shuffles with illegal mask.
11623     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11624       // Compute the commuted shuffle mask and test again.
11625       for (unsigned i = 0; i != NumElts; ++i) {
11626         int idx = Mask[i];
11627         if (idx < 0)
11628           continue;
11629         else if (idx < (int)NumElts)
11630           Mask[i] = idx + NumElts;
11631         else
11632           Mask[i] = idx - NumElts;
11633       }
11634
11635       if (!TLI.isShuffleMaskLegal(Mask, VT))
11636         return SDValue();
11637  
11638       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11639       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11640       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11641       std::swap(SV0, SV1);
11642     }
11643
11644     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11645     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11646     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11647     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11648   }
11649
11650   return SDValue();
11651 }
11652
11653 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11654   SDValue N0 = N->getOperand(0);
11655   SDValue N2 = N->getOperand(2);
11656
11657   // If the input vector is a concatenation, and the insert replaces
11658   // one of the halves, we can optimize into a single concat_vectors.
11659   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11660       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11661     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11662     EVT VT = N->getValueType(0);
11663
11664     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11665     // (concat_vectors Z, Y)
11666     if (InsIdx == 0)
11667       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11668                          N->getOperand(1), N0.getOperand(1));
11669
11670     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11671     // (concat_vectors X, Z)
11672     if (InsIdx == VT.getVectorNumElements()/2)
11673       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11674                          N0.getOperand(0), N->getOperand(1));
11675   }
11676
11677   return SDValue();
11678 }
11679
11680 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11681 /// with the destination vector and a zero vector.
11682 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11683 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11684 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11685   EVT VT = N->getValueType(0);
11686   SDLoc dl(N);
11687   SDValue LHS = N->getOperand(0);
11688   SDValue RHS = N->getOperand(1);
11689   if (N->getOpcode() == ISD::AND) {
11690     if (RHS.getOpcode() == ISD::BITCAST)
11691       RHS = RHS.getOperand(0);
11692     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11693       SmallVector<int, 8> Indices;
11694       unsigned NumElts = RHS.getNumOperands();
11695       for (unsigned i = 0; i != NumElts; ++i) {
11696         SDValue Elt = RHS.getOperand(i);
11697         if (!isa<ConstantSDNode>(Elt))
11698           return SDValue();
11699
11700         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11701           Indices.push_back(i);
11702         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11703           Indices.push_back(NumElts+i);
11704         else
11705           return SDValue();
11706       }
11707
11708       // Let's see if the target supports this vector_shuffle.
11709       EVT RVT = RHS.getValueType();
11710       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11711         return SDValue();
11712
11713       // Return the new VECTOR_SHUFFLE node.
11714       EVT EltVT = RVT.getVectorElementType();
11715       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11716                                      DAG.getConstant(0, EltVT));
11717       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11718       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11719       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11720       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11721     }
11722   }
11723
11724   return SDValue();
11725 }
11726
11727 /// Visit a binary vector operation, like ADD.
11728 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11729   assert(N->getValueType(0).isVector() &&
11730          "SimplifyVBinOp only works on vectors!");
11731
11732   SDValue LHS = N->getOperand(0);
11733   SDValue RHS = N->getOperand(1);
11734   SDValue Shuffle = XformToShuffleWithZero(N);
11735   if (Shuffle.getNode()) return Shuffle;
11736
11737   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11738   // this operation.
11739   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11740       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11741     // Check if both vectors are constants. If not bail out.
11742     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11743           cast<BuildVectorSDNode>(RHS)->isConstant()))
11744       return SDValue();
11745
11746     SmallVector<SDValue, 8> Ops;
11747     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11748       SDValue LHSOp = LHS.getOperand(i);
11749       SDValue RHSOp = RHS.getOperand(i);
11750
11751       // Can't fold divide by zero.
11752       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11753           N->getOpcode() == ISD::FDIV) {
11754         if ((RHSOp.getOpcode() == ISD::Constant &&
11755              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11756             (RHSOp.getOpcode() == ISD::ConstantFP &&
11757              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11758           break;
11759       }
11760
11761       EVT VT = LHSOp.getValueType();
11762       EVT RVT = RHSOp.getValueType();
11763       if (RVT != VT) {
11764         // Integer BUILD_VECTOR operands may have types larger than the element
11765         // size (e.g., when the element type is not legal).  Prior to type
11766         // legalization, the types may not match between the two BUILD_VECTORS.
11767         // Truncate one of the operands to make them match.
11768         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11769           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11770         } else {
11771           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11772           VT = RVT;
11773         }
11774       }
11775       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11776                                    LHSOp, RHSOp);
11777       if (FoldOp.getOpcode() != ISD::UNDEF &&
11778           FoldOp.getOpcode() != ISD::Constant &&
11779           FoldOp.getOpcode() != ISD::ConstantFP)
11780         break;
11781       Ops.push_back(FoldOp);
11782       AddToWorklist(FoldOp.getNode());
11783     }
11784
11785     if (Ops.size() == LHS.getNumOperands())
11786       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11787   }
11788
11789   // Type legalization might introduce new shuffles in the DAG.
11790   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11791   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11792   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11793       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11794       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11795       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11796     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11797     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11798
11799     if (SVN0->getMask().equals(SVN1->getMask())) {
11800       EVT VT = N->getValueType(0);
11801       SDValue UndefVector = LHS.getOperand(1);
11802       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11803                                      LHS.getOperand(0), RHS.getOperand(0));
11804       AddUsersToWorklist(N);
11805       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11806                                   &SVN0->getMask()[0]);
11807     }
11808   }
11809
11810   return SDValue();
11811 }
11812
11813 /// Visit a binary vector operation, like FABS/FNEG.
11814 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11815   assert(N->getValueType(0).isVector() &&
11816          "SimplifyVUnaryOp only works on vectors!");
11817
11818   SDValue N0 = N->getOperand(0);
11819
11820   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11821     return SDValue();
11822
11823   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11824   SmallVector<SDValue, 8> Ops;
11825   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11826     SDValue Op = N0.getOperand(i);
11827     if (Op.getOpcode() != ISD::UNDEF &&
11828         Op.getOpcode() != ISD::ConstantFP)
11829       break;
11830     EVT EltVT = Op.getValueType();
11831     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11832     if (FoldOp.getOpcode() != ISD::UNDEF &&
11833         FoldOp.getOpcode() != ISD::ConstantFP)
11834       break;
11835     Ops.push_back(FoldOp);
11836     AddToWorklist(FoldOp.getNode());
11837   }
11838
11839   if (Ops.size() != N0.getNumOperands())
11840     return SDValue();
11841
11842   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11843 }
11844
11845 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11846                                     SDValue N1, SDValue N2){
11847   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11848
11849   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11850                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11851
11852   // If we got a simplified select_cc node back from SimplifySelectCC, then
11853   // break it down into a new SETCC node, and a new SELECT node, and then return
11854   // the SELECT node, since we were called with a SELECT node.
11855   if (SCC.getNode()) {
11856     // Check to see if we got a select_cc back (to turn into setcc/select).
11857     // Otherwise, just return whatever node we got back, like fabs.
11858     if (SCC.getOpcode() == ISD::SELECT_CC) {
11859       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11860                                   N0.getValueType(),
11861                                   SCC.getOperand(0), SCC.getOperand(1),
11862                                   SCC.getOperand(4));
11863       AddToWorklist(SETCC.getNode());
11864       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11865                            SCC.getOperand(2), SCC.getOperand(3));
11866     }
11867
11868     return SCC;
11869   }
11870   return SDValue();
11871 }
11872
11873 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11874 /// being selected between, see if we can simplify the select.  Callers of this
11875 /// should assume that TheSelect is deleted if this returns true.  As such, they
11876 /// should return the appropriate thing (e.g. the node) back to the top-level of
11877 /// the DAG combiner loop to avoid it being looked at.
11878 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11879                                     SDValue RHS) {
11880
11881   // Cannot simplify select with vector condition
11882   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11883
11884   // If this is a select from two identical things, try to pull the operation
11885   // through the select.
11886   if (LHS.getOpcode() != RHS.getOpcode() ||
11887       !LHS.hasOneUse() || !RHS.hasOneUse())
11888     return false;
11889
11890   // If this is a load and the token chain is identical, replace the select
11891   // of two loads with a load through a select of the address to load from.
11892   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11893   // constants have been dropped into the constant pool.
11894   if (LHS.getOpcode() == ISD::LOAD) {
11895     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11896     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11897
11898     // Token chains must be identical.
11899     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11900         // Do not let this transformation reduce the number of volatile loads.
11901         LLD->isVolatile() || RLD->isVolatile() ||
11902         // If this is an EXTLOAD, the VT's must match.
11903         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11904         // If this is an EXTLOAD, the kind of extension must match.
11905         (LLD->getExtensionType() != RLD->getExtensionType() &&
11906          // The only exception is if one of the extensions is anyext.
11907          LLD->getExtensionType() != ISD::EXTLOAD &&
11908          RLD->getExtensionType() != ISD::EXTLOAD) ||
11909         // FIXME: this discards src value information.  This is
11910         // over-conservative. It would be beneficial to be able to remember
11911         // both potential memory locations.  Since we are discarding
11912         // src value info, don't do the transformation if the memory
11913         // locations are not in the default address space.
11914         LLD->getPointerInfo().getAddrSpace() != 0 ||
11915         RLD->getPointerInfo().getAddrSpace() != 0 ||
11916         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11917                                       LLD->getBasePtr().getValueType()))
11918       return false;
11919
11920     // Check that the select condition doesn't reach either load.  If so,
11921     // folding this will induce a cycle into the DAG.  If not, this is safe to
11922     // xform, so create a select of the addresses.
11923     SDValue Addr;
11924     if (TheSelect->getOpcode() == ISD::SELECT) {
11925       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11926       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11927           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11928         return false;
11929       // The loads must not depend on one another.
11930       if (LLD->isPredecessorOf(RLD) ||
11931           RLD->isPredecessorOf(LLD))
11932         return false;
11933       Addr = DAG.getSelect(SDLoc(TheSelect),
11934                            LLD->getBasePtr().getValueType(),
11935                            TheSelect->getOperand(0), LLD->getBasePtr(),
11936                            RLD->getBasePtr());
11937     } else {  // Otherwise SELECT_CC
11938       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11939       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11940
11941       if ((LLD->hasAnyUseOfValue(1) &&
11942            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11943           (RLD->hasAnyUseOfValue(1) &&
11944            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11945         return false;
11946
11947       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11948                          LLD->getBasePtr().getValueType(),
11949                          TheSelect->getOperand(0),
11950                          TheSelect->getOperand(1),
11951                          LLD->getBasePtr(), RLD->getBasePtr(),
11952                          TheSelect->getOperand(4));
11953     }
11954
11955     SDValue Load;
11956     // It is safe to replace the two loads if they have different alignments,
11957     // but the new load must be the minimum (most restrictive) alignment of the
11958     // inputs.
11959     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11960     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11961     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11962       Load = DAG.getLoad(TheSelect->getValueType(0),
11963                          SDLoc(TheSelect),
11964                          // FIXME: Discards pointer and AA info.
11965                          LLD->getChain(), Addr, MachinePointerInfo(),
11966                          LLD->isVolatile(), LLD->isNonTemporal(),
11967                          isInvariant, Alignment);
11968     } else {
11969       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11970                             RLD->getExtensionType() : LLD->getExtensionType(),
11971                             SDLoc(TheSelect),
11972                             TheSelect->getValueType(0),
11973                             // FIXME: Discards pointer and AA info.
11974                             LLD->getChain(), Addr, MachinePointerInfo(),
11975                             LLD->getMemoryVT(), LLD->isVolatile(),
11976                             LLD->isNonTemporal(), isInvariant, Alignment);
11977     }
11978
11979     // Users of the select now use the result of the load.
11980     CombineTo(TheSelect, Load);
11981
11982     // Users of the old loads now use the new load's chain.  We know the
11983     // old-load value is dead now.
11984     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11985     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11986     return true;
11987   }
11988
11989   return false;
11990 }
11991
11992 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11993 /// where 'cond' is the comparison specified by CC.
11994 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11995                                       SDValue N2, SDValue N3,
11996                                       ISD::CondCode CC, bool NotExtCompare) {
11997   // (x ? y : y) -> y.
11998   if (N2 == N3) return N2;
11999
12000   EVT VT = N2.getValueType();
12001   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12002   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12003   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12004
12005   // Determine if the condition we're dealing with is constant
12006   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12007                               N0, N1, CC, DL, false);
12008   if (SCC.getNode()) AddToWorklist(SCC.getNode());
12009   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12010
12011   // fold select_cc true, x, y -> x
12012   if (SCCC && !SCCC->isNullValue())
12013     return N2;
12014   // fold select_cc false, x, y -> y
12015   if (SCCC && SCCC->isNullValue())
12016     return N3;
12017
12018   // Check to see if we can simplify the select into an fabs node
12019   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12020     // Allow either -0.0 or 0.0
12021     if (CFP->getValueAPF().isZero()) {
12022       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12023       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12024           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12025           N2 == N3.getOperand(0))
12026         return DAG.getNode(ISD::FABS, DL, VT, N0);
12027
12028       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12029       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12030           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12031           N2.getOperand(0) == N3)
12032         return DAG.getNode(ISD::FABS, DL, VT, N3);
12033     }
12034   }
12035
12036   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12037   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12038   // in it.  This is a win when the constant is not otherwise available because
12039   // it replaces two constant pool loads with one.  We only do this if the FP
12040   // type is known to be legal, because if it isn't, then we are before legalize
12041   // types an we want the other legalization to happen first (e.g. to avoid
12042   // messing with soft float) and if the ConstantFP is not legal, because if
12043   // it is legal, we may not need to store the FP constant in a constant pool.
12044   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12045     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12046       if (TLI.isTypeLegal(N2.getValueType()) &&
12047           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12048                TargetLowering::Legal &&
12049            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12050            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12051           // If both constants have multiple uses, then we won't need to do an
12052           // extra load, they are likely around in registers for other users.
12053           (TV->hasOneUse() || FV->hasOneUse())) {
12054         Constant *Elts[] = {
12055           const_cast<ConstantFP*>(FV->getConstantFPValue()),
12056           const_cast<ConstantFP*>(TV->getConstantFPValue())
12057         };
12058         Type *FPTy = Elts[0]->getType();
12059         const DataLayout &TD = *TLI.getDataLayout();
12060
12061         // Create a ConstantArray of the two constants.
12062         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12063         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12064                                             TD.getPrefTypeAlignment(FPTy));
12065         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12066
12067         // Get the offsets to the 0 and 1 element of the array so that we can
12068         // select between them.
12069         SDValue Zero = DAG.getIntPtrConstant(0);
12070         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12071         SDValue One = DAG.getIntPtrConstant(EltSize);
12072
12073         SDValue Cond = DAG.getSetCC(DL,
12074                                     getSetCCResultType(N0.getValueType()),
12075                                     N0, N1, CC);
12076         AddToWorklist(Cond.getNode());
12077         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12078                                           Cond, One, Zero);
12079         AddToWorklist(CstOffset.getNode());
12080         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12081                             CstOffset);
12082         AddToWorklist(CPIdx.getNode());
12083         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12084                            MachinePointerInfo::getConstantPool(), false,
12085                            false, false, Alignment);
12086
12087       }
12088     }
12089
12090   // Check to see if we can perform the "gzip trick", transforming
12091   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12092   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12093       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
12094        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
12095     EVT XType = N0.getValueType();
12096     EVT AType = N2.getValueType();
12097     if (XType.bitsGE(AType)) {
12098       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12099       // single-bit constant.
12100       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12101         unsigned ShCtV = N2C->getAPIntValue().logBase2();
12102         ShCtV = XType.getSizeInBits()-ShCtV-1;
12103         SDValue ShCt = DAG.getConstant(ShCtV,
12104                                        getShiftAmountTy(N0.getValueType()));
12105         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12106                                     XType, N0, ShCt);
12107         AddToWorklist(Shift.getNode());
12108
12109         if (XType.bitsGT(AType)) {
12110           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12111           AddToWorklist(Shift.getNode());
12112         }
12113
12114         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12115       }
12116
12117       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12118                                   XType, N0,
12119                                   DAG.getConstant(XType.getSizeInBits()-1,
12120                                          getShiftAmountTy(N0.getValueType())));
12121       AddToWorklist(Shift.getNode());
12122
12123       if (XType.bitsGT(AType)) {
12124         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12125         AddToWorklist(Shift.getNode());
12126       }
12127
12128       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12129     }
12130   }
12131
12132   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12133   // where y is has a single bit set.
12134   // A plaintext description would be, we can turn the SELECT_CC into an AND
12135   // when the condition can be materialized as an all-ones register.  Any
12136   // single bit-test can be materialized as an all-ones register with
12137   // shift-left and shift-right-arith.
12138   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12139       N0->getValueType(0) == VT &&
12140       N1C && N1C->isNullValue() &&
12141       N2C && N2C->isNullValue()) {
12142     SDValue AndLHS = N0->getOperand(0);
12143     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12144     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12145       // Shift the tested bit over the sign bit.
12146       APInt AndMask = ConstAndRHS->getAPIntValue();
12147       SDValue ShlAmt =
12148         DAG.getConstant(AndMask.countLeadingZeros(),
12149                         getShiftAmountTy(AndLHS.getValueType()));
12150       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12151
12152       // Now arithmetic right shift it all the way over, so the result is either
12153       // all-ones, or zero.
12154       SDValue ShrAmt =
12155         DAG.getConstant(AndMask.getBitWidth()-1,
12156                         getShiftAmountTy(Shl.getValueType()));
12157       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12158
12159       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12160     }
12161   }
12162
12163   // fold select C, 16, 0 -> shl C, 4
12164   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12165       TLI.getBooleanContents(N0.getValueType()) ==
12166           TargetLowering::ZeroOrOneBooleanContent) {
12167
12168     // If the caller doesn't want us to simplify this into a zext of a compare,
12169     // don't do it.
12170     if (NotExtCompare && N2C->getAPIntValue() == 1)
12171       return SDValue();
12172
12173     // Get a SetCC of the condition
12174     // NOTE: Don't create a SETCC if it's not legal on this target.
12175     if (!LegalOperations ||
12176         TLI.isOperationLegal(ISD::SETCC,
12177           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12178       SDValue Temp, SCC;
12179       // cast from setcc result type to select result type
12180       if (LegalTypes) {
12181         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12182                             N0, N1, CC);
12183         if (N2.getValueType().bitsLT(SCC.getValueType()))
12184           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12185                                         N2.getValueType());
12186         else
12187           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12188                              N2.getValueType(), SCC);
12189       } else {
12190         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12191         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12192                            N2.getValueType(), SCC);
12193       }
12194
12195       AddToWorklist(SCC.getNode());
12196       AddToWorklist(Temp.getNode());
12197
12198       if (N2C->getAPIntValue() == 1)
12199         return Temp;
12200
12201       // shl setcc result by log2 n2c
12202       return DAG.getNode(
12203           ISD::SHL, DL, N2.getValueType(), Temp,
12204           DAG.getConstant(N2C->getAPIntValue().logBase2(),
12205                           getShiftAmountTy(Temp.getValueType())));
12206     }
12207   }
12208
12209   // Check to see if this is the equivalent of setcc
12210   // FIXME: Turn all of these into setcc if setcc if setcc is legal
12211   // otherwise, go ahead with the folds.
12212   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12213     EVT XType = N0.getValueType();
12214     if (!LegalOperations ||
12215         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12216       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12217       if (Res.getValueType() != VT)
12218         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12219       return Res;
12220     }
12221
12222     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12223     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12224         (!LegalOperations ||
12225          TLI.isOperationLegal(ISD::CTLZ, XType))) {
12226       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12227       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12228                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
12229                                        getShiftAmountTy(Ctlz.getValueType())));
12230     }
12231     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12232     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12233       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12234                                   XType, DAG.getConstant(0, XType), N0);
12235       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12236       return DAG.getNode(ISD::SRL, DL, XType,
12237                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12238                          DAG.getConstant(XType.getSizeInBits()-1,
12239                                          getShiftAmountTy(XType)));
12240     }
12241     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12242     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12243       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12244                                  DAG.getConstant(XType.getSizeInBits()-1,
12245                                          getShiftAmountTy(N0.getValueType())));
12246       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12247     }
12248   }
12249
12250   // Check to see if this is an integer abs.
12251   // select_cc setg[te] X,  0,  X, -X ->
12252   // select_cc setgt    X, -1,  X, -X ->
12253   // select_cc setl[te] X,  0, -X,  X ->
12254   // select_cc setlt    X,  1, -X,  X ->
12255   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12256   if (N1C) {
12257     ConstantSDNode *SubC = nullptr;
12258     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12259          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12260         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12261       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12262     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12263               (N1C->isOne() && CC == ISD::SETLT)) &&
12264              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12265       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12266
12267     EVT XType = N0.getValueType();
12268     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12269       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12270                                   N0,
12271                                   DAG.getConstant(XType.getSizeInBits()-1,
12272                                          getShiftAmountTy(N0.getValueType())));
12273       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12274                                 XType, N0, Shift);
12275       AddToWorklist(Shift.getNode());
12276       AddToWorklist(Add.getNode());
12277       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12278     }
12279   }
12280
12281   return SDValue();
12282 }
12283
12284 /// This is a stub for TargetLowering::SimplifySetCC.
12285 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12286                                    SDValue N1, ISD::CondCode Cond,
12287                                    SDLoc DL, bool foldBooleans) {
12288   TargetLowering::DAGCombinerInfo
12289     DagCombineInfo(DAG, Level, false, this);
12290   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12291 }
12292
12293 /// Given an ISD::SDIV node expressing a divide by constant, return
12294 /// a DAG expression to select that will generate the same value by multiplying
12295 /// by a magic number.
12296 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12297 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12298   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12299   if (!C)
12300     return SDValue();
12301
12302   // Avoid division by zero.
12303   if (!C->getAPIntValue())
12304     return SDValue();
12305
12306   std::vector<SDNode*> Built;
12307   SDValue S =
12308       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12309
12310   for (SDNode *N : Built)
12311     AddToWorklist(N);
12312   return S;
12313 }
12314
12315 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12316 /// DAG expression that will generate the same value by right shifting.
12317 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12318   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12319   if (!C)
12320     return SDValue();
12321
12322   // Avoid division by zero.
12323   if (!C->getAPIntValue())
12324     return SDValue();
12325
12326   std::vector<SDNode *> Built;
12327   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12328
12329   for (SDNode *N : Built)
12330     AddToWorklist(N);
12331   return S;
12332 }
12333
12334 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12335 /// expression that will generate the same value by multiplying by a magic
12336 /// number.
12337 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12338 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12339   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12340   if (!C)
12341     return SDValue();
12342
12343   // Avoid division by zero.
12344   if (!C->getAPIntValue())
12345     return SDValue();
12346
12347   std::vector<SDNode*> Built;
12348   SDValue S =
12349       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12350
12351   for (SDNode *N : Built)
12352     AddToWorklist(N);
12353   return S;
12354 }
12355
12356 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12357   if (Level >= AfterLegalizeDAG)
12358     return SDValue();
12359
12360   // Expose the DAG combiner to the target combiner implementations.
12361   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12362
12363   unsigned Iterations = 0;
12364   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12365     if (Iterations) {
12366       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12367       // For the reciprocal, we need to find the zero of the function:
12368       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12369       //     =>
12370       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12371       //     does not require additional intermediate precision]
12372       EVT VT = Op.getValueType();
12373       SDLoc DL(Op);
12374       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12375
12376       AddToWorklist(Est.getNode());
12377
12378       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12379       for (unsigned i = 0; i < Iterations; ++i) {
12380         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12381         AddToWorklist(NewEst.getNode());
12382
12383         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12384         AddToWorklist(NewEst.getNode());
12385
12386         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12387         AddToWorklist(NewEst.getNode());
12388
12389         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12390         AddToWorklist(Est.getNode());
12391       }
12392     }
12393     return Est;
12394   }
12395
12396   return SDValue();
12397 }
12398
12399 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12400 /// For the reciprocal sqrt, we need to find the zero of the function:
12401 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12402 ///     =>
12403 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12404 /// As a result, we precompute A/2 prior to the iteration loop.
12405 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12406                                           unsigned Iterations) {
12407   EVT VT = Arg.getValueType();
12408   SDLoc DL(Arg);
12409   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12410
12411   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12412   // this entire sequence requires only one FP constant.
12413   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12414   AddToWorklist(HalfArg.getNode());
12415
12416   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12417   AddToWorklist(HalfArg.getNode());
12418
12419   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12420   for (unsigned i = 0; i < Iterations; ++i) {
12421     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12422     AddToWorklist(NewEst.getNode());
12423
12424     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12425     AddToWorklist(NewEst.getNode());
12426
12427     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12428     AddToWorklist(NewEst.getNode());
12429
12430     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12431     AddToWorklist(Est.getNode());
12432   }
12433   return Est;
12434 }
12435
12436 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12437 /// For the reciprocal sqrt, we need to find the zero of the function:
12438 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12439 ///     =>
12440 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12441 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12442                                           unsigned Iterations) {
12443   EVT VT = Arg.getValueType();
12444   SDLoc DL(Arg);
12445   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12446   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12447
12448   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12449   for (unsigned i = 0; i < Iterations; ++i) {
12450     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12451     AddToWorklist(HalfEst.getNode());
12452
12453     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12454     AddToWorklist(Est.getNode());
12455
12456     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12457     AddToWorklist(Est.getNode());
12458
12459     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12460     AddToWorklist(Est.getNode());
12461
12462     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12463     AddToWorklist(Est.getNode());
12464   }
12465   return Est;
12466 }
12467
12468 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12469   if (Level >= AfterLegalizeDAG)
12470     return SDValue();
12471
12472   // Expose the DAG combiner to the target combiner implementations.
12473   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12474   unsigned Iterations = 0;
12475   bool UseOneConstNR = false;
12476   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12477     AddToWorklist(Est.getNode());
12478     if (Iterations) {
12479       Est = UseOneConstNR ?
12480         BuildRsqrtNROneConst(Op, Est, Iterations) :
12481         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12482     }
12483     return Est;
12484   }
12485
12486   return SDValue();
12487 }
12488
12489 /// Return true if base is a frame index, which is known not to alias with
12490 /// anything but itself.  Provides base object and offset as results.
12491 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12492                            const GlobalValue *&GV, const void *&CV) {
12493   // Assume it is a primitive operation.
12494   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12495
12496   // If it's an adding a simple constant then integrate the offset.
12497   if (Base.getOpcode() == ISD::ADD) {
12498     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12499       Base = Base.getOperand(0);
12500       Offset += C->getZExtValue();
12501     }
12502   }
12503
12504   // Return the underlying GlobalValue, and update the Offset.  Return false
12505   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12506   // by multiple nodes with different offsets.
12507   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12508     GV = G->getGlobal();
12509     Offset += G->getOffset();
12510     return false;
12511   }
12512
12513   // Return the underlying Constant value, and update the Offset.  Return false
12514   // for ConstantSDNodes since the same constant pool entry may be represented
12515   // by multiple nodes with different offsets.
12516   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12517     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12518                                          : (const void *)C->getConstVal();
12519     Offset += C->getOffset();
12520     return false;
12521   }
12522   // If it's any of the following then it can't alias with anything but itself.
12523   return isa<FrameIndexSDNode>(Base);
12524 }
12525
12526 /// Return true if there is any possibility that the two addresses overlap.
12527 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12528   // If they are the same then they must be aliases.
12529   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12530
12531   // If they are both volatile then they cannot be reordered.
12532   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12533
12534   // Gather base node and offset information.
12535   SDValue Base1, Base2;
12536   int64_t Offset1, Offset2;
12537   const GlobalValue *GV1, *GV2;
12538   const void *CV1, *CV2;
12539   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12540                                       Base1, Offset1, GV1, CV1);
12541   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12542                                       Base2, Offset2, GV2, CV2);
12543
12544   // If they have a same base address then check to see if they overlap.
12545   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12546     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12547              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12548
12549   // It is possible for different frame indices to alias each other, mostly
12550   // when tail call optimization reuses return address slots for arguments.
12551   // To catch this case, look up the actual index of frame indices to compute
12552   // the real alias relationship.
12553   if (isFrameIndex1 && isFrameIndex2) {
12554     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12555     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12556     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12557     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12558              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12559   }
12560
12561   // Otherwise, if we know what the bases are, and they aren't identical, then
12562   // we know they cannot alias.
12563   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12564     return false;
12565
12566   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12567   // compared to the size and offset of the access, we may be able to prove they
12568   // do not alias.  This check is conservative for now to catch cases created by
12569   // splitting vector types.
12570   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12571       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12572       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12573        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12574       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12575     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12576     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12577
12578     // There is no overlap between these relatively aligned accesses of similar
12579     // size, return no alias.
12580     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12581         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12582       return false;
12583   }
12584
12585   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12586                    ? CombinerGlobalAA
12587                    : DAG.getSubtarget().useAA();
12588 #ifndef NDEBUG
12589   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12590       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12591     UseAA = false;
12592 #endif
12593   if (UseAA &&
12594       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12595     // Use alias analysis information.
12596     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12597                                  Op1->getSrcValueOffset());
12598     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12599         Op0->getSrcValueOffset() - MinOffset;
12600     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12601         Op1->getSrcValueOffset() - MinOffset;
12602     AliasAnalysis::AliasResult AAResult =
12603         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12604                                          Overlap1,
12605                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12606                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12607                                          Overlap2,
12608                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12609     if (AAResult == AliasAnalysis::NoAlias)
12610       return false;
12611   }
12612
12613   // Otherwise we have to assume they alias.
12614   return true;
12615 }
12616
12617 /// Walk up chain skipping non-aliasing memory nodes,
12618 /// looking for aliasing nodes and adding them to the Aliases vector.
12619 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12620                                    SmallVectorImpl<SDValue> &Aliases) {
12621   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12622   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12623
12624   // Get alias information for node.
12625   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12626
12627   // Starting off.
12628   Chains.push_back(OriginalChain);
12629   unsigned Depth = 0;
12630
12631   // Look at each chain and determine if it is an alias.  If so, add it to the
12632   // aliases list.  If not, then continue up the chain looking for the next
12633   // candidate.
12634   while (!Chains.empty()) {
12635     SDValue Chain = Chains.back();
12636     Chains.pop_back();
12637
12638     // For TokenFactor nodes, look at each operand and only continue up the
12639     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12640     // find more and revert to original chain since the xform is unlikely to be
12641     // profitable.
12642     //
12643     // FIXME: The depth check could be made to return the last non-aliasing
12644     // chain we found before we hit a tokenfactor rather than the original
12645     // chain.
12646     if (Depth > 6 || Aliases.size() == 2) {
12647       Aliases.clear();
12648       Aliases.push_back(OriginalChain);
12649       return;
12650     }
12651
12652     // Don't bother if we've been before.
12653     if (!Visited.insert(Chain.getNode()).second)
12654       continue;
12655
12656     switch (Chain.getOpcode()) {
12657     case ISD::EntryToken:
12658       // Entry token is ideal chain operand, but handled in FindBetterChain.
12659       break;
12660
12661     case ISD::LOAD:
12662     case ISD::STORE: {
12663       // Get alias information for Chain.
12664       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12665           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12666
12667       // If chain is alias then stop here.
12668       if (!(IsLoad && IsOpLoad) &&
12669           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12670         Aliases.push_back(Chain);
12671       } else {
12672         // Look further up the chain.
12673         Chains.push_back(Chain.getOperand(0));
12674         ++Depth;
12675       }
12676       break;
12677     }
12678
12679     case ISD::TokenFactor:
12680       // We have to check each of the operands of the token factor for "small"
12681       // token factors, so we queue them up.  Adding the operands to the queue
12682       // (stack) in reverse order maintains the original order and increases the
12683       // likelihood that getNode will find a matching token factor (CSE.)
12684       if (Chain.getNumOperands() > 16) {
12685         Aliases.push_back(Chain);
12686         break;
12687       }
12688       for (unsigned n = Chain.getNumOperands(); n;)
12689         Chains.push_back(Chain.getOperand(--n));
12690       ++Depth;
12691       break;
12692
12693     default:
12694       // For all other instructions we will just have to take what we can get.
12695       Aliases.push_back(Chain);
12696       break;
12697     }
12698   }
12699
12700   // We need to be careful here to also search for aliases through the
12701   // value operand of a store, etc. Consider the following situation:
12702   //   Token1 = ...
12703   //   L1 = load Token1, %52
12704   //   S1 = store Token1, L1, %51
12705   //   L2 = load Token1, %52+8
12706   //   S2 = store Token1, L2, %51+8
12707   //   Token2 = Token(S1, S2)
12708   //   L3 = load Token2, %53
12709   //   S3 = store Token2, L3, %52
12710   //   L4 = load Token2, %53+8
12711   //   S4 = store Token2, L4, %52+8
12712   // If we search for aliases of S3 (which loads address %52), and we look
12713   // only through the chain, then we'll miss the trivial dependence on L1
12714   // (which also loads from %52). We then might change all loads and
12715   // stores to use Token1 as their chain operand, which could result in
12716   // copying %53 into %52 before copying %52 into %51 (which should
12717   // happen first).
12718   //
12719   // The problem is, however, that searching for such data dependencies
12720   // can become expensive, and the cost is not directly related to the
12721   // chain depth. Instead, we'll rule out such configurations here by
12722   // insisting that we've visited all chain users (except for users
12723   // of the original chain, which is not necessary). When doing this,
12724   // we need to look through nodes we don't care about (otherwise, things
12725   // like register copies will interfere with trivial cases).
12726
12727   SmallVector<const SDNode *, 16> Worklist;
12728   for (const SDNode *N : Visited)
12729     if (N != OriginalChain.getNode())
12730       Worklist.push_back(N);
12731
12732   while (!Worklist.empty()) {
12733     const SDNode *M = Worklist.pop_back_val();
12734
12735     // We have already visited M, and want to make sure we've visited any uses
12736     // of M that we care about. For uses that we've not visisted, and don't
12737     // care about, queue them to the worklist.
12738
12739     for (SDNode::use_iterator UI = M->use_begin(),
12740          UIE = M->use_end(); UI != UIE; ++UI)
12741       if (UI.getUse().getValueType() == MVT::Other &&
12742           Visited.insert(*UI).second) {
12743         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12744           // We've not visited this use, and we care about it (it could have an
12745           // ordering dependency with the original node).
12746           Aliases.clear();
12747           Aliases.push_back(OriginalChain);
12748           return;
12749         }
12750
12751         // We've not visited this use, but we don't care about it. Mark it as
12752         // visited and enqueue it to the worklist.
12753         Worklist.push_back(*UI);
12754       }
12755   }
12756 }
12757
12758 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12759 /// (aliasing node.)
12760 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12761   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12762
12763   // Accumulate all the aliases to this node.
12764   GatherAllAliases(N, OldChain, Aliases);
12765
12766   // If no operands then chain to entry token.
12767   if (Aliases.size() == 0)
12768     return DAG.getEntryNode();
12769
12770   // If a single operand then chain to it.  We don't need to revisit it.
12771   if (Aliases.size() == 1)
12772     return Aliases[0];
12773
12774   // Construct a custom tailored token factor.
12775   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12776 }
12777
12778 /// This is the entry point for the file.
12779 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12780                            CodeGenOpt::Level OptLevel) {
12781   /// This is the main entry point to this class.
12782   DAGCombiner(*this, AA, OptLevel).Run(Level);
12783 }