Semantically revert r236031, which is not a good idea for in-order targets.
[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/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.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 visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitCTLZ(SDNode *N);
259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTTZ(SDNode *N);
261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTPOP(SDNode *N);
263     SDValue visitSELECT(SDNode *N);
264     SDValue visitVSELECT(SDNode *N);
265     SDValue visitSELECT_CC(SDNode *N);
266     SDValue visitSETCC(SDNode *N);
267     SDValue visitSIGN_EXTEND(SDNode *N);
268     SDValue visitZERO_EXTEND(SDNode *N);
269     SDValue visitANY_EXTEND(SDNode *N);
270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271     SDValue visitTRUNCATE(SDNode *N);
272     SDValue visitBITCAST(SDNode *N);
273     SDValue visitBUILD_PAIR(SDNode *N);
274     SDValue visitFADD(SDNode *N);
275     SDValue visitFSUB(SDNode *N);
276     SDValue visitFMUL(SDNode *N);
277     SDValue visitFMA(SDNode *N);
278     SDValue visitFDIV(SDNode *N);
279     SDValue visitFREM(SDNode *N);
280     SDValue visitFSQRT(SDNode *N);
281     SDValue visitFCOPYSIGN(SDNode *N);
282     SDValue visitSINT_TO_FP(SDNode *N);
283     SDValue visitUINT_TO_FP(SDNode *N);
284     SDValue visitFP_TO_SINT(SDNode *N);
285     SDValue visitFP_TO_UINT(SDNode *N);
286     SDValue visitFP_ROUND(SDNode *N);
287     SDValue visitFP_ROUND_INREG(SDNode *N);
288     SDValue visitFP_EXTEND(SDNode *N);
289     SDValue visitFNEG(SDNode *N);
290     SDValue visitFABS(SDNode *N);
291     SDValue visitFCEIL(SDNode *N);
292     SDValue visitFTRUNC(SDNode *N);
293     SDValue visitFFLOOR(SDNode *N);
294     SDValue visitFMINNUM(SDNode *N);
295     SDValue visitFMAXNUM(SDNode *N);
296     SDValue visitBRCOND(SDNode *N);
297     SDValue visitBR_CC(SDNode *N);
298     SDValue visitLOAD(SDNode *N);
299     SDValue visitSTORE(SDNode *N);
300     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302     SDValue visitBUILD_VECTOR(SDNode *N);
303     SDValue visitCONCAT_VECTORS(SDNode *N);
304     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305     SDValue visitVECTOR_SHUFFLE(SDNode *N);
306     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307     SDValue visitINSERT_SUBVECTOR(SDNode *N);
308     SDValue visitMLOAD(SDNode *N);
309     SDValue visitMSTORE(SDNode *N);
310     SDValue visitFP_TO_FP16(SDNode *N);
311
312     SDValue visitFADDForFMACombine(SDNode *N);
313     SDValue visitFSUBForFMACombine(SDNode *N);
314
315     SDValue XformToShuffleWithZero(SDNode *N);
316     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
317
318     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
319
320     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
321     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
322     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
323     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
324                              SDValue N3, ISD::CondCode CC,
325                              bool NotExtCompare = false);
326     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
327                           SDLoc DL, bool foldBooleans = true);
328
329     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
330                            SDValue &CC) const;
331     bool isOneUseSetCC(SDValue N) const;
332
333     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
334                                          unsigned HiOp);
335     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
336     SDValue CombineExtLoad(SDNode *N);
337     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
338     SDValue BuildSDIV(SDNode *N);
339     SDValue BuildSDIVPow2(SDNode *N);
340     SDValue BuildUDIV(SDNode *N);
341     SDValue BuildReciprocalEstimate(SDValue Op);
342     SDValue BuildRsqrtEstimate(SDValue Op);
343     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
344     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
345     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
346                                bool DemandHighBits = true);
347     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
348     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
349                               SDValue InnerPos, SDValue InnerNeg,
350                               unsigned PosOpcode, unsigned NegOpcode,
351                               SDLoc DL);
352     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
353     SDValue ReduceLoadWidth(SDNode *N);
354     SDValue ReduceLoadOpStoreWidth(SDNode *N);
355     SDValue TransformFPLoadStorePair(SDNode *N);
356     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
357     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
358
359     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
360
361     /// Walk up chain skipping non-aliasing memory nodes,
362     /// looking for aliasing nodes and adding them to the Aliases vector.
363     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
364                           SmallVectorImpl<SDValue> &Aliases);
365
366     /// Return true if there is any possibility that the two addresses overlap.
367     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
368
369     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
370     /// chain (aliasing node.)
371     SDValue FindBetterChain(SDNode *N, SDValue Chain);
372
373     /// Holds a pointer to an LSBaseSDNode as well as information on where it
374     /// is located in a sequence of memory operations connected by a chain.
375     struct MemOpLink {
376       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
377       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
378       // Ptr to the mem node.
379       LSBaseSDNode *MemNode;
380       // Offset from the base ptr.
381       int64_t OffsetFromBase;
382       // What is the sequence number of this mem node.
383       // Lowest mem operand in the DAG starts at zero.
384       unsigned SequenceNum;
385     };
386
387     /// This is a helper function for MergeConsecutiveStores. When the source
388     /// elements of the consecutive stores are all constants or all extracted
389     /// vector elements, try to merge them into one larger store.
390     /// \return True if a merged store was created.
391     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
392                                          EVT MemVT, unsigned NumElem,
393                                          bool IsConstantSrc, bool UseVector);
394
395     /// Merge consecutive store operations into a wide store.
396     /// This optimization uses wide integers or vectors when possible.
397     /// \return True if some memory operations were changed.
398     bool MergeConsecutiveStores(StoreSDNode *N);
399
400     /// \brief Try to transform a truncation where C is a constant:
401     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
402     ///
403     /// \p N needs to be a truncation and its first operand an AND. Other
404     /// requirements are checked by the function (e.g. that trunc is
405     /// single-use) and if missed an empty SDValue is returned.
406     SDValue distributeTruncateThroughAnd(SDNode *N);
407
408   public:
409     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
410         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
411           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
412       auto *F = DAG.getMachineFunction().getFunction();
413       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
414                     F->hasFnAttribute(Attribute::MinSize);
415     }
416
417     /// Runs the dag combiner on all nodes in the work list
418     void Run(CombineLevel AtLevel);
419
420     SelectionDAG &getDAG() const { return DAG; }
421
422     /// Returns a type large enough to hold any valid shift amount - before type
423     /// legalization these can be huge.
424     EVT getShiftAmountTy(EVT LHSTy) {
425       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
426       if (LHSTy.isVector())
427         return LHSTy;
428       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
429                         : TLI.getPointerTy();
430     }
431
432     /// This method returns true if we are running before type legalization or
433     /// if the specified VT is legal.
434     bool isTypeLegal(const EVT &VT) {
435       if (!LegalTypes) return true;
436       return TLI.isTypeLegal(VT);
437     }
438
439     /// Convenience wrapper around TargetLowering::getSetCCResultType
440     EVT getSetCCResultType(EVT VT) const {
441       return TLI.getSetCCResultType(*DAG.getContext(), VT);
442     }
443   };
444 }
445
446
447 namespace {
448 /// This class is a DAGUpdateListener that removes any deleted
449 /// nodes from the worklist.
450 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
451   DAGCombiner &DC;
452 public:
453   explicit WorklistRemover(DAGCombiner &dc)
454     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
455
456   void NodeDeleted(SDNode *N, SDNode *E) override {
457     DC.removeFromWorklist(N);
458   }
459 };
460 }
461
462 //===----------------------------------------------------------------------===//
463 //  TargetLowering::DAGCombinerInfo implementation
464 //===----------------------------------------------------------------------===//
465
466 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
467   ((DAGCombiner*)DC)->AddToWorklist(N);
468 }
469
470 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
471   ((DAGCombiner*)DC)->removeFromWorklist(N);
472 }
473
474 SDValue TargetLowering::DAGCombinerInfo::
475 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
476   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
477 }
478
479 SDValue TargetLowering::DAGCombinerInfo::
480 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
481   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
482 }
483
484
485 SDValue TargetLowering::DAGCombinerInfo::
486 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
487   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
488 }
489
490 void TargetLowering::DAGCombinerInfo::
491 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
492   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
493 }
494
495 //===----------------------------------------------------------------------===//
496 // Helper Functions
497 //===----------------------------------------------------------------------===//
498
499 void DAGCombiner::deleteAndRecombine(SDNode *N) {
500   removeFromWorklist(N);
501
502   // If the operands of this node are only used by the node, they will now be
503   // dead. Make sure to re-visit them and recursively delete dead nodes.
504   for (const SDValue &Op : N->ops())
505     // For an operand generating multiple values, one of the values may
506     // become dead allowing further simplification (e.g. split index
507     // arithmetic from an indexed load).
508     if (Op->hasOneUse() || Op->getNumValues() > 1)
509       AddToWorklist(Op.getNode());
510
511   DAG.DeleteNode(N);
512 }
513
514 /// Return 1 if we can compute the negated form of the specified expression for
515 /// the same cost as the expression itself, or 2 if we can compute the negated
516 /// form more cheaply than the expression itself.
517 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
518                                const TargetLowering &TLI,
519                                const TargetOptions *Options,
520                                unsigned Depth = 0) {
521   // fneg is removable even if it has multiple uses.
522   if (Op.getOpcode() == ISD::FNEG) return 2;
523
524   // Don't allow anything with multiple uses.
525   if (!Op.hasOneUse()) return 0;
526
527   // Don't recurse exponentially.
528   if (Depth > 6) return 0;
529
530   switch (Op.getOpcode()) {
531   default: return false;
532   case ISD::ConstantFP:
533     // Don't invert constant FP values after legalize.  The negated constant
534     // isn't necessarily legal.
535     return LegalOperations ? 0 : 1;
536   case ISD::FADD:
537     // FIXME: determine better conditions for this xform.
538     if (!Options->UnsafeFPMath) return 0;
539
540     // After operation legalization, it might not be legal to create new FSUBs.
541     if (LegalOperations &&
542         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
543       return 0;
544
545     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
546     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
547                                     Options, Depth + 1))
548       return V;
549     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
551                               Depth + 1);
552   case ISD::FSUB:
553     // We can't turn -(A-B) into B-A when we honor signed zeros.
554     if (!Options->UnsafeFPMath) return 0;
555
556     // fold (fneg (fsub A, B)) -> (fsub B, A)
557     return 1;
558
559   case ISD::FMUL:
560   case ISD::FDIV:
561     if (Options->HonorSignDependentRoundingFPMath()) return 0;
562
563     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
564     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
565                                     Options, Depth + 1))
566       return V;
567
568     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
569                               Depth + 1);
570
571   case ISD::FP_EXTEND:
572   case ISD::FP_ROUND:
573   case ISD::FSIN:
574     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
575                               Depth + 1);
576   }
577 }
578
579 /// If isNegatibleForFree returns true, return the newly negated expression.
580 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
581                                     bool LegalOperations, unsigned Depth = 0) {
582   const TargetOptions &Options = DAG.getTarget().Options;
583   // fneg is removable even if it has multiple uses.
584   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
585
586   // Don't allow anything with multiple uses.
587   assert(Op.hasOneUse() && "Unknown reuse!");
588
589   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
590   switch (Op.getOpcode()) {
591   default: llvm_unreachable("Unknown code");
592   case ISD::ConstantFP: {
593     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
594     V.changeSign();
595     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
596   }
597   case ISD::FADD:
598     // FIXME: determine better conditions for this xform.
599     assert(Options.UnsafeFPMath);
600
601     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
602     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
603                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
604       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
605                          GetNegatedExpression(Op.getOperand(0), DAG,
606                                               LegalOperations, Depth+1),
607                          Op.getOperand(1));
608     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
609     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
610                        GetNegatedExpression(Op.getOperand(1), DAG,
611                                             LegalOperations, Depth+1),
612                        Op.getOperand(0));
613   case ISD::FSUB:
614     // We can't turn -(A-B) into B-A when we honor signed zeros.
615     assert(Options.UnsafeFPMath);
616
617     // fold (fneg (fsub 0, B)) -> B
618     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
619       if (N0CFP->getValueAPF().isZero())
620         return Op.getOperand(1);
621
622     // fold (fneg (fsub A, B)) -> (fsub B, A)
623     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
624                        Op.getOperand(1), Op.getOperand(0));
625
626   case ISD::FMUL:
627   case ISD::FDIV:
628     assert(!Options.HonorSignDependentRoundingFPMath());
629
630     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
631     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
632                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
633       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
634                          GetNegatedExpression(Op.getOperand(0), DAG,
635                                               LegalOperations, Depth+1),
636                          Op.getOperand(1));
637
638     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
639     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
640                        Op.getOperand(0),
641                        GetNegatedExpression(Op.getOperand(1), DAG,
642                                             LegalOperations, Depth+1));
643
644   case ISD::FP_EXTEND:
645   case ISD::FSIN:
646     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
647                        GetNegatedExpression(Op.getOperand(0), DAG,
648                                             LegalOperations, Depth+1));
649   case ISD::FP_ROUND:
650       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
651                          GetNegatedExpression(Op.getOperand(0), DAG,
652                                               LegalOperations, Depth+1),
653                          Op.getOperand(1));
654   }
655 }
656
657 // Return true if this node is a setcc, or is a select_cc
658 // that selects between the target values used for true and false, making it
659 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
660 // the appropriate nodes based on the type of node we are checking. This
661 // simplifies life a bit for the callers.
662 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
663                                     SDValue &CC) const {
664   if (N.getOpcode() == ISD::SETCC) {
665     LHS = N.getOperand(0);
666     RHS = N.getOperand(1);
667     CC  = N.getOperand(2);
668     return true;
669   }
670
671   if (N.getOpcode() != ISD::SELECT_CC ||
672       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
673       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
674     return false;
675
676   if (TLI.getBooleanContents(N.getValueType()) ==
677       TargetLowering::UndefinedBooleanContent)
678     return false;
679
680   LHS = N.getOperand(0);
681   RHS = N.getOperand(1);
682   CC  = N.getOperand(4);
683   return true;
684 }
685
686 /// Return true if this is a SetCC-equivalent operation with only one use.
687 /// If this is true, it allows the users to invert the operation for free when
688 /// it is profitable to do so.
689 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
690   SDValue N0, N1, N2;
691   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
692     return true;
693   return false;
694 }
695
696 /// Returns true if N is a BUILD_VECTOR node whose
697 /// elements are all the same constant or undefined.
698 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
699   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
700   if (!C)
701     return false;
702
703   APInt SplatUndef;
704   unsigned SplatBitSize;
705   bool HasAnyUndefs;
706   EVT EltVT = N->getValueType(0).getVectorElementType();
707   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
708                              HasAnyUndefs) &&
709           EltVT.getSizeInBits() >= SplatBitSize);
710 }
711
712 // \brief Returns the SDNode if it is a constant integer BuildVector
713 // or constant integer.
714 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
715   if (isa<ConstantSDNode>(N))
716     return N.getNode();
717   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
718     return N.getNode();
719   return nullptr;
720 }
721
722 // \brief Returns the SDNode if it is a constant float BuildVector
723 // or constant float.
724 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
725   if (isa<ConstantFPSDNode>(N))
726     return N.getNode();
727   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
728     return N.getNode();
729   return nullptr;
730 }
731
732 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
733 // int.
734 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
735   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
736     return CN;
737
738   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
739     BitVector UndefElements;
740     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
741
742     // BuildVectors can truncate their operands. Ignore that case here.
743     // FIXME: We blindly ignore splats which include undef which is overly
744     // pessimistic.
745     if (CN && UndefElements.none() &&
746         CN->getValueType(0) == N.getValueType().getScalarType())
747       return CN;
748   }
749
750   return nullptr;
751 }
752
753 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
754 // float.
755 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
756   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
757     return CN;
758
759   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
760     BitVector UndefElements;
761     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
762
763     if (CN && UndefElements.none())
764       return CN;
765   }
766
767   return nullptr;
768 }
769
770 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
771                                     SDValue N0, SDValue N1) {
772   EVT VT = N0.getValueType();
773   if (N0.getOpcode() == Opc) {
774     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
775       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
776         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
777         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
778           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
779         return SDValue();
780       }
781       if (N0.hasOneUse()) {
782         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
783         // use
784         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
785         if (!OpNode.getNode())
786           return SDValue();
787         AddToWorklist(OpNode.getNode());
788         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
789       }
790     }
791   }
792
793   if (N1.getOpcode() == Opc) {
794     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
795       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
796         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
797         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
798           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
799         return SDValue();
800       }
801       if (N1.hasOneUse()) {
802         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
803         // use
804         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
805         if (!OpNode.getNode())
806           return SDValue();
807         AddToWorklist(OpNode.getNode());
808         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
809       }
810     }
811   }
812
813   return SDValue();
814 }
815
816 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
817                                bool AddTo) {
818   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
819   ++NodesCombined;
820   DEBUG(dbgs() << "\nReplacing.1 ";
821         N->dump(&DAG);
822         dbgs() << "\nWith: ";
823         To[0].getNode()->dump(&DAG);
824         dbgs() << " and " << NumTo-1 << " other values\n");
825   for (unsigned i = 0, e = NumTo; i != e; ++i)
826     assert((!To[i].getNode() ||
827             N->getValueType(i) == To[i].getValueType()) &&
828            "Cannot combine value to value of different type!");
829
830   WorklistRemover DeadNodes(*this);
831   DAG.ReplaceAllUsesWith(N, To);
832   if (AddTo) {
833     // Push the new nodes and any users onto the worklist
834     for (unsigned i = 0, e = NumTo; i != e; ++i) {
835       if (To[i].getNode()) {
836         AddToWorklist(To[i].getNode());
837         AddUsersToWorklist(To[i].getNode());
838       }
839     }
840   }
841
842   // Finally, if the node is now dead, remove it from the graph.  The node
843   // may not be dead if the replacement process recursively simplified to
844   // something else needing this node.
845   if (N->use_empty())
846     deleteAndRecombine(N);
847   return SDValue(N, 0);
848 }
849
850 void DAGCombiner::
851 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
852   // Replace all uses.  If any nodes become isomorphic to other nodes and
853   // are deleted, make sure to remove them from our worklist.
854   WorklistRemover DeadNodes(*this);
855   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
856
857   // Push the new node and any (possibly new) users onto the worklist.
858   AddToWorklist(TLO.New.getNode());
859   AddUsersToWorklist(TLO.New.getNode());
860
861   // Finally, if the node is now dead, remove it from the graph.  The node
862   // may not be dead if the replacement process recursively simplified to
863   // something else needing this node.
864   if (TLO.Old.getNode()->use_empty())
865     deleteAndRecombine(TLO.Old.getNode());
866 }
867
868 /// Check the specified integer node value to see if it can be simplified or if
869 /// things it uses can be simplified by bit propagation. If so, return true.
870 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
871   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
872   APInt KnownZero, KnownOne;
873   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
874     return false;
875
876   // Revisit the node.
877   AddToWorklist(Op.getNode());
878
879   // Replace the old value with the new one.
880   ++NodesCombined;
881   DEBUG(dbgs() << "\nReplacing.2 ";
882         TLO.Old.getNode()->dump(&DAG);
883         dbgs() << "\nWith: ";
884         TLO.New.getNode()->dump(&DAG);
885         dbgs() << '\n');
886
887   CommitTargetLoweringOpt(TLO);
888   return true;
889 }
890
891 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
892   SDLoc dl(Load);
893   EVT VT = Load->getValueType(0);
894   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
895
896   DEBUG(dbgs() << "\nReplacing.9 ";
897         Load->dump(&DAG);
898         dbgs() << "\nWith: ";
899         Trunc.getNode()->dump(&DAG);
900         dbgs() << '\n');
901   WorklistRemover DeadNodes(*this);
902   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
903   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
904   deleteAndRecombine(Load);
905   AddToWorklist(Trunc.getNode());
906 }
907
908 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
909   Replace = false;
910   SDLoc dl(Op);
911   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
912     EVT MemVT = LD->getMemoryVT();
913     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
914       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
915                                                        : ISD::EXTLOAD)
916       : LD->getExtensionType();
917     Replace = true;
918     return DAG.getExtLoad(ExtType, dl, PVT,
919                           LD->getChain(), LD->getBasePtr(),
920                           MemVT, LD->getMemOperand());
921   }
922
923   unsigned Opc = Op.getOpcode();
924   switch (Opc) {
925   default: break;
926   case ISD::AssertSext:
927     return DAG.getNode(ISD::AssertSext, dl, PVT,
928                        SExtPromoteOperand(Op.getOperand(0), PVT),
929                        Op.getOperand(1));
930   case ISD::AssertZext:
931     return DAG.getNode(ISD::AssertZext, dl, PVT,
932                        ZExtPromoteOperand(Op.getOperand(0), PVT),
933                        Op.getOperand(1));
934   case ISD::Constant: {
935     unsigned ExtOpc =
936       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
937     return DAG.getNode(ExtOpc, dl, PVT, Op);
938   }
939   }
940
941   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
942     return SDValue();
943   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
944 }
945
946 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
947   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
948     return SDValue();
949   EVT OldVT = Op.getValueType();
950   SDLoc dl(Op);
951   bool Replace = false;
952   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
953   if (!NewOp.getNode())
954     return SDValue();
955   AddToWorklist(NewOp.getNode());
956
957   if (Replace)
958     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
959   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
960                      DAG.getValueType(OldVT));
961 }
962
963 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
964   EVT OldVT = Op.getValueType();
965   SDLoc dl(Op);
966   bool Replace = false;
967   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
968   if (!NewOp.getNode())
969     return SDValue();
970   AddToWorklist(NewOp.getNode());
971
972   if (Replace)
973     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
974   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
975 }
976
977 /// Promote the specified integer binary operation if the target indicates it is
978 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
979 /// i32 since i16 instructions are longer.
980 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
981   if (!LegalOperations)
982     return SDValue();
983
984   EVT VT = Op.getValueType();
985   if (VT.isVector() || !VT.isInteger())
986     return SDValue();
987
988   // If operation type is 'undesirable', e.g. i16 on x86, consider
989   // promoting it.
990   unsigned Opc = Op.getOpcode();
991   if (TLI.isTypeDesirableForOp(Opc, VT))
992     return SDValue();
993
994   EVT PVT = VT;
995   // Consult target whether it is a good idea to promote this operation and
996   // what's the right type to promote it to.
997   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
998     assert(PVT != VT && "Don't know what type to promote to!");
999
1000     bool Replace0 = false;
1001     SDValue N0 = Op.getOperand(0);
1002     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1003     if (!NN0.getNode())
1004       return SDValue();
1005
1006     bool Replace1 = false;
1007     SDValue N1 = Op.getOperand(1);
1008     SDValue NN1;
1009     if (N0 == N1)
1010       NN1 = NN0;
1011     else {
1012       NN1 = PromoteOperand(N1, PVT, Replace1);
1013       if (!NN1.getNode())
1014         return SDValue();
1015     }
1016
1017     AddToWorklist(NN0.getNode());
1018     if (NN1.getNode())
1019       AddToWorklist(NN1.getNode());
1020
1021     if (Replace0)
1022       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1023     if (Replace1)
1024       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1025
1026     DEBUG(dbgs() << "\nPromoting ";
1027           Op.getNode()->dump(&DAG));
1028     SDLoc dl(Op);
1029     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1030                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1031   }
1032   return SDValue();
1033 }
1034
1035 /// Promote the specified integer shift operation if the target indicates it is
1036 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1037 /// i32 since i16 instructions are longer.
1038 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1039   if (!LegalOperations)
1040     return SDValue();
1041
1042   EVT VT = Op.getValueType();
1043   if (VT.isVector() || !VT.isInteger())
1044     return SDValue();
1045
1046   // If operation type is 'undesirable', e.g. i16 on x86, consider
1047   // promoting it.
1048   unsigned Opc = Op.getOpcode();
1049   if (TLI.isTypeDesirableForOp(Opc, VT))
1050     return SDValue();
1051
1052   EVT PVT = VT;
1053   // Consult target whether it is a good idea to promote this operation and
1054   // what's the right type to promote it to.
1055   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056     assert(PVT != VT && "Don't know what type to promote to!");
1057
1058     bool Replace = false;
1059     SDValue N0 = Op.getOperand(0);
1060     if (Opc == ISD::SRA)
1061       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1062     else if (Opc == ISD::SRL)
1063       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1064     else
1065       N0 = PromoteOperand(N0, PVT, Replace);
1066     if (!N0.getNode())
1067       return SDValue();
1068
1069     AddToWorklist(N0.getNode());
1070     if (Replace)
1071       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1072
1073     DEBUG(dbgs() << "\nPromoting ";
1074           Op.getNode()->dump(&DAG));
1075     SDLoc dl(Op);
1076     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1077                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1078   }
1079   return SDValue();
1080 }
1081
1082 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1083   if (!LegalOperations)
1084     return SDValue();
1085
1086   EVT VT = Op.getValueType();
1087   if (VT.isVector() || !VT.isInteger())
1088     return SDValue();
1089
1090   // If operation type is 'undesirable', e.g. i16 on x86, consider
1091   // promoting it.
1092   unsigned Opc = Op.getOpcode();
1093   if (TLI.isTypeDesirableForOp(Opc, VT))
1094     return SDValue();
1095
1096   EVT PVT = VT;
1097   // Consult target whether it is a good idea to promote this operation and
1098   // what's the right type to promote it to.
1099   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1100     assert(PVT != VT && "Don't know what type to promote to!");
1101     // fold (aext (aext x)) -> (aext x)
1102     // fold (aext (zext x)) -> (zext x)
1103     // fold (aext (sext x)) -> (sext x)
1104     DEBUG(dbgs() << "\nPromoting ";
1105           Op.getNode()->dump(&DAG));
1106     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1107   }
1108   return SDValue();
1109 }
1110
1111 bool DAGCombiner::PromoteLoad(SDValue Op) {
1112   if (!LegalOperations)
1113     return false;
1114
1115   EVT VT = Op.getValueType();
1116   if (VT.isVector() || !VT.isInteger())
1117     return false;
1118
1119   // If operation type is 'undesirable', e.g. i16 on x86, consider
1120   // promoting it.
1121   unsigned Opc = Op.getOpcode();
1122   if (TLI.isTypeDesirableForOp(Opc, VT))
1123     return false;
1124
1125   EVT PVT = VT;
1126   // Consult target whether it is a good idea to promote this operation and
1127   // what's the right type to promote it to.
1128   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1129     assert(PVT != VT && "Don't know what type to promote to!");
1130
1131     SDLoc dl(Op);
1132     SDNode *N = Op.getNode();
1133     LoadSDNode *LD = cast<LoadSDNode>(N);
1134     EVT MemVT = LD->getMemoryVT();
1135     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1136       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1137                                                        : ISD::EXTLOAD)
1138       : LD->getExtensionType();
1139     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1140                                    LD->getChain(), LD->getBasePtr(),
1141                                    MemVT, LD->getMemOperand());
1142     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1143
1144     DEBUG(dbgs() << "\nPromoting ";
1145           N->dump(&DAG);
1146           dbgs() << "\nTo: ";
1147           Result.getNode()->dump(&DAG);
1148           dbgs() << '\n');
1149     WorklistRemover DeadNodes(*this);
1150     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1151     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1152     deleteAndRecombine(N);
1153     AddToWorklist(Result.getNode());
1154     return true;
1155   }
1156   return false;
1157 }
1158
1159 /// \brief Recursively delete a node which has no uses and any operands for
1160 /// which it is the only use.
1161 ///
1162 /// Note that this both deletes the nodes and removes them from the worklist.
1163 /// It also adds any nodes who have had a user deleted to the worklist as they
1164 /// may now have only one use and subject to other combines.
1165 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1166   if (!N->use_empty())
1167     return false;
1168
1169   SmallSetVector<SDNode *, 16> Nodes;
1170   Nodes.insert(N);
1171   do {
1172     N = Nodes.pop_back_val();
1173     if (!N)
1174       continue;
1175
1176     if (N->use_empty()) {
1177       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1178         Nodes.insert(N->getOperand(i).getNode());
1179
1180       removeFromWorklist(N);
1181       DAG.DeleteNode(N);
1182     } else {
1183       AddToWorklist(N);
1184     }
1185   } while (!Nodes.empty());
1186   return true;
1187 }
1188
1189 //===----------------------------------------------------------------------===//
1190 //  Main DAG Combiner implementation
1191 //===----------------------------------------------------------------------===//
1192
1193 void DAGCombiner::Run(CombineLevel AtLevel) {
1194   // set the instance variables, so that the various visit routines may use it.
1195   Level = AtLevel;
1196   LegalOperations = Level >= AfterLegalizeVectorOps;
1197   LegalTypes = Level >= AfterLegalizeTypes;
1198
1199   // Add all the dag nodes to the worklist.
1200   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1201        E = DAG.allnodes_end(); I != E; ++I)
1202     AddToWorklist(I);
1203
1204   // Create a dummy node (which is not added to allnodes), that adds a reference
1205   // to the root node, preventing it from being deleted, and tracking any
1206   // changes of the root.
1207   HandleSDNode Dummy(DAG.getRoot());
1208
1209   // while the worklist isn't empty, find a node and
1210   // try and combine it.
1211   while (!WorklistMap.empty()) {
1212     SDNode *N;
1213     // The Worklist holds the SDNodes in order, but it may contain null entries.
1214     do {
1215       N = Worklist.pop_back_val();
1216     } while (!N);
1217
1218     bool GoodWorklistEntry = WorklistMap.erase(N);
1219     (void)GoodWorklistEntry;
1220     assert(GoodWorklistEntry &&
1221            "Found a worklist entry without a corresponding map entry!");
1222
1223     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1224     // N is deleted from the DAG, since they too may now be dead or may have a
1225     // reduced number of uses, allowing other xforms.
1226     if (recursivelyDeleteUnusedNodes(N))
1227       continue;
1228
1229     WorklistRemover DeadNodes(*this);
1230
1231     // If this combine is running after legalizing the DAG, re-legalize any
1232     // nodes pulled off the worklist.
1233     if (Level == AfterLegalizeDAG) {
1234       SmallSetVector<SDNode *, 16> UpdatedNodes;
1235       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1236
1237       for (SDNode *LN : UpdatedNodes) {
1238         AddToWorklist(LN);
1239         AddUsersToWorklist(LN);
1240       }
1241       if (!NIsValid)
1242         continue;
1243     }
1244
1245     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1246
1247     // Add any operands of the new node which have not yet been combined to the
1248     // worklist as well. Because the worklist uniques things already, this
1249     // won't repeatedly process the same operand.
1250     CombinedNodes.insert(N);
1251     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1252       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1253         AddToWorklist(N->getOperand(i).getNode());
1254
1255     SDValue RV = combine(N);
1256
1257     if (!RV.getNode())
1258       continue;
1259
1260     ++NodesCombined;
1261
1262     // If we get back the same node we passed in, rather than a new node or
1263     // zero, we know that the node must have defined multiple values and
1264     // CombineTo was used.  Since CombineTo takes care of the worklist
1265     // mechanics for us, we have no work to do in this case.
1266     if (RV.getNode() == N)
1267       continue;
1268
1269     assert(N->getOpcode() != ISD::DELETED_NODE &&
1270            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1271            "Node was deleted but visit returned new node!");
1272
1273     DEBUG(dbgs() << " ... into: ";
1274           RV.getNode()->dump(&DAG));
1275
1276     // Transfer debug value.
1277     DAG.TransferDbgValues(SDValue(N, 0), RV);
1278     if (N->getNumValues() == RV.getNode()->getNumValues())
1279       DAG.ReplaceAllUsesWith(N, RV.getNode());
1280     else {
1281       assert(N->getValueType(0) == RV.getValueType() &&
1282              N->getNumValues() == 1 && "Type mismatch");
1283       SDValue OpV = RV;
1284       DAG.ReplaceAllUsesWith(N, &OpV);
1285     }
1286
1287     // Push the new node and any users onto the worklist
1288     AddToWorklist(RV.getNode());
1289     AddUsersToWorklist(RV.getNode());
1290
1291     // Finally, if the node is now dead, remove it from the graph.  The node
1292     // may not be dead if the replacement process recursively simplified to
1293     // something else needing this node. This will also take care of adding any
1294     // operands which have lost a user to the worklist.
1295     recursivelyDeleteUnusedNodes(N);
1296   }
1297
1298   // If the root changed (e.g. it was a dead load, update the root).
1299   DAG.setRoot(Dummy.getValue());
1300   DAG.RemoveDeadNodes();
1301 }
1302
1303 SDValue DAGCombiner::visit(SDNode *N) {
1304   switch (N->getOpcode()) {
1305   default: break;
1306   case ISD::TokenFactor:        return visitTokenFactor(N);
1307   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1308   case ISD::ADD:                return visitADD(N);
1309   case ISD::SUB:                return visitSUB(N);
1310   case ISD::ADDC:               return visitADDC(N);
1311   case ISD::SUBC:               return visitSUBC(N);
1312   case ISD::ADDE:               return visitADDE(N);
1313   case ISD::SUBE:               return visitSUBE(N);
1314   case ISD::MUL:                return visitMUL(N);
1315   case ISD::SDIV:               return visitSDIV(N);
1316   case ISD::UDIV:               return visitUDIV(N);
1317   case ISD::SREM:               return visitSREM(N);
1318   case ISD::UREM:               return visitUREM(N);
1319   case ISD::MULHU:              return visitMULHU(N);
1320   case ISD::MULHS:              return visitMULHS(N);
1321   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1322   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1323   case ISD::SMULO:              return visitSMULO(N);
1324   case ISD::UMULO:              return visitUMULO(N);
1325   case ISD::SDIVREM:            return visitSDIVREM(N);
1326   case ISD::UDIVREM:            return visitUDIVREM(N);
1327   case ISD::AND:                return visitAND(N);
1328   case ISD::OR:                 return visitOR(N);
1329   case ISD::XOR:                return visitXOR(N);
1330   case ISD::SHL:                return visitSHL(N);
1331   case ISD::SRA:                return visitSRA(N);
1332   case ISD::SRL:                return visitSRL(N);
1333   case ISD::ROTR:
1334   case ISD::ROTL:               return visitRotate(N);
1335   case ISD::CTLZ:               return visitCTLZ(N);
1336   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1337   case ISD::CTTZ:               return visitCTTZ(N);
1338   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1339   case ISD::CTPOP:              return visitCTPOP(N);
1340   case ISD::SELECT:             return visitSELECT(N);
1341   case ISD::VSELECT:            return visitVSELECT(N);
1342   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1343   case ISD::SETCC:              return visitSETCC(N);
1344   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1345   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1346   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1347   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1348   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1349   case ISD::BITCAST:            return visitBITCAST(N);
1350   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1351   case ISD::FADD:               return visitFADD(N);
1352   case ISD::FSUB:               return visitFSUB(N);
1353   case ISD::FMUL:               return visitFMUL(N);
1354   case ISD::FMA:                return visitFMA(N);
1355   case ISD::FDIV:               return visitFDIV(N);
1356   case ISD::FREM:               return visitFREM(N);
1357   case ISD::FSQRT:              return visitFSQRT(N);
1358   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1359   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1360   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1361   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1362   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1363   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1364   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1365   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1366   case ISD::FNEG:               return visitFNEG(N);
1367   case ISD::FABS:               return visitFABS(N);
1368   case ISD::FFLOOR:             return visitFFLOOR(N);
1369   case ISD::FMINNUM:            return visitFMINNUM(N);
1370   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1371   case ISD::FCEIL:              return visitFCEIL(N);
1372   case ISD::FTRUNC:             return visitFTRUNC(N);
1373   case ISD::BRCOND:             return visitBRCOND(N);
1374   case ISD::BR_CC:              return visitBR_CC(N);
1375   case ISD::LOAD:               return visitLOAD(N);
1376   case ISD::STORE:              return visitSTORE(N);
1377   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1378   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1379   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1380   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1381   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1382   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1383   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1384   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1385   case ISD::MLOAD:              return visitMLOAD(N);
1386   case ISD::MSTORE:             return visitMSTORE(N);
1387   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1388   }
1389   return SDValue();
1390 }
1391
1392 SDValue DAGCombiner::combine(SDNode *N) {
1393   SDValue RV = visit(N);
1394
1395   // If nothing happened, try a target-specific DAG combine.
1396   if (!RV.getNode()) {
1397     assert(N->getOpcode() != ISD::DELETED_NODE &&
1398            "Node was deleted but visit returned NULL!");
1399
1400     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1401         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1402
1403       // Expose the DAG combiner to the target combiner impls.
1404       TargetLowering::DAGCombinerInfo
1405         DagCombineInfo(DAG, Level, false, this);
1406
1407       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1408     }
1409   }
1410
1411   // If nothing happened still, try promoting the operation.
1412   if (!RV.getNode()) {
1413     switch (N->getOpcode()) {
1414     default: break;
1415     case ISD::ADD:
1416     case ISD::SUB:
1417     case ISD::MUL:
1418     case ISD::AND:
1419     case ISD::OR:
1420     case ISD::XOR:
1421       RV = PromoteIntBinOp(SDValue(N, 0));
1422       break;
1423     case ISD::SHL:
1424     case ISD::SRA:
1425     case ISD::SRL:
1426       RV = PromoteIntShiftOp(SDValue(N, 0));
1427       break;
1428     case ISD::SIGN_EXTEND:
1429     case ISD::ZERO_EXTEND:
1430     case ISD::ANY_EXTEND:
1431       RV = PromoteExtend(SDValue(N, 0));
1432       break;
1433     case ISD::LOAD:
1434       if (PromoteLoad(SDValue(N, 0)))
1435         RV = SDValue(N, 0);
1436       break;
1437     }
1438   }
1439
1440   // If N is a commutative binary node, try commuting it to enable more
1441   // sdisel CSE.
1442   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1443       N->getNumValues() == 1) {
1444     SDValue N0 = N->getOperand(0);
1445     SDValue N1 = N->getOperand(1);
1446
1447     // Constant operands are canonicalized to RHS.
1448     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1449       SDValue Ops[] = {N1, N0};
1450       SDNode *CSENode;
1451       if (const BinaryWithFlagsSDNode *BinNode =
1452               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1453         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1454                                       BinNode->Flags.hasNoUnsignedWrap(),
1455                                       BinNode->Flags.hasNoSignedWrap(),
1456                                       BinNode->Flags.hasExact());
1457       } else {
1458         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1459       }
1460       if (CSENode)
1461         return SDValue(CSENode, 0);
1462     }
1463   }
1464
1465   return RV;
1466 }
1467
1468 /// Given a node, return its input chain if it has one, otherwise return a null
1469 /// sd operand.
1470 static SDValue getInputChainForNode(SDNode *N) {
1471   if (unsigned NumOps = N->getNumOperands()) {
1472     if (N->getOperand(0).getValueType() == MVT::Other)
1473       return N->getOperand(0);
1474     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1475       return N->getOperand(NumOps-1);
1476     for (unsigned i = 1; i < NumOps-1; ++i)
1477       if (N->getOperand(i).getValueType() == MVT::Other)
1478         return N->getOperand(i);
1479   }
1480   return SDValue();
1481 }
1482
1483 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1484   // If N has two operands, where one has an input chain equal to the other,
1485   // the 'other' chain is redundant.
1486   if (N->getNumOperands() == 2) {
1487     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1488       return N->getOperand(0);
1489     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1490       return N->getOperand(1);
1491   }
1492
1493   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1494   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1495   SmallPtrSet<SDNode*, 16> SeenOps;
1496   bool Changed = false;             // If we should replace this token factor.
1497
1498   // Start out with this token factor.
1499   TFs.push_back(N);
1500
1501   // Iterate through token factors.  The TFs grows when new token factors are
1502   // encountered.
1503   for (unsigned i = 0; i < TFs.size(); ++i) {
1504     SDNode *TF = TFs[i];
1505
1506     // Check each of the operands.
1507     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1508       SDValue Op = TF->getOperand(i);
1509
1510       switch (Op.getOpcode()) {
1511       case ISD::EntryToken:
1512         // Entry tokens don't need to be added to the list. They are
1513         // redundant.
1514         Changed = true;
1515         break;
1516
1517       case ISD::TokenFactor:
1518         if (Op.hasOneUse() &&
1519             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1520           // Queue up for processing.
1521           TFs.push_back(Op.getNode());
1522           // Clean up in case the token factor is removed.
1523           AddToWorklist(Op.getNode());
1524           Changed = true;
1525           break;
1526         }
1527         // Fall thru
1528
1529       default:
1530         // Only add if it isn't already in the list.
1531         if (SeenOps.insert(Op.getNode()).second)
1532           Ops.push_back(Op);
1533         else
1534           Changed = true;
1535         break;
1536       }
1537     }
1538   }
1539
1540   SDValue Result;
1541
1542   // If we've changed things around then replace token factor.
1543   if (Changed) {
1544     if (Ops.empty()) {
1545       // The entry token is the only possible outcome.
1546       Result = DAG.getEntryNode();
1547     } else {
1548       // New and improved token factor.
1549       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1550     }
1551
1552     // Add users to worklist if AA is enabled, since it may introduce
1553     // a lot of new chained token factors while removing memory deps.
1554     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1555       : DAG.getSubtarget().useAA();
1556     return CombineTo(N, Result, UseAA /*add to worklist*/);
1557   }
1558
1559   return Result;
1560 }
1561
1562 /// MERGE_VALUES can always be eliminated.
1563 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1564   WorklistRemover DeadNodes(*this);
1565   // Replacing results may cause a different MERGE_VALUES to suddenly
1566   // be CSE'd with N, and carry its uses with it. Iterate until no
1567   // uses remain, to ensure that the node can be safely deleted.
1568   // First add the users of this node to the work list so that they
1569   // can be tried again once they have new operands.
1570   AddUsersToWorklist(N);
1571   do {
1572     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1573       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1574   } while (!N->use_empty());
1575   deleteAndRecombine(N);
1576   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1577 }
1578
1579 SDValue DAGCombiner::visitADD(SDNode *N) {
1580   SDValue N0 = N->getOperand(0);
1581   SDValue N1 = N->getOperand(1);
1582   EVT VT = N0.getValueType();
1583
1584   // fold vector ops
1585   if (VT.isVector()) {
1586     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1587       return FoldedVOp;
1588
1589     // fold (add x, 0) -> x, vector edition
1590     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1591       return N0;
1592     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1593       return N1;
1594   }
1595
1596   // fold (add x, undef) -> undef
1597   if (N0.getOpcode() == ISD::UNDEF)
1598     return N0;
1599   if (N1.getOpcode() == ISD::UNDEF)
1600     return N1;
1601   // fold (add c1, c2) -> c1+c2
1602   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1603   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1604   if (N0C && N1C)
1605     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1606   // canonicalize constant to RHS
1607   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1608      !isConstantIntBuildVectorOrConstantInt(N1))
1609     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1610   // fold (add x, 0) -> x
1611   if (N1C && N1C->isNullValue())
1612     return N0;
1613   // fold (add Sym, c) -> Sym+c
1614   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1615     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1616         GA->getOpcode() == ISD::GlobalAddress)
1617       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1618                                   GA->getOffset() +
1619                                     (uint64_t)N1C->getSExtValue());
1620   // fold ((c1-A)+c2) -> (c1+c2)-A
1621   if (N1C && N0.getOpcode() == ISD::SUB)
1622     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1623       SDLoc DL(N);
1624       return DAG.getNode(ISD::SUB, DL, VT,
1625                          DAG.getConstant(N1C->getAPIntValue()+
1626                                          N0C->getAPIntValue(), DL, VT),
1627                          N0.getOperand(1));
1628     }
1629   // reassociate add
1630   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1631     return RADD;
1632   // fold ((0-A) + B) -> B-A
1633   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1634       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1635     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1636   // fold (A + (0-B)) -> A-B
1637   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1638       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1639     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1640   // fold (A+(B-A)) -> B
1641   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1642     return N1.getOperand(0);
1643   // fold ((B-A)+A) -> B
1644   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1645     return N0.getOperand(0);
1646   // fold (A+(B-(A+C))) to (B-C)
1647   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1648       N0 == N1.getOperand(1).getOperand(0))
1649     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1650                        N1.getOperand(1).getOperand(1));
1651   // fold (A+(B-(C+A))) to (B-C)
1652   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1653       N0 == N1.getOperand(1).getOperand(1))
1654     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1655                        N1.getOperand(1).getOperand(0));
1656   // fold (A+((B-A)+or-C)) to (B+or-C)
1657   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1658       N1.getOperand(0).getOpcode() == ISD::SUB &&
1659       N0 == N1.getOperand(0).getOperand(1))
1660     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1661                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1662
1663   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1664   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1665     SDValue N00 = N0.getOperand(0);
1666     SDValue N01 = N0.getOperand(1);
1667     SDValue N10 = N1.getOperand(0);
1668     SDValue N11 = N1.getOperand(1);
1669
1670     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1671       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1672                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1673                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1674   }
1675
1676   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1677     return SDValue(N, 0);
1678
1679   // fold (a+b) -> (a|b) iff a and b share no bits.
1680   if (VT.isInteger() && !VT.isVector()) {
1681     APInt LHSZero, LHSOne;
1682     APInt RHSZero, RHSOne;
1683     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1684
1685     if (LHSZero.getBoolValue()) {
1686       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1687
1688       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1689       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1690       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1691         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1692           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1693       }
1694     }
1695   }
1696
1697   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1698   if (N1.getOpcode() == ISD::SHL &&
1699       N1.getOperand(0).getOpcode() == ISD::SUB)
1700     if (ConstantSDNode *C =
1701           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1702       if (C->getAPIntValue() == 0)
1703         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1704                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1705                                        N1.getOperand(0).getOperand(1),
1706                                        N1.getOperand(1)));
1707   if (N0.getOpcode() == ISD::SHL &&
1708       N0.getOperand(0).getOpcode() == ISD::SUB)
1709     if (ConstantSDNode *C =
1710           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1711       if (C->getAPIntValue() == 0)
1712         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1713                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1714                                        N0.getOperand(0).getOperand(1),
1715                                        N0.getOperand(1)));
1716
1717   if (N1.getOpcode() == ISD::AND) {
1718     SDValue AndOp0 = N1.getOperand(0);
1719     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1720     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1721     unsigned DestBits = VT.getScalarType().getSizeInBits();
1722
1723     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1724     // and similar xforms where the inner op is either ~0 or 0.
1725     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1726       SDLoc DL(N);
1727       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1728     }
1729   }
1730
1731   // add (sext i1), X -> sub X, (zext i1)
1732   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1733       N0.getOperand(0).getValueType() == MVT::i1 &&
1734       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1735     SDLoc DL(N);
1736     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1737     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1738   }
1739
1740   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1741   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1742     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1743     if (TN->getVT() == MVT::i1) {
1744       SDLoc DL(N);
1745       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1746                                  DAG.getConstant(1, DL, VT));
1747       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1748     }
1749   }
1750
1751   return SDValue();
1752 }
1753
1754 SDValue DAGCombiner::visitADDC(SDNode *N) {
1755   SDValue N0 = N->getOperand(0);
1756   SDValue N1 = N->getOperand(1);
1757   EVT VT = N0.getValueType();
1758
1759   // If the flag result is dead, turn this into an ADD.
1760   if (!N->hasAnyUseOfValue(1))
1761     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1762                      DAG.getNode(ISD::CARRY_FALSE,
1763                                  SDLoc(N), MVT::Glue));
1764
1765   // canonicalize constant to RHS.
1766   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1767   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1768   if (N0C && !N1C)
1769     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1770
1771   // fold (addc x, 0) -> x + no carry out
1772   if (N1C && N1C->isNullValue())
1773     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1774                                         SDLoc(N), MVT::Glue));
1775
1776   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1777   APInt LHSZero, LHSOne;
1778   APInt RHSZero, RHSOne;
1779   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1780
1781   if (LHSZero.getBoolValue()) {
1782     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1783
1784     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1785     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1786     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1787       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1788                        DAG.getNode(ISD::CARRY_FALSE,
1789                                    SDLoc(N), MVT::Glue));
1790   }
1791
1792   return SDValue();
1793 }
1794
1795 SDValue DAGCombiner::visitADDE(SDNode *N) {
1796   SDValue N0 = N->getOperand(0);
1797   SDValue N1 = N->getOperand(1);
1798   SDValue CarryIn = N->getOperand(2);
1799
1800   // canonicalize constant to RHS
1801   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1802   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1803   if (N0C && !N1C)
1804     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1805                        N1, N0, CarryIn);
1806
1807   // fold (adde x, y, false) -> (addc x, y)
1808   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1809     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1810
1811   return SDValue();
1812 }
1813
1814 // Since it may not be valid to emit a fold to zero for vector initializers
1815 // check if we can before folding.
1816 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1817                              SelectionDAG &DAG,
1818                              bool LegalOperations, bool LegalTypes) {
1819   if (!VT.isVector())
1820     return DAG.getConstant(0, DL, VT);
1821   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1822     return DAG.getConstant(0, DL, VT);
1823   return SDValue();
1824 }
1825
1826 SDValue DAGCombiner::visitSUB(SDNode *N) {
1827   SDValue N0 = N->getOperand(0);
1828   SDValue N1 = N->getOperand(1);
1829   EVT VT = N0.getValueType();
1830
1831   // fold vector ops
1832   if (VT.isVector()) {
1833     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1834       return FoldedVOp;
1835
1836     // fold (sub x, 0) -> x, vector edition
1837     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1838       return N0;
1839   }
1840
1841   // fold (sub x, x) -> 0
1842   // FIXME: Refactor this and xor and other similar operations together.
1843   if (N0 == N1)
1844     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1845   // fold (sub c1, c2) -> c1-c2
1846   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1847   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1848   if (N0C && N1C)
1849     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1850   // fold (sub x, c) -> (add x, -c)
1851   if (N1C) {
1852     SDLoc DL(N);
1853     return DAG.getNode(ISD::ADD, DL, VT, N0,
1854                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1855   }
1856   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1857   if (N0C && N0C->isAllOnesValue())
1858     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1859   // fold A-(A-B) -> B
1860   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1861     return N1.getOperand(1);
1862   // fold (A+B)-A -> B
1863   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1864     return N0.getOperand(1);
1865   // fold (A+B)-B -> A
1866   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1867     return N0.getOperand(0);
1868   // fold C2-(A+C1) -> (C2-C1)-A
1869   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1870     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1871   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1872     SDLoc DL(N);
1873     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1874                                    DL, VT);
1875     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1876                        N1.getOperand(0));
1877   }
1878   // fold ((A+(B+or-C))-B) -> A+or-C
1879   if (N0.getOpcode() == ISD::ADD &&
1880       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1881        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1882       N0.getOperand(1).getOperand(0) == N1)
1883     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1884                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1885   // fold ((A+(C+B))-B) -> A+C
1886   if (N0.getOpcode() == ISD::ADD &&
1887       N0.getOperand(1).getOpcode() == ISD::ADD &&
1888       N0.getOperand(1).getOperand(1) == N1)
1889     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1890                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1891   // fold ((A-(B-C))-C) -> A-B
1892   if (N0.getOpcode() == ISD::SUB &&
1893       N0.getOperand(1).getOpcode() == ISD::SUB &&
1894       N0.getOperand(1).getOperand(1) == N1)
1895     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1896                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1897
1898   // If either operand of a sub is undef, the result is undef
1899   if (N0.getOpcode() == ISD::UNDEF)
1900     return N0;
1901   if (N1.getOpcode() == ISD::UNDEF)
1902     return N1;
1903
1904   // If the relocation model supports it, consider symbol offsets.
1905   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1906     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1907       // fold (sub Sym, c) -> Sym-c
1908       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1909         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1910                                     GA->getOffset() -
1911                                       (uint64_t)N1C->getSExtValue());
1912       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1913       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1914         if (GA->getGlobal() == GB->getGlobal())
1915           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1916                                  SDLoc(N), VT);
1917     }
1918
1919   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1920   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1921     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1922     if (TN->getVT() == MVT::i1) {
1923       SDLoc DL(N);
1924       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1925                                  DAG.getConstant(1, DL, VT));
1926       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1927     }
1928   }
1929
1930   return SDValue();
1931 }
1932
1933 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1934   SDValue N0 = N->getOperand(0);
1935   SDValue N1 = N->getOperand(1);
1936   EVT VT = N0.getValueType();
1937
1938   // If the flag result is dead, turn this into an SUB.
1939   if (!N->hasAnyUseOfValue(1))
1940     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1941                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1942                                  MVT::Glue));
1943
1944   // fold (subc x, x) -> 0 + no borrow
1945   if (N0 == N1) {
1946     SDLoc DL(N);
1947     return CombineTo(N, DAG.getConstant(0, DL, VT),
1948                      DAG.getNode(ISD::CARRY_FALSE, DL,
1949                                  MVT::Glue));
1950   }
1951
1952   // fold (subc x, 0) -> x + no borrow
1953   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1954   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1955   if (N1C && N1C->isNullValue())
1956     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1957                                         MVT::Glue));
1958
1959   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1960   if (N0C && N0C->isAllOnesValue())
1961     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1962                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1963                                  MVT::Glue));
1964
1965   return SDValue();
1966 }
1967
1968 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1969   SDValue N0 = N->getOperand(0);
1970   SDValue N1 = N->getOperand(1);
1971   SDValue CarryIn = N->getOperand(2);
1972
1973   // fold (sube x, y, false) -> (subc x, y)
1974   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1975     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1976
1977   return SDValue();
1978 }
1979
1980 SDValue DAGCombiner::visitMUL(SDNode *N) {
1981   SDValue N0 = N->getOperand(0);
1982   SDValue N1 = N->getOperand(1);
1983   EVT VT = N0.getValueType();
1984
1985   // fold (mul x, undef) -> 0
1986   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1987     return DAG.getConstant(0, SDLoc(N), VT);
1988
1989   bool N0IsConst = false;
1990   bool N1IsConst = false;
1991   APInt ConstValue0, ConstValue1;
1992   // fold vector ops
1993   if (VT.isVector()) {
1994     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1995       return FoldedVOp;
1996
1997     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1998     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1999   } else {
2000     N0IsConst = isa<ConstantSDNode>(N0);
2001     if (N0IsConst)
2002       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2003     N1IsConst = isa<ConstantSDNode>(N1);
2004     if (N1IsConst)
2005       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2006   }
2007
2008   // fold (mul c1, c2) -> c1*c2
2009   if (N0IsConst && N1IsConst)
2010     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2011                                       N0.getNode(), N1.getNode());
2012
2013   // canonicalize constant to RHS (vector doesn't have to splat)
2014   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2015      !isConstantIntBuildVectorOrConstantInt(N1))
2016     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2017   // fold (mul x, 0) -> 0
2018   if (N1IsConst && ConstValue1 == 0)
2019     return N1;
2020   // We require a splat of the entire scalar bit width for non-contiguous
2021   // bit patterns.
2022   bool IsFullSplat =
2023     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2024   // fold (mul x, 1) -> x
2025   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2026     return N0;
2027   // fold (mul x, -1) -> 0-x
2028   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2029     SDLoc DL(N);
2030     return DAG.getNode(ISD::SUB, DL, VT,
2031                        DAG.getConstant(0, DL, VT), N0);
2032   }
2033   // fold (mul x, (1 << c)) -> x << c
2034   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2035     SDLoc DL(N);
2036     return DAG.getNode(ISD::SHL, DL, VT, N0,
2037                        DAG.getConstant(ConstValue1.logBase2(), DL,
2038                                        getShiftAmountTy(N0.getValueType())));
2039   }
2040   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2041   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2042     unsigned Log2Val = (-ConstValue1).logBase2();
2043     SDLoc DL(N);
2044     // FIXME: If the input is something that is easily negated (e.g. a
2045     // single-use add), we should put the negate there.
2046     return DAG.getNode(ISD::SUB, DL, VT,
2047                        DAG.getConstant(0, DL, VT),
2048                        DAG.getNode(ISD::SHL, DL, VT, N0,
2049                             DAG.getConstant(Log2Val, DL,
2050                                       getShiftAmountTy(N0.getValueType()))));
2051   }
2052
2053   APInt Val;
2054   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2055   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2056       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2057                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2058     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2059                              N1, N0.getOperand(1));
2060     AddToWorklist(C3.getNode());
2061     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2062                        N0.getOperand(0), C3);
2063   }
2064
2065   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2066   // use.
2067   {
2068     SDValue Sh(nullptr,0), Y(nullptr,0);
2069     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2070     if (N0.getOpcode() == ISD::SHL &&
2071         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2072                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2073         N0.getNode()->hasOneUse()) {
2074       Sh = N0; Y = N1;
2075     } else if (N1.getOpcode() == ISD::SHL &&
2076                isa<ConstantSDNode>(N1.getOperand(1)) &&
2077                N1.getNode()->hasOneUse()) {
2078       Sh = N1; Y = N0;
2079     }
2080
2081     if (Sh.getNode()) {
2082       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2083                                 Sh.getOperand(0), Y);
2084       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2085                          Mul, Sh.getOperand(1));
2086     }
2087   }
2088
2089   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2090   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2091       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2092                      isa<ConstantSDNode>(N0.getOperand(1))))
2093     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2094                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2095                                    N0.getOperand(0), N1),
2096                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2097                                    N0.getOperand(1), N1));
2098
2099   // reassociate mul
2100   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2101     return RMUL;
2102
2103   return SDValue();
2104 }
2105
2106 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2107   SDValue N0 = N->getOperand(0);
2108   SDValue N1 = N->getOperand(1);
2109   EVT VT = N->getValueType(0);
2110
2111   // fold vector ops
2112   if (VT.isVector())
2113     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2114       return FoldedVOp;
2115
2116   // fold (sdiv c1, c2) -> c1/c2
2117   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2118   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2119   if (N0C && N1C && !N1C->isNullValue())
2120     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2121   // fold (sdiv X, 1) -> X
2122   if (N1C && N1C->getAPIntValue() == 1LL)
2123     return N0;
2124   // fold (sdiv X, -1) -> 0-X
2125   if (N1C && N1C->isAllOnesValue()) {
2126     SDLoc DL(N);
2127     return DAG.getNode(ISD::SUB, DL, VT,
2128                        DAG.getConstant(0, DL, VT), N0);
2129   }
2130   // If we know the sign bits of both operands are zero, strength reduce to a
2131   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2132   if (!VT.isVector()) {
2133     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2134       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2135                          N0, N1);
2136   }
2137
2138   // fold (sdiv X, pow2) -> simple ops after legalize
2139   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2140                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2141     // If dividing by powers of two is cheap, then don't perform the following
2142     // fold.
2143     if (TLI.isPow2SDivCheap())
2144       return SDValue();
2145
2146     // Target-specific implementation of sdiv x, pow2.
2147     SDValue Res = BuildSDIVPow2(N);
2148     if (Res.getNode())
2149       return Res;
2150
2151     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2152     SDLoc DL(N);
2153
2154     // Splat the sign bit into the register
2155     SDValue SGN =
2156         DAG.getNode(ISD::SRA, DL, VT, N0,
2157                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2158                                     getShiftAmountTy(N0.getValueType())));
2159     AddToWorklist(SGN.getNode());
2160
2161     // Add (N0 < 0) ? abs2 - 1 : 0;
2162     SDValue SRL =
2163         DAG.getNode(ISD::SRL, DL, VT, SGN,
2164                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2165                                     getShiftAmountTy(SGN.getValueType())));
2166     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2167     AddToWorklist(SRL.getNode());
2168     AddToWorklist(ADD.getNode());    // Divide by pow2
2169     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2170                   DAG.getConstant(lg2, DL,
2171                                   getShiftAmountTy(ADD.getValueType())));
2172
2173     // If we're dividing by a positive value, we're done.  Otherwise, we must
2174     // negate the result.
2175     if (N1C->getAPIntValue().isNonNegative())
2176       return SRA;
2177
2178     AddToWorklist(SRA.getNode());
2179     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2180   }
2181
2182   // If integer divide is expensive and we satisfy the requirements, emit an
2183   // alternate sequence.
2184   if (N1C && !TLI.isIntDivCheap()) {
2185     SDValue Op = BuildSDIV(N);
2186     if (Op.getNode()) return Op;
2187   }
2188
2189   // undef / X -> 0
2190   if (N0.getOpcode() == ISD::UNDEF)
2191     return DAG.getConstant(0, SDLoc(N), VT);
2192   // X / undef -> undef
2193   if (N1.getOpcode() == ISD::UNDEF)
2194     return N1;
2195
2196   return SDValue();
2197 }
2198
2199 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2200   SDValue N0 = N->getOperand(0);
2201   SDValue N1 = N->getOperand(1);
2202   EVT VT = N->getValueType(0);
2203
2204   // fold vector ops
2205   if (VT.isVector())
2206     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2207       return FoldedVOp;
2208
2209   // fold (udiv c1, c2) -> c1/c2
2210   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2211   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2212   if (N0C && N1C && !N1C->isNullValue())
2213     return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2214   // fold (udiv x, (1 << c)) -> x >>u c
2215   if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2216     SDLoc DL(N);
2217     return DAG.getNode(ISD::SRL, DL, VT, N0,
2218                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2219                                        getShiftAmountTy(N0.getValueType())));
2220   }
2221   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2222   if (N1.getOpcode() == ISD::SHL) {
2223     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2224       if (SHC->getAPIntValue().isPowerOf2()) {
2225         EVT ADDVT = N1.getOperand(1).getValueType();
2226         SDLoc DL(N);
2227         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2228                                   N1.getOperand(1),
2229                                   DAG.getConstant(SHC->getAPIntValue()
2230                                                                   .logBase2(),
2231                                                   DL, ADDVT));
2232         AddToWorklist(Add.getNode());
2233         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2234       }
2235     }
2236   }
2237   // fold (udiv x, c) -> alternate
2238   if (N1C && !TLI.isIntDivCheap()) {
2239     SDValue Op = BuildUDIV(N);
2240     if (Op.getNode()) return Op;
2241   }
2242
2243   // undef / X -> 0
2244   if (N0.getOpcode() == ISD::UNDEF)
2245     return DAG.getConstant(0, SDLoc(N), VT);
2246   // X / undef -> undef
2247   if (N1.getOpcode() == ISD::UNDEF)
2248     return N1;
2249
2250   return SDValue();
2251 }
2252
2253 SDValue DAGCombiner::visitSREM(SDNode *N) {
2254   SDValue N0 = N->getOperand(0);
2255   SDValue N1 = N->getOperand(1);
2256   EVT VT = N->getValueType(0);
2257
2258   // fold (srem c1, c2) -> c1%c2
2259   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2260   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2261   if (N0C && N1C && !N1C->isNullValue())
2262     return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2263   // If we know the sign bits of both operands are zero, strength reduce to a
2264   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2265   if (!VT.isVector()) {
2266     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2267       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
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::SDIV, 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, SDLoc(N), VT);
2288   // X % undef -> undef
2289   if (N1.getOpcode() == ISD::UNDEF)
2290     return N1;
2291
2292   return SDValue();
2293 }
2294
2295 SDValue DAGCombiner::visitUREM(SDNode *N) {
2296   SDValue N0 = N->getOperand(0);
2297   SDValue N1 = N->getOperand(1);
2298   EVT VT = N->getValueType(0);
2299
2300   // fold (urem c1, c2) -> c1%c2
2301   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2302   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2303   if (N0C && N1C && !N1C->isNullValue())
2304     return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2305   // fold (urem x, pow2) -> (and x, pow2-1)
2306   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2307     SDLoc DL(N);
2308     return DAG.getNode(ISD::AND, DL, VT, N0,
2309                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2310   }
2311   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2312   if (N1.getOpcode() == ISD::SHL) {
2313     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2314       if (SHC->getAPIntValue().isPowerOf2()) {
2315         SDLoc DL(N);
2316         SDValue Add =
2317           DAG.getNode(ISD::ADD, DL, VT, N1,
2318                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2319                                  VT));
2320         AddToWorklist(Add.getNode());
2321         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2322       }
2323     }
2324   }
2325
2326   // If X/C can be simplified by the division-by-constant logic, lower
2327   // X%C to the equivalent of X-X/C*C.
2328   if (N1C && !N1C->isNullValue()) {
2329     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2330     AddToWorklist(Div.getNode());
2331     SDValue OptimizedDiv = combine(Div.getNode());
2332     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2333       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2334                                 OptimizedDiv, N1);
2335       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2336       AddToWorklist(Mul.getNode());
2337       return Sub;
2338     }
2339   }
2340
2341   // undef % X -> 0
2342   if (N0.getOpcode() == ISD::UNDEF)
2343     return DAG.getConstant(0, SDLoc(N), VT);
2344   // X % undef -> undef
2345   if (N1.getOpcode() == ISD::UNDEF)
2346     return N1;
2347
2348   return SDValue();
2349 }
2350
2351 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2352   SDValue N0 = N->getOperand(0);
2353   SDValue N1 = N->getOperand(1);
2354   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2355   EVT VT = N->getValueType(0);
2356   SDLoc DL(N);
2357
2358   // fold (mulhs x, 0) -> 0
2359   if (N1C && N1C->isNullValue())
2360     return N1;
2361   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2362   if (N1C && N1C->getAPIntValue() == 1) {
2363     SDLoc DL(N);
2364     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2365                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2366                                        DL,
2367                                        getShiftAmountTy(N0.getValueType())));
2368   }
2369   // fold (mulhs x, undef) -> 0
2370   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2371     return DAG.getConstant(0, SDLoc(N), VT);
2372
2373   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2374   // plus a shift.
2375   if (VT.isSimple() && !VT.isVector()) {
2376     MVT Simple = VT.getSimpleVT();
2377     unsigned SimpleSize = Simple.getSizeInBits();
2378     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2379     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2380       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2381       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2382       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2383       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2384             DAG.getConstant(SimpleSize, DL,
2385                             getShiftAmountTy(N1.getValueType())));
2386       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2387     }
2388   }
2389
2390   return SDValue();
2391 }
2392
2393 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2394   SDValue N0 = N->getOperand(0);
2395   SDValue N1 = N->getOperand(1);
2396   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2397   EVT VT = N->getValueType(0);
2398   SDLoc DL(N);
2399
2400   // fold (mulhu x, 0) -> 0
2401   if (N1C && N1C->isNullValue())
2402     return N1;
2403   // fold (mulhu x, 1) -> 0
2404   if (N1C && N1C->getAPIntValue() == 1)
2405     return DAG.getConstant(0, DL, N0.getValueType());
2406   // fold (mulhu x, undef) -> 0
2407   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2408     return DAG.getConstant(0, DL, VT);
2409
2410   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2411   // plus a shift.
2412   if (VT.isSimple() && !VT.isVector()) {
2413     MVT Simple = VT.getSimpleVT();
2414     unsigned SimpleSize = Simple.getSizeInBits();
2415     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2416     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2417       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2418       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2419       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2420       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2421             DAG.getConstant(SimpleSize, DL,
2422                             getShiftAmountTy(N1.getValueType())));
2423       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2424     }
2425   }
2426
2427   return SDValue();
2428 }
2429
2430 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2431 /// give the opcodes for the two computations that are being performed. Return
2432 /// true if a simplification was made.
2433 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2434                                                 unsigned HiOp) {
2435   // If the high half is not needed, just compute the low half.
2436   bool HiExists = N->hasAnyUseOfValue(1);
2437   if (!HiExists &&
2438       (!LegalOperations ||
2439        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2440     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2441     return CombineTo(N, Res, Res);
2442   }
2443
2444   // If the low half is not needed, just compute the high half.
2445   bool LoExists = N->hasAnyUseOfValue(0);
2446   if (!LoExists &&
2447       (!LegalOperations ||
2448        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2449     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2450     return CombineTo(N, Res, Res);
2451   }
2452
2453   // If both halves are used, return as it is.
2454   if (LoExists && HiExists)
2455     return SDValue();
2456
2457   // If the two computed results can be simplified separately, separate them.
2458   if (LoExists) {
2459     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2460     AddToWorklist(Lo.getNode());
2461     SDValue LoOpt = combine(Lo.getNode());
2462     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2463         (!LegalOperations ||
2464          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2465       return CombineTo(N, LoOpt, LoOpt);
2466   }
2467
2468   if (HiExists) {
2469     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2470     AddToWorklist(Hi.getNode());
2471     SDValue HiOpt = combine(Hi.getNode());
2472     if (HiOpt.getNode() && HiOpt != Hi &&
2473         (!LegalOperations ||
2474          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2475       return CombineTo(N, HiOpt, HiOpt);
2476   }
2477
2478   return SDValue();
2479 }
2480
2481 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2482   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2483   if (Res.getNode()) return Res;
2484
2485   EVT VT = N->getValueType(0);
2486   SDLoc DL(N);
2487
2488   // If the type is twice as wide is legal, transform the mulhu to a wider
2489   // multiply plus a shift.
2490   if (VT.isSimple() && !VT.isVector()) {
2491     MVT Simple = VT.getSimpleVT();
2492     unsigned SimpleSize = Simple.getSizeInBits();
2493     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2494     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2495       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2496       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2497       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2498       // Compute the high part as N1.
2499       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2500             DAG.getConstant(SimpleSize, DL,
2501                             getShiftAmountTy(Lo.getValueType())));
2502       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2503       // Compute the low part as N0.
2504       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2505       return CombineTo(N, Lo, Hi);
2506     }
2507   }
2508
2509   return SDValue();
2510 }
2511
2512 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2513   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2514   if (Res.getNode()) return Res;
2515
2516   EVT VT = N->getValueType(0);
2517   SDLoc DL(N);
2518
2519   // If the type is twice as wide is legal, transform the mulhu to a wider
2520   // multiply plus a shift.
2521   if (VT.isSimple() && !VT.isVector()) {
2522     MVT Simple = VT.getSimpleVT();
2523     unsigned SimpleSize = Simple.getSizeInBits();
2524     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2525     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2526       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2527       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2528       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2529       // Compute the high part as N1.
2530       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2531             DAG.getConstant(SimpleSize, DL,
2532                             getShiftAmountTy(Lo.getValueType())));
2533       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2534       // Compute the low part as N0.
2535       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2536       return CombineTo(N, Lo, Hi);
2537     }
2538   }
2539
2540   return SDValue();
2541 }
2542
2543 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2544   // (smulo x, 2) -> (saddo x, x)
2545   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2546     if (C2->getAPIntValue() == 2)
2547       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2548                          N->getOperand(0), N->getOperand(0));
2549
2550   return SDValue();
2551 }
2552
2553 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2554   // (umulo x, 2) -> (uaddo x, x)
2555   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2556     if (C2->getAPIntValue() == 2)
2557       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2558                          N->getOperand(0), N->getOperand(0));
2559
2560   return SDValue();
2561 }
2562
2563 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2564   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2565   if (Res.getNode()) return Res;
2566
2567   return SDValue();
2568 }
2569
2570 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2571   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2572   if (Res.getNode()) return Res;
2573
2574   return SDValue();
2575 }
2576
2577 /// If this is a binary operator with two operands of the same opcode, try to
2578 /// simplify it.
2579 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2580   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2581   EVT VT = N0.getValueType();
2582   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2583
2584   // Bail early if none of these transforms apply.
2585   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2586
2587   // For each of OP in AND/OR/XOR:
2588   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2589   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2590   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2591   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2592   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2593   //
2594   // do not sink logical op inside of a vector extend, since it may combine
2595   // into a vsetcc.
2596   EVT Op0VT = N0.getOperand(0).getValueType();
2597   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2598        N0.getOpcode() == ISD::SIGN_EXTEND ||
2599        N0.getOpcode() == ISD::BSWAP ||
2600        // Avoid infinite looping with PromoteIntBinOp.
2601        (N0.getOpcode() == ISD::ANY_EXTEND &&
2602         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2603        (N0.getOpcode() == ISD::TRUNCATE &&
2604         (!TLI.isZExtFree(VT, Op0VT) ||
2605          !TLI.isTruncateFree(Op0VT, VT)) &&
2606         TLI.isTypeLegal(Op0VT))) &&
2607       !VT.isVector() &&
2608       Op0VT == N1.getOperand(0).getValueType() &&
2609       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2610     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2611                                  N0.getOperand(0).getValueType(),
2612                                  N0.getOperand(0), N1.getOperand(0));
2613     AddToWorklist(ORNode.getNode());
2614     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2615   }
2616
2617   // For each of OP in SHL/SRL/SRA/AND...
2618   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2619   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2620   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2621   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2622        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2623       N0.getOperand(1) == N1.getOperand(1)) {
2624     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2625                                  N0.getOperand(0).getValueType(),
2626                                  N0.getOperand(0), N1.getOperand(0));
2627     AddToWorklist(ORNode.getNode());
2628     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2629                        ORNode, N0.getOperand(1));
2630   }
2631
2632   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2633   // Only perform this optimization after type legalization and before
2634   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2635   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2636   // we don't want to undo this promotion.
2637   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2638   // on scalars.
2639   if ((N0.getOpcode() == ISD::BITCAST ||
2640        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2641       Level == AfterLegalizeTypes) {
2642     SDValue In0 = N0.getOperand(0);
2643     SDValue In1 = N1.getOperand(0);
2644     EVT In0Ty = In0.getValueType();
2645     EVT In1Ty = In1.getValueType();
2646     SDLoc DL(N);
2647     // If both incoming values are integers, and the original types are the
2648     // same.
2649     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2650       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2651       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2652       AddToWorklist(Op.getNode());
2653       return BC;
2654     }
2655   }
2656
2657   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2658   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2659   // If both shuffles use the same mask, and both shuffle within a single
2660   // vector, then it is worthwhile to move the swizzle after the operation.
2661   // The type-legalizer generates this pattern when loading illegal
2662   // vector types from memory. In many cases this allows additional shuffle
2663   // optimizations.
2664   // There are other cases where moving the shuffle after the xor/and/or
2665   // is profitable even if shuffles don't perform a swizzle.
2666   // If both shuffles use the same mask, and both shuffles have the same first
2667   // or second operand, then it might still be profitable to move the shuffle
2668   // after the xor/and/or operation.
2669   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2670     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2671     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2672
2673     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2674            "Inputs to shuffles are not the same type");
2675
2676     // Check that both shuffles use the same mask. The masks are known to be of
2677     // the same length because the result vector type is the same.
2678     // Check also that shuffles have only one use to avoid introducing extra
2679     // instructions.
2680     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2681         SVN0->getMask().equals(SVN1->getMask())) {
2682       SDValue ShOp = N0->getOperand(1);
2683
2684       // Don't try to fold this node if it requires introducing a
2685       // build vector of all zeros that might be illegal at this stage.
2686       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2687         if (!LegalTypes)
2688           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2689         else
2690           ShOp = SDValue();
2691       }
2692
2693       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2694       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2695       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2696       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2697         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2698                                       N0->getOperand(0), N1->getOperand(0));
2699         AddToWorklist(NewNode.getNode());
2700         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2701                                     &SVN0->getMask()[0]);
2702       }
2703
2704       // Don't try to fold this node if it requires introducing a
2705       // build vector of all zeros that might be illegal at this stage.
2706       ShOp = N0->getOperand(0);
2707       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2708         if (!LegalTypes)
2709           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2710         else
2711           ShOp = SDValue();
2712       }
2713
2714       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2715       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2716       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2717       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2718         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2719                                       N0->getOperand(1), N1->getOperand(1));
2720         AddToWorklist(NewNode.getNode());
2721         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2722                                     &SVN0->getMask()[0]);
2723       }
2724     }
2725   }
2726
2727   return SDValue();
2728 }
2729
2730 /// This contains all DAGCombine rules which reduce two values combined by
2731 /// an And operation to a single value. This makes them reusable in the context
2732 /// of visitSELECT(). Rules involving constants are not included as
2733 /// visitSELECT() already handles those cases.
2734 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2735                                   SDNode *LocReference) {
2736   EVT VT = N1.getValueType();
2737
2738   // fold (and x, undef) -> 0
2739   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2740     return DAG.getConstant(0, SDLoc(LocReference), VT);
2741   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2742   SDValue LL, LR, RL, RR, CC0, CC1;
2743   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2744     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2745     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2746
2747     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2748         LL.getValueType().isInteger()) {
2749       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2750       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2751         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2752                                      LR.getValueType(), LL, RL);
2753         AddToWorklist(ORNode.getNode());
2754         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2755       }
2756       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2757       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2758         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2759                                       LR.getValueType(), LL, RL);
2760         AddToWorklist(ANDNode.getNode());
2761         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2762       }
2763       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2764       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2765         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2766                                      LR.getValueType(), LL, RL);
2767         AddToWorklist(ORNode.getNode());
2768         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2769       }
2770     }
2771     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2772     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2773         Op0 == Op1 && LL.getValueType().isInteger() &&
2774       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2775                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2776                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2777                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2778       SDLoc DL(N0);
2779       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2780                                     LL, DAG.getConstant(1, DL,
2781                                                         LL.getValueType()));
2782       AddToWorklist(ADDNode.getNode());
2783       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2784                           DAG.getConstant(2, DL, LL.getValueType()),
2785                           ISD::SETUGE);
2786     }
2787     // canonicalize equivalent to ll == rl
2788     if (LL == RR && LR == RL) {
2789       Op1 = ISD::getSetCCSwappedOperands(Op1);
2790       std::swap(RL, RR);
2791     }
2792     if (LL == RL && LR == RR) {
2793       bool isInteger = LL.getValueType().isInteger();
2794       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2795       if (Result != ISD::SETCC_INVALID &&
2796           (!LegalOperations ||
2797            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2798             TLI.isOperationLegal(ISD::SETCC,
2799                             getSetCCResultType(N0.getSimpleValueType())))))
2800         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2801                             LL, LR, Result);
2802     }
2803   }
2804
2805   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2806       VT.getSizeInBits() <= 64) {
2807     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2808       APInt ADDC = ADDI->getAPIntValue();
2809       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2810         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2811         // immediate for an add, but it is legal if its top c2 bits are set,
2812         // transform the ADD so the immediate doesn't need to be materialized
2813         // in a register.
2814         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2815           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2816                                              SRLI->getZExtValue());
2817           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2818             ADDC |= Mask;
2819             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2820               SDLoc DL(N0);
2821               SDValue NewAdd =
2822                 DAG.getNode(ISD::ADD, DL, VT,
2823                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2824               CombineTo(N0.getNode(), NewAdd);
2825               // Return N so it doesn't get rechecked!
2826               return SDValue(LocReference, 0);
2827             }
2828           }
2829         }
2830       }
2831     }
2832   }
2833
2834   return SDValue();
2835 }
2836
2837 SDValue DAGCombiner::visitAND(SDNode *N) {
2838   SDValue N0 = N->getOperand(0);
2839   SDValue N1 = N->getOperand(1);
2840   EVT VT = N1.getValueType();
2841
2842   // fold vector ops
2843   if (VT.isVector()) {
2844     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2845       return FoldedVOp;
2846
2847     // fold (and x, 0) -> 0, vector edition
2848     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2849       // do not return N0, because undef node may exist in N0
2850       return DAG.getConstant(
2851           APInt::getNullValue(
2852               N0.getValueType().getScalarType().getSizeInBits()),
2853           SDLoc(N), N0.getValueType());
2854     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2855       // do not return N1, because undef node may exist in N1
2856       return DAG.getConstant(
2857           APInt::getNullValue(
2858               N1.getValueType().getScalarType().getSizeInBits()),
2859           SDLoc(N), N1.getValueType());
2860
2861     // fold (and x, -1) -> x, vector edition
2862     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2863       return N1;
2864     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2865       return N0;
2866   }
2867
2868   // fold (and c1, c2) -> c1&c2
2869   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2870   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2871   if (N0C && N1C)
2872     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2873   // canonicalize constant to RHS
2874   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2875      !isConstantIntBuildVectorOrConstantInt(N1))
2876     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2877   // fold (and x, -1) -> x
2878   if (N1C && N1C->isAllOnesValue())
2879     return N0;
2880   // if (and x, c) is known to be zero, return 0
2881   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2882   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2883                                    APInt::getAllOnesValue(BitWidth)))
2884     return DAG.getConstant(0, SDLoc(N), VT);
2885   // reassociate and
2886   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2887     return RAND;
2888   // fold (and (or x, C), D) -> D if (C & D) == D
2889   if (N1C && N0.getOpcode() == ISD::OR)
2890     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2891       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2892         return N1;
2893   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2894   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2895     SDValue N0Op0 = N0.getOperand(0);
2896     APInt Mask = ~N1C->getAPIntValue();
2897     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2898     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2899       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2900                                  N0.getValueType(), N0Op0);
2901
2902       // Replace uses of the AND with uses of the Zero extend node.
2903       CombineTo(N, Zext);
2904
2905       // We actually want to replace all uses of the any_extend with the
2906       // zero_extend, to avoid duplicating things.  This will later cause this
2907       // AND to be folded.
2908       CombineTo(N0.getNode(), Zext);
2909       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2910     }
2911   }
2912   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2913   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2914   // already be zero by virtue of the width of the base type of the load.
2915   //
2916   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2917   // more cases.
2918   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2919        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2920       N0.getOpcode() == ISD::LOAD) {
2921     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2922                                          N0 : N0.getOperand(0) );
2923
2924     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2925     // This can be a pure constant or a vector splat, in which case we treat the
2926     // vector as a scalar and use the splat value.
2927     APInt Constant = APInt::getNullValue(1);
2928     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2929       Constant = C->getAPIntValue();
2930     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2931       APInt SplatValue, SplatUndef;
2932       unsigned SplatBitSize;
2933       bool HasAnyUndefs;
2934       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2935                                              SplatBitSize, HasAnyUndefs);
2936       if (IsSplat) {
2937         // Undef bits can contribute to a possible optimisation if set, so
2938         // set them.
2939         SplatValue |= SplatUndef;
2940
2941         // The splat value may be something like "0x00FFFFFF", which means 0 for
2942         // the first vector value and FF for the rest, repeating. We need a mask
2943         // that will apply equally to all members of the vector, so AND all the
2944         // lanes of the constant together.
2945         EVT VT = Vector->getValueType(0);
2946         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2947
2948         // If the splat value has been compressed to a bitlength lower
2949         // than the size of the vector lane, we need to re-expand it to
2950         // the lane size.
2951         if (BitWidth > SplatBitSize)
2952           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2953                SplatBitSize < BitWidth;
2954                SplatBitSize = SplatBitSize * 2)
2955             SplatValue |= SplatValue.shl(SplatBitSize);
2956
2957         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2958         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2959         if (SplatBitSize % BitWidth == 0) {
2960           Constant = APInt::getAllOnesValue(BitWidth);
2961           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2962             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2963         }
2964       }
2965     }
2966
2967     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2968     // actually legal and isn't going to get expanded, else this is a false
2969     // optimisation.
2970     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2971                                                     Load->getValueType(0),
2972                                                     Load->getMemoryVT());
2973
2974     // Resize the constant to the same size as the original memory access before
2975     // extension. If it is still the AllOnesValue then this AND is completely
2976     // unneeded.
2977     Constant =
2978       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2979
2980     bool B;
2981     switch (Load->getExtensionType()) {
2982     default: B = false; break;
2983     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2984     case ISD::ZEXTLOAD:
2985     case ISD::NON_EXTLOAD: B = true; break;
2986     }
2987
2988     if (B && Constant.isAllOnesValue()) {
2989       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2990       // preserve semantics once we get rid of the AND.
2991       SDValue NewLoad(Load, 0);
2992       if (Load->getExtensionType() == ISD::EXTLOAD) {
2993         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2994                               Load->getValueType(0), SDLoc(Load),
2995                               Load->getChain(), Load->getBasePtr(),
2996                               Load->getOffset(), Load->getMemoryVT(),
2997                               Load->getMemOperand());
2998         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2999         if (Load->getNumValues() == 3) {
3000           // PRE/POST_INC loads have 3 values.
3001           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3002                            NewLoad.getValue(2) };
3003           CombineTo(Load, To, 3, true);
3004         } else {
3005           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3006         }
3007       }
3008
3009       // Fold the AND away, taking care not to fold to the old load node if we
3010       // replaced it.
3011       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3012
3013       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3014     }
3015   }
3016
3017   // fold (and (load x), 255) -> (zextload x, i8)
3018   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3019   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3020   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3021               (N0.getOpcode() == ISD::ANY_EXTEND &&
3022                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3023     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3024     LoadSDNode *LN0 = HasAnyExt
3025       ? cast<LoadSDNode>(N0.getOperand(0))
3026       : cast<LoadSDNode>(N0);
3027     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3028         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3029       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3030       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3031         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3032         EVT LoadedVT = LN0->getMemoryVT();
3033         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3034
3035         if (ExtVT == LoadedVT &&
3036             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3037                                                     ExtVT))) {
3038
3039           SDValue NewLoad =
3040             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3041                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3042                            LN0->getMemOperand());
3043           AddToWorklist(N);
3044           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3045           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3046         }
3047
3048         // Do not change the width of a volatile load.
3049         // Do not generate loads of non-round integer types since these can
3050         // be expensive (and would be wrong if the type is not byte sized).
3051         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3052             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3053                                                     ExtVT))) {
3054           EVT PtrType = LN0->getOperand(1).getValueType();
3055
3056           unsigned Alignment = LN0->getAlignment();
3057           SDValue NewPtr = LN0->getBasePtr();
3058
3059           // For big endian targets, we need to add an offset to the pointer
3060           // to load the correct bytes.  For little endian systems, we merely
3061           // need to read fewer bytes from the same pointer.
3062           if (TLI.isBigEndian()) {
3063             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3064             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3065             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3066             SDLoc DL(LN0);
3067             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3068                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3069             Alignment = MinAlign(Alignment, PtrOff);
3070           }
3071
3072           AddToWorklist(NewPtr.getNode());
3073
3074           SDValue Load =
3075             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3076                            LN0->getChain(), NewPtr,
3077                            LN0->getPointerInfo(),
3078                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3079                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3080           AddToWorklist(N);
3081           CombineTo(LN0, Load, Load.getValue(1));
3082           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3083         }
3084       }
3085     }
3086   }
3087
3088   if (SDValue Combined = visitANDLike(N0, N1, N))
3089     return Combined;
3090
3091   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3092   if (N0.getOpcode() == N1.getOpcode()) {
3093     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3094     if (Tmp.getNode()) return Tmp;
3095   }
3096
3097   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3098   // fold (and (sra)) -> (and (srl)) when possible.
3099   if (!VT.isVector() &&
3100       SimplifyDemandedBits(SDValue(N, 0)))
3101     return SDValue(N, 0);
3102
3103   // fold (zext_inreg (extload x)) -> (zextload x)
3104   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3105     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3106     EVT MemVT = LN0->getMemoryVT();
3107     // If we zero all the possible extended bits, then we can turn this into
3108     // a zextload if we are running before legalize or the operation is legal.
3109     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3110     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3111                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3112         ((!LegalOperations && !LN0->isVolatile()) ||
3113          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3114       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3115                                        LN0->getChain(), LN0->getBasePtr(),
3116                                        MemVT, LN0->getMemOperand());
3117       AddToWorklist(N);
3118       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3119       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3120     }
3121   }
3122   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3123   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3124       N0.hasOneUse()) {
3125     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3126     EVT MemVT = LN0->getMemoryVT();
3127     // If we zero all the possible extended bits, then we can turn this into
3128     // a zextload if we are running before legalize or the operation is legal.
3129     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3130     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3131                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3132         ((!LegalOperations && !LN0->isVolatile()) ||
3133          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3134       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3135                                        LN0->getChain(), LN0->getBasePtr(),
3136                                        MemVT, LN0->getMemOperand());
3137       AddToWorklist(N);
3138       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3139       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3140     }
3141   }
3142   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3143   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3144     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3145                                        N0.getOperand(1), false);
3146     if (BSwap.getNode())
3147       return BSwap;
3148   }
3149
3150   return SDValue();
3151 }
3152
3153 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3154 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3155                                         bool DemandHighBits) {
3156   if (!LegalOperations)
3157     return SDValue();
3158
3159   EVT VT = N->getValueType(0);
3160   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3161     return SDValue();
3162   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3163     return SDValue();
3164
3165   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3166   bool LookPassAnd0 = false;
3167   bool LookPassAnd1 = false;
3168   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3169       std::swap(N0, N1);
3170   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3171       std::swap(N0, N1);
3172   if (N0.getOpcode() == ISD::AND) {
3173     if (!N0.getNode()->hasOneUse())
3174       return SDValue();
3175     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3176     if (!N01C || N01C->getZExtValue() != 0xFF00)
3177       return SDValue();
3178     N0 = N0.getOperand(0);
3179     LookPassAnd0 = true;
3180   }
3181
3182   if (N1.getOpcode() == ISD::AND) {
3183     if (!N1.getNode()->hasOneUse())
3184       return SDValue();
3185     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3186     if (!N11C || N11C->getZExtValue() != 0xFF)
3187       return SDValue();
3188     N1 = N1.getOperand(0);
3189     LookPassAnd1 = true;
3190   }
3191
3192   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3193     std::swap(N0, N1);
3194   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3195     return SDValue();
3196   if (!N0.getNode()->hasOneUse() ||
3197       !N1.getNode()->hasOneUse())
3198     return SDValue();
3199
3200   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3201   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3202   if (!N01C || !N11C)
3203     return SDValue();
3204   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3205     return SDValue();
3206
3207   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3208   SDValue N00 = N0->getOperand(0);
3209   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3210     if (!N00.getNode()->hasOneUse())
3211       return SDValue();
3212     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3213     if (!N001C || N001C->getZExtValue() != 0xFF)
3214       return SDValue();
3215     N00 = N00.getOperand(0);
3216     LookPassAnd0 = true;
3217   }
3218
3219   SDValue N10 = N1->getOperand(0);
3220   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3221     if (!N10.getNode()->hasOneUse())
3222       return SDValue();
3223     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3224     if (!N101C || N101C->getZExtValue() != 0xFF00)
3225       return SDValue();
3226     N10 = N10.getOperand(0);
3227     LookPassAnd1 = true;
3228   }
3229
3230   if (N00 != N10)
3231     return SDValue();
3232
3233   // Make sure everything beyond the low halfword gets set to zero since the SRL
3234   // 16 will clear the top bits.
3235   unsigned OpSizeInBits = VT.getSizeInBits();
3236   if (DemandHighBits && OpSizeInBits > 16) {
3237     // If the left-shift isn't masked out then the only way this is a bswap is
3238     // if all bits beyond the low 8 are 0. In that case the entire pattern
3239     // reduces to a left shift anyway: leave it for other parts of the combiner.
3240     if (!LookPassAnd0)
3241       return SDValue();
3242
3243     // However, if the right shift isn't masked out then it might be because
3244     // it's not needed. See if we can spot that too.
3245     if (!LookPassAnd1 &&
3246         !DAG.MaskedValueIsZero(
3247             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3248       return SDValue();
3249   }
3250
3251   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3252   if (OpSizeInBits > 16) {
3253     SDLoc DL(N);
3254     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3255                       DAG.getConstant(OpSizeInBits - 16, DL,
3256                                       getShiftAmountTy(VT)));
3257   }
3258   return Res;
3259 }
3260
3261 /// Return true if the specified node is an element that makes up a 32-bit
3262 /// packed halfword byteswap.
3263 /// ((x & 0x000000ff) << 8) |
3264 /// ((x & 0x0000ff00) >> 8) |
3265 /// ((x & 0x00ff0000) << 8) |
3266 /// ((x & 0xff000000) >> 8)
3267 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3268   if (!N.getNode()->hasOneUse())
3269     return false;
3270
3271   unsigned Opc = N.getOpcode();
3272   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3273     return false;
3274
3275   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3276   if (!N1C)
3277     return false;
3278
3279   unsigned Num;
3280   switch (N1C->getZExtValue()) {
3281   default:
3282     return false;
3283   case 0xFF:       Num = 0; break;
3284   case 0xFF00:     Num = 1; break;
3285   case 0xFF0000:   Num = 2; break;
3286   case 0xFF000000: Num = 3; break;
3287   }
3288
3289   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3290   SDValue N0 = N.getOperand(0);
3291   if (Opc == ISD::AND) {
3292     if (Num == 0 || Num == 2) {
3293       // (x >> 8) & 0xff
3294       // (x >> 8) & 0xff0000
3295       if (N0.getOpcode() != ISD::SRL)
3296         return false;
3297       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3298       if (!C || C->getZExtValue() != 8)
3299         return false;
3300     } else {
3301       // (x << 8) & 0xff00
3302       // (x << 8) & 0xff000000
3303       if (N0.getOpcode() != ISD::SHL)
3304         return false;
3305       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3306       if (!C || C->getZExtValue() != 8)
3307         return false;
3308     }
3309   } else if (Opc == ISD::SHL) {
3310     // (x & 0xff) << 8
3311     // (x & 0xff0000) << 8
3312     if (Num != 0 && Num != 2)
3313       return false;
3314     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3315     if (!C || C->getZExtValue() != 8)
3316       return false;
3317   } else { // Opc == ISD::SRL
3318     // (x & 0xff00) >> 8
3319     // (x & 0xff000000) >> 8
3320     if (Num != 1 && Num != 3)
3321       return false;
3322     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3323     if (!C || C->getZExtValue() != 8)
3324       return false;
3325   }
3326
3327   if (Parts[Num])
3328     return false;
3329
3330   Parts[Num] = N0.getOperand(0).getNode();
3331   return true;
3332 }
3333
3334 /// Match a 32-bit packed halfword bswap. That is
3335 /// ((x & 0x000000ff) << 8) |
3336 /// ((x & 0x0000ff00) >> 8) |
3337 /// ((x & 0x00ff0000) << 8) |
3338 /// ((x & 0xff000000) >> 8)
3339 /// => (rotl (bswap x), 16)
3340 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3341   if (!LegalOperations)
3342     return SDValue();
3343
3344   EVT VT = N->getValueType(0);
3345   if (VT != MVT::i32)
3346     return SDValue();
3347   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3348     return SDValue();
3349
3350   // Look for either
3351   // (or (or (and), (and)), (or (and), (and)))
3352   // (or (or (or (and), (and)), (and)), (and))
3353   if (N0.getOpcode() != ISD::OR)
3354     return SDValue();
3355   SDValue N00 = N0.getOperand(0);
3356   SDValue N01 = N0.getOperand(1);
3357   SDNode *Parts[4] = {};
3358
3359   if (N1.getOpcode() == ISD::OR &&
3360       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3361     // (or (or (and), (and)), (or (and), (and)))
3362     SDValue N000 = N00.getOperand(0);
3363     if (!isBSwapHWordElement(N000, Parts))
3364       return SDValue();
3365
3366     SDValue N001 = N00.getOperand(1);
3367     if (!isBSwapHWordElement(N001, Parts))
3368       return SDValue();
3369     SDValue N010 = N01.getOperand(0);
3370     if (!isBSwapHWordElement(N010, Parts))
3371       return SDValue();
3372     SDValue N011 = N01.getOperand(1);
3373     if (!isBSwapHWordElement(N011, Parts))
3374       return SDValue();
3375   } else {
3376     // (or (or (or (and), (and)), (and)), (and))
3377     if (!isBSwapHWordElement(N1, Parts))
3378       return SDValue();
3379     if (!isBSwapHWordElement(N01, Parts))
3380       return SDValue();
3381     if (N00.getOpcode() != ISD::OR)
3382       return SDValue();
3383     SDValue N000 = N00.getOperand(0);
3384     if (!isBSwapHWordElement(N000, Parts))
3385       return SDValue();
3386     SDValue N001 = N00.getOperand(1);
3387     if (!isBSwapHWordElement(N001, Parts))
3388       return SDValue();
3389   }
3390
3391   // Make sure the parts are all coming from the same node.
3392   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3393     return SDValue();
3394
3395   SDLoc DL(N);
3396   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3397                               SDValue(Parts[0], 0));
3398
3399   // Result of the bswap should be rotated by 16. If it's not legal, then
3400   // do  (x << 16) | (x >> 16).
3401   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3402   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3403     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3404   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3405     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3406   return DAG.getNode(ISD::OR, DL, VT,
3407                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3408                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3409 }
3410
3411 /// This contains all DAGCombine rules which reduce two values combined by
3412 /// an Or operation to a single value \see visitANDLike().
3413 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3414   EVT VT = N1.getValueType();
3415   // fold (or x, undef) -> -1
3416   if (!LegalOperations &&
3417       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3418     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3419     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3420                            SDLoc(LocReference), VT);
3421   }
3422   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3423   SDValue LL, LR, RL, RR, CC0, CC1;
3424   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3425     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3426     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3427
3428     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3429         LL.getValueType().isInteger()) {
3430       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3431       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3432       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3433           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3434         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3435                                      LR.getValueType(), LL, RL);
3436         AddToWorklist(ORNode.getNode());
3437         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3438       }
3439       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3440       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3441       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3442           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3443         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3444                                       LR.getValueType(), LL, RL);
3445         AddToWorklist(ANDNode.getNode());
3446         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3447       }
3448     }
3449     // canonicalize equivalent to ll == rl
3450     if (LL == RR && LR == RL) {
3451       Op1 = ISD::getSetCCSwappedOperands(Op1);
3452       std::swap(RL, RR);
3453     }
3454     if (LL == RL && LR == RR) {
3455       bool isInteger = LL.getValueType().isInteger();
3456       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3457       if (Result != ISD::SETCC_INVALID &&
3458           (!LegalOperations ||
3459            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3460             TLI.isOperationLegal(ISD::SETCC,
3461               getSetCCResultType(N0.getValueType())))))
3462         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3463                             LL, LR, Result);
3464     }
3465   }
3466
3467   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3468   if (N0.getOpcode() == ISD::AND &&
3469       N1.getOpcode() == ISD::AND &&
3470       N0.getOperand(1).getOpcode() == ISD::Constant &&
3471       N1.getOperand(1).getOpcode() == ISD::Constant &&
3472       // Don't increase # computations.
3473       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3474     // We can only do this xform if we know that bits from X that are set in C2
3475     // but not in C1 are already zero.  Likewise for Y.
3476     const APInt &LHSMask =
3477       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3478     const APInt &RHSMask =
3479       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3480
3481     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3482         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3483       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3484                               N0.getOperand(0), N1.getOperand(0));
3485       SDLoc DL(LocReference);
3486       return DAG.getNode(ISD::AND, DL, VT, X,
3487                          DAG.getConstant(LHSMask | RHSMask, DL, VT));
3488     }
3489   }
3490
3491   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3492   if (N0.getOpcode() == ISD::AND &&
3493       N1.getOpcode() == ISD::AND &&
3494       N0.getOperand(0) == N1.getOperand(0) &&
3495       // Don't increase # computations.
3496       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3497     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3498                             N0.getOperand(1), N1.getOperand(1));
3499     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3500   }
3501
3502   return SDValue();
3503 }
3504
3505 SDValue DAGCombiner::visitOR(SDNode *N) {
3506   SDValue N0 = N->getOperand(0);
3507   SDValue N1 = N->getOperand(1);
3508   EVT VT = N1.getValueType();
3509
3510   // fold vector ops
3511   if (VT.isVector()) {
3512     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3513       return FoldedVOp;
3514
3515     // fold (or x, 0) -> x, vector edition
3516     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3517       return N1;
3518     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3519       return N0;
3520
3521     // fold (or x, -1) -> -1, vector edition
3522     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3523       // do not return N0, because undef node may exist in N0
3524       return DAG.getConstant(
3525           APInt::getAllOnesValue(
3526               N0.getValueType().getScalarType().getSizeInBits()),
3527           SDLoc(N), N0.getValueType());
3528     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3529       // do not return N1, because undef node may exist in N1
3530       return DAG.getConstant(
3531           APInt::getAllOnesValue(
3532               N1.getValueType().getScalarType().getSizeInBits()),
3533           SDLoc(N), N1.getValueType());
3534
3535     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3536     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3537     // Do this only if the resulting shuffle is legal.
3538     if (isa<ShuffleVectorSDNode>(N0) &&
3539         isa<ShuffleVectorSDNode>(N1) &&
3540         // Avoid folding a node with illegal type.
3541         TLI.isTypeLegal(VT) &&
3542         N0->getOperand(1) == N1->getOperand(1) &&
3543         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3544       bool CanFold = true;
3545       unsigned NumElts = VT.getVectorNumElements();
3546       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3547       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3548       // We construct two shuffle masks:
3549       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3550       // and N1 as the second operand.
3551       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3552       // and N0 as the second operand.
3553       // We do this because OR is commutable and therefore there might be
3554       // two ways to fold this node into a shuffle.
3555       SmallVector<int,4> Mask1;
3556       SmallVector<int,4> Mask2;
3557
3558       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3559         int M0 = SV0->getMaskElt(i);
3560         int M1 = SV1->getMaskElt(i);
3561
3562         // Both shuffle indexes are undef. Propagate Undef.
3563         if (M0 < 0 && M1 < 0) {
3564           Mask1.push_back(M0);
3565           Mask2.push_back(M0);
3566           continue;
3567         }
3568
3569         if (M0 < 0 || M1 < 0 ||
3570             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3571             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3572           CanFold = false;
3573           break;
3574         }
3575
3576         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3577         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3578       }
3579
3580       if (CanFold) {
3581         // Fold this sequence only if the resulting shuffle is 'legal'.
3582         if (TLI.isShuffleMaskLegal(Mask1, VT))
3583           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3584                                       N1->getOperand(0), &Mask1[0]);
3585         if (TLI.isShuffleMaskLegal(Mask2, VT))
3586           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3587                                       N0->getOperand(0), &Mask2[0]);
3588       }
3589     }
3590   }
3591
3592   // fold (or c1, c2) -> c1|c2
3593   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3594   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3595   if (N0C && N1C)
3596     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3597   // canonicalize constant to RHS
3598   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3599      !isConstantIntBuildVectorOrConstantInt(N1))
3600     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3601   // fold (or x, 0) -> x
3602   if (N1C && N1C->isNullValue())
3603     return N0;
3604   // fold (or x, -1) -> -1
3605   if (N1C && N1C->isAllOnesValue())
3606     return N1;
3607   // fold (or x, c) -> c iff (x & ~c) == 0
3608   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3609     return N1;
3610
3611   if (SDValue Combined = visitORLike(N0, N1, N))
3612     return Combined;
3613
3614   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3615   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3616   if (BSwap.getNode())
3617     return BSwap;
3618   BSwap = MatchBSwapHWordLow(N, N0, N1);
3619   if (BSwap.getNode())
3620     return BSwap;
3621
3622   // reassociate or
3623   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3624     return ROR;
3625   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3626   // iff (c1 & c2) == 0.
3627   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3628              isa<ConstantSDNode>(N0.getOperand(1))) {
3629     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3630     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3631       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3632                                                    N1C, C1))
3633         return DAG.getNode(
3634             ISD::AND, SDLoc(N), VT,
3635             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3636       return SDValue();
3637     }
3638   }
3639   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3640   if (N0.getOpcode() == N1.getOpcode()) {
3641     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3642     if (Tmp.getNode()) return Tmp;
3643   }
3644
3645   // See if this is some rotate idiom.
3646   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3647     return SDValue(Rot, 0);
3648
3649   // Simplify the operands using demanded-bits information.
3650   if (!VT.isVector() &&
3651       SimplifyDemandedBits(SDValue(N, 0)))
3652     return SDValue(N, 0);
3653
3654   return SDValue();
3655 }
3656
3657 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3658 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3659   if (Op.getOpcode() == ISD::AND) {
3660     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3661       Mask = Op.getOperand(1);
3662       Op = Op.getOperand(0);
3663     } else {
3664       return false;
3665     }
3666   }
3667
3668   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3669     Shift = Op;
3670     return true;
3671   }
3672
3673   return false;
3674 }
3675
3676 // Return true if we can prove that, whenever Neg and Pos are both in the
3677 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3678 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3679 //
3680 //     (or (shift1 X, Neg), (shift2 X, Pos))
3681 //
3682 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3683 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3684 // to consider shift amounts with defined behavior.
3685 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3686   // If OpSize is a power of 2 then:
3687   //
3688   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3689   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3690   //
3691   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3692   // for the stronger condition:
3693   //
3694   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3695   //
3696   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3697   // we can just replace Neg with Neg' for the rest of the function.
3698   //
3699   // In other cases we check for the even stronger condition:
3700   //
3701   //     Neg == OpSize - Pos                                    [B]
3702   //
3703   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3704   // behavior if Pos == 0 (and consequently Neg == OpSize).
3705   //
3706   // We could actually use [A] whenever OpSize is a power of 2, but the
3707   // only extra cases that it would match are those uninteresting ones
3708   // where Neg and Pos are never in range at the same time.  E.g. for
3709   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3710   // as well as (sub 32, Pos), but:
3711   //
3712   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3713   //
3714   // always invokes undefined behavior for 32-bit X.
3715   //
3716   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3717   unsigned MaskLoBits = 0;
3718   if (Neg.getOpcode() == ISD::AND &&
3719       isPowerOf2_64(OpSize) &&
3720       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3721       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3722     Neg = Neg.getOperand(0);
3723     MaskLoBits = Log2_64(OpSize);
3724   }
3725
3726   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3727   if (Neg.getOpcode() != ISD::SUB)
3728     return 0;
3729   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3730   if (!NegC)
3731     return 0;
3732   SDValue NegOp1 = Neg.getOperand(1);
3733
3734   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3735   // Pos'.  The truncation is redundant for the purpose of the equality.
3736   if (MaskLoBits &&
3737       Pos.getOpcode() == ISD::AND &&
3738       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3739       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3740     Pos = Pos.getOperand(0);
3741
3742   // The condition we need is now:
3743   //
3744   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3745   //
3746   // If NegOp1 == Pos then we need:
3747   //
3748   //              OpSize & Mask == NegC & Mask
3749   //
3750   // (because "x & Mask" is a truncation and distributes through subtraction).
3751   APInt Width;
3752   if (Pos == NegOp1)
3753     Width = NegC->getAPIntValue();
3754   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3755   // Then the condition we want to prove becomes:
3756   //
3757   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3758   //
3759   // which, again because "x & Mask" is a truncation, becomes:
3760   //
3761   //                NegC & Mask == (OpSize - PosC) & Mask
3762   //              OpSize & Mask == (NegC + PosC) & Mask
3763   else if (Pos.getOpcode() == ISD::ADD &&
3764            Pos.getOperand(0) == NegOp1 &&
3765            Pos.getOperand(1).getOpcode() == ISD::Constant)
3766     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3767              NegC->getAPIntValue());
3768   else
3769     return false;
3770
3771   // Now we just need to check that OpSize & Mask == Width & Mask.
3772   if (MaskLoBits)
3773     // Opsize & Mask is 0 since Mask is Opsize - 1.
3774     return Width.getLoBits(MaskLoBits) == 0;
3775   return Width == OpSize;
3776 }
3777
3778 // A subroutine of MatchRotate used once we have found an OR of two opposite
3779 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3780 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3781 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3782 // Neg with outer conversions stripped away.
3783 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3784                                        SDValue Neg, SDValue InnerPos,
3785                                        SDValue InnerNeg, unsigned PosOpcode,
3786                                        unsigned NegOpcode, SDLoc DL) {
3787   // fold (or (shl x, (*ext y)),
3788   //          (srl x, (*ext (sub 32, y)))) ->
3789   //   (rotl x, y) or (rotr x, (sub 32, y))
3790   //
3791   // fold (or (shl x, (*ext (sub 32, y))),
3792   //          (srl x, (*ext y))) ->
3793   //   (rotr x, y) or (rotl x, (sub 32, y))
3794   EVT VT = Shifted.getValueType();
3795   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3796     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3797     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3798                        HasPos ? Pos : Neg).getNode();
3799   }
3800
3801   return nullptr;
3802 }
3803
3804 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3805 // idioms for rotate, and if the target supports rotation instructions, generate
3806 // a rot[lr].
3807 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3808   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3809   EVT VT = LHS.getValueType();
3810   if (!TLI.isTypeLegal(VT)) return nullptr;
3811
3812   // The target must have at least one rotate flavor.
3813   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3814   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3815   if (!HasROTL && !HasROTR) return nullptr;
3816
3817   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3818   SDValue LHSShift;   // The shift.
3819   SDValue LHSMask;    // AND value if any.
3820   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3821     return nullptr; // Not part of a rotate.
3822
3823   SDValue RHSShift;   // The shift.
3824   SDValue RHSMask;    // AND value if any.
3825   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3826     return nullptr; // Not part of a rotate.
3827
3828   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3829     return nullptr;   // Not shifting the same value.
3830
3831   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3832     return nullptr;   // Shifts must disagree.
3833
3834   // Canonicalize shl to left side in a shl/srl pair.
3835   if (RHSShift.getOpcode() == ISD::SHL) {
3836     std::swap(LHS, RHS);
3837     std::swap(LHSShift, RHSShift);
3838     std::swap(LHSMask , RHSMask );
3839   }
3840
3841   unsigned OpSizeInBits = VT.getSizeInBits();
3842   SDValue LHSShiftArg = LHSShift.getOperand(0);
3843   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3844   SDValue RHSShiftArg = RHSShift.getOperand(0);
3845   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3846
3847   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3848   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3849   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3850       RHSShiftAmt.getOpcode() == ISD::Constant) {
3851     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3852     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3853     if ((LShVal + RShVal) != OpSizeInBits)
3854       return nullptr;
3855
3856     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3857                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3858
3859     // If there is an AND of either shifted operand, apply it to the result.
3860     if (LHSMask.getNode() || RHSMask.getNode()) {
3861       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3862
3863       if (LHSMask.getNode()) {
3864         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3865         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3866       }
3867       if (RHSMask.getNode()) {
3868         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3869         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3870       }
3871
3872       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3873     }
3874
3875     return Rot.getNode();
3876   }
3877
3878   // If there is a mask here, and we have a variable shift, we can't be sure
3879   // that we're masking out the right stuff.
3880   if (LHSMask.getNode() || RHSMask.getNode())
3881     return nullptr;
3882
3883   // If the shift amount is sign/zext/any-extended just peel it off.
3884   SDValue LExtOp0 = LHSShiftAmt;
3885   SDValue RExtOp0 = RHSShiftAmt;
3886   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3887        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3888        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3889        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3890       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3891        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3892        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3893        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3894     LExtOp0 = LHSShiftAmt.getOperand(0);
3895     RExtOp0 = RHSShiftAmt.getOperand(0);
3896   }
3897
3898   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3899                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3900   if (TryL)
3901     return TryL;
3902
3903   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3904                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3905   if (TryR)
3906     return TryR;
3907
3908   return nullptr;
3909 }
3910
3911 SDValue DAGCombiner::visitXOR(SDNode *N) {
3912   SDValue N0 = N->getOperand(0);
3913   SDValue N1 = N->getOperand(1);
3914   EVT VT = N0.getValueType();
3915
3916   // fold vector ops
3917   if (VT.isVector()) {
3918     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3919       return FoldedVOp;
3920
3921     // fold (xor x, 0) -> x, vector edition
3922     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3923       return N1;
3924     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3925       return N0;
3926   }
3927
3928   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3929   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3930     return DAG.getConstant(0, SDLoc(N), VT);
3931   // fold (xor x, undef) -> undef
3932   if (N0.getOpcode() == ISD::UNDEF)
3933     return N0;
3934   if (N1.getOpcode() == ISD::UNDEF)
3935     return N1;
3936   // fold (xor c1, c2) -> c1^c2
3937   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3938   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3939   if (N0C && N1C)
3940     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3941   // canonicalize constant to RHS
3942   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3943      !isConstantIntBuildVectorOrConstantInt(N1))
3944     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3945   // fold (xor x, 0) -> x
3946   if (N1C && N1C->isNullValue())
3947     return N0;
3948   // reassociate xor
3949   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3950     return RXOR;
3951
3952   // fold !(x cc y) -> (x !cc y)
3953   SDValue LHS, RHS, CC;
3954   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3955     bool isInt = LHS.getValueType().isInteger();
3956     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3957                                                isInt);
3958
3959     if (!LegalOperations ||
3960         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3961       switch (N0.getOpcode()) {
3962       default:
3963         llvm_unreachable("Unhandled SetCC Equivalent!");
3964       case ISD::SETCC:
3965         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3966       case ISD::SELECT_CC:
3967         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3968                                N0.getOperand(3), NotCC);
3969       }
3970     }
3971   }
3972
3973   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3974   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3975       N0.getNode()->hasOneUse() &&
3976       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3977     SDValue V = N0.getOperand(0);
3978     SDLoc DL(N0);
3979     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3980                     DAG.getConstant(1, DL, V.getValueType()));
3981     AddToWorklist(V.getNode());
3982     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3983   }
3984
3985   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3986   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3987       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3988     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3989     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3990       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3991       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3992       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3993       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3994       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3995     }
3996   }
3997   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3998   if (N1C && N1C->isAllOnesValue() &&
3999       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4000     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4001     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4002       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4003       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4004       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4005       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4006       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4007     }
4008   }
4009   // fold (xor (and x, y), y) -> (and (not x), y)
4010   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4011       N0->getOperand(1) == N1) {
4012     SDValue X = N0->getOperand(0);
4013     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4014     AddToWorklist(NotX.getNode());
4015     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4016   }
4017   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4018   if (N1C && N0.getOpcode() == ISD::XOR) {
4019     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4020     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4021     if (N00C) {
4022       SDLoc DL(N);
4023       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4024                          DAG.getConstant(N1C->getAPIntValue() ^
4025                                          N00C->getAPIntValue(), DL, VT));
4026     }
4027     if (N01C) {
4028       SDLoc DL(N);
4029       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4030                          DAG.getConstant(N1C->getAPIntValue() ^
4031                                          N01C->getAPIntValue(), DL, VT));
4032     }
4033   }
4034   // fold (xor x, x) -> 0
4035   if (N0 == N1)
4036     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4037
4038   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4039   // Here is a concrete example of this equivalence:
4040   // i16   x ==  14
4041   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4042   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4043   //
4044   // =>
4045   //
4046   // i16     ~1      == 0b1111111111111110
4047   // i16 rol(~1, 14) == 0b1011111111111111
4048   //
4049   // Some additional tips to help conceptualize this transform:
4050   // - Try to see the operation as placing a single zero in a value of all ones.
4051   // - There exists no value for x which would allow the result to contain zero.
4052   // - Values of x larger than the bitwidth are undefined and do not require a
4053   //   consistent result.
4054   // - Pushing the zero left requires shifting one bits in from the right.
4055   // A rotate left of ~1 is a nice way of achieving the desired result.
4056   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4057     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4058       if (N0.getOpcode() == ISD::SHL)
4059         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4060           if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4061             SDLoc DL(N);
4062             return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4063                                N0.getOperand(1));
4064           }
4065
4066   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4067   if (N0.getOpcode() == N1.getOpcode()) {
4068     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4069     if (Tmp.getNode()) return Tmp;
4070   }
4071
4072   // Simplify the expression using non-local knowledge.
4073   if (!VT.isVector() &&
4074       SimplifyDemandedBits(SDValue(N, 0)))
4075     return SDValue(N, 0);
4076
4077   return SDValue();
4078 }
4079
4080 /// Handle transforms common to the three shifts, when the shift amount is a
4081 /// constant.
4082 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4083   // We can't and shouldn't fold opaque constants.
4084   if (Amt->isOpaque())
4085     return SDValue();
4086
4087   SDNode *LHS = N->getOperand(0).getNode();
4088   if (!LHS->hasOneUse()) return SDValue();
4089
4090   // We want to pull some binops through shifts, so that we have (and (shift))
4091   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4092   // thing happens with address calculations, so it's important to canonicalize
4093   // it.
4094   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4095
4096   switch (LHS->getOpcode()) {
4097   default: return SDValue();
4098   case ISD::OR:
4099   case ISD::XOR:
4100     HighBitSet = false; // We can only transform sra if the high bit is clear.
4101     break;
4102   case ISD::AND:
4103     HighBitSet = true;  // We can only transform sra if the high bit is set.
4104     break;
4105   case ISD::ADD:
4106     if (N->getOpcode() != ISD::SHL)
4107       return SDValue(); // only shl(add) not sr[al](add).
4108     HighBitSet = false; // We can only transform sra if the high bit is clear.
4109     break;
4110   }
4111
4112   // We require the RHS of the binop to be a constant and not opaque as well.
4113   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4114   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4115
4116   // FIXME: disable this unless the input to the binop is a shift by a constant.
4117   // If it is not a shift, it pessimizes some common cases like:
4118   //
4119   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4120   //    int bar(int *X, int i) { return X[i & 255]; }
4121   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4122   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4123        BinOpLHSVal->getOpcode() != ISD::SRA &&
4124        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4125       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4126     return SDValue();
4127
4128   EVT VT = N->getValueType(0);
4129
4130   // If this is a signed shift right, and the high bit is modified by the
4131   // logical operation, do not perform the transformation. The highBitSet
4132   // boolean indicates the value of the high bit of the constant which would
4133   // cause it to be modified for this operation.
4134   if (N->getOpcode() == ISD::SRA) {
4135     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4136     if (BinOpRHSSignSet != HighBitSet)
4137       return SDValue();
4138   }
4139
4140   if (!TLI.isDesirableToCommuteWithShift(LHS))
4141     return SDValue();
4142
4143   // Fold the constants, shifting the binop RHS by the shift amount.
4144   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4145                                N->getValueType(0),
4146                                LHS->getOperand(1), N->getOperand(1));
4147   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4148
4149   // Create the new shift.
4150   SDValue NewShift = DAG.getNode(N->getOpcode(),
4151                                  SDLoc(LHS->getOperand(0)),
4152                                  VT, LHS->getOperand(0), N->getOperand(1));
4153
4154   // Create the new binop.
4155   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4156 }
4157
4158 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4159   assert(N->getOpcode() == ISD::TRUNCATE);
4160   assert(N->getOperand(0).getOpcode() == ISD::AND);
4161
4162   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4163   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4164     SDValue N01 = N->getOperand(0).getOperand(1);
4165
4166     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4167       EVT TruncVT = N->getValueType(0);
4168       SDValue N00 = N->getOperand(0).getOperand(0);
4169       APInt TruncC = N01C->getAPIntValue();
4170       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4171       SDLoc DL(N);
4172
4173       return DAG.getNode(ISD::AND, DL, TruncVT,
4174                          DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4175                          DAG.getConstant(TruncC, DL, TruncVT));
4176     }
4177   }
4178
4179   return SDValue();
4180 }
4181
4182 SDValue DAGCombiner::visitRotate(SDNode *N) {
4183   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4184   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4185       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4186     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4187     if (NewOp1.getNode())
4188       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4189                          N->getOperand(0), NewOp1);
4190   }
4191   return SDValue();
4192 }
4193
4194 SDValue DAGCombiner::visitSHL(SDNode *N) {
4195   SDValue N0 = N->getOperand(0);
4196   SDValue N1 = N->getOperand(1);
4197   EVT VT = N0.getValueType();
4198   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4199
4200   // fold vector ops
4201   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4202   if (VT.isVector()) {
4203     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4204       return FoldedVOp;
4205
4206     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4207     // If setcc produces all-one true value then:
4208     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4209     if (N1CV && N1CV->isConstant()) {
4210       if (N0.getOpcode() == ISD::AND) {
4211         SDValue N00 = N0->getOperand(0);
4212         SDValue N01 = N0->getOperand(1);
4213         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4214
4215         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4216             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4217                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4218           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4219                                                      N01CV, N1CV))
4220             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4221         }
4222       } else {
4223         N1C = isConstOrConstSplat(N1);
4224       }
4225     }
4226   }
4227
4228   // fold (shl c1, c2) -> c1<<c2
4229   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4230   if (N0C && N1C)
4231     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4232   // fold (shl 0, x) -> 0
4233   if (N0C && N0C->isNullValue())
4234     return N0;
4235   // fold (shl x, c >= size(x)) -> undef
4236   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4237     return DAG.getUNDEF(VT);
4238   // fold (shl x, 0) -> x
4239   if (N1C && N1C->isNullValue())
4240     return N0;
4241   // fold (shl undef, x) -> 0
4242   if (N0.getOpcode() == ISD::UNDEF)
4243     return DAG.getConstant(0, SDLoc(N), VT);
4244   // if (shl x, c) is known to be zero, return 0
4245   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4246                             APInt::getAllOnesValue(OpSizeInBits)))
4247     return DAG.getConstant(0, SDLoc(N), VT);
4248   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4249   if (N1.getOpcode() == ISD::TRUNCATE &&
4250       N1.getOperand(0).getOpcode() == ISD::AND) {
4251     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4252     if (NewOp1.getNode())
4253       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4254   }
4255
4256   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4257     return SDValue(N, 0);
4258
4259   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4260   if (N1C && N0.getOpcode() == ISD::SHL) {
4261     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4262       uint64_t c1 = N0C1->getZExtValue();
4263       uint64_t c2 = N1C->getZExtValue();
4264       SDLoc DL(N);
4265       if (c1 + c2 >= OpSizeInBits)
4266         return DAG.getConstant(0, DL, VT);
4267       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4268                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4269     }
4270   }
4271
4272   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4273   // For this to be valid, the second form must not preserve any of the bits
4274   // that are shifted out by the inner shift in the first form.  This means
4275   // the outer shift size must be >= the number of bits added by the ext.
4276   // As a corollary, we don't care what kind of ext it is.
4277   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4278               N0.getOpcode() == ISD::ANY_EXTEND ||
4279               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4280       N0.getOperand(0).getOpcode() == ISD::SHL) {
4281     SDValue N0Op0 = N0.getOperand(0);
4282     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4283       uint64_t c1 = N0Op0C1->getZExtValue();
4284       uint64_t c2 = N1C->getZExtValue();
4285       EVT InnerShiftVT = N0Op0.getValueType();
4286       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4287       if (c2 >= OpSizeInBits - InnerShiftSize) {
4288         SDLoc DL(N0);
4289         if (c1 + c2 >= OpSizeInBits)
4290           return DAG.getConstant(0, DL, VT);
4291         return DAG.getNode(ISD::SHL, DL, VT,
4292                            DAG.getNode(N0.getOpcode(), DL, VT,
4293                                        N0Op0->getOperand(0)),
4294                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4295       }
4296     }
4297   }
4298
4299   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4300   // Only fold this if the inner zext has no other uses to avoid increasing
4301   // the total number of instructions.
4302   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4303       N0.getOperand(0).getOpcode() == ISD::SRL) {
4304     SDValue N0Op0 = N0.getOperand(0);
4305     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4306       uint64_t c1 = N0Op0C1->getZExtValue();
4307       if (c1 < VT.getScalarSizeInBits()) {
4308         uint64_t c2 = N1C->getZExtValue();
4309         if (c1 == c2) {
4310           SDValue NewOp0 = N0.getOperand(0);
4311           EVT CountVT = NewOp0.getOperand(1).getValueType();
4312           SDLoc DL(N);
4313           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4314                                        NewOp0,
4315                                        DAG.getConstant(c2, DL, CountVT));
4316           AddToWorklist(NewSHL.getNode());
4317           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4318         }
4319       }
4320     }
4321   }
4322
4323   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4324   //                               (and (srl x, (sub c1, c2), MASK)
4325   // Only fold this if the inner shift has no other uses -- if it does, folding
4326   // this will increase the total number of instructions.
4327   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4328     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4329       uint64_t c1 = N0C1->getZExtValue();
4330       if (c1 < OpSizeInBits) {
4331         uint64_t c2 = N1C->getZExtValue();
4332         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4333         SDValue Shift;
4334         if (c2 > c1) {
4335           Mask = Mask.shl(c2 - c1);
4336           SDLoc DL(N);
4337           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4338                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4339         } else {
4340           Mask = Mask.lshr(c1 - c2);
4341           SDLoc DL(N);
4342           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4343                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4344         }
4345         SDLoc DL(N0);
4346         return DAG.getNode(ISD::AND, DL, VT, Shift,
4347                            DAG.getConstant(Mask, DL, VT));
4348       }
4349     }
4350   }
4351   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4352   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4353     unsigned BitSize = VT.getScalarSizeInBits();
4354     SDLoc DL(N);
4355     SDValue HiBitsMask =
4356       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4357                                             BitSize - N1C->getZExtValue()),
4358                       DL, VT);
4359     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4360                        HiBitsMask);
4361   }
4362
4363   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4364   // Variant of version done on multiply, except mul by a power of 2 is turned
4365   // into a shift.
4366   APInt Val;
4367   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4368       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4369        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4370     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4371     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4372     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4373   }
4374
4375   if (N1C) {
4376     SDValue NewSHL = visitShiftByConstant(N, N1C);
4377     if (NewSHL.getNode())
4378       return NewSHL;
4379   }
4380
4381   return SDValue();
4382 }
4383
4384 SDValue DAGCombiner::visitSRA(SDNode *N) {
4385   SDValue N0 = N->getOperand(0);
4386   SDValue N1 = N->getOperand(1);
4387   EVT VT = N0.getValueType();
4388   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4389
4390   // fold vector ops
4391   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4392   if (VT.isVector()) {
4393     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4394       return FoldedVOp;
4395
4396     N1C = isConstOrConstSplat(N1);
4397   }
4398
4399   // fold (sra c1, c2) -> (sra c1, c2)
4400   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4401   if (N0C && N1C)
4402     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4403   // fold (sra 0, x) -> 0
4404   if (N0C && N0C->isNullValue())
4405     return N0;
4406   // fold (sra -1, x) -> -1
4407   if (N0C && N0C->isAllOnesValue())
4408     return N0;
4409   // fold (sra x, (setge c, size(x))) -> undef
4410   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4411     return DAG.getUNDEF(VT);
4412   // fold (sra x, 0) -> x
4413   if (N1C && N1C->isNullValue())
4414     return N0;
4415   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4416   // sext_inreg.
4417   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4418     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4419     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4420     if (VT.isVector())
4421       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4422                                ExtVT, VT.getVectorNumElements());
4423     if ((!LegalOperations ||
4424          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4425       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4426                          N0.getOperand(0), DAG.getValueType(ExtVT));
4427   }
4428
4429   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4430   if (N1C && N0.getOpcode() == ISD::SRA) {
4431     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4432       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4433       if (Sum >= OpSizeInBits)
4434         Sum = OpSizeInBits - 1;
4435       SDLoc DL(N);
4436       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4437                          DAG.getConstant(Sum, DL, N1.getValueType()));
4438     }
4439   }
4440
4441   // fold (sra (shl X, m), (sub result_size, n))
4442   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4443   // result_size - n != m.
4444   // If truncate is free for the target sext(shl) is likely to result in better
4445   // code.
4446   if (N0.getOpcode() == ISD::SHL && N1C) {
4447     // Get the two constanst of the shifts, CN0 = m, CN = n.
4448     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4449     if (N01C) {
4450       LLVMContext &Ctx = *DAG.getContext();
4451       // Determine what the truncate's result bitsize and type would be.
4452       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4453
4454       if (VT.isVector())
4455         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4456
4457       // Determine the residual right-shift amount.
4458       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4459
4460       // If the shift is not a no-op (in which case this should be just a sign
4461       // extend already), the truncated to type is legal, sign_extend is legal
4462       // on that type, and the truncate to that type is both legal and free,
4463       // perform the transform.
4464       if ((ShiftAmt > 0) &&
4465           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4466           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4467           TLI.isTruncateFree(VT, TruncVT)) {
4468
4469         SDLoc DL(N);
4470         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4471             getShiftAmountTy(N0.getOperand(0).getValueType()));
4472         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4473                                     N0.getOperand(0), Amt);
4474         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4475                                     Shift);
4476         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4477                            N->getValueType(0), Trunc);
4478       }
4479     }
4480   }
4481
4482   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4483   if (N1.getOpcode() == ISD::TRUNCATE &&
4484       N1.getOperand(0).getOpcode() == ISD::AND) {
4485     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4486     if (NewOp1.getNode())
4487       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4488   }
4489
4490   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4491   //      if c1 is equal to the number of bits the trunc removes
4492   if (N0.getOpcode() == ISD::TRUNCATE &&
4493       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4494        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4495       N0.getOperand(0).hasOneUse() &&
4496       N0.getOperand(0).getOperand(1).hasOneUse() &&
4497       N1C) {
4498     SDValue N0Op0 = N0.getOperand(0);
4499     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4500       unsigned LargeShiftVal = LargeShift->getZExtValue();
4501       EVT LargeVT = N0Op0.getValueType();
4502
4503       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4504         SDLoc DL(N);
4505         SDValue Amt =
4506           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4507                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4508         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4509                                   N0Op0.getOperand(0), Amt);
4510         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4511       }
4512     }
4513   }
4514
4515   // Simplify, based on bits shifted out of the LHS.
4516   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4517     return SDValue(N, 0);
4518
4519
4520   // If the sign bit is known to be zero, switch this to a SRL.
4521   if (DAG.SignBitIsZero(N0))
4522     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4523
4524   if (N1C) {
4525     SDValue NewSRA = visitShiftByConstant(N, N1C);
4526     if (NewSRA.getNode())
4527       return NewSRA;
4528   }
4529
4530   return SDValue();
4531 }
4532
4533 SDValue DAGCombiner::visitSRL(SDNode *N) {
4534   SDValue N0 = N->getOperand(0);
4535   SDValue N1 = N->getOperand(1);
4536   EVT VT = N0.getValueType();
4537   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4538
4539   // fold vector ops
4540   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4541   if (VT.isVector()) {
4542     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4543       return FoldedVOp;
4544
4545     N1C = isConstOrConstSplat(N1);
4546   }
4547
4548   // fold (srl c1, c2) -> c1 >>u c2
4549   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4550   if (N0C && N1C)
4551     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4552   // fold (srl 0, x) -> 0
4553   if (N0C && N0C->isNullValue())
4554     return N0;
4555   // fold (srl x, c >= size(x)) -> undef
4556   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4557     return DAG.getUNDEF(VT);
4558   // fold (srl x, 0) -> x
4559   if (N1C && N1C->isNullValue())
4560     return N0;
4561   // if (srl x, c) is known to be zero, return 0
4562   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4563                                    APInt::getAllOnesValue(OpSizeInBits)))
4564     return DAG.getConstant(0, SDLoc(N), VT);
4565
4566   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4567   if (N1C && N0.getOpcode() == ISD::SRL) {
4568     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4569       uint64_t c1 = N01C->getZExtValue();
4570       uint64_t c2 = N1C->getZExtValue();
4571       SDLoc DL(N);
4572       if (c1 + c2 >= OpSizeInBits)
4573         return DAG.getConstant(0, DL, VT);
4574       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4575                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4576     }
4577   }
4578
4579   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4580   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4581       N0.getOperand(0).getOpcode() == ISD::SRL &&
4582       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4583     uint64_t c1 =
4584       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4585     uint64_t c2 = N1C->getZExtValue();
4586     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4587     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4588     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4589     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4590     if (c1 + OpSizeInBits == InnerShiftSize) {
4591       SDLoc DL(N0);
4592       if (c1 + c2 >= InnerShiftSize)
4593         return DAG.getConstant(0, DL, VT);
4594       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4595                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4596                                      N0.getOperand(0)->getOperand(0),
4597                                      DAG.getConstant(c1 + c2, DL,
4598                                                      ShiftCountVT)));
4599     }
4600   }
4601
4602   // fold (srl (shl x, c), c) -> (and x, cst2)
4603   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4604     unsigned BitSize = N0.getScalarValueSizeInBits();
4605     if (BitSize <= 64) {
4606       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4607       SDLoc DL(N);
4608       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4609                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4610     }
4611   }
4612
4613   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4614   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4615     // Shifting in all undef bits?
4616     EVT SmallVT = N0.getOperand(0).getValueType();
4617     unsigned BitSize = SmallVT.getScalarSizeInBits();
4618     if (N1C->getZExtValue() >= BitSize)
4619       return DAG.getUNDEF(VT);
4620
4621     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4622       uint64_t ShiftAmt = N1C->getZExtValue();
4623       SDLoc DL0(N0);
4624       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4625                                        N0.getOperand(0),
4626                           DAG.getConstant(ShiftAmt, DL0,
4627                                           getShiftAmountTy(SmallVT)));
4628       AddToWorklist(SmallShift.getNode());
4629       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4630       SDLoc DL(N);
4631       return DAG.getNode(ISD::AND, DL, VT,
4632                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4633                          DAG.getConstant(Mask, DL, VT));
4634     }
4635   }
4636
4637   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4638   // bit, which is unmodified by sra.
4639   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4640     if (N0.getOpcode() == ISD::SRA)
4641       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4642   }
4643
4644   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4645   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4646       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4647     APInt KnownZero, KnownOne;
4648     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4649
4650     // If any of the input bits are KnownOne, then the input couldn't be all
4651     // zeros, thus the result of the srl will always be zero.
4652     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4653
4654     // If all of the bits input the to ctlz node are known to be zero, then
4655     // the result of the ctlz is "32" and the result of the shift is one.
4656     APInt UnknownBits = ~KnownZero;
4657     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4658
4659     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4660     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4661       // Okay, we know that only that the single bit specified by UnknownBits
4662       // could be set on input to the CTLZ node. If this bit is set, the SRL
4663       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4664       // to an SRL/XOR pair, which is likely to simplify more.
4665       unsigned ShAmt = UnknownBits.countTrailingZeros();
4666       SDValue Op = N0.getOperand(0);
4667
4668       if (ShAmt) {
4669         SDLoc DL(N0);
4670         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4671                   DAG.getConstant(ShAmt, DL,
4672                                   getShiftAmountTy(Op.getValueType())));
4673         AddToWorklist(Op.getNode());
4674       }
4675
4676       SDLoc DL(N);
4677       return DAG.getNode(ISD::XOR, DL, VT,
4678                          Op, DAG.getConstant(1, DL, VT));
4679     }
4680   }
4681
4682   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4683   if (N1.getOpcode() == ISD::TRUNCATE &&
4684       N1.getOperand(0).getOpcode() == ISD::AND) {
4685     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4686     if (NewOp1.getNode())
4687       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4688   }
4689
4690   // fold operands of srl based on knowledge that the low bits are not
4691   // demanded.
4692   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4693     return SDValue(N, 0);
4694
4695   if (N1C) {
4696     SDValue NewSRL = visitShiftByConstant(N, N1C);
4697     if (NewSRL.getNode())
4698       return NewSRL;
4699   }
4700
4701   // Attempt to convert a srl of a load into a narrower zero-extending load.
4702   SDValue NarrowLoad = ReduceLoadWidth(N);
4703   if (NarrowLoad.getNode())
4704     return NarrowLoad;
4705
4706   // Here is a common situation. We want to optimize:
4707   //
4708   //   %a = ...
4709   //   %b = and i32 %a, 2
4710   //   %c = srl i32 %b, 1
4711   //   brcond i32 %c ...
4712   //
4713   // into
4714   //
4715   //   %a = ...
4716   //   %b = and %a, 2
4717   //   %c = setcc eq %b, 0
4718   //   brcond %c ...
4719   //
4720   // However when after the source operand of SRL is optimized into AND, the SRL
4721   // itself may not be optimized further. Look for it and add the BRCOND into
4722   // the worklist.
4723   if (N->hasOneUse()) {
4724     SDNode *Use = *N->use_begin();
4725     if (Use->getOpcode() == ISD::BRCOND)
4726       AddToWorklist(Use);
4727     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4728       // Also look pass the truncate.
4729       Use = *Use->use_begin();
4730       if (Use->getOpcode() == ISD::BRCOND)
4731         AddToWorklist(Use);
4732     }
4733   }
4734
4735   return SDValue();
4736 }
4737
4738 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4739   SDValue N0 = N->getOperand(0);
4740   EVT VT = N->getValueType(0);
4741
4742   // fold (ctlz c1) -> c2
4743   if (isa<ConstantSDNode>(N0))
4744     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4745   return SDValue();
4746 }
4747
4748 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4749   SDValue N0 = N->getOperand(0);
4750   EVT VT = N->getValueType(0);
4751
4752   // fold (ctlz_zero_undef c1) -> c2
4753   if (isa<ConstantSDNode>(N0))
4754     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4755   return SDValue();
4756 }
4757
4758 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4759   SDValue N0 = N->getOperand(0);
4760   EVT VT = N->getValueType(0);
4761
4762   // fold (cttz c1) -> c2
4763   if (isa<ConstantSDNode>(N0))
4764     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4765   return SDValue();
4766 }
4767
4768 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4769   SDValue N0 = N->getOperand(0);
4770   EVT VT = N->getValueType(0);
4771
4772   // fold (cttz_zero_undef c1) -> c2
4773   if (isa<ConstantSDNode>(N0))
4774     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4775   return SDValue();
4776 }
4777
4778 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4779   SDValue N0 = N->getOperand(0);
4780   EVT VT = N->getValueType(0);
4781
4782   // fold (ctpop c1) -> c2
4783   if (isa<ConstantSDNode>(N0))
4784     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4785   return SDValue();
4786 }
4787
4788
4789 /// \brief Generate Min/Max node
4790 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4791                                    SDValue True, SDValue False,
4792                                    ISD::CondCode CC, const TargetLowering &TLI,
4793                                    SelectionDAG &DAG) {
4794   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4795     return SDValue();
4796
4797   switch (CC) {
4798   case ISD::SETOLT:
4799   case ISD::SETOLE:
4800   case ISD::SETLT:
4801   case ISD::SETLE:
4802   case ISD::SETULT:
4803   case ISD::SETULE: {
4804     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4805     if (TLI.isOperationLegal(Opcode, VT))
4806       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4807     return SDValue();
4808   }
4809   case ISD::SETOGT:
4810   case ISD::SETOGE:
4811   case ISD::SETGT:
4812   case ISD::SETGE:
4813   case ISD::SETUGT:
4814   case ISD::SETUGE: {
4815     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4816     if (TLI.isOperationLegal(Opcode, VT))
4817       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4818     return SDValue();
4819   }
4820   default:
4821     return SDValue();
4822   }
4823 }
4824
4825 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4826   SDValue N0 = N->getOperand(0);
4827   SDValue N1 = N->getOperand(1);
4828   SDValue N2 = N->getOperand(2);
4829   EVT VT = N->getValueType(0);
4830   EVT VT0 = N0.getValueType();
4831
4832   // fold (select C, X, X) -> X
4833   if (N1 == N2)
4834     return N1;
4835   // fold (select true, X, Y) -> X
4836   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4837   if (N0C && !N0C->isNullValue())
4838     return N1;
4839   // fold (select false, X, Y) -> Y
4840   if (N0C && N0C->isNullValue())
4841     return N2;
4842   // fold (select C, 1, X) -> (or C, X)
4843   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4844   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4845     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4846   // fold (select C, 0, 1) -> (xor C, 1)
4847   // We can't do this reliably if integer based booleans have different contents
4848   // to floating point based booleans. This is because we can't tell whether we
4849   // have an integer-based boolean or a floating-point-based boolean unless we
4850   // can find the SETCC that produced it and inspect its operands. This is
4851   // fairly easy if C is the SETCC node, but it can potentially be
4852   // undiscoverable (or not reasonably discoverable). For example, it could be
4853   // in another basic block or it could require searching a complicated
4854   // expression.
4855   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4856   if (VT.isInteger() &&
4857       (VT0 == MVT::i1 || (VT0.isInteger() &&
4858                           TLI.getBooleanContents(false, false) ==
4859                               TLI.getBooleanContents(false, true) &&
4860                           TLI.getBooleanContents(false, false) ==
4861                               TargetLowering::ZeroOrOneBooleanContent)) &&
4862       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4863     SDValue XORNode;
4864     if (VT == VT0) {
4865       SDLoc DL(N);
4866       return DAG.getNode(ISD::XOR, DL, VT0,
4867                          N0, DAG.getConstant(1, DL, VT0));
4868     }
4869     SDLoc DL0(N0);
4870     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4871                           N0, DAG.getConstant(1, DL0, VT0));
4872     AddToWorklist(XORNode.getNode());
4873     if (VT.bitsGT(VT0))
4874       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4875     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4876   }
4877   // fold (select C, 0, X) -> (and (not C), X)
4878   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4879     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4880     AddToWorklist(NOTNode.getNode());
4881     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4882   }
4883   // fold (select C, X, 1) -> (or (not C), X)
4884   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4885     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4886     AddToWorklist(NOTNode.getNode());
4887     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4888   }
4889   // fold (select C, X, 0) -> (and C, X)
4890   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4891     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4892   // fold (select X, X, Y) -> (or X, Y)
4893   // fold (select X, 1, Y) -> (or X, Y)
4894   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4895     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4896   // fold (select X, Y, X) -> (and X, Y)
4897   // fold (select X, Y, 0) -> (and X, Y)
4898   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4899     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4900
4901   // If we can fold this based on the true/false value, do so.
4902   if (SimplifySelectOps(N, N1, N2))
4903     return SDValue(N, 0);  // Don't revisit N.
4904
4905   // fold selects based on a setcc into other things, such as min/max/abs
4906   if (N0.getOpcode() == ISD::SETCC) {
4907     // select x, y (fcmp lt x, y) -> fminnum x, y
4908     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4909     //
4910     // This is OK if we don't care about what happens if either operand is a
4911     // NaN.
4912     //
4913
4914     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4915     // no signed zeros as well as no nans.
4916     const TargetOptions &Options = DAG.getTarget().Options;
4917     if (Options.UnsafeFPMath &&
4918         VT.isFloatingPoint() && N0.hasOneUse() &&
4919         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4920       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4921
4922       SDValue FMinMax =
4923           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4924                               N1, N2, CC, TLI, DAG);
4925       if (FMinMax)
4926         return FMinMax;
4927     }
4928
4929     if ((!LegalOperations &&
4930          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4931         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4932       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4933                          N0.getOperand(0), N0.getOperand(1),
4934                          N1, N2, N0.getOperand(2));
4935     return SimplifySelect(SDLoc(N), N0, N1, N2);
4936   }
4937
4938   if (VT0 == MVT::i1) {
4939     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4940       // select (and Cond0, Cond1), X, Y
4941       //   -> select Cond0, (select Cond1, X, Y), Y
4942       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4943         SDValue Cond0 = N0->getOperand(0);
4944         SDValue Cond1 = N0->getOperand(1);
4945         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4946                                           N1.getValueType(), Cond1, N1, N2);
4947         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4948                            InnerSelect, N2);
4949       }
4950       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4951       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4952         SDValue Cond0 = N0->getOperand(0);
4953         SDValue Cond1 = N0->getOperand(1);
4954         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4955                                           N1.getValueType(), Cond1, N1, N2);
4956         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4957                            InnerSelect);
4958       }
4959     }
4960
4961     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4962     if (N1->getOpcode() == ISD::SELECT) {
4963       SDValue N1_0 = N1->getOperand(0);
4964       SDValue N1_1 = N1->getOperand(1);
4965       SDValue N1_2 = N1->getOperand(2);
4966       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4967         // Create the actual and node if we can generate good code for it.
4968         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4969           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4970                                     N0, N1_0);
4971           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4972                              N1_1, N2);
4973         }
4974         // Otherwise see if we can optimize the "and" to a better pattern.
4975         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4976           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4977                              N1_1, N2);
4978       }
4979     }
4980     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4981     if (N2->getOpcode() == ISD::SELECT) {
4982       SDValue N2_0 = N2->getOperand(0);
4983       SDValue N2_1 = N2->getOperand(1);
4984       SDValue N2_2 = N2->getOperand(2);
4985       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4986         // Create the actual or node if we can generate good code for it.
4987         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4988           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4989                                    N0, N2_0);
4990           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4991                              N1, N2_2);
4992         }
4993         // Otherwise see if we can optimize to a better pattern.
4994         if (SDValue Combined = visitORLike(N0, N2_0, N))
4995           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4996                              N1, N2_2);
4997       }
4998     }
4999   }
5000
5001   return SDValue();
5002 }
5003
5004 static
5005 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5006   SDLoc DL(N);
5007   EVT LoVT, HiVT;
5008   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5009
5010   // Split the inputs.
5011   SDValue Lo, Hi, LL, LH, RL, RH;
5012   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5013   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5014
5015   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5016   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5017
5018   return std::make_pair(Lo, Hi);
5019 }
5020
5021 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5022 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5023 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5024   SDLoc dl(N);
5025   SDValue Cond = N->getOperand(0);
5026   SDValue LHS = N->getOperand(1);
5027   SDValue RHS = N->getOperand(2);
5028   EVT VT = N->getValueType(0);
5029   int NumElems = VT.getVectorNumElements();
5030   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5031          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5032          Cond.getOpcode() == ISD::BUILD_VECTOR);
5033
5034   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5035   // binary ones here.
5036   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5037     return SDValue();
5038
5039   // We're sure we have an even number of elements due to the
5040   // concat_vectors we have as arguments to vselect.
5041   // Skip BV elements until we find one that's not an UNDEF
5042   // After we find an UNDEF element, keep looping until we get to half the
5043   // length of the BV and see if all the non-undef nodes are the same.
5044   ConstantSDNode *BottomHalf = nullptr;
5045   for (int i = 0; i < NumElems / 2; ++i) {
5046     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5047       continue;
5048
5049     if (BottomHalf == nullptr)
5050       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5051     else if (Cond->getOperand(i).getNode() != BottomHalf)
5052       return SDValue();
5053   }
5054
5055   // Do the same for the second half of the BuildVector
5056   ConstantSDNode *TopHalf = nullptr;
5057   for (int i = NumElems / 2; i < NumElems; ++i) {
5058     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5059       continue;
5060
5061     if (TopHalf == nullptr)
5062       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5063     else if (Cond->getOperand(i).getNode() != TopHalf)
5064       return SDValue();
5065   }
5066
5067   assert(TopHalf && BottomHalf &&
5068          "One half of the selector was all UNDEFs and the other was all the "
5069          "same value. This should have been addressed before this function.");
5070   return DAG.getNode(
5071       ISD::CONCAT_VECTORS, dl, VT,
5072       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5073       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5074 }
5075
5076 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5077
5078   if (Level >= AfterLegalizeTypes)
5079     return SDValue();
5080
5081   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5082   SDValue Mask = MST->getMask();
5083   SDValue Data  = MST->getValue();
5084   SDLoc DL(N);
5085
5086   // If the MSTORE data type requires splitting and the mask is provided by a
5087   // SETCC, then split both nodes and its operands before legalization. This
5088   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5089   // and enables future optimizations (e.g. min/max pattern matching on X86).
5090   if (Mask.getOpcode() == ISD::SETCC) {
5091
5092     // Check if any splitting is required.
5093     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5094         TargetLowering::TypeSplitVector)
5095       return SDValue();
5096
5097     SDValue MaskLo, MaskHi, Lo, Hi;
5098     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5099
5100     EVT LoVT, HiVT;
5101     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5102
5103     SDValue Chain = MST->getChain();
5104     SDValue Ptr   = MST->getBasePtr();
5105
5106     EVT MemoryVT = MST->getMemoryVT();
5107     unsigned Alignment = MST->getOriginalAlignment();
5108
5109     // if Alignment is equal to the vector size,
5110     // take the half of it for the second part
5111     unsigned SecondHalfAlignment =
5112       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5113          Alignment/2 : Alignment;
5114
5115     EVT LoMemVT, HiMemVT;
5116     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5117
5118     SDValue DataLo, DataHi;
5119     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5120
5121     MachineMemOperand *MMO = DAG.getMachineFunction().
5122       getMachineMemOperand(MST->getPointerInfo(),
5123                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5124                            Alignment, MST->getAAInfo(), MST->getRanges());
5125
5126     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5127                             MST->isTruncatingStore());
5128
5129     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5130     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5131                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5132
5133     MMO = DAG.getMachineFunction().
5134       getMachineMemOperand(MST->getPointerInfo(),
5135                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5136                            SecondHalfAlignment, MST->getAAInfo(),
5137                            MST->getRanges());
5138
5139     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5140                             MST->isTruncatingStore());
5141
5142     AddToWorklist(Lo.getNode());
5143     AddToWorklist(Hi.getNode());
5144
5145     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5146   }
5147   return SDValue();
5148 }
5149
5150 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5151
5152   if (Level >= AfterLegalizeTypes)
5153     return SDValue();
5154
5155   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5156   SDValue Mask = MLD->getMask();
5157   SDLoc DL(N);
5158
5159   // If the MLOAD result requires splitting and the mask is provided by a
5160   // SETCC, then split both nodes and its operands before legalization. This
5161   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5162   // and enables future optimizations (e.g. min/max pattern matching on X86).
5163
5164   if (Mask.getOpcode() == ISD::SETCC) {
5165     EVT VT = N->getValueType(0);
5166
5167     // Check if any splitting is required.
5168     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5169         TargetLowering::TypeSplitVector)
5170       return SDValue();
5171
5172     SDValue MaskLo, MaskHi, Lo, Hi;
5173     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5174
5175     SDValue Src0 = MLD->getSrc0();
5176     SDValue Src0Lo, Src0Hi;
5177     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5178
5179     EVT LoVT, HiVT;
5180     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5181
5182     SDValue Chain = MLD->getChain();
5183     SDValue Ptr   = MLD->getBasePtr();
5184     EVT MemoryVT = MLD->getMemoryVT();
5185     unsigned Alignment = MLD->getOriginalAlignment();
5186
5187     // if Alignment is equal to the vector size,
5188     // take the half of it for the second part
5189     unsigned SecondHalfAlignment =
5190       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5191          Alignment/2 : Alignment;
5192
5193     EVT LoMemVT, HiMemVT;
5194     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5195
5196     MachineMemOperand *MMO = DAG.getMachineFunction().
5197     getMachineMemOperand(MLD->getPointerInfo(),
5198                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5199                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5200
5201     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5202                            ISD::NON_EXTLOAD);
5203
5204     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5205     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5206                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5207
5208     MMO = DAG.getMachineFunction().
5209     getMachineMemOperand(MLD->getPointerInfo(),
5210                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5211                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5212
5213     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5214                            ISD::NON_EXTLOAD);
5215
5216     AddToWorklist(Lo.getNode());
5217     AddToWorklist(Hi.getNode());
5218
5219     // Build a factor node to remember that this load is independent of the
5220     // other one.
5221     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5222                         Hi.getValue(1));
5223
5224     // Legalized the chain result - switch anything that used the old chain to
5225     // use the new one.
5226     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5227
5228     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5229
5230     SDValue RetOps[] = { LoadRes, Chain };
5231     return DAG.getMergeValues(RetOps, DL);
5232   }
5233   return SDValue();
5234 }
5235
5236 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5237   SDValue N0 = N->getOperand(0);
5238   SDValue N1 = N->getOperand(1);
5239   SDValue N2 = N->getOperand(2);
5240   SDLoc DL(N);
5241
5242   // Canonicalize integer abs.
5243   // vselect (setg[te] X,  0),  X, -X ->
5244   // vselect (setgt    X, -1),  X, -X ->
5245   // vselect (setl[te] X,  0), -X,  X ->
5246   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5247   if (N0.getOpcode() == ISD::SETCC) {
5248     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5249     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5250     bool isAbs = false;
5251     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5252
5253     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5254          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5255         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5256       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5257     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5258              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5259       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5260
5261     if (isAbs) {
5262       EVT VT = LHS.getValueType();
5263       SDValue Shift = DAG.getNode(
5264           ISD::SRA, DL, VT, LHS,
5265           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5266       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5267       AddToWorklist(Shift.getNode());
5268       AddToWorklist(Add.getNode());
5269       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5270     }
5271   }
5272
5273   if (SimplifySelectOps(N, N1, N2))
5274     return SDValue(N, 0);  // Don't revisit N.
5275
5276   // If the VSELECT result requires splitting and the mask is provided by a
5277   // SETCC, then split both nodes and its operands before legalization. This
5278   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5279   // and enables future optimizations (e.g. min/max pattern matching on X86).
5280   if (N0.getOpcode() == ISD::SETCC) {
5281     EVT VT = N->getValueType(0);
5282
5283     // Check if any splitting is required.
5284     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5285         TargetLowering::TypeSplitVector)
5286       return SDValue();
5287
5288     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5289     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5290     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5291     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5292
5293     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5294     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5295
5296     // Add the new VSELECT nodes to the work list in case they need to be split
5297     // again.
5298     AddToWorklist(Lo.getNode());
5299     AddToWorklist(Hi.getNode());
5300
5301     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5302   }
5303
5304   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5305   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5306     return N1;
5307   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5308   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5309     return N2;
5310
5311   // The ConvertSelectToConcatVector function is assuming both the above
5312   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5313   // and addressed.
5314   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5315       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5316       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5317     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5318     if (CV.getNode())
5319       return CV;
5320   }
5321
5322   return SDValue();
5323 }
5324
5325 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5326   SDValue N0 = N->getOperand(0);
5327   SDValue N1 = N->getOperand(1);
5328   SDValue N2 = N->getOperand(2);
5329   SDValue N3 = N->getOperand(3);
5330   SDValue N4 = N->getOperand(4);
5331   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5332
5333   // fold select_cc lhs, rhs, x, x, cc -> x
5334   if (N2 == N3)
5335     return N2;
5336
5337   // Determine if the condition we're dealing with is constant
5338   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5339                               N0, N1, CC, SDLoc(N), false);
5340   if (SCC.getNode()) {
5341     AddToWorklist(SCC.getNode());
5342
5343     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5344       if (!SCCC->isNullValue())
5345         return N2;    // cond always true -> true val
5346       else
5347         return N3;    // cond always false -> false val
5348     } else if (SCC->getOpcode() == ISD::UNDEF) {
5349       // When the condition is UNDEF, just return the first operand. This is
5350       // coherent the DAG creation, no setcc node is created in this case
5351       return N2;
5352     } else if (SCC.getOpcode() == ISD::SETCC) {
5353       // Fold to a simpler select_cc
5354       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5355                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5356                          SCC.getOperand(2));
5357     }
5358   }
5359
5360   // If we can fold this based on the true/false value, do so.
5361   if (SimplifySelectOps(N, N2, N3))
5362     return SDValue(N, 0);  // Don't revisit N.
5363
5364   // fold select_cc into other things, such as min/max/abs
5365   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5366 }
5367
5368 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5369   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5370                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5371                        SDLoc(N));
5372 }
5373
5374 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5375 // dag node into a ConstantSDNode or a build_vector of constants.
5376 // This function is called by the DAGCombiner when visiting sext/zext/aext
5377 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5378 // Vector extends are not folded if operations are legal; this is to
5379 // avoid introducing illegal build_vector dag nodes.
5380 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5381                                          SelectionDAG &DAG, bool LegalTypes,
5382                                          bool LegalOperations) {
5383   unsigned Opcode = N->getOpcode();
5384   SDValue N0 = N->getOperand(0);
5385   EVT VT = N->getValueType(0);
5386
5387   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5388          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5389
5390   // fold (sext c1) -> c1
5391   // fold (zext c1) -> c1
5392   // fold (aext c1) -> c1
5393   if (isa<ConstantSDNode>(N0))
5394     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5395
5396   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5397   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5398   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5399   EVT SVT = VT.getScalarType();
5400   if (!(VT.isVector() &&
5401       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5402       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5403     return nullptr;
5404
5405   // We can fold this node into a build_vector.
5406   unsigned VTBits = SVT.getSizeInBits();
5407   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5408   unsigned ShAmt = VTBits - EVTBits;
5409   SmallVector<SDValue, 8> Elts;
5410   unsigned NumElts = N0->getNumOperands();
5411   SDLoc DL(N);
5412
5413   for (unsigned i=0; i != NumElts; ++i) {
5414     SDValue Op = N0->getOperand(i);
5415     if (Op->getOpcode() == ISD::UNDEF) {
5416       Elts.push_back(DAG.getUNDEF(SVT));
5417       continue;
5418     }
5419
5420     SDLoc DL(Op);
5421     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5422     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5423     if (Opcode == ISD::SIGN_EXTEND)
5424       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5425                                      DL, SVT));
5426     else
5427       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5428                                      DL, SVT));
5429   }
5430
5431   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5432 }
5433
5434 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5435 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5436 // transformation. Returns true if extension are possible and the above
5437 // mentioned transformation is profitable.
5438 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5439                                     unsigned ExtOpc,
5440                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5441                                     const TargetLowering &TLI) {
5442   bool HasCopyToRegUses = false;
5443   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5444   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5445                             UE = N0.getNode()->use_end();
5446        UI != UE; ++UI) {
5447     SDNode *User = *UI;
5448     if (User == N)
5449       continue;
5450     if (UI.getUse().getResNo() != N0.getResNo())
5451       continue;
5452     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5453     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5454       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5455       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5456         // Sign bits will be lost after a zext.
5457         return false;
5458       bool Add = false;
5459       for (unsigned i = 0; i != 2; ++i) {
5460         SDValue UseOp = User->getOperand(i);
5461         if (UseOp == N0)
5462           continue;
5463         if (!isa<ConstantSDNode>(UseOp))
5464           return false;
5465         Add = true;
5466       }
5467       if (Add)
5468         ExtendNodes.push_back(User);
5469       continue;
5470     }
5471     // If truncates aren't free and there are users we can't
5472     // extend, it isn't worthwhile.
5473     if (!isTruncFree)
5474       return false;
5475     // Remember if this value is live-out.
5476     if (User->getOpcode() == ISD::CopyToReg)
5477       HasCopyToRegUses = true;
5478   }
5479
5480   if (HasCopyToRegUses) {
5481     bool BothLiveOut = false;
5482     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5483          UI != UE; ++UI) {
5484       SDUse &Use = UI.getUse();
5485       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5486         BothLiveOut = true;
5487         break;
5488       }
5489     }
5490     if (BothLiveOut)
5491       // Both unextended and extended values are live out. There had better be
5492       // a good reason for the transformation.
5493       return ExtendNodes.size();
5494   }
5495   return true;
5496 }
5497
5498 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5499                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5500                                   ISD::NodeType ExtType) {
5501   // Extend SetCC uses if necessary.
5502   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5503     SDNode *SetCC = SetCCs[i];
5504     SmallVector<SDValue, 4> Ops;
5505
5506     for (unsigned j = 0; j != 2; ++j) {
5507       SDValue SOp = SetCC->getOperand(j);
5508       if (SOp == Trunc)
5509         Ops.push_back(ExtLoad);
5510       else
5511         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5512     }
5513
5514     Ops.push_back(SetCC->getOperand(2));
5515     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5516   }
5517 }
5518
5519 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5520 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5521   SDValue N0 = N->getOperand(0);
5522   EVT DstVT = N->getValueType(0);
5523   EVT SrcVT = N0.getValueType();
5524
5525   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5526           N->getOpcode() == ISD::ZERO_EXTEND) &&
5527          "Unexpected node type (not an extend)!");
5528
5529   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5530   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5531   //   (v8i32 (sext (v8i16 (load x))))
5532   // into:
5533   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5534   //                          (v4i32 (sextload (x + 16)))))
5535   // Where uses of the original load, i.e.:
5536   //   (v8i16 (load x))
5537   // are replaced with:
5538   //   (v8i16 (truncate
5539   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5540   //                            (v4i32 (sextload (x + 16)))))))
5541   //
5542   // This combine is only applicable to illegal, but splittable, vectors.
5543   // All legal types, and illegal non-vector types, are handled elsewhere.
5544   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5545   //
5546   if (N0->getOpcode() != ISD::LOAD)
5547     return SDValue();
5548
5549   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5550
5551   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5552       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5553       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5554     return SDValue();
5555
5556   SmallVector<SDNode *, 4> SetCCs;
5557   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5558     return SDValue();
5559
5560   ISD::LoadExtType ExtType =
5561       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5562
5563   // Try to split the vector types to get down to legal types.
5564   EVT SplitSrcVT = SrcVT;
5565   EVT SplitDstVT = DstVT;
5566   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5567          SplitSrcVT.getVectorNumElements() > 1) {
5568     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5569     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5570   }
5571
5572   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5573     return SDValue();
5574
5575   SDLoc DL(N);
5576   const unsigned NumSplits =
5577       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5578   const unsigned Stride = SplitSrcVT.getStoreSize();
5579   SmallVector<SDValue, 4> Loads;
5580   SmallVector<SDValue, 4> Chains;
5581
5582   SDValue BasePtr = LN0->getBasePtr();
5583   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5584     const unsigned Offset = Idx * Stride;
5585     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5586
5587     SDValue SplitLoad = DAG.getExtLoad(
5588         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5589         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5590         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5591         Align, LN0->getAAInfo());
5592
5593     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5594                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5595
5596     Loads.push_back(SplitLoad.getValue(0));
5597     Chains.push_back(SplitLoad.getValue(1));
5598   }
5599
5600   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5601   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5602
5603   CombineTo(N, NewValue);
5604
5605   // Replace uses of the original load (before extension)
5606   // with a truncate of the concatenated sextloaded vectors.
5607   SDValue Trunc =
5608       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5609   CombineTo(N0.getNode(), Trunc, NewChain);
5610   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5611                   (ISD::NodeType)N->getOpcode());
5612   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5613 }
5614
5615 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5616   SDValue N0 = N->getOperand(0);
5617   EVT VT = N->getValueType(0);
5618
5619   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5620                                               LegalOperations))
5621     return SDValue(Res, 0);
5622
5623   // fold (sext (sext x)) -> (sext x)
5624   // fold (sext (aext x)) -> (sext x)
5625   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5626     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5627                        N0.getOperand(0));
5628
5629   if (N0.getOpcode() == ISD::TRUNCATE) {
5630     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5631     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5632     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5633     if (NarrowLoad.getNode()) {
5634       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5635       if (NarrowLoad.getNode() != N0.getNode()) {
5636         CombineTo(N0.getNode(), NarrowLoad);
5637         // CombineTo deleted the truncate, if needed, but not what's under it.
5638         AddToWorklist(oye);
5639       }
5640       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5641     }
5642
5643     // See if the value being truncated is already sign extended.  If so, just
5644     // eliminate the trunc/sext pair.
5645     SDValue Op = N0.getOperand(0);
5646     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5647     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5648     unsigned DestBits = VT.getScalarType().getSizeInBits();
5649     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5650
5651     if (OpBits == DestBits) {
5652       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5653       // bits, it is already ready.
5654       if (NumSignBits > DestBits-MidBits)
5655         return Op;
5656     } else if (OpBits < DestBits) {
5657       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5658       // bits, just sext from i32.
5659       if (NumSignBits > OpBits-MidBits)
5660         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5661     } else {
5662       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5663       // bits, just truncate to i32.
5664       if (NumSignBits > OpBits-MidBits)
5665         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5666     }
5667
5668     // fold (sext (truncate x)) -> (sextinreg x).
5669     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5670                                                  N0.getValueType())) {
5671       if (OpBits < DestBits)
5672         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5673       else if (OpBits > DestBits)
5674         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5675       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5676                          DAG.getValueType(N0.getValueType()));
5677     }
5678   }
5679
5680   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5681   // Only generate vector extloads when 1) they're legal, and 2) they are
5682   // deemed desirable by the target.
5683   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5684       ((!LegalOperations && !VT.isVector() &&
5685         !cast<LoadSDNode>(N0)->isVolatile()) ||
5686        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5687     bool DoXform = true;
5688     SmallVector<SDNode*, 4> SetCCs;
5689     if (!N0.hasOneUse())
5690       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5691     if (VT.isVector())
5692       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5693     if (DoXform) {
5694       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5695       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5696                                        LN0->getChain(),
5697                                        LN0->getBasePtr(), N0.getValueType(),
5698                                        LN0->getMemOperand());
5699       CombineTo(N, ExtLoad);
5700       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5701                                   N0.getValueType(), ExtLoad);
5702       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5703       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5704                       ISD::SIGN_EXTEND);
5705       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5706     }
5707   }
5708
5709   // fold (sext (load x)) to multiple smaller sextloads.
5710   // Only on illegal but splittable vectors.
5711   if (SDValue ExtLoad = CombineExtLoad(N))
5712     return ExtLoad;
5713
5714   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5715   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5716   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5717       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5718     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5719     EVT MemVT = LN0->getMemoryVT();
5720     if ((!LegalOperations && !LN0->isVolatile()) ||
5721         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5722       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5723                                        LN0->getChain(),
5724                                        LN0->getBasePtr(), MemVT,
5725                                        LN0->getMemOperand());
5726       CombineTo(N, ExtLoad);
5727       CombineTo(N0.getNode(),
5728                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5729                             N0.getValueType(), ExtLoad),
5730                 ExtLoad.getValue(1));
5731       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5732     }
5733   }
5734
5735   // fold (sext (and/or/xor (load x), cst)) ->
5736   //      (and/or/xor (sextload x), (sext cst))
5737   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5738        N0.getOpcode() == ISD::XOR) &&
5739       isa<LoadSDNode>(N0.getOperand(0)) &&
5740       N0.getOperand(1).getOpcode() == ISD::Constant &&
5741       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5742       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5743     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5744     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5745       bool DoXform = true;
5746       SmallVector<SDNode*, 4> SetCCs;
5747       if (!N0.hasOneUse())
5748         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5749                                           SetCCs, TLI);
5750       if (DoXform) {
5751         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5752                                          LN0->getChain(), LN0->getBasePtr(),
5753                                          LN0->getMemoryVT(),
5754                                          LN0->getMemOperand());
5755         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5756         Mask = Mask.sext(VT.getSizeInBits());
5757         SDLoc DL(N);
5758         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5759                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5760         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5761                                     SDLoc(N0.getOperand(0)),
5762                                     N0.getOperand(0).getValueType(), ExtLoad);
5763         CombineTo(N, And);
5764         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5765         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5766                         ISD::SIGN_EXTEND);
5767         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5768       }
5769     }
5770   }
5771
5772   if (N0.getOpcode() == ISD::SETCC) {
5773     EVT N0VT = N0.getOperand(0).getValueType();
5774     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5775     // Only do this before legalize for now.
5776     if (VT.isVector() && !LegalOperations &&
5777         TLI.getBooleanContents(N0VT) ==
5778             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5779       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5780       // of the same size as the compared operands. Only optimize sext(setcc())
5781       // if this is the case.
5782       EVT SVT = getSetCCResultType(N0VT);
5783
5784       // We know that the # elements of the results is the same as the
5785       // # elements of the compare (and the # elements of the compare result
5786       // for that matter).  Check to see that they are the same size.  If so,
5787       // we know that the element size of the sext'd result matches the
5788       // element size of the compare operands.
5789       if (VT.getSizeInBits() == SVT.getSizeInBits())
5790         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5791                              N0.getOperand(1),
5792                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5793
5794       // If the desired elements are smaller or larger than the source
5795       // elements we can use a matching integer vector type and then
5796       // truncate/sign extend
5797       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5798       if (SVT == MatchingVectorType) {
5799         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5800                                N0.getOperand(0), N0.getOperand(1),
5801                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5802         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5803       }
5804     }
5805
5806     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5807     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5808     SDLoc DL(N);
5809     SDValue NegOne =
5810       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5811     SDValue SCC =
5812       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5813                        NegOne, DAG.getConstant(0, DL, VT),
5814                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5815     if (SCC.getNode()) return SCC;
5816
5817     if (!VT.isVector()) {
5818       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5819       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5820         SDLoc DL(N);
5821         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5822         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5823                                      N0.getOperand(0), N0.getOperand(1), CC);
5824         return DAG.getSelect(DL, VT, SetCC,
5825                              NegOne, DAG.getConstant(0, DL, VT));
5826       }
5827     }
5828   }
5829
5830   // fold (sext x) -> (zext x) if the sign bit is known zero.
5831   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5832       DAG.SignBitIsZero(N0))
5833     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5834
5835   return SDValue();
5836 }
5837
5838 // isTruncateOf - If N is a truncate of some other value, return true, record
5839 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5840 // This function computes KnownZero to avoid a duplicated call to
5841 // computeKnownBits in the caller.
5842 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5843                          APInt &KnownZero) {
5844   APInt KnownOne;
5845   if (N->getOpcode() == ISD::TRUNCATE) {
5846     Op = N->getOperand(0);
5847     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5848     return true;
5849   }
5850
5851   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5852       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5853     return false;
5854
5855   SDValue Op0 = N->getOperand(0);
5856   SDValue Op1 = N->getOperand(1);
5857   assert(Op0.getValueType() == Op1.getValueType());
5858
5859   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5860   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5861   if (COp0 && COp0->isNullValue())
5862     Op = Op1;
5863   else if (COp1 && COp1->isNullValue())
5864     Op = Op0;
5865   else
5866     return false;
5867
5868   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5869
5870   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5871     return false;
5872
5873   return true;
5874 }
5875
5876 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5877   SDValue N0 = N->getOperand(0);
5878   EVT VT = N->getValueType(0);
5879
5880   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5881                                               LegalOperations))
5882     return SDValue(Res, 0);
5883
5884   // fold (zext (zext x)) -> (zext x)
5885   // fold (zext (aext x)) -> (zext x)
5886   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5887     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5888                        N0.getOperand(0));
5889
5890   // fold (zext (truncate x)) -> (zext x) or
5891   //      (zext (truncate x)) -> (truncate x)
5892   // This is valid when the truncated bits of x are already zero.
5893   // FIXME: We should extend this to work for vectors too.
5894   SDValue Op;
5895   APInt KnownZero;
5896   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5897     APInt TruncatedBits =
5898       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5899       APInt(Op.getValueSizeInBits(), 0) :
5900       APInt::getBitsSet(Op.getValueSizeInBits(),
5901                         N0.getValueSizeInBits(),
5902                         std::min(Op.getValueSizeInBits(),
5903                                  VT.getSizeInBits()));
5904     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5905       if (VT.bitsGT(Op.getValueType()))
5906         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5907       if (VT.bitsLT(Op.getValueType()))
5908         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5909
5910       return Op;
5911     }
5912   }
5913
5914   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5915   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5916   if (N0.getOpcode() == ISD::TRUNCATE) {
5917     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5918     if (NarrowLoad.getNode()) {
5919       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5920       if (NarrowLoad.getNode() != N0.getNode()) {
5921         CombineTo(N0.getNode(), NarrowLoad);
5922         // CombineTo deleted the truncate, if needed, but not what's under it.
5923         AddToWorklist(oye);
5924       }
5925       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5926     }
5927   }
5928
5929   // fold (zext (truncate x)) -> (and x, mask)
5930   if (N0.getOpcode() == ISD::TRUNCATE &&
5931       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5932
5933     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5934     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5935     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5936     if (NarrowLoad.getNode()) {
5937       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5938       if (NarrowLoad.getNode() != N0.getNode()) {
5939         CombineTo(N0.getNode(), NarrowLoad);
5940         // CombineTo deleted the truncate, if needed, but not what's under it.
5941         AddToWorklist(oye);
5942       }
5943       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5944     }
5945
5946     SDValue Op = N0.getOperand(0);
5947     if (Op.getValueType().bitsLT(VT)) {
5948       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5949       AddToWorklist(Op.getNode());
5950     } else if (Op.getValueType().bitsGT(VT)) {
5951       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5952       AddToWorklist(Op.getNode());
5953     }
5954     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5955                                   N0.getValueType().getScalarType());
5956   }
5957
5958   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5959   // if either of the casts is not free.
5960   if (N0.getOpcode() == ISD::AND &&
5961       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5962       N0.getOperand(1).getOpcode() == ISD::Constant &&
5963       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5964                            N0.getValueType()) ||
5965        !TLI.isZExtFree(N0.getValueType(), VT))) {
5966     SDValue X = N0.getOperand(0).getOperand(0);
5967     if (X.getValueType().bitsLT(VT)) {
5968       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5969     } else if (X.getValueType().bitsGT(VT)) {
5970       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5971     }
5972     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5973     Mask = Mask.zext(VT.getSizeInBits());
5974     SDLoc DL(N);
5975     return DAG.getNode(ISD::AND, DL, VT,
5976                        X, DAG.getConstant(Mask, DL, VT));
5977   }
5978
5979   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5980   // Only generate vector extloads when 1) they're legal, and 2) they are
5981   // deemed desirable by the target.
5982   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5983       ((!LegalOperations && !VT.isVector() &&
5984         !cast<LoadSDNode>(N0)->isVolatile()) ||
5985        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5986     bool DoXform = true;
5987     SmallVector<SDNode*, 4> SetCCs;
5988     if (!N0.hasOneUse())
5989       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5990     if (VT.isVector())
5991       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5992     if (DoXform) {
5993       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5994       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5995                                        LN0->getChain(),
5996                                        LN0->getBasePtr(), N0.getValueType(),
5997                                        LN0->getMemOperand());
5998       CombineTo(N, ExtLoad);
5999       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6000                                   N0.getValueType(), ExtLoad);
6001       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6002
6003       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6004                       ISD::ZERO_EXTEND);
6005       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6006     }
6007   }
6008
6009   // fold (zext (load x)) to multiple smaller zextloads.
6010   // Only on illegal but splittable vectors.
6011   if (SDValue ExtLoad = CombineExtLoad(N))
6012     return ExtLoad;
6013
6014   // fold (zext (and/or/xor (load x), cst)) ->
6015   //      (and/or/xor (zextload x), (zext cst))
6016   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6017        N0.getOpcode() == ISD::XOR) &&
6018       isa<LoadSDNode>(N0.getOperand(0)) &&
6019       N0.getOperand(1).getOpcode() == ISD::Constant &&
6020       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6021       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6022     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6023     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6024       bool DoXform = true;
6025       SmallVector<SDNode*, 4> SetCCs;
6026       if (!N0.hasOneUse())
6027         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6028                                           SetCCs, TLI);
6029       if (DoXform) {
6030         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6031                                          LN0->getChain(), LN0->getBasePtr(),
6032                                          LN0->getMemoryVT(),
6033                                          LN0->getMemOperand());
6034         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6035         Mask = Mask.zext(VT.getSizeInBits());
6036         SDLoc DL(N);
6037         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6038                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6039         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6040                                     SDLoc(N0.getOperand(0)),
6041                                     N0.getOperand(0).getValueType(), ExtLoad);
6042         CombineTo(N, And);
6043         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6044         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6045                         ISD::ZERO_EXTEND);
6046         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6047       }
6048     }
6049   }
6050
6051   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6052   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6053   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6054       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6055     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6056     EVT MemVT = LN0->getMemoryVT();
6057     if ((!LegalOperations && !LN0->isVolatile()) ||
6058         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6059       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6060                                        LN0->getChain(),
6061                                        LN0->getBasePtr(), MemVT,
6062                                        LN0->getMemOperand());
6063       CombineTo(N, ExtLoad);
6064       CombineTo(N0.getNode(),
6065                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6066                             ExtLoad),
6067                 ExtLoad.getValue(1));
6068       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6069     }
6070   }
6071
6072   if (N0.getOpcode() == ISD::SETCC) {
6073     if (!LegalOperations && VT.isVector() &&
6074         N0.getValueType().getVectorElementType() == MVT::i1) {
6075       EVT N0VT = N0.getOperand(0).getValueType();
6076       if (getSetCCResultType(N0VT) == N0.getValueType())
6077         return SDValue();
6078
6079       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6080       // Only do this before legalize for now.
6081       EVT EltVT = VT.getVectorElementType();
6082       SDLoc DL(N);
6083       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6084                                     DAG.getConstant(1, DL, EltVT));
6085       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6086         // We know that the # elements of the results is the same as the
6087         // # elements of the compare (and the # elements of the compare result
6088         // for that matter).  Check to see that they are the same size.  If so,
6089         // we know that the element size of the sext'd result matches the
6090         // element size of the compare operands.
6091         return DAG.getNode(ISD::AND, DL, VT,
6092                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6093                                          N0.getOperand(1),
6094                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6095                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6096                                        OneOps));
6097
6098       // If the desired elements are smaller or larger than the source
6099       // elements we can use a matching integer vector type and then
6100       // truncate/sign extend
6101       EVT MatchingElementType =
6102         EVT::getIntegerVT(*DAG.getContext(),
6103                           N0VT.getScalarType().getSizeInBits());
6104       EVT MatchingVectorType =
6105         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6106                          N0VT.getVectorNumElements());
6107       SDValue VsetCC =
6108         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6109                       N0.getOperand(1),
6110                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6111       return DAG.getNode(ISD::AND, DL, VT,
6112                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6113                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6114     }
6115
6116     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6117     SDLoc DL(N);
6118     SDValue SCC =
6119       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6120                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6121                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6122     if (SCC.getNode()) return SCC;
6123   }
6124
6125   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6126   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6127       isa<ConstantSDNode>(N0.getOperand(1)) &&
6128       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6129       N0.hasOneUse()) {
6130     SDValue ShAmt = N0.getOperand(1);
6131     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6132     if (N0.getOpcode() == ISD::SHL) {
6133       SDValue InnerZExt = N0.getOperand(0);
6134       // If the original shl may be shifting out bits, do not perform this
6135       // transformation.
6136       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6137         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6138       if (ShAmtVal > KnownZeroBits)
6139         return SDValue();
6140     }
6141
6142     SDLoc DL(N);
6143
6144     // Ensure that the shift amount is wide enough for the shifted value.
6145     if (VT.getSizeInBits() >= 256)
6146       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6147
6148     return DAG.getNode(N0.getOpcode(), DL, VT,
6149                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6150                        ShAmt);
6151   }
6152
6153   return SDValue();
6154 }
6155
6156 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6157   SDValue N0 = N->getOperand(0);
6158   EVT VT = N->getValueType(0);
6159
6160   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6161                                               LegalOperations))
6162     return SDValue(Res, 0);
6163
6164   // fold (aext (aext x)) -> (aext x)
6165   // fold (aext (zext x)) -> (zext x)
6166   // fold (aext (sext x)) -> (sext x)
6167   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6168       N0.getOpcode() == ISD::ZERO_EXTEND ||
6169       N0.getOpcode() == ISD::SIGN_EXTEND)
6170     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6171
6172   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6173   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6174   if (N0.getOpcode() == ISD::TRUNCATE) {
6175     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6176     if (NarrowLoad.getNode()) {
6177       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6178       if (NarrowLoad.getNode() != N0.getNode()) {
6179         CombineTo(N0.getNode(), NarrowLoad);
6180         // CombineTo deleted the truncate, if needed, but not what's under it.
6181         AddToWorklist(oye);
6182       }
6183       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6184     }
6185   }
6186
6187   // fold (aext (truncate x))
6188   if (N0.getOpcode() == ISD::TRUNCATE) {
6189     SDValue TruncOp = N0.getOperand(0);
6190     if (TruncOp.getValueType() == VT)
6191       return TruncOp; // x iff x size == zext size.
6192     if (TruncOp.getValueType().bitsGT(VT))
6193       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6194     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6195   }
6196
6197   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6198   // if the trunc is not free.
6199   if (N0.getOpcode() == ISD::AND &&
6200       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6201       N0.getOperand(1).getOpcode() == ISD::Constant &&
6202       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6203                           N0.getValueType())) {
6204     SDValue X = N0.getOperand(0).getOperand(0);
6205     if (X.getValueType().bitsLT(VT)) {
6206       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6207     } else if (X.getValueType().bitsGT(VT)) {
6208       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6209     }
6210     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6211     Mask = Mask.zext(VT.getSizeInBits());
6212     SDLoc DL(N);
6213     return DAG.getNode(ISD::AND, DL, VT,
6214                        X, DAG.getConstant(Mask, DL, VT));
6215   }
6216
6217   // fold (aext (load x)) -> (aext (truncate (extload x)))
6218   // None of the supported targets knows how to perform load and any_ext
6219   // on vectors in one instruction.  We only perform this transformation on
6220   // scalars.
6221   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6222       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6223       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6224     bool DoXform = true;
6225     SmallVector<SDNode*, 4> SetCCs;
6226     if (!N0.hasOneUse())
6227       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6228     if (DoXform) {
6229       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6230       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6231                                        LN0->getChain(),
6232                                        LN0->getBasePtr(), N0.getValueType(),
6233                                        LN0->getMemOperand());
6234       CombineTo(N, ExtLoad);
6235       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6236                                   N0.getValueType(), ExtLoad);
6237       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6238       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6239                       ISD::ANY_EXTEND);
6240       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6241     }
6242   }
6243
6244   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6245   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6246   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6247   if (N0.getOpcode() == ISD::LOAD &&
6248       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6249       N0.hasOneUse()) {
6250     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6251     ISD::LoadExtType ExtType = LN0->getExtensionType();
6252     EVT MemVT = LN0->getMemoryVT();
6253     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6254       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6255                                        VT, LN0->getChain(), LN0->getBasePtr(),
6256                                        MemVT, LN0->getMemOperand());
6257       CombineTo(N, ExtLoad);
6258       CombineTo(N0.getNode(),
6259                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6260                             N0.getValueType(), ExtLoad),
6261                 ExtLoad.getValue(1));
6262       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6263     }
6264   }
6265
6266   if (N0.getOpcode() == ISD::SETCC) {
6267     // For vectors:
6268     // aext(setcc) -> vsetcc
6269     // aext(setcc) -> truncate(vsetcc)
6270     // aext(setcc) -> aext(vsetcc)
6271     // Only do this before legalize for now.
6272     if (VT.isVector() && !LegalOperations) {
6273       EVT N0VT = N0.getOperand(0).getValueType();
6274         // We know that the # elements of the results is the same as the
6275         // # elements of the compare (and the # elements of the compare result
6276         // for that matter).  Check to see that they are the same size.  If so,
6277         // we know that the element size of the sext'd result matches the
6278         // element size of the compare operands.
6279       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6280         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6281                              N0.getOperand(1),
6282                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6283       // If the desired elements are smaller or larger than the source
6284       // elements we can use a matching integer vector type and then
6285       // truncate/any extend
6286       else {
6287         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6288         SDValue VsetCC =
6289           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6290                         N0.getOperand(1),
6291                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6292         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6293       }
6294     }
6295
6296     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6297     SDLoc DL(N);
6298     SDValue SCC =
6299       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6300                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6301                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6302     if (SCC.getNode())
6303       return SCC;
6304   }
6305
6306   return SDValue();
6307 }
6308
6309 /// See if the specified operand can be simplified with the knowledge that only
6310 /// the bits specified by Mask are used.  If so, return the simpler operand,
6311 /// otherwise return a null SDValue.
6312 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6313   switch (V.getOpcode()) {
6314   default: break;
6315   case ISD::Constant: {
6316     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6317     assert(CV && "Const value should be ConstSDNode.");
6318     const APInt &CVal = CV->getAPIntValue();
6319     APInt NewVal = CVal & Mask;
6320     if (NewVal != CVal)
6321       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6322     break;
6323   }
6324   case ISD::OR:
6325   case ISD::XOR:
6326     // If the LHS or RHS don't contribute bits to the or, drop them.
6327     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6328       return V.getOperand(1);
6329     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6330       return V.getOperand(0);
6331     break;
6332   case ISD::SRL:
6333     // Only look at single-use SRLs.
6334     if (!V.getNode()->hasOneUse())
6335       break;
6336     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6337       // See if we can recursively simplify the LHS.
6338       unsigned Amt = RHSC->getZExtValue();
6339
6340       // Watch out for shift count overflow though.
6341       if (Amt >= Mask.getBitWidth()) break;
6342       APInt NewMask = Mask << Amt;
6343       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6344       if (SimplifyLHS.getNode())
6345         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6346                            SimplifyLHS, V.getOperand(1));
6347     }
6348   }
6349   return SDValue();
6350 }
6351
6352 /// If the result of a wider load is shifted to right of N  bits and then
6353 /// truncated to a narrower type and where N is a multiple of number of bits of
6354 /// the narrower type, transform it to a narrower load from address + N / num of
6355 /// bits of new type. If the result is to be extended, also fold the extension
6356 /// to form a extending load.
6357 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6358   unsigned Opc = N->getOpcode();
6359
6360   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6361   SDValue N0 = N->getOperand(0);
6362   EVT VT = N->getValueType(0);
6363   EVT ExtVT = VT;
6364
6365   // This transformation isn't valid for vector loads.
6366   if (VT.isVector())
6367     return SDValue();
6368
6369   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6370   // extended to VT.
6371   if (Opc == ISD::SIGN_EXTEND_INREG) {
6372     ExtType = ISD::SEXTLOAD;
6373     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6374   } else if (Opc == ISD::SRL) {
6375     // Another special-case: SRL is basically zero-extending a narrower value.
6376     ExtType = ISD::ZEXTLOAD;
6377     N0 = SDValue(N, 0);
6378     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6379     if (!N01) return SDValue();
6380     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6381                               VT.getSizeInBits() - N01->getZExtValue());
6382   }
6383   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6384     return SDValue();
6385
6386   unsigned EVTBits = ExtVT.getSizeInBits();
6387
6388   // Do not generate loads of non-round integer types since these can
6389   // be expensive (and would be wrong if the type is not byte sized).
6390   if (!ExtVT.isRound())
6391     return SDValue();
6392
6393   unsigned ShAmt = 0;
6394   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6395     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6396       ShAmt = N01->getZExtValue();
6397       // Is the shift amount a multiple of size of VT?
6398       if ((ShAmt & (EVTBits-1)) == 0) {
6399         N0 = N0.getOperand(0);
6400         // Is the load width a multiple of size of VT?
6401         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6402           return SDValue();
6403       }
6404
6405       // At this point, we must have a load or else we can't do the transform.
6406       if (!isa<LoadSDNode>(N0)) return SDValue();
6407
6408       // Because a SRL must be assumed to *need* to zero-extend the high bits
6409       // (as opposed to anyext the high bits), we can't combine the zextload
6410       // lowering of SRL and an sextload.
6411       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6412         return SDValue();
6413
6414       // If the shift amount is larger than the input type then we're not
6415       // accessing any of the loaded bytes.  If the load was a zextload/extload
6416       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6417       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6418         return SDValue();
6419     }
6420   }
6421
6422   // If the load is shifted left (and the result isn't shifted back right),
6423   // we can fold the truncate through the shift.
6424   unsigned ShLeftAmt = 0;
6425   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6426       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6427     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6428       ShLeftAmt = N01->getZExtValue();
6429       N0 = N0.getOperand(0);
6430     }
6431   }
6432
6433   // If we haven't found a load, we can't narrow it.  Don't transform one with
6434   // multiple uses, this would require adding a new load.
6435   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6436     return SDValue();
6437
6438   // Don't change the width of a volatile load.
6439   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6440   if (LN0->isVolatile())
6441     return SDValue();
6442
6443   // Verify that we are actually reducing a load width here.
6444   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6445     return SDValue();
6446
6447   // For the transform to be legal, the load must produce only two values
6448   // (the value loaded and the chain).  Don't transform a pre-increment
6449   // load, for example, which produces an extra value.  Otherwise the
6450   // transformation is not equivalent, and the downstream logic to replace
6451   // uses gets things wrong.
6452   if (LN0->getNumValues() > 2)
6453     return SDValue();
6454
6455   // If the load that we're shrinking is an extload and we're not just
6456   // discarding the extension we can't simply shrink the load. Bail.
6457   // TODO: It would be possible to merge the extensions in some cases.
6458   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6459       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6460     return SDValue();
6461
6462   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6463     return SDValue();
6464
6465   EVT PtrType = N0.getOperand(1).getValueType();
6466
6467   if (PtrType == MVT::Untyped || PtrType.isExtended())
6468     // It's not possible to generate a constant of extended or untyped type.
6469     return SDValue();
6470
6471   // For big endian targets, we need to adjust the offset to the pointer to
6472   // load the correct bytes.
6473   if (TLI.isBigEndian()) {
6474     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6475     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6476     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6477   }
6478
6479   uint64_t PtrOff = ShAmt / 8;
6480   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6481   SDLoc DL(LN0);
6482   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6483                                PtrType, LN0->getBasePtr(),
6484                                DAG.getConstant(PtrOff, DL, PtrType));
6485   AddToWorklist(NewPtr.getNode());
6486
6487   SDValue Load;
6488   if (ExtType == ISD::NON_EXTLOAD)
6489     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6490                         LN0->getPointerInfo().getWithOffset(PtrOff),
6491                         LN0->isVolatile(), LN0->isNonTemporal(),
6492                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6493   else
6494     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6495                           LN0->getPointerInfo().getWithOffset(PtrOff),
6496                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6497                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6498
6499   // Replace the old load's chain with the new load's chain.
6500   WorklistRemover DeadNodes(*this);
6501   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6502
6503   // Shift the result left, if we've swallowed a left shift.
6504   SDValue Result = Load;
6505   if (ShLeftAmt != 0) {
6506     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6507     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6508       ShImmTy = VT;
6509     // If the shift amount is as large as the result size (but, presumably,
6510     // no larger than the source) then the useful bits of the result are
6511     // zero; we can't simply return the shortened shift, because the result
6512     // of that operation is undefined.
6513     SDLoc DL(N0);
6514     if (ShLeftAmt >= VT.getSizeInBits())
6515       Result = DAG.getConstant(0, DL, VT);
6516     else
6517       Result = DAG.getNode(ISD::SHL, DL, VT,
6518                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6519   }
6520
6521   // Return the new loaded value.
6522   return Result;
6523 }
6524
6525 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6526   SDValue N0 = N->getOperand(0);
6527   SDValue N1 = N->getOperand(1);
6528   EVT VT = N->getValueType(0);
6529   EVT EVT = cast<VTSDNode>(N1)->getVT();
6530   unsigned VTBits = VT.getScalarType().getSizeInBits();
6531   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6532
6533   // fold (sext_in_reg c1) -> c1
6534   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6535     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6536
6537   // If the input is already sign extended, just drop the extension.
6538   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6539     return N0;
6540
6541   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6542   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6543       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6544     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6545                        N0.getOperand(0), N1);
6546
6547   // fold (sext_in_reg (sext x)) -> (sext x)
6548   // fold (sext_in_reg (aext x)) -> (sext x)
6549   // if x is small enough.
6550   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6551     SDValue N00 = N0.getOperand(0);
6552     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6553         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6554       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6555   }
6556
6557   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6558   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6559     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6560
6561   // fold operands of sext_in_reg based on knowledge that the top bits are not
6562   // demanded.
6563   if (SimplifyDemandedBits(SDValue(N, 0)))
6564     return SDValue(N, 0);
6565
6566   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6567   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6568   SDValue NarrowLoad = ReduceLoadWidth(N);
6569   if (NarrowLoad.getNode())
6570     return NarrowLoad;
6571
6572   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6573   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6574   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6575   if (N0.getOpcode() == ISD::SRL) {
6576     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6577       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6578         // We can turn this into an SRA iff the input to the SRL is already sign
6579         // extended enough.
6580         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6581         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6582           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6583                              N0.getOperand(0), N0.getOperand(1));
6584       }
6585   }
6586
6587   // fold (sext_inreg (extload x)) -> (sextload x)
6588   if (ISD::isEXTLoad(N0.getNode()) &&
6589       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6590       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6591       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6592        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6593     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6594     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6595                                      LN0->getChain(),
6596                                      LN0->getBasePtr(), EVT,
6597                                      LN0->getMemOperand());
6598     CombineTo(N, ExtLoad);
6599     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6600     AddToWorklist(ExtLoad.getNode());
6601     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6602   }
6603   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6604   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6605       N0.hasOneUse() &&
6606       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6607       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6608        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6609     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6610     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6611                                      LN0->getChain(),
6612                                      LN0->getBasePtr(), EVT,
6613                                      LN0->getMemOperand());
6614     CombineTo(N, ExtLoad);
6615     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6616     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6617   }
6618
6619   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6620   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6621     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6622                                        N0.getOperand(1), false);
6623     if (BSwap.getNode())
6624       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6625                          BSwap, N1);
6626   }
6627
6628   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6629   // into a build_vector.
6630   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6631     SmallVector<SDValue, 8> Elts;
6632     unsigned NumElts = N0->getNumOperands();
6633     unsigned ShAmt = VTBits - EVTBits;
6634
6635     for (unsigned i = 0; i != NumElts; ++i) {
6636       SDValue Op = N0->getOperand(i);
6637       if (Op->getOpcode() == ISD::UNDEF) {
6638         Elts.push_back(Op);
6639         continue;
6640       }
6641
6642       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6643       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6644       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6645                                      SDLoc(Op), Op.getValueType()));
6646     }
6647
6648     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6649   }
6650
6651   return SDValue();
6652 }
6653
6654 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6655   SDValue N0 = N->getOperand(0);
6656   EVT VT = N->getValueType(0);
6657   bool isLE = TLI.isLittleEndian();
6658
6659   // noop truncate
6660   if (N0.getValueType() == N->getValueType(0))
6661     return N0;
6662   // fold (truncate c1) -> c1
6663   if (isConstantIntBuildVectorOrConstantInt(N0))
6664     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6665   // fold (truncate (truncate x)) -> (truncate x)
6666   if (N0.getOpcode() == ISD::TRUNCATE)
6667     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6668   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6669   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6670       N0.getOpcode() == ISD::SIGN_EXTEND ||
6671       N0.getOpcode() == ISD::ANY_EXTEND) {
6672     if (N0.getOperand(0).getValueType().bitsLT(VT))
6673       // if the source is smaller than the dest, we still need an extend
6674       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6675                          N0.getOperand(0));
6676     if (N0.getOperand(0).getValueType().bitsGT(VT))
6677       // if the source is larger than the dest, than we just need the truncate
6678       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6679     // if the source and dest are the same type, we can drop both the extend
6680     // and the truncate.
6681     return N0.getOperand(0);
6682   }
6683
6684   // Fold extract-and-trunc into a narrow extract. For example:
6685   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6686   //   i32 y = TRUNCATE(i64 x)
6687   //        -- becomes --
6688   //   v16i8 b = BITCAST (v2i64 val)
6689   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6690   //
6691   // Note: We only run this optimization after type legalization (which often
6692   // creates this pattern) and before operation legalization after which
6693   // we need to be more careful about the vector instructions that we generate.
6694   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6695       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6696
6697     EVT VecTy = N0.getOperand(0).getValueType();
6698     EVT ExTy = N0.getValueType();
6699     EVT TrTy = N->getValueType(0);
6700
6701     unsigned NumElem = VecTy.getVectorNumElements();
6702     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6703
6704     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6705     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6706
6707     SDValue EltNo = N0->getOperand(1);
6708     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6709       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6710       EVT IndexTy = TLI.getVectorIdxTy();
6711       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6712
6713       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6714                               NVT, N0.getOperand(0));
6715
6716       SDLoc DL(N);
6717       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6718                          DL, TrTy, V,
6719                          DAG.getConstant(Index, DL, IndexTy));
6720     }
6721   }
6722
6723   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6724   if (N0.getOpcode() == ISD::SELECT) {
6725     EVT SrcVT = N0.getValueType();
6726     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6727         TLI.isTruncateFree(SrcVT, VT)) {
6728       SDLoc SL(N0);
6729       SDValue Cond = N0.getOperand(0);
6730       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6731       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6732       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6733     }
6734   }
6735
6736   // Fold a series of buildvector, bitcast, and truncate if possible.
6737   // For example fold
6738   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6739   //   (2xi32 (buildvector x, y)).
6740   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6741       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6742       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6743       N0.getOperand(0).hasOneUse()) {
6744
6745     SDValue BuildVect = N0.getOperand(0);
6746     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6747     EVT TruncVecEltTy = VT.getVectorElementType();
6748
6749     // Check that the element types match.
6750     if (BuildVectEltTy == TruncVecEltTy) {
6751       // Now we only need to compute the offset of the truncated elements.
6752       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6753       unsigned TruncVecNumElts = VT.getVectorNumElements();
6754       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6755
6756       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6757              "Invalid number of elements");
6758
6759       SmallVector<SDValue, 8> Opnds;
6760       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6761         Opnds.push_back(BuildVect.getOperand(i));
6762
6763       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6764     }
6765   }
6766
6767   // See if we can simplify the input to this truncate through knowledge that
6768   // only the low bits are being used.
6769   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6770   // Currently we only perform this optimization on scalars because vectors
6771   // may have different active low bits.
6772   if (!VT.isVector()) {
6773     SDValue Shorter =
6774       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6775                                                VT.getSizeInBits()));
6776     if (Shorter.getNode())
6777       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6778   }
6779   // fold (truncate (load x)) -> (smaller load x)
6780   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6781   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6782     SDValue Reduced = ReduceLoadWidth(N);
6783     if (Reduced.getNode())
6784       return Reduced;
6785     // Handle the case where the load remains an extending load even
6786     // after truncation.
6787     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6788       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6789       if (!LN0->isVolatile() &&
6790           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6791         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6792                                          VT, LN0->getChain(), LN0->getBasePtr(),
6793                                          LN0->getMemoryVT(),
6794                                          LN0->getMemOperand());
6795         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6796         return NewLoad;
6797       }
6798     }
6799   }
6800   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6801   // where ... are all 'undef'.
6802   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6803     SmallVector<EVT, 8> VTs;
6804     SDValue V;
6805     unsigned Idx = 0;
6806     unsigned NumDefs = 0;
6807
6808     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6809       SDValue X = N0.getOperand(i);
6810       if (X.getOpcode() != ISD::UNDEF) {
6811         V = X;
6812         Idx = i;
6813         NumDefs++;
6814       }
6815       // Stop if more than one members are non-undef.
6816       if (NumDefs > 1)
6817         break;
6818       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6819                                      VT.getVectorElementType(),
6820                                      X.getValueType().getVectorNumElements()));
6821     }
6822
6823     if (NumDefs == 0)
6824       return DAG.getUNDEF(VT);
6825
6826     if (NumDefs == 1) {
6827       assert(V.getNode() && "The single defined operand is empty!");
6828       SmallVector<SDValue, 8> Opnds;
6829       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6830         if (i != Idx) {
6831           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6832           continue;
6833         }
6834         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6835         AddToWorklist(NV.getNode());
6836         Opnds.push_back(NV);
6837       }
6838       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6839     }
6840   }
6841
6842   // Simplify the operands using demanded-bits information.
6843   if (!VT.isVector() &&
6844       SimplifyDemandedBits(SDValue(N, 0)))
6845     return SDValue(N, 0);
6846
6847   return SDValue();
6848 }
6849
6850 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6851   SDValue Elt = N->getOperand(i);
6852   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6853     return Elt.getNode();
6854   return Elt.getOperand(Elt.getResNo()).getNode();
6855 }
6856
6857 /// build_pair (load, load) -> load
6858 /// if load locations are consecutive.
6859 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6860   assert(N->getOpcode() == ISD::BUILD_PAIR);
6861
6862   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6863   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6864   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6865       LD1->getAddressSpace() != LD2->getAddressSpace())
6866     return SDValue();
6867   EVT LD1VT = LD1->getValueType(0);
6868
6869   if (ISD::isNON_EXTLoad(LD2) &&
6870       LD2->hasOneUse() &&
6871       // If both are volatile this would reduce the number of volatile loads.
6872       // If one is volatile it might be ok, but play conservative and bail out.
6873       !LD1->isVolatile() &&
6874       !LD2->isVolatile() &&
6875       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6876     unsigned Align = LD1->getAlignment();
6877     unsigned NewAlign = TLI.getDataLayout()->
6878       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6879
6880     if (NewAlign <= Align &&
6881         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6882       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6883                          LD1->getBasePtr(), LD1->getPointerInfo(),
6884                          false, false, false, Align);
6885   }
6886
6887   return SDValue();
6888 }
6889
6890 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6891   SDValue N0 = N->getOperand(0);
6892   EVT VT = N->getValueType(0);
6893
6894   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6895   // Only do this before legalize, since afterward the target may be depending
6896   // on the bitconvert.
6897   // First check to see if this is all constant.
6898   if (!LegalTypes &&
6899       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6900       VT.isVector()) {
6901     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6902
6903     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6904     assert(!DestEltVT.isVector() &&
6905            "Element type of vector ValueType must not be vector!");
6906     if (isSimple)
6907       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6908   }
6909
6910   // If the input is a constant, let getNode fold it.
6911   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6912     // If we can't allow illegal operations, we need to check that this is just
6913     // a fp -> int or int -> conversion and that the resulting operation will
6914     // be legal.
6915     if (!LegalOperations ||
6916         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6917          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6918         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6919          TLI.isOperationLegal(ISD::Constant, VT)))
6920       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6921   }
6922
6923   // (conv (conv x, t1), t2) -> (conv x, t2)
6924   if (N0.getOpcode() == ISD::BITCAST)
6925     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6926                        N0.getOperand(0));
6927
6928   // fold (conv (load x)) -> (load (conv*)x)
6929   // If the resultant load doesn't need a higher alignment than the original!
6930   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6931       // Do not change the width of a volatile load.
6932       !cast<LoadSDNode>(N0)->isVolatile() &&
6933       // Do not remove the cast if the types differ in endian layout.
6934       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6935       TLI.hasBigEndianPartOrdering(VT) &&
6936       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6937       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6938     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6939     unsigned Align = TLI.getDataLayout()->
6940       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6941     unsigned OrigAlign = LN0->getAlignment();
6942
6943     if (Align <= OrigAlign) {
6944       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6945                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6946                                  LN0->isVolatile(), LN0->isNonTemporal(),
6947                                  LN0->isInvariant(), OrigAlign,
6948                                  LN0->getAAInfo());
6949       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6950       return Load;
6951     }
6952   }
6953
6954   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6955   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6956   // This often reduces constant pool loads.
6957   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6958        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6959       N0.getNode()->hasOneUse() && VT.isInteger() &&
6960       !VT.isVector() && !N0.getValueType().isVector()) {
6961     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6962                                   N0.getOperand(0));
6963     AddToWorklist(NewConv.getNode());
6964
6965     SDLoc DL(N);
6966     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6967     if (N0.getOpcode() == ISD::FNEG)
6968       return DAG.getNode(ISD::XOR, DL, VT,
6969                          NewConv, DAG.getConstant(SignBit, DL, VT));
6970     assert(N0.getOpcode() == ISD::FABS);
6971     return DAG.getNode(ISD::AND, DL, VT,
6972                        NewConv, DAG.getConstant(~SignBit, DL, VT));
6973   }
6974
6975   // fold (bitconvert (fcopysign cst, x)) ->
6976   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6977   // Note that we don't handle (copysign x, cst) because this can always be
6978   // folded to an fneg or fabs.
6979   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6980       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6981       VT.isInteger() && !VT.isVector()) {
6982     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6983     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6984     if (isTypeLegal(IntXVT)) {
6985       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6986                               IntXVT, N0.getOperand(1));
6987       AddToWorklist(X.getNode());
6988
6989       // If X has a different width than the result/lhs, sext it or truncate it.
6990       unsigned VTWidth = VT.getSizeInBits();
6991       if (OrigXWidth < VTWidth) {
6992         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6993         AddToWorklist(X.getNode());
6994       } else if (OrigXWidth > VTWidth) {
6995         // To get the sign bit in the right place, we have to shift it right
6996         // before truncating.
6997         SDLoc DL(X);
6998         X = DAG.getNode(ISD::SRL, DL,
6999                         X.getValueType(), X,
7000                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7001                                         X.getValueType()));
7002         AddToWorklist(X.getNode());
7003         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7004         AddToWorklist(X.getNode());
7005       }
7006
7007       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7008       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7009                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7010       AddToWorklist(X.getNode());
7011
7012       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7013                                 VT, N0.getOperand(0));
7014       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7015                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7016       AddToWorklist(Cst.getNode());
7017
7018       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7019     }
7020   }
7021
7022   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7023   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7024     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7025     if (CombineLD.getNode())
7026       return CombineLD;
7027   }
7028
7029   // Remove double bitcasts from shuffles - this is often a legacy of
7030   // XformToShuffleWithZero being used to combine bitmaskings (of
7031   // float vectors bitcast to integer vectors) into shuffles.
7032   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7033   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7034       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7035       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7036       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7037     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7038
7039     // If operands are a bitcast, peek through if it casts the original VT.
7040     // If operands are a UNDEF or constant, just bitcast back to original VT.
7041     auto PeekThroughBitcast = [&](SDValue Op) {
7042       if (Op.getOpcode() == ISD::BITCAST &&
7043           Op.getOperand(0)->getValueType(0) == VT)
7044         return SDValue(Op.getOperand(0));
7045       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7046           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7047         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7048       return SDValue();
7049     };
7050
7051     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7052     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7053     if (!(SV0 && SV1))
7054       return SDValue();
7055
7056     int MaskScale =
7057         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7058     SmallVector<int, 8> NewMask;
7059     for (int M : SVN->getMask())
7060       for (int i = 0; i != MaskScale; ++i)
7061         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7062
7063     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7064     if (!LegalMask) {
7065       std::swap(SV0, SV1);
7066       ShuffleVectorSDNode::commuteMask(NewMask);
7067       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7068     }
7069
7070     if (LegalMask)
7071       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7072   }
7073
7074   return SDValue();
7075 }
7076
7077 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7078   EVT VT = N->getValueType(0);
7079   return CombineConsecutiveLoads(N, VT);
7080 }
7081
7082 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7083 /// operands. DstEltVT indicates the destination element value type.
7084 SDValue DAGCombiner::
7085 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7086   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7087
7088   // If this is already the right type, we're done.
7089   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7090
7091   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7092   unsigned DstBitSize = DstEltVT.getSizeInBits();
7093
7094   // If this is a conversion of N elements of one type to N elements of another
7095   // type, convert each element.  This handles FP<->INT cases.
7096   if (SrcBitSize == DstBitSize) {
7097     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7098                               BV->getValueType(0).getVectorNumElements());
7099
7100     // Due to the FP element handling below calling this routine recursively,
7101     // we can end up with a scalar-to-vector node here.
7102     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7103       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7104                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7105                                      DstEltVT, BV->getOperand(0)));
7106
7107     SmallVector<SDValue, 8> Ops;
7108     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7109       SDValue Op = BV->getOperand(i);
7110       // If the vector element type is not legal, the BUILD_VECTOR operands
7111       // are promoted and implicitly truncated.  Make that explicit here.
7112       if (Op.getValueType() != SrcEltVT)
7113         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7114       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7115                                 DstEltVT, Op));
7116       AddToWorklist(Ops.back().getNode());
7117     }
7118     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7119   }
7120
7121   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7122   // handle annoying details of growing/shrinking FP values, we convert them to
7123   // int first.
7124   if (SrcEltVT.isFloatingPoint()) {
7125     // Convert the input float vector to a int vector where the elements are the
7126     // same sizes.
7127     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7128     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7129     SrcEltVT = IntVT;
7130   }
7131
7132   // Now we know the input is an integer vector.  If the output is a FP type,
7133   // convert to integer first, then to FP of the right size.
7134   if (DstEltVT.isFloatingPoint()) {
7135     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7136     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7137
7138     // Next, convert to FP elements of the same size.
7139     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7140   }
7141
7142   SDLoc DL(BV);
7143
7144   // Okay, we know the src/dst types are both integers of differing types.
7145   // Handling growing first.
7146   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7147   if (SrcBitSize < DstBitSize) {
7148     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7149
7150     SmallVector<SDValue, 8> Ops;
7151     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7152          i += NumInputsPerOutput) {
7153       bool isLE = TLI.isLittleEndian();
7154       APInt NewBits = APInt(DstBitSize, 0);
7155       bool EltIsUndef = true;
7156       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7157         // Shift the previously computed bits over.
7158         NewBits <<= SrcBitSize;
7159         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7160         if (Op.getOpcode() == ISD::UNDEF) continue;
7161         EltIsUndef = false;
7162
7163         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7164                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7165       }
7166
7167       if (EltIsUndef)
7168         Ops.push_back(DAG.getUNDEF(DstEltVT));
7169       else
7170         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7171     }
7172
7173     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7174     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7175   }
7176
7177   // Finally, this must be the case where we are shrinking elements: each input
7178   // turns into multiple outputs.
7179   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7180   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7181                             NumOutputsPerInput*BV->getNumOperands());
7182   SmallVector<SDValue, 8> Ops;
7183
7184   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7185     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7186       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7187       continue;
7188     }
7189
7190     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7191                   getAPIntValue().zextOrTrunc(SrcBitSize);
7192
7193     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7194       APInt ThisVal = OpVal.trunc(DstBitSize);
7195       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7196       OpVal = OpVal.lshr(DstBitSize);
7197     }
7198
7199     // For big endian targets, swap the order of the pieces of each element.
7200     if (TLI.isBigEndian())
7201       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7202   }
7203
7204   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7205 }
7206
7207 /// Try to perform FMA combining on a given FADD node.
7208 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7209   SDValue N0 = N->getOperand(0);
7210   SDValue N1 = N->getOperand(1);
7211   EVT VT = N->getValueType(0);
7212   SDLoc SL(N);
7213
7214   const TargetOptions &Options = DAG.getTarget().Options;
7215   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7216                        Options.UnsafeFPMath);
7217
7218   // Floating-point multiply-add with intermediate rounding.
7219   bool HasFMAD = (LegalOperations &&
7220                   TLI.isOperationLegal(ISD::FMAD, VT));
7221
7222   // Floating-point multiply-add without intermediate rounding.
7223   bool HasFMA = ((!LegalOperations ||
7224                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7225                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7226                  UnsafeFPMath);
7227
7228   // No valid opcode, do not combine.
7229   if (!HasFMAD && !HasFMA)
7230     return SDValue();
7231
7232   // Always prefer FMAD to FMA for precision.
7233   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7234   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7235   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7236
7237   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7238   if (N0.getOpcode() == ISD::FMUL &&
7239       (Aggressive || N0->hasOneUse())) {
7240     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7241                        N0.getOperand(0), N0.getOperand(1), N1);
7242   }
7243
7244   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7245   // Note: Commutes FADD operands.
7246   if (N1.getOpcode() == ISD::FMUL &&
7247       (Aggressive || N1->hasOneUse())) {
7248     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7249                        N1.getOperand(0), N1.getOperand(1), N0);
7250   }
7251
7252   // Look through FP_EXTEND nodes to do more combining.
7253   if (UnsafeFPMath && LookThroughFPExt) {
7254     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7255     if (N0.getOpcode() == ISD::FP_EXTEND) {
7256       SDValue N00 = N0.getOperand(0);
7257       if (N00.getOpcode() == ISD::FMUL)
7258         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7259                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7260                                        N00.getOperand(0)),
7261                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7262                                        N00.getOperand(1)), N1);
7263     }
7264
7265     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7266     // Note: Commutes FADD operands.
7267     if (N1.getOpcode() == ISD::FP_EXTEND) {
7268       SDValue N10 = N1.getOperand(0);
7269       if (N10.getOpcode() == ISD::FMUL)
7270         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7271                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7272                                        N10.getOperand(0)),
7273                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7274                                        N10.getOperand(1)), N0);
7275     }
7276   }
7277
7278   // More folding opportunities when target permits.
7279   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7280     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7281     if (N0.getOpcode() == PreferredFusedOpcode &&
7282         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7283       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7284                          N0.getOperand(0), N0.getOperand(1),
7285                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7286                                      N0.getOperand(2).getOperand(0),
7287                                      N0.getOperand(2).getOperand(1),
7288                                      N1));
7289     }
7290
7291     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7292     if (N1->getOpcode() == PreferredFusedOpcode &&
7293         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7294       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7295                          N1.getOperand(0), N1.getOperand(1),
7296                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7297                                      N1.getOperand(2).getOperand(0),
7298                                      N1.getOperand(2).getOperand(1),
7299                                      N0));
7300     }
7301
7302     if (UnsafeFPMath && LookThroughFPExt) {
7303       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7304       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7305       auto FoldFAddFMAFPExtFMul = [&] (
7306           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7307         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7308                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7309                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7310                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7311                                        Z));
7312       };
7313       if (N0.getOpcode() == PreferredFusedOpcode) {
7314         SDValue N02 = N0.getOperand(2);
7315         if (N02.getOpcode() == ISD::FP_EXTEND) {
7316           SDValue N020 = N02.getOperand(0);
7317           if (N020.getOpcode() == ISD::FMUL)
7318             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7319                                         N020.getOperand(0), N020.getOperand(1),
7320                                         N1);
7321         }
7322       }
7323
7324       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7325       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7326       // FIXME: This turns two single-precision and one double-precision
7327       // operation into two double-precision operations, which might not be
7328       // interesting for all targets, especially GPUs.
7329       auto FoldFAddFPExtFMAFMul = [&] (
7330           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7331         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7332                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7333                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7334                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7335                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7336                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7337                                        Z));
7338       };
7339       if (N0.getOpcode() == ISD::FP_EXTEND) {
7340         SDValue N00 = N0.getOperand(0);
7341         if (N00.getOpcode() == PreferredFusedOpcode) {
7342           SDValue N002 = N00.getOperand(2);
7343           if (N002.getOpcode() == ISD::FMUL)
7344             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7345                                         N002.getOperand(0), N002.getOperand(1),
7346                                         N1);
7347         }
7348       }
7349
7350       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7351       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7352       if (N1.getOpcode() == PreferredFusedOpcode) {
7353         SDValue N12 = N1.getOperand(2);
7354         if (N12.getOpcode() == ISD::FP_EXTEND) {
7355           SDValue N120 = N12.getOperand(0);
7356           if (N120.getOpcode() == ISD::FMUL)
7357             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7358                                         N120.getOperand(0), N120.getOperand(1),
7359                                         N0);
7360         }
7361       }
7362
7363       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7364       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7365       // FIXME: This turns two single-precision and one double-precision
7366       // operation into two double-precision operations, which might not be
7367       // interesting for all targets, especially GPUs.
7368       if (N1.getOpcode() == ISD::FP_EXTEND) {
7369         SDValue N10 = N1.getOperand(0);
7370         if (N10.getOpcode() == PreferredFusedOpcode) {
7371           SDValue N102 = N10.getOperand(2);
7372           if (N102.getOpcode() == ISD::FMUL)
7373             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7374                                         N102.getOperand(0), N102.getOperand(1),
7375                                         N0);
7376         }
7377       }
7378     }
7379   }
7380
7381   return SDValue();
7382 }
7383
7384 /// Try to perform FMA combining on a given FSUB node.
7385 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7386   SDValue N0 = N->getOperand(0);
7387   SDValue N1 = N->getOperand(1);
7388   EVT VT = N->getValueType(0);
7389   SDLoc SL(N);
7390
7391   const TargetOptions &Options = DAG.getTarget().Options;
7392   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7393                        Options.UnsafeFPMath);
7394
7395   // Floating-point multiply-add with intermediate rounding.
7396   bool HasFMAD = (LegalOperations &&
7397                   TLI.isOperationLegal(ISD::FMAD, VT));
7398
7399   // Floating-point multiply-add without intermediate rounding.
7400   bool HasFMA = ((!LegalOperations ||
7401                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7402                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7403                  UnsafeFPMath);
7404
7405   // No valid opcode, do not combine.
7406   if (!HasFMAD && !HasFMA)
7407     return SDValue();
7408
7409   // Always prefer FMAD to FMA for precision.
7410   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7411   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7412   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7413
7414   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7415   if (N0.getOpcode() == ISD::FMUL &&
7416       (Aggressive || N0->hasOneUse())) {
7417     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7418                        N0.getOperand(0), N0.getOperand(1),
7419                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7420   }
7421
7422   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7423   // Note: Commutes FSUB operands.
7424   if (N1.getOpcode() == ISD::FMUL &&
7425       (Aggressive || N1->hasOneUse()))
7426     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7427                        DAG.getNode(ISD::FNEG, SL, VT,
7428                                    N1.getOperand(0)),
7429                        N1.getOperand(1), N0);
7430
7431   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7432   if (N0.getOpcode() == ISD::FNEG &&
7433       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7434       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7435     SDValue N00 = N0.getOperand(0).getOperand(0);
7436     SDValue N01 = N0.getOperand(0).getOperand(1);
7437     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7438                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7439                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7440   }
7441
7442   // Look through FP_EXTEND nodes to do more combining.
7443   if (UnsafeFPMath && LookThroughFPExt) {
7444     // fold (fsub (fpext (fmul x, y)), z)
7445     //   -> (fma (fpext x), (fpext y), (fneg z))
7446     if (N0.getOpcode() == ISD::FP_EXTEND) {
7447       SDValue N00 = N0.getOperand(0);
7448       if (N00.getOpcode() == ISD::FMUL)
7449         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7450                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7451                                        N00.getOperand(0)),
7452                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7453                                        N00.getOperand(1)),
7454                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7455     }
7456
7457     // fold (fsub x, (fpext (fmul y, z)))
7458     //   -> (fma (fneg (fpext y)), (fpext z), x)
7459     // Note: Commutes FSUB operands.
7460     if (N1.getOpcode() == ISD::FP_EXTEND) {
7461       SDValue N10 = N1.getOperand(0);
7462       if (N10.getOpcode() == ISD::FMUL)
7463         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7464                            DAG.getNode(ISD::FNEG, SL, VT,
7465                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7466                                                    N10.getOperand(0))),
7467                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7468                                        N10.getOperand(1)),
7469                            N0);
7470     }
7471
7472     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7473     //   -> (fneg (fma (fpext x), (fpext y), z))
7474     // Note: This could be removed with appropriate canonicalization of the
7475     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7476     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7477     // from implementing the canonicalization in visitFSUB.
7478     if (N0.getOpcode() == ISD::FP_EXTEND) {
7479       SDValue N00 = N0.getOperand(0);
7480       if (N00.getOpcode() == ISD::FNEG) {
7481         SDValue N000 = N00.getOperand(0);
7482         if (N000.getOpcode() == ISD::FMUL) {
7483           return DAG.getNode(ISD::FNEG, SL, VT,
7484                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7485                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7486                                                      N000.getOperand(0)),
7487                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7488                                                      N000.getOperand(1)),
7489                                          N1));
7490         }
7491       }
7492     }
7493
7494     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7495     //   -> (fneg (fma (fpext x)), (fpext y), z)
7496     // Note: This could be removed with appropriate canonicalization of the
7497     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7498     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7499     // from implementing the canonicalization in visitFSUB.
7500     if (N0.getOpcode() == ISD::FNEG) {
7501       SDValue N00 = N0.getOperand(0);
7502       if (N00.getOpcode() == ISD::FP_EXTEND) {
7503         SDValue N000 = N00.getOperand(0);
7504         if (N000.getOpcode() == ISD::FMUL) {
7505           return DAG.getNode(ISD::FNEG, SL, VT,
7506                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7507                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7508                                                      N000.getOperand(0)),
7509                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7510                                                      N000.getOperand(1)),
7511                                          N1));
7512         }
7513       }
7514     }
7515
7516   }
7517
7518   // More folding opportunities when target permits.
7519   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7520     // fold (fsub (fma x, y, (fmul u, v)), z)
7521     //   -> (fma x, y (fma u, v, (fneg z)))
7522     if (N0.getOpcode() == PreferredFusedOpcode &&
7523         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7524       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7525                          N0.getOperand(0), N0.getOperand(1),
7526                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7527                                      N0.getOperand(2).getOperand(0),
7528                                      N0.getOperand(2).getOperand(1),
7529                                      DAG.getNode(ISD::FNEG, SL, VT,
7530                                                  N1)));
7531     }
7532
7533     // fold (fsub x, (fma y, z, (fmul u, v)))
7534     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7535     if (N1.getOpcode() == PreferredFusedOpcode &&
7536         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7537       SDValue N20 = N1.getOperand(2).getOperand(0);
7538       SDValue N21 = N1.getOperand(2).getOperand(1);
7539       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7540                          DAG.getNode(ISD::FNEG, SL, VT,
7541                                      N1.getOperand(0)),
7542                          N1.getOperand(1),
7543                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7544                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7545
7546                                      N21, N0));
7547     }
7548
7549     if (UnsafeFPMath && LookThroughFPExt) {
7550       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7551       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7552       if (N0.getOpcode() == PreferredFusedOpcode) {
7553         SDValue N02 = N0.getOperand(2);
7554         if (N02.getOpcode() == ISD::FP_EXTEND) {
7555           SDValue N020 = N02.getOperand(0);
7556           if (N020.getOpcode() == ISD::FMUL)
7557             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7558                                N0.getOperand(0), N0.getOperand(1),
7559                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7560                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7561                                                        N020.getOperand(0)),
7562                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7563                                                        N020.getOperand(1)),
7564                                            DAG.getNode(ISD::FNEG, SL, VT,
7565                                                        N1)));
7566         }
7567       }
7568
7569       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7570       //   -> (fma (fpext x), (fpext y),
7571       //           (fma (fpext u), (fpext v), (fneg z)))
7572       // FIXME: This turns two single-precision and one double-precision
7573       // operation into two double-precision operations, which might not be
7574       // interesting for all targets, especially GPUs.
7575       if (N0.getOpcode() == ISD::FP_EXTEND) {
7576         SDValue N00 = N0.getOperand(0);
7577         if (N00.getOpcode() == PreferredFusedOpcode) {
7578           SDValue N002 = N00.getOperand(2);
7579           if (N002.getOpcode() == ISD::FMUL)
7580             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7581                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7582                                            N00.getOperand(0)),
7583                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7584                                            N00.getOperand(1)),
7585                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7586                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7587                                                        N002.getOperand(0)),
7588                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7589                                                        N002.getOperand(1)),
7590                                            DAG.getNode(ISD::FNEG, SL, VT,
7591                                                        N1)));
7592         }
7593       }
7594
7595       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7596       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7597       if (N1.getOpcode() == PreferredFusedOpcode &&
7598         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7599         SDValue N120 = N1.getOperand(2).getOperand(0);
7600         if (N120.getOpcode() == ISD::FMUL) {
7601           SDValue N1200 = N120.getOperand(0);
7602           SDValue N1201 = N120.getOperand(1);
7603           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7604                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7605                              N1.getOperand(1),
7606                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7607                                          DAG.getNode(ISD::FNEG, SL, VT,
7608                                              DAG.getNode(ISD::FP_EXTEND, SL,
7609                                                          VT, N1200)),
7610                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7611                                                      N1201),
7612                                          N0));
7613         }
7614       }
7615
7616       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7617       //   -> (fma (fneg (fpext y)), (fpext z),
7618       //           (fma (fneg (fpext u)), (fpext v), x))
7619       // FIXME: This turns two single-precision and one double-precision
7620       // operation into two double-precision operations, which might not be
7621       // interesting for all targets, especially GPUs.
7622       if (N1.getOpcode() == ISD::FP_EXTEND &&
7623         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7624         SDValue N100 = N1.getOperand(0).getOperand(0);
7625         SDValue N101 = N1.getOperand(0).getOperand(1);
7626         SDValue N102 = N1.getOperand(0).getOperand(2);
7627         if (N102.getOpcode() == ISD::FMUL) {
7628           SDValue N1020 = N102.getOperand(0);
7629           SDValue N1021 = N102.getOperand(1);
7630           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7631                              DAG.getNode(ISD::FNEG, SL, VT,
7632                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7633                                                      N100)),
7634                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7635                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7636                                          DAG.getNode(ISD::FNEG, SL, VT,
7637                                              DAG.getNode(ISD::FP_EXTEND, SL,
7638                                                          VT, N1020)),
7639                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7640                                                      N1021),
7641                                          N0));
7642         }
7643       }
7644     }
7645   }
7646
7647   return SDValue();
7648 }
7649
7650 SDValue DAGCombiner::visitFADD(SDNode *N) {
7651   SDValue N0 = N->getOperand(0);
7652   SDValue N1 = N->getOperand(1);
7653   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7654   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7655   EVT VT = N->getValueType(0);
7656   SDLoc DL(N);
7657   const TargetOptions &Options = DAG.getTarget().Options;
7658
7659   // fold vector ops
7660   if (VT.isVector())
7661     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7662       return FoldedVOp;
7663
7664   // fold (fadd c1, c2) -> c1 + c2
7665   if (N0CFP && N1CFP)
7666     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7667
7668   // canonicalize constant to RHS
7669   if (N0CFP && !N1CFP)
7670     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7671
7672   // fold (fadd A, (fneg B)) -> (fsub A, B)
7673   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7674       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7675     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7676                        GetNegatedExpression(N1, DAG, LegalOperations));
7677
7678   // fold (fadd (fneg A), B) -> (fsub B, A)
7679   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7680       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7681     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7682                        GetNegatedExpression(N0, DAG, LegalOperations));
7683
7684   // If 'unsafe math' is enabled, fold lots of things.
7685   if (Options.UnsafeFPMath) {
7686     // No FP constant should be created after legalization as Instruction
7687     // Selection pass has a hard time dealing with FP constants.
7688     bool AllowNewConst = (Level < AfterLegalizeDAG);
7689
7690     // fold (fadd A, 0) -> A
7691     if (N1CFP && N1CFP->getValueAPF().isZero())
7692       return N0;
7693
7694     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7695     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7696         isa<ConstantFPSDNode>(N0.getOperand(1)))
7697       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7698                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7699
7700     // If allowed, fold (fadd (fneg x), x) -> 0.0
7701     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7702       return DAG.getConstantFP(0.0, DL, VT);
7703
7704     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7705     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7706       return DAG.getConstantFP(0.0, DL, VT);
7707
7708     // We can fold chains of FADD's of the same value into multiplications.
7709     // This transform is not safe in general because we are reducing the number
7710     // of rounding steps.
7711     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7712       if (N0.getOpcode() == ISD::FMUL) {
7713         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7714         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7715
7716         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7717         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7718           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7719                                        DAG.getConstantFP(1.0, DL, VT));
7720           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7721         }
7722
7723         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7724         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7725             N1.getOperand(0) == N1.getOperand(1) &&
7726             N0.getOperand(0) == N1.getOperand(0)) {
7727           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7728                                        DAG.getConstantFP(2.0, DL, VT));
7729           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7730         }
7731       }
7732
7733       if (N1.getOpcode() == ISD::FMUL) {
7734         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7735         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7736
7737         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7738         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7739           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7740                                        DAG.getConstantFP(1.0, DL, VT));
7741           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7742         }
7743
7744         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7745         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7746             N0.getOperand(0) == N0.getOperand(1) &&
7747             N1.getOperand(0) == N0.getOperand(0)) {
7748           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7749                                        DAG.getConstantFP(2.0, DL, VT));
7750           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7751         }
7752       }
7753
7754       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7755         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7756         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7757         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7758             (N0.getOperand(0) == N1)) {
7759           return DAG.getNode(ISD::FMUL, DL, VT,
7760                              N1, DAG.getConstantFP(3.0, DL, VT));
7761         }
7762       }
7763
7764       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7765         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7766         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7767         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7768             N1.getOperand(0) == N0) {
7769           return DAG.getNode(ISD::FMUL, DL, VT,
7770                              N0, DAG.getConstantFP(3.0, DL, VT));
7771         }
7772       }
7773
7774       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7775       if (AllowNewConst &&
7776           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7777           N0.getOperand(0) == N0.getOperand(1) &&
7778           N1.getOperand(0) == N1.getOperand(1) &&
7779           N0.getOperand(0) == N1.getOperand(0)) {
7780         return DAG.getNode(ISD::FMUL, DL, VT,
7781                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7782       }
7783     }
7784   } // enable-unsafe-fp-math
7785
7786   // FADD -> FMA combines:
7787   SDValue Fused = visitFADDForFMACombine(N);
7788   if (Fused) {
7789     AddToWorklist(Fused.getNode());
7790     return Fused;
7791   }
7792
7793   return SDValue();
7794 }
7795
7796 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7797   SDValue N0 = N->getOperand(0);
7798   SDValue N1 = N->getOperand(1);
7799   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7800   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7801   EVT VT = N->getValueType(0);
7802   SDLoc dl(N);
7803   const TargetOptions &Options = DAG.getTarget().Options;
7804
7805   // fold vector ops
7806   if (VT.isVector())
7807     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7808       return FoldedVOp;
7809
7810   // fold (fsub c1, c2) -> c1-c2
7811   if (N0CFP && N1CFP)
7812     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7813
7814   // fold (fsub A, (fneg B)) -> (fadd A, B)
7815   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7816     return DAG.getNode(ISD::FADD, dl, VT, N0,
7817                        GetNegatedExpression(N1, DAG, LegalOperations));
7818
7819   // If 'unsafe math' is enabled, fold lots of things.
7820   if (Options.UnsafeFPMath) {
7821     // (fsub A, 0) -> A
7822     if (N1CFP && N1CFP->getValueAPF().isZero())
7823       return N0;
7824
7825     // (fsub 0, B) -> -B
7826     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7827       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7828         return GetNegatedExpression(N1, DAG, LegalOperations);
7829       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7830         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7831     }
7832
7833     // (fsub x, x) -> 0.0
7834     if (N0 == N1)
7835       return DAG.getConstantFP(0.0f, dl, VT);
7836
7837     // (fsub x, (fadd x, y)) -> (fneg y)
7838     // (fsub x, (fadd y, x)) -> (fneg y)
7839     if (N1.getOpcode() == ISD::FADD) {
7840       SDValue N10 = N1->getOperand(0);
7841       SDValue N11 = N1->getOperand(1);
7842
7843       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7844         return GetNegatedExpression(N11, DAG, LegalOperations);
7845
7846       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7847         return GetNegatedExpression(N10, DAG, LegalOperations);
7848     }
7849   }
7850
7851   // FSUB -> FMA combines:
7852   SDValue Fused = visitFSUBForFMACombine(N);
7853   if (Fused) {
7854     AddToWorklist(Fused.getNode());
7855     return Fused;
7856   }
7857
7858   return SDValue();
7859 }
7860
7861 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7862   SDValue N0 = N->getOperand(0);
7863   SDValue N1 = N->getOperand(1);
7864   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7865   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7866   EVT VT = N->getValueType(0);
7867   SDLoc DL(N);
7868   const TargetOptions &Options = DAG.getTarget().Options;
7869
7870   // fold vector ops
7871   if (VT.isVector()) {
7872     // This just handles C1 * C2 for vectors. Other vector folds are below.
7873     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7874       return FoldedVOp;
7875   }
7876
7877   // fold (fmul c1, c2) -> c1*c2
7878   if (N0CFP && N1CFP)
7879     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
7880
7881   // canonicalize constant to RHS
7882   if (isConstantFPBuildVectorOrConstantFP(N0) &&
7883      !isConstantFPBuildVectorOrConstantFP(N1))
7884     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
7885
7886   // fold (fmul A, 1.0) -> A
7887   if (N1CFP && N1CFP->isExactlyValue(1.0))
7888     return N0;
7889
7890   if (Options.UnsafeFPMath) {
7891     // fold (fmul A, 0) -> 0
7892     if (N1CFP && N1CFP->getValueAPF().isZero())
7893       return N1;
7894
7895     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7896     if (N0.getOpcode() == ISD::FMUL) {
7897       // Fold scalars or any vector constants (not just splats).
7898       // This fold is done in general by InstCombine, but extra fmul insts
7899       // may have been generated during lowering.
7900       SDValue N00 = N0.getOperand(0);
7901       SDValue N01 = N0.getOperand(1);
7902       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7903       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7904       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7905       
7906       // Check 1: Make sure that the first operand of the inner multiply is NOT
7907       // a constant. Otherwise, we may induce infinite looping.
7908       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7909         // Check 2: Make sure that the second operand of the inner multiply and
7910         // the second operand of the outer multiply are constants.
7911         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7912             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7913           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
7914           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
7915         }
7916       }
7917     }
7918
7919     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7920     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7921     // during an early run of DAGCombiner can prevent folding with fmuls
7922     // inserted during lowering.
7923     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7924       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
7925       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
7926       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
7927     }
7928   }
7929
7930   // fold (fmul X, 2.0) -> (fadd X, X)
7931   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7932     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
7933
7934   // fold (fmul X, -1.0) -> (fneg X)
7935   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7936     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7937       return DAG.getNode(ISD::FNEG, DL, VT, N0);
7938
7939   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7940   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7941     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7942       // Both can be negated for free, check to see if at least one is cheaper
7943       // negated.
7944       if (LHSNeg == 2 || RHSNeg == 2)
7945         return DAG.getNode(ISD::FMUL, DL, VT,
7946                            GetNegatedExpression(N0, DAG, LegalOperations),
7947                            GetNegatedExpression(N1, DAG, LegalOperations));
7948     }
7949   }
7950
7951   return SDValue();
7952 }
7953
7954 SDValue DAGCombiner::visitFMA(SDNode *N) {
7955   SDValue N0 = N->getOperand(0);
7956   SDValue N1 = N->getOperand(1);
7957   SDValue N2 = N->getOperand(2);
7958   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7959   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7960   EVT VT = N->getValueType(0);
7961   SDLoc dl(N);
7962   const TargetOptions &Options = DAG.getTarget().Options;
7963
7964   // Constant fold FMA.
7965   if (isa<ConstantFPSDNode>(N0) &&
7966       isa<ConstantFPSDNode>(N1) &&
7967       isa<ConstantFPSDNode>(N2)) {
7968     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7969   }
7970
7971   if (Options.UnsafeFPMath) {
7972     if (N0CFP && N0CFP->isZero())
7973       return N2;
7974     if (N1CFP && N1CFP->isZero())
7975       return N2;
7976   }
7977   if (N0CFP && N0CFP->isExactlyValue(1.0))
7978     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7979   if (N1CFP && N1CFP->isExactlyValue(1.0))
7980     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7981
7982   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7983   if (N0CFP && !N1CFP)
7984     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7985
7986   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7987   if (Options.UnsafeFPMath && N1CFP &&
7988       N2.getOpcode() == ISD::FMUL &&
7989       N0 == N2.getOperand(0) &&
7990       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7991     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7992                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7993   }
7994
7995
7996   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7997   if (Options.UnsafeFPMath &&
7998       N0.getOpcode() == ISD::FMUL && N1CFP &&
7999       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8000     return DAG.getNode(ISD::FMA, dl, VT,
8001                        N0.getOperand(0),
8002                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8003                        N2);
8004   }
8005
8006   // (fma x, 1, y) -> (fadd x, y)
8007   // (fma x, -1, y) -> (fadd (fneg x), y)
8008   if (N1CFP) {
8009     if (N1CFP->isExactlyValue(1.0))
8010       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8011
8012     if (N1CFP->isExactlyValue(-1.0) &&
8013         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8014       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8015       AddToWorklist(RHSNeg.getNode());
8016       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8017     }
8018   }
8019
8020   // (fma x, c, x) -> (fmul x, (c+1))
8021   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8022     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8023                        DAG.getNode(ISD::FADD, dl, VT,
8024                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8025
8026   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8027   if (Options.UnsafeFPMath && N1CFP &&
8028       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8029     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8030                        DAG.getNode(ISD::FADD, dl, VT,
8031                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8032
8033
8034   return SDValue();
8035 }
8036
8037 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8038   SDValue N0 = N->getOperand(0);
8039   SDValue N1 = N->getOperand(1);
8040   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8041   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8042   EVT VT = N->getValueType(0);
8043   SDLoc DL(N);
8044   const TargetOptions &Options = DAG.getTarget().Options;
8045
8046   // fold vector ops
8047   if (VT.isVector())
8048     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8049       return FoldedVOp;
8050
8051   // fold (fdiv c1, c2) -> c1/c2
8052   if (N0CFP && N1CFP)
8053     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8054
8055   if (Options.UnsafeFPMath) {
8056     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8057     if (N1CFP) {
8058       // Compute the reciprocal 1.0 / c2.
8059       APFloat N1APF = N1CFP->getValueAPF();
8060       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8061       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8062       // Only do the transform if the reciprocal is a legal fp immediate that
8063       // isn't too nasty (eg NaN, denormal, ...).
8064       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8065           (!LegalOperations ||
8066            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8067            // backend)... we should handle this gracefully after Legalize.
8068            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8069            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8070            TLI.isFPImmLegal(Recip, VT)))
8071         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8072                            DAG.getConstantFP(Recip, DL, VT));
8073     }
8074
8075     // If this FDIV is part of a reciprocal square root, it may be folded
8076     // into a target-specific square root estimate instruction.
8077     if (N1.getOpcode() == ISD::FSQRT) {
8078       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8079         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8080       }
8081     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8082                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8083       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8084         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8085         AddToWorklist(RV.getNode());
8086         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8087       }
8088     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8089                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8090       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8091         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8092         AddToWorklist(RV.getNode());
8093         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8094       }
8095     } else if (N1.getOpcode() == ISD::FMUL) {
8096       // Look through an FMUL. Even though this won't remove the FDIV directly,
8097       // it's still worthwhile to get rid of the FSQRT if possible.
8098       SDValue SqrtOp;
8099       SDValue OtherOp;
8100       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8101         SqrtOp = N1.getOperand(0);
8102         OtherOp = N1.getOperand(1);
8103       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8104         SqrtOp = N1.getOperand(1);
8105         OtherOp = N1.getOperand(0);
8106       }
8107       if (SqrtOp.getNode()) {
8108         // We found a FSQRT, so try to make this fold:
8109         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8110         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8111           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8112           AddToWorklist(RV.getNode());
8113           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8114         }
8115       }
8116     }
8117
8118     // Fold into a reciprocal estimate and multiply instead of a real divide.
8119     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8120       AddToWorklist(RV.getNode());
8121       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8122     }
8123   }
8124
8125   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8126   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8127     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8128       // Both can be negated for free, check to see if at least one is cheaper
8129       // negated.
8130       if (LHSNeg == 2 || RHSNeg == 2)
8131         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8132                            GetNegatedExpression(N0, DAG, LegalOperations),
8133                            GetNegatedExpression(N1, DAG, LegalOperations));
8134     }
8135   }
8136
8137   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8138   // reciprocal.
8139   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8140   // Notice that this is not always beneficial. One reason is different target
8141   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8142   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8143   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8144   if (Options.UnsafeFPMath) {
8145     // Skip if current node is a reciprocal.
8146     if (N0CFP && N0CFP->isExactlyValue(1.0))
8147       return SDValue();
8148
8149     SmallVector<SDNode *, 4> Users;
8150     // Find all FDIV users of the same divisor.
8151     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8152                               UE = N1.getNode()->use_end();
8153          UI != UE; ++UI) {
8154       SDNode *User = UI.getUse().getUser();
8155       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8156         Users.push_back(User);
8157     }
8158
8159     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8160       SDLoc DL(N);
8161       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8162       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8163
8164       // Dividend / Divisor -> Dividend * Reciprocal
8165       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8166         if ((*I)->getOperand(0) != FPOne) {
8167           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8168                                         (*I)->getOperand(0), Reciprocal);
8169           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8170         }
8171       }
8172       return SDValue();
8173     }
8174   }
8175
8176   return SDValue();
8177 }
8178
8179 SDValue DAGCombiner::visitFREM(SDNode *N) {
8180   SDValue N0 = N->getOperand(0);
8181   SDValue N1 = N->getOperand(1);
8182   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8183   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8184   EVT VT = N->getValueType(0);
8185
8186   // fold (frem c1, c2) -> fmod(c1,c2)
8187   if (N0CFP && N1CFP)
8188     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8189
8190   return SDValue();
8191 }
8192
8193 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8194   if (DAG.getTarget().Options.UnsafeFPMath &&
8195       !TLI.isFsqrtCheap()) {
8196     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8197     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8198       EVT VT = RV.getValueType();
8199       SDLoc DL(N);
8200       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8201       AddToWorklist(RV.getNode());
8202
8203       // Unfortunately, RV is now NaN if the input was exactly 0.
8204       // Select out this case and force the answer to 0.
8205       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8206       SDValue ZeroCmp =
8207         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8208                      N->getOperand(0), Zero, ISD::SETEQ);
8209       AddToWorklist(ZeroCmp.getNode());
8210       AddToWorklist(RV.getNode());
8211
8212       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8213                        DL, VT, ZeroCmp, Zero, RV);
8214       return RV;
8215     }
8216   }
8217   return SDValue();
8218 }
8219
8220 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8221   SDValue N0 = N->getOperand(0);
8222   SDValue N1 = N->getOperand(1);
8223   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8224   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8225   EVT VT = N->getValueType(0);
8226
8227   if (N0CFP && N1CFP)  // Constant fold
8228     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8229
8230   if (N1CFP) {
8231     const APFloat& V = N1CFP->getValueAPF();
8232     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8233     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8234     if (!V.isNegative()) {
8235       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8236         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8237     } else {
8238       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8239         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8240                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8241     }
8242   }
8243
8244   // copysign(fabs(x), y) -> copysign(x, y)
8245   // copysign(fneg(x), y) -> copysign(x, y)
8246   // copysign(copysign(x,z), y) -> copysign(x, y)
8247   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8248       N0.getOpcode() == ISD::FCOPYSIGN)
8249     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8250                        N0.getOperand(0), N1);
8251
8252   // copysign(x, abs(y)) -> abs(x)
8253   if (N1.getOpcode() == ISD::FABS)
8254     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8255
8256   // copysign(x, copysign(y,z)) -> copysign(x, z)
8257   if (N1.getOpcode() == ISD::FCOPYSIGN)
8258     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8259                        N0, N1.getOperand(1));
8260
8261   // copysign(x, fp_extend(y)) -> copysign(x, y)
8262   // copysign(x, fp_round(y)) -> copysign(x, y)
8263   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8264     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8265                        N0, N1.getOperand(0));
8266
8267   return SDValue();
8268 }
8269
8270 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8271   SDValue N0 = N->getOperand(0);
8272   EVT VT = N->getValueType(0);
8273   EVT OpVT = N0.getValueType();
8274
8275   // fold (sint_to_fp c1) -> c1fp
8276   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8277       // ...but only if the target supports immediate floating-point values
8278       (!LegalOperations ||
8279        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8280     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8281
8282   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8283   // but UINT_TO_FP is legal on this target, try to convert.
8284   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8285       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8286     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8287     if (DAG.SignBitIsZero(N0))
8288       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8289   }
8290
8291   // The next optimizations are desirable only if SELECT_CC can be lowered.
8292   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8293     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8294     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8295         !VT.isVector() &&
8296         (!LegalOperations ||
8297          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8298       SDLoc DL(N);
8299       SDValue Ops[] =
8300         { N0.getOperand(0), N0.getOperand(1),
8301           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8302           N0.getOperand(2) };
8303       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8304     }
8305
8306     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8307     //      (select_cc x, y, 1.0, 0.0,, cc)
8308     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8309         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8310         (!LegalOperations ||
8311          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8312       SDLoc DL(N);
8313       SDValue Ops[] =
8314         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8315           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8316           N0.getOperand(0).getOperand(2) };
8317       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8318     }
8319   }
8320
8321   return SDValue();
8322 }
8323
8324 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8325   SDValue N0 = N->getOperand(0);
8326   EVT VT = N->getValueType(0);
8327   EVT OpVT = N0.getValueType();
8328
8329   // fold (uint_to_fp c1) -> c1fp
8330   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8331       // ...but only if the target supports immediate floating-point values
8332       (!LegalOperations ||
8333        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8334     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8335
8336   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8337   // but SINT_TO_FP is legal on this target, try to convert.
8338   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8339       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8340     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8341     if (DAG.SignBitIsZero(N0))
8342       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8343   }
8344
8345   // The next optimizations are desirable only if SELECT_CC can be lowered.
8346   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8347     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8348
8349     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8350         (!LegalOperations ||
8351          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8352       SDLoc DL(N);
8353       SDValue Ops[] =
8354         { N0.getOperand(0), N0.getOperand(1),
8355           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8356           N0.getOperand(2) };
8357       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8358     }
8359   }
8360
8361   return SDValue();
8362 }
8363
8364 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8365 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8366   SDValue N0 = N->getOperand(0);
8367   EVT VT = N->getValueType(0);
8368
8369   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8370     return SDValue();
8371
8372   SDValue Src = N0.getOperand(0);
8373   EVT SrcVT = Src.getValueType();
8374   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8375   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8376
8377   // We can safely assume the conversion won't overflow the output range,
8378   // because (for example) (uint8_t)18293.f is undefined behavior.
8379
8380   // Since we can assume the conversion won't overflow, our decision as to
8381   // whether the input will fit in the float should depend on the minimum
8382   // of the input range and output range.
8383
8384   // This means this is also safe for a signed input and unsigned output, since
8385   // a negative input would lead to undefined behavior.
8386   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8387   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8388   unsigned ActualSize = std::min(InputSize, OutputSize);
8389   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8390
8391   // We can only fold away the float conversion if the input range can be
8392   // represented exactly in the float range.
8393   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8394     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8395       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8396                                                        : ISD::ZERO_EXTEND;
8397       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8398     }
8399     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8400       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8401     if (SrcVT == VT)
8402       return Src;
8403     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8404   }
8405   return SDValue();
8406 }
8407
8408 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8409   SDValue N0 = N->getOperand(0);
8410   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8411   EVT VT = N->getValueType(0);
8412
8413   // fold (fp_to_sint c1fp) -> c1
8414   if (N0CFP)
8415     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8416
8417   return FoldIntToFPToInt(N, DAG);
8418 }
8419
8420 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8421   SDValue N0 = N->getOperand(0);
8422   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8423   EVT VT = N->getValueType(0);
8424
8425   // fold (fp_to_uint c1fp) -> c1
8426   if (N0CFP)
8427     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8428
8429   return FoldIntToFPToInt(N, DAG);
8430 }
8431
8432 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8433   SDValue N0 = N->getOperand(0);
8434   SDValue N1 = N->getOperand(1);
8435   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8436   EVT VT = N->getValueType(0);
8437
8438   // fold (fp_round c1fp) -> c1fp
8439   if (N0CFP)
8440     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8441
8442   // fold (fp_round (fp_extend x)) -> x
8443   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8444     return N0.getOperand(0);
8445
8446   // fold (fp_round (fp_round x)) -> (fp_round x)
8447   if (N0.getOpcode() == ISD::FP_ROUND) {
8448     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8449     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8450     // If the first fp_round isn't a value preserving truncation, it might
8451     // introduce a tie in the second fp_round, that wouldn't occur in the
8452     // single-step fp_round we want to fold to.
8453     // In other words, double rounding isn't the same as rounding.
8454     // Also, this is a value preserving truncation iff both fp_round's are.
8455     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8456       SDLoc DL(N);
8457       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8458                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8459     }
8460   }
8461
8462   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8463   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8464     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8465                               N0.getOperand(0), N1);
8466     AddToWorklist(Tmp.getNode());
8467     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8468                        Tmp, N0.getOperand(1));
8469   }
8470
8471   return SDValue();
8472 }
8473
8474 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8475   SDValue N0 = N->getOperand(0);
8476   EVT VT = N->getValueType(0);
8477   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8478   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8479
8480   // fold (fp_round_inreg c1fp) -> c1fp
8481   if (N0CFP && isTypeLegal(EVT)) {
8482     SDLoc DL(N);
8483     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8484     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8485   }
8486
8487   return SDValue();
8488 }
8489
8490 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8491   SDValue N0 = N->getOperand(0);
8492   EVT VT = N->getValueType(0);
8493
8494   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8495   if (N->hasOneUse() &&
8496       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8497     return SDValue();
8498
8499   // fold (fp_extend c1fp) -> c1fp
8500   if (isConstantFPBuildVectorOrConstantFP(N0))
8501     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8502
8503   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8504   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8505       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8506     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8507
8508   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8509   // value of X.
8510   if (N0.getOpcode() == ISD::FP_ROUND
8511       && N0.getNode()->getConstantOperandVal(1) == 1) {
8512     SDValue In = N0.getOperand(0);
8513     if (In.getValueType() == VT) return In;
8514     if (VT.bitsLT(In.getValueType()))
8515       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8516                          In, N0.getOperand(1));
8517     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8518   }
8519
8520   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8521   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8522        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8523     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8524     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8525                                      LN0->getChain(),
8526                                      LN0->getBasePtr(), N0.getValueType(),
8527                                      LN0->getMemOperand());
8528     CombineTo(N, ExtLoad);
8529     CombineTo(N0.getNode(),
8530               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8531                           N0.getValueType(), ExtLoad,
8532                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8533               ExtLoad.getValue(1));
8534     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8535   }
8536
8537   return SDValue();
8538 }
8539
8540 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8541   SDValue N0 = N->getOperand(0);
8542   EVT VT = N->getValueType(0);
8543
8544   // fold (fceil c1) -> fceil(c1)
8545   if (isConstantFPBuildVectorOrConstantFP(N0))
8546     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8547
8548   return SDValue();
8549 }
8550
8551 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8552   SDValue N0 = N->getOperand(0);
8553   EVT VT = N->getValueType(0);
8554
8555   // fold (ftrunc c1) -> ftrunc(c1)
8556   if (isConstantFPBuildVectorOrConstantFP(N0))
8557     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8558
8559   return SDValue();
8560 }
8561
8562 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8563   SDValue N0 = N->getOperand(0);
8564   EVT VT = N->getValueType(0);
8565
8566   // fold (ffloor c1) -> ffloor(c1)
8567   if (isConstantFPBuildVectorOrConstantFP(N0))
8568     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8569
8570   return SDValue();
8571 }
8572
8573 // FIXME: FNEG and FABS have a lot in common; refactor.
8574 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8575   SDValue N0 = N->getOperand(0);
8576   EVT VT = N->getValueType(0);
8577
8578   // Constant fold FNEG.
8579   if (isConstantFPBuildVectorOrConstantFP(N0))
8580     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8581
8582   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8583                          &DAG.getTarget().Options))
8584     return GetNegatedExpression(N0, DAG, LegalOperations);
8585
8586   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8587   // constant pool values.
8588   if (!TLI.isFNegFree(VT) &&
8589       N0.getOpcode() == ISD::BITCAST &&
8590       N0.getNode()->hasOneUse()) {
8591     SDValue Int = N0.getOperand(0);
8592     EVT IntVT = Int.getValueType();
8593     if (IntVT.isInteger() && !IntVT.isVector()) {
8594       APInt SignMask;
8595       if (N0.getValueType().isVector()) {
8596         // For a vector, get a mask such as 0x80... per scalar element
8597         // and splat it.
8598         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8599         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8600       } else {
8601         // For a scalar, just generate 0x80...
8602         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8603       }
8604       SDLoc DL0(N0);
8605       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8606                         DAG.getConstant(SignMask, DL0, IntVT));
8607       AddToWorklist(Int.getNode());
8608       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8609     }
8610   }
8611
8612   // (fneg (fmul c, x)) -> (fmul -c, x)
8613   if (N0.getOpcode() == ISD::FMUL) {
8614     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8615     if (CFP1) {
8616       APFloat CVal = CFP1->getValueAPF();
8617       CVal.changeSign();
8618       if (Level >= AfterLegalizeDAG &&
8619           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8620            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8621         return DAG.getNode(
8622             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8623             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8624     }
8625   }
8626
8627   return SDValue();
8628 }
8629
8630 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8631   SDValue N0 = N->getOperand(0);
8632   SDValue N1 = N->getOperand(1);
8633   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8634   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8635
8636   if (N0CFP && N1CFP) {
8637     const APFloat &C0 = N0CFP->getValueAPF();
8638     const APFloat &C1 = N1CFP->getValueAPF();
8639     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8640   }
8641
8642   if (N0CFP) {
8643     EVT VT = N->getValueType(0);
8644     // Canonicalize to constant on RHS.
8645     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8646   }
8647
8648   return SDValue();
8649 }
8650
8651 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8652   SDValue N0 = N->getOperand(0);
8653   SDValue N1 = N->getOperand(1);
8654   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8655   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8656
8657   if (N0CFP && N1CFP) {
8658     const APFloat &C0 = N0CFP->getValueAPF();
8659     const APFloat &C1 = N1CFP->getValueAPF();
8660     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8661   }
8662
8663   if (N0CFP) {
8664     EVT VT = N->getValueType(0);
8665     // Canonicalize to constant on RHS.
8666     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8667   }
8668
8669   return SDValue();
8670 }
8671
8672 SDValue DAGCombiner::visitFABS(SDNode *N) {
8673   SDValue N0 = N->getOperand(0);
8674   EVT VT = N->getValueType(0);
8675
8676   // fold (fabs c1) -> fabs(c1)
8677   if (isConstantFPBuildVectorOrConstantFP(N0))
8678     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8679
8680   // fold (fabs (fabs x)) -> (fabs x)
8681   if (N0.getOpcode() == ISD::FABS)
8682     return N->getOperand(0);
8683
8684   // fold (fabs (fneg x)) -> (fabs x)
8685   // fold (fabs (fcopysign x, y)) -> (fabs x)
8686   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8687     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8688
8689   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8690   // constant pool values.
8691   if (!TLI.isFAbsFree(VT) &&
8692       N0.getOpcode() == ISD::BITCAST &&
8693       N0.getNode()->hasOneUse()) {
8694     SDValue Int = N0.getOperand(0);
8695     EVT IntVT = Int.getValueType();
8696     if (IntVT.isInteger() && !IntVT.isVector()) {
8697       APInt SignMask;
8698       if (N0.getValueType().isVector()) {
8699         // For a vector, get a mask such as 0x7f... per scalar element
8700         // and splat it.
8701         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8702         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8703       } else {
8704         // For a scalar, just generate 0x7f...
8705         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8706       }
8707       SDLoc DL(N0);
8708       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8709                         DAG.getConstant(SignMask, DL, IntVT));
8710       AddToWorklist(Int.getNode());
8711       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8712     }
8713   }
8714
8715   return SDValue();
8716 }
8717
8718 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8719   SDValue Chain = N->getOperand(0);
8720   SDValue N1 = N->getOperand(1);
8721   SDValue N2 = N->getOperand(2);
8722
8723   // If N is a constant we could fold this into a fallthrough or unconditional
8724   // branch. However that doesn't happen very often in normal code, because
8725   // Instcombine/SimplifyCFG should have handled the available opportunities.
8726   // If we did this folding here, it would be necessary to update the
8727   // MachineBasicBlock CFG, which is awkward.
8728
8729   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8730   // on the target.
8731   if (N1.getOpcode() == ISD::SETCC &&
8732       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8733                                    N1.getOperand(0).getValueType())) {
8734     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8735                        Chain, N1.getOperand(2),
8736                        N1.getOperand(0), N1.getOperand(1), N2);
8737   }
8738
8739   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8740       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8741        (N1.getOperand(0).hasOneUse() &&
8742         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8743     SDNode *Trunc = nullptr;
8744     if (N1.getOpcode() == ISD::TRUNCATE) {
8745       // Look pass the truncate.
8746       Trunc = N1.getNode();
8747       N1 = N1.getOperand(0);
8748     }
8749
8750     // Match this pattern so that we can generate simpler code:
8751     //
8752     //   %a = ...
8753     //   %b = and i32 %a, 2
8754     //   %c = srl i32 %b, 1
8755     //   brcond i32 %c ...
8756     //
8757     // into
8758     //
8759     //   %a = ...
8760     //   %b = and i32 %a, 2
8761     //   %c = setcc eq %b, 0
8762     //   brcond %c ...
8763     //
8764     // This applies only when the AND constant value has one bit set and the
8765     // SRL constant is equal to the log2 of the AND constant. The back-end is
8766     // smart enough to convert the result into a TEST/JMP sequence.
8767     SDValue Op0 = N1.getOperand(0);
8768     SDValue Op1 = N1.getOperand(1);
8769
8770     if (Op0.getOpcode() == ISD::AND &&
8771         Op1.getOpcode() == ISD::Constant) {
8772       SDValue AndOp1 = Op0.getOperand(1);
8773
8774       if (AndOp1.getOpcode() == ISD::Constant) {
8775         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8776
8777         if (AndConst.isPowerOf2() &&
8778             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8779           SDLoc DL(N);
8780           SDValue SetCC =
8781             DAG.getSetCC(DL,
8782                          getSetCCResultType(Op0.getValueType()),
8783                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8784                          ISD::SETNE);
8785
8786           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8787                                           MVT::Other, Chain, SetCC, N2);
8788           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8789           // will convert it back to (X & C1) >> C2.
8790           CombineTo(N, NewBRCond, false);
8791           // Truncate is dead.
8792           if (Trunc)
8793             deleteAndRecombine(Trunc);
8794           // Replace the uses of SRL with SETCC
8795           WorklistRemover DeadNodes(*this);
8796           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8797           deleteAndRecombine(N1.getNode());
8798           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8799         }
8800       }
8801     }
8802
8803     if (Trunc)
8804       // Restore N1 if the above transformation doesn't match.
8805       N1 = N->getOperand(1);
8806   }
8807
8808   // Transform br(xor(x, y)) -> br(x != y)
8809   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8810   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8811     SDNode *TheXor = N1.getNode();
8812     SDValue Op0 = TheXor->getOperand(0);
8813     SDValue Op1 = TheXor->getOperand(1);
8814     if (Op0.getOpcode() == Op1.getOpcode()) {
8815       // Avoid missing important xor optimizations.
8816       SDValue Tmp = visitXOR(TheXor);
8817       if (Tmp.getNode()) {
8818         if (Tmp.getNode() != TheXor) {
8819           DEBUG(dbgs() << "\nReplacing.8 ";
8820                 TheXor->dump(&DAG);
8821                 dbgs() << "\nWith: ";
8822                 Tmp.getNode()->dump(&DAG);
8823                 dbgs() << '\n');
8824           WorklistRemover DeadNodes(*this);
8825           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8826           deleteAndRecombine(TheXor);
8827           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8828                              MVT::Other, Chain, Tmp, N2);
8829         }
8830
8831         // visitXOR has changed XOR's operands or replaced the XOR completely,
8832         // bail out.
8833         return SDValue(N, 0);
8834       }
8835     }
8836
8837     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8838       bool Equal = false;
8839       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8840         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8841             Op0.getOpcode() == ISD::XOR) {
8842           TheXor = Op0.getNode();
8843           Equal = true;
8844         }
8845
8846       EVT SetCCVT = N1.getValueType();
8847       if (LegalTypes)
8848         SetCCVT = getSetCCResultType(SetCCVT);
8849       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8850                                    SetCCVT,
8851                                    Op0, Op1,
8852                                    Equal ? ISD::SETEQ : ISD::SETNE);
8853       // Replace the uses of XOR with SETCC
8854       WorklistRemover DeadNodes(*this);
8855       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8856       deleteAndRecombine(N1.getNode());
8857       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8858                          MVT::Other, Chain, SetCC, N2);
8859     }
8860   }
8861
8862   return SDValue();
8863 }
8864
8865 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8866 //
8867 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8868   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8869   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8870
8871   // If N is a constant we could fold this into a fallthrough or unconditional
8872   // branch. However that doesn't happen very often in normal code, because
8873   // Instcombine/SimplifyCFG should have handled the available opportunities.
8874   // If we did this folding here, it would be necessary to update the
8875   // MachineBasicBlock CFG, which is awkward.
8876
8877   // Use SimplifySetCC to simplify SETCC's.
8878   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8879                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8880                                false);
8881   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8882
8883   // fold to a simpler setcc
8884   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8885     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8886                        N->getOperand(0), Simp.getOperand(2),
8887                        Simp.getOperand(0), Simp.getOperand(1),
8888                        N->getOperand(4));
8889
8890   return SDValue();
8891 }
8892
8893 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8894 /// and that N may be folded in the load / store addressing mode.
8895 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8896                                     SelectionDAG &DAG,
8897                                     const TargetLowering &TLI) {
8898   EVT VT;
8899   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8900     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8901       return false;
8902     VT = LD->getMemoryVT();
8903   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8904     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8905       return false;
8906     VT = ST->getMemoryVT();
8907   } else
8908     return false;
8909
8910   TargetLowering::AddrMode AM;
8911   if (N->getOpcode() == ISD::ADD) {
8912     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8913     if (Offset)
8914       // [reg +/- imm]
8915       AM.BaseOffs = Offset->getSExtValue();
8916     else
8917       // [reg +/- reg]
8918       AM.Scale = 1;
8919   } else if (N->getOpcode() == ISD::SUB) {
8920     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8921     if (Offset)
8922       // [reg +/- imm]
8923       AM.BaseOffs = -Offset->getSExtValue();
8924     else
8925       // [reg +/- reg]
8926       AM.Scale = 1;
8927   } else
8928     return false;
8929
8930   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8931 }
8932
8933 /// Try turning a load/store into a pre-indexed load/store when the base
8934 /// pointer is an add or subtract and it has other uses besides the load/store.
8935 /// After the transformation, the new indexed load/store has effectively folded
8936 /// the add/subtract in and all of its other uses are redirected to the
8937 /// new load/store.
8938 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8939   if (Level < AfterLegalizeDAG)
8940     return false;
8941
8942   bool isLoad = true;
8943   SDValue Ptr;
8944   EVT VT;
8945   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8946     if (LD->isIndexed())
8947       return false;
8948     VT = LD->getMemoryVT();
8949     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8950         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8951       return false;
8952     Ptr = LD->getBasePtr();
8953   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8954     if (ST->isIndexed())
8955       return false;
8956     VT = ST->getMemoryVT();
8957     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8958         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8959       return false;
8960     Ptr = ST->getBasePtr();
8961     isLoad = false;
8962   } else {
8963     return false;
8964   }
8965
8966   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8967   // out.  There is no reason to make this a preinc/predec.
8968   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8969       Ptr.getNode()->hasOneUse())
8970     return false;
8971
8972   // Ask the target to do addressing mode selection.
8973   SDValue BasePtr;
8974   SDValue Offset;
8975   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8976   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8977     return false;
8978
8979   // Backends without true r+i pre-indexed forms may need to pass a
8980   // constant base with a variable offset so that constant coercion
8981   // will work with the patterns in canonical form.
8982   bool Swapped = false;
8983   if (isa<ConstantSDNode>(BasePtr)) {
8984     std::swap(BasePtr, Offset);
8985     Swapped = true;
8986   }
8987
8988   // Don't create a indexed load / store with zero offset.
8989   if (isa<ConstantSDNode>(Offset) &&
8990       cast<ConstantSDNode>(Offset)->isNullValue())
8991     return false;
8992
8993   // Try turning it into a pre-indexed load / store except when:
8994   // 1) The new base ptr is a frame index.
8995   // 2) If N is a store and the new base ptr is either the same as or is a
8996   //    predecessor of the value being stored.
8997   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8998   //    that would create a cycle.
8999   // 4) All uses are load / store ops that use it as old base ptr.
9000
9001   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9002   // (plus the implicit offset) to a register to preinc anyway.
9003   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9004     return false;
9005
9006   // Check #2.
9007   if (!isLoad) {
9008     SDValue Val = cast<StoreSDNode>(N)->getValue();
9009     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9010       return false;
9011   }
9012
9013   // If the offset is a constant, there may be other adds of constants that
9014   // can be folded with this one. We should do this to avoid having to keep
9015   // a copy of the original base pointer.
9016   SmallVector<SDNode *, 16> OtherUses;
9017   if (isa<ConstantSDNode>(Offset))
9018     for (SDNode *Use : BasePtr.getNode()->uses()) {
9019       if (Use == Ptr.getNode())
9020         continue;
9021
9022       if (Use->isPredecessorOf(N))
9023         continue;
9024
9025       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
9026         OtherUses.clear();
9027         break;
9028       }
9029
9030       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
9031       if (Op1.getNode() == BasePtr.getNode())
9032         std::swap(Op0, Op1);
9033       assert(Op0.getNode() == BasePtr.getNode() &&
9034              "Use of ADD/SUB but not an operand");
9035
9036       if (!isa<ConstantSDNode>(Op1)) {
9037         OtherUses.clear();
9038         break;
9039       }
9040
9041       // FIXME: In some cases, we can be smarter about this.
9042       if (Op1.getValueType() != Offset.getValueType()) {
9043         OtherUses.clear();
9044         break;
9045       }
9046
9047       OtherUses.push_back(Use);
9048     }
9049
9050   if (Swapped)
9051     std::swap(BasePtr, Offset);
9052
9053   // Now check for #3 and #4.
9054   bool RealUse = false;
9055
9056   // Caches for hasPredecessorHelper
9057   SmallPtrSet<const SDNode *, 32> Visited;
9058   SmallVector<const SDNode *, 16> Worklist;
9059
9060   for (SDNode *Use : Ptr.getNode()->uses()) {
9061     if (Use == N)
9062       continue;
9063     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9064       return false;
9065
9066     // If Ptr may be folded in addressing mode of other use, then it's
9067     // not profitable to do this transformation.
9068     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9069       RealUse = true;
9070   }
9071
9072   if (!RealUse)
9073     return false;
9074
9075   SDValue Result;
9076   if (isLoad)
9077     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9078                                 BasePtr, Offset, AM);
9079   else
9080     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9081                                  BasePtr, Offset, AM);
9082   ++PreIndexedNodes;
9083   ++NodesCombined;
9084   DEBUG(dbgs() << "\nReplacing.4 ";
9085         N->dump(&DAG);
9086         dbgs() << "\nWith: ";
9087         Result.getNode()->dump(&DAG);
9088         dbgs() << '\n');
9089   WorklistRemover DeadNodes(*this);
9090   if (isLoad) {
9091     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9092     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9093   } else {
9094     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9095   }
9096
9097   // Finally, since the node is now dead, remove it from the graph.
9098   deleteAndRecombine(N);
9099
9100   if (Swapped)
9101     std::swap(BasePtr, Offset);
9102
9103   // Replace other uses of BasePtr that can be updated to use Ptr
9104   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9105     unsigned OffsetIdx = 1;
9106     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9107       OffsetIdx = 0;
9108     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9109            BasePtr.getNode() && "Expected BasePtr operand");
9110
9111     // We need to replace ptr0 in the following expression:
9112     //   x0 * offset0 + y0 * ptr0 = t0
9113     // knowing that
9114     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9115     //
9116     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9117     // indexed load/store and the expresion that needs to be re-written.
9118     //
9119     // Therefore, we have:
9120     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9121
9122     ConstantSDNode *CN =
9123       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9124     int X0, X1, Y0, Y1;
9125     APInt Offset0 = CN->getAPIntValue();
9126     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9127
9128     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9129     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9130     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9131     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9132
9133     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9134
9135     APInt CNV = Offset0;
9136     if (X0 < 0) CNV = -CNV;
9137     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9138     else CNV = CNV - Offset1;
9139
9140     SDLoc DL(OtherUses[i]);
9141
9142     // We can now generate the new expression.
9143     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9144     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9145
9146     SDValue NewUse = DAG.getNode(Opcode,
9147                                  DL,
9148                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9149     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9150     deleteAndRecombine(OtherUses[i]);
9151   }
9152
9153   // Replace the uses of Ptr with uses of the updated base value.
9154   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9155   deleteAndRecombine(Ptr.getNode());
9156
9157   return true;
9158 }
9159
9160 /// Try to combine a load/store with a add/sub of the base pointer node into a
9161 /// post-indexed load/store. The transformation folded the add/subtract into the
9162 /// new indexed load/store effectively and all of its uses are redirected to the
9163 /// new load/store.
9164 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9165   if (Level < AfterLegalizeDAG)
9166     return false;
9167
9168   bool isLoad = true;
9169   SDValue Ptr;
9170   EVT VT;
9171   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9172     if (LD->isIndexed())
9173       return false;
9174     VT = LD->getMemoryVT();
9175     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9176         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9177       return false;
9178     Ptr = LD->getBasePtr();
9179   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9180     if (ST->isIndexed())
9181       return false;
9182     VT = ST->getMemoryVT();
9183     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9184         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9185       return false;
9186     Ptr = ST->getBasePtr();
9187     isLoad = false;
9188   } else {
9189     return false;
9190   }
9191
9192   if (Ptr.getNode()->hasOneUse())
9193     return false;
9194
9195   for (SDNode *Op : Ptr.getNode()->uses()) {
9196     if (Op == N ||
9197         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9198       continue;
9199
9200     SDValue BasePtr;
9201     SDValue Offset;
9202     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9203     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9204       // Don't create a indexed load / store with zero offset.
9205       if (isa<ConstantSDNode>(Offset) &&
9206           cast<ConstantSDNode>(Offset)->isNullValue())
9207         continue;
9208
9209       // Try turning it into a post-indexed load / store except when
9210       // 1) All uses are load / store ops that use it as base ptr (and
9211       //    it may be folded as addressing mmode).
9212       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9213       //    nor a successor of N. Otherwise, if Op is folded that would
9214       //    create a cycle.
9215
9216       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9217         continue;
9218
9219       // Check for #1.
9220       bool TryNext = false;
9221       for (SDNode *Use : BasePtr.getNode()->uses()) {
9222         if (Use == Ptr.getNode())
9223           continue;
9224
9225         // If all the uses are load / store addresses, then don't do the
9226         // transformation.
9227         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9228           bool RealUse = false;
9229           for (SDNode *UseUse : Use->uses()) {
9230             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9231               RealUse = true;
9232           }
9233
9234           if (!RealUse) {
9235             TryNext = true;
9236             break;
9237           }
9238         }
9239       }
9240
9241       if (TryNext)
9242         continue;
9243
9244       // Check for #2
9245       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9246         SDValue Result = isLoad
9247           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9248                                BasePtr, Offset, AM)
9249           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9250                                 BasePtr, Offset, AM);
9251         ++PostIndexedNodes;
9252         ++NodesCombined;
9253         DEBUG(dbgs() << "\nReplacing.5 ";
9254               N->dump(&DAG);
9255               dbgs() << "\nWith: ";
9256               Result.getNode()->dump(&DAG);
9257               dbgs() << '\n');
9258         WorklistRemover DeadNodes(*this);
9259         if (isLoad) {
9260           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9261           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9262         } else {
9263           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9264         }
9265
9266         // Finally, since the node is now dead, remove it from the graph.
9267         deleteAndRecombine(N);
9268
9269         // Replace the uses of Use with uses of the updated base value.
9270         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9271                                       Result.getValue(isLoad ? 1 : 0));
9272         deleteAndRecombine(Op);
9273         return true;
9274       }
9275     }
9276   }
9277
9278   return false;
9279 }
9280
9281 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9282 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9283   ISD::MemIndexedMode AM = LD->getAddressingMode();
9284   assert(AM != ISD::UNINDEXED);
9285   SDValue BP = LD->getOperand(1);
9286   SDValue Inc = LD->getOperand(2);
9287
9288   // Some backends use TargetConstants for load offsets, but don't expect
9289   // TargetConstants in general ADD nodes. We can convert these constants into
9290   // regular Constants (if the constant is not opaque).
9291   assert((Inc.getOpcode() != ISD::TargetConstant ||
9292           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9293          "Cannot split out indexing using opaque target constants");
9294   if (Inc.getOpcode() == ISD::TargetConstant) {
9295     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9296     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9297                           ConstInc->getValueType(0));
9298   }
9299
9300   unsigned Opc =
9301       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9302   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9303 }
9304
9305 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9306   LoadSDNode *LD  = cast<LoadSDNode>(N);
9307   SDValue Chain = LD->getChain();
9308   SDValue Ptr   = LD->getBasePtr();
9309
9310   // If load is not volatile and there are no uses of the loaded value (and
9311   // the updated indexed value in case of indexed loads), change uses of the
9312   // chain value into uses of the chain input (i.e. delete the dead load).
9313   if (!LD->isVolatile()) {
9314     if (N->getValueType(1) == MVT::Other) {
9315       // Unindexed loads.
9316       if (!N->hasAnyUseOfValue(0)) {
9317         // It's not safe to use the two value CombineTo variant here. e.g.
9318         // v1, chain2 = load chain1, loc
9319         // v2, chain3 = load chain2, loc
9320         // v3         = add v2, c
9321         // Now we replace use of chain2 with chain1.  This makes the second load
9322         // isomorphic to the one we are deleting, and thus makes this load live.
9323         DEBUG(dbgs() << "\nReplacing.6 ";
9324               N->dump(&DAG);
9325               dbgs() << "\nWith chain: ";
9326               Chain.getNode()->dump(&DAG);
9327               dbgs() << "\n");
9328         WorklistRemover DeadNodes(*this);
9329         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9330
9331         if (N->use_empty())
9332           deleteAndRecombine(N);
9333
9334         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9335       }
9336     } else {
9337       // Indexed loads.
9338       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9339
9340       // If this load has an opaque TargetConstant offset, then we cannot split
9341       // the indexing into an add/sub directly (that TargetConstant may not be
9342       // valid for a different type of node, and we cannot convert an opaque
9343       // target constant into a regular constant).
9344       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9345                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9346
9347       if (!N->hasAnyUseOfValue(0) &&
9348           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9349         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9350         SDValue Index;
9351         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9352           Index = SplitIndexingFromLoad(LD);
9353           // Try to fold the base pointer arithmetic into subsequent loads and
9354           // stores.
9355           AddUsersToWorklist(N);
9356         } else
9357           Index = DAG.getUNDEF(N->getValueType(1));
9358         DEBUG(dbgs() << "\nReplacing.7 ";
9359               N->dump(&DAG);
9360               dbgs() << "\nWith: ";
9361               Undef.getNode()->dump(&DAG);
9362               dbgs() << " and 2 other values\n");
9363         WorklistRemover DeadNodes(*this);
9364         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9365         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9366         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9367         deleteAndRecombine(N);
9368         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9369       }
9370     }
9371   }
9372
9373   // If this load is directly stored, replace the load value with the stored
9374   // value.
9375   // TODO: Handle store large -> read small portion.
9376   // TODO: Handle TRUNCSTORE/LOADEXT
9377   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9378     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9379       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9380       if (PrevST->getBasePtr() == Ptr &&
9381           PrevST->getValue().getValueType() == N->getValueType(0))
9382       return CombineTo(N, Chain.getOperand(1), Chain);
9383     }
9384   }
9385
9386   // Try to infer better alignment information than the load already has.
9387   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9388     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9389       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9390         SDValue NewLoad =
9391                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9392                               LD->getValueType(0),
9393                               Chain, Ptr, LD->getPointerInfo(),
9394                               LD->getMemoryVT(),
9395                               LD->isVolatile(), LD->isNonTemporal(),
9396                               LD->isInvariant(), Align, LD->getAAInfo());
9397         if (NewLoad.getNode() != N)
9398           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9399       }
9400     }
9401   }
9402
9403   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9404                                                   : DAG.getSubtarget().useAA();
9405 #ifndef NDEBUG
9406   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9407       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9408     UseAA = false;
9409 #endif
9410   if (UseAA && LD->isUnindexed()) {
9411     // Walk up chain skipping non-aliasing memory nodes.
9412     SDValue BetterChain = FindBetterChain(N, Chain);
9413
9414     // If there is a better chain.
9415     if (Chain != BetterChain) {
9416       SDValue ReplLoad;
9417
9418       // Replace the chain to void dependency.
9419       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9420         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9421                                BetterChain, Ptr, LD->getMemOperand());
9422       } else {
9423         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9424                                   LD->getValueType(0),
9425                                   BetterChain, Ptr, LD->getMemoryVT(),
9426                                   LD->getMemOperand());
9427       }
9428
9429       // Create token factor to keep old chain connected.
9430       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9431                                   MVT::Other, Chain, ReplLoad.getValue(1));
9432
9433       // Make sure the new and old chains are cleaned up.
9434       AddToWorklist(Token.getNode());
9435
9436       // Replace uses with load result and token factor. Don't add users
9437       // to work list.
9438       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9439     }
9440   }
9441
9442   // Try transforming N to an indexed load.
9443   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9444     return SDValue(N, 0);
9445
9446   // Try to slice up N to more direct loads if the slices are mapped to
9447   // different register banks or pairing can take place.
9448   if (SliceUpLoad(N))
9449     return SDValue(N, 0);
9450
9451   return SDValue();
9452 }
9453
9454 namespace {
9455 /// \brief Helper structure used to slice a load in smaller loads.
9456 /// Basically a slice is obtained from the following sequence:
9457 /// Origin = load Ty1, Base
9458 /// Shift = srl Ty1 Origin, CstTy Amount
9459 /// Inst = trunc Shift to Ty2
9460 ///
9461 /// Then, it will be rewriten into:
9462 /// Slice = load SliceTy, Base + SliceOffset
9463 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9464 ///
9465 /// SliceTy is deduced from the number of bits that are actually used to
9466 /// build Inst.
9467 struct LoadedSlice {
9468   /// \brief Helper structure used to compute the cost of a slice.
9469   struct Cost {
9470     /// Are we optimizing for code size.
9471     bool ForCodeSize;
9472     /// Various cost.
9473     unsigned Loads;
9474     unsigned Truncates;
9475     unsigned CrossRegisterBanksCopies;
9476     unsigned ZExts;
9477     unsigned Shift;
9478
9479     Cost(bool ForCodeSize = false)
9480         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9481           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9482
9483     /// \brief Get the cost of one isolated slice.
9484     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9485         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9486           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9487       EVT TruncType = LS.Inst->getValueType(0);
9488       EVT LoadedType = LS.getLoadedType();
9489       if (TruncType != LoadedType &&
9490           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9491         ZExts = 1;
9492     }
9493
9494     /// \brief Account for slicing gain in the current cost.
9495     /// Slicing provide a few gains like removing a shift or a
9496     /// truncate. This method allows to grow the cost of the original
9497     /// load with the gain from this slice.
9498     void addSliceGain(const LoadedSlice &LS) {
9499       // Each slice saves a truncate.
9500       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9501       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9502                               LS.Inst->getOperand(0).getValueType()))
9503         ++Truncates;
9504       // If there is a shift amount, this slice gets rid of it.
9505       if (LS.Shift)
9506         ++Shift;
9507       // If this slice can merge a cross register bank copy, account for it.
9508       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9509         ++CrossRegisterBanksCopies;
9510     }
9511
9512     Cost &operator+=(const Cost &RHS) {
9513       Loads += RHS.Loads;
9514       Truncates += RHS.Truncates;
9515       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9516       ZExts += RHS.ZExts;
9517       Shift += RHS.Shift;
9518       return *this;
9519     }
9520
9521     bool operator==(const Cost &RHS) const {
9522       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9523              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9524              ZExts == RHS.ZExts && Shift == RHS.Shift;
9525     }
9526
9527     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9528
9529     bool operator<(const Cost &RHS) const {
9530       // Assume cross register banks copies are as expensive as loads.
9531       // FIXME: Do we want some more target hooks?
9532       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9533       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9534       // Unless we are optimizing for code size, consider the
9535       // expensive operation first.
9536       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9537         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9538       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9539              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9540     }
9541
9542     bool operator>(const Cost &RHS) const { return RHS < *this; }
9543
9544     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9545
9546     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9547   };
9548   // The last instruction that represent the slice. This should be a
9549   // truncate instruction.
9550   SDNode *Inst;
9551   // The original load instruction.
9552   LoadSDNode *Origin;
9553   // The right shift amount in bits from the original load.
9554   unsigned Shift;
9555   // The DAG from which Origin came from.
9556   // This is used to get some contextual information about legal types, etc.
9557   SelectionDAG *DAG;
9558
9559   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9560               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9561       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9562
9563   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9564   /// \return Result is \p BitWidth and has used bits set to 1 and
9565   ///         not used bits set to 0.
9566   APInt getUsedBits() const {
9567     // Reproduce the trunc(lshr) sequence:
9568     // - Start from the truncated value.
9569     // - Zero extend to the desired bit width.
9570     // - Shift left.
9571     assert(Origin && "No original load to compare against.");
9572     unsigned BitWidth = Origin->getValueSizeInBits(0);
9573     assert(Inst && "This slice is not bound to an instruction");
9574     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9575            "Extracted slice is bigger than the whole type!");
9576     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9577     UsedBits.setAllBits();
9578     UsedBits = UsedBits.zext(BitWidth);
9579     UsedBits <<= Shift;
9580     return UsedBits;
9581   }
9582
9583   /// \brief Get the size of the slice to be loaded in bytes.
9584   unsigned getLoadedSize() const {
9585     unsigned SliceSize = getUsedBits().countPopulation();
9586     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9587     return SliceSize / 8;
9588   }
9589
9590   /// \brief Get the type that will be loaded for this slice.
9591   /// Note: This may not be the final type for the slice.
9592   EVT getLoadedType() const {
9593     assert(DAG && "Missing context");
9594     LLVMContext &Ctxt = *DAG->getContext();
9595     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9596   }
9597
9598   /// \brief Get the alignment of the load used for this slice.
9599   unsigned getAlignment() const {
9600     unsigned Alignment = Origin->getAlignment();
9601     unsigned Offset = getOffsetFromBase();
9602     if (Offset != 0)
9603       Alignment = MinAlign(Alignment, Alignment + Offset);
9604     return Alignment;
9605   }
9606
9607   /// \brief Check if this slice can be rewritten with legal operations.
9608   bool isLegal() const {
9609     // An invalid slice is not legal.
9610     if (!Origin || !Inst || !DAG)
9611       return false;
9612
9613     // Offsets are for indexed load only, we do not handle that.
9614     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9615       return false;
9616
9617     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9618
9619     // Check that the type is legal.
9620     EVT SliceType = getLoadedType();
9621     if (!TLI.isTypeLegal(SliceType))
9622       return false;
9623
9624     // Check that the load is legal for this type.
9625     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9626       return false;
9627
9628     // Check that the offset can be computed.
9629     // 1. Check its type.
9630     EVT PtrType = Origin->getBasePtr().getValueType();
9631     if (PtrType == MVT::Untyped || PtrType.isExtended())
9632       return false;
9633
9634     // 2. Check that it fits in the immediate.
9635     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9636       return false;
9637
9638     // 3. Check that the computation is legal.
9639     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9640       return false;
9641
9642     // Check that the zext is legal if it needs one.
9643     EVT TruncateType = Inst->getValueType(0);
9644     if (TruncateType != SliceType &&
9645         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9646       return false;
9647
9648     return true;
9649   }
9650
9651   /// \brief Get the offset in bytes of this slice in the original chunk of
9652   /// bits.
9653   /// \pre DAG != nullptr.
9654   uint64_t getOffsetFromBase() const {
9655     assert(DAG && "Missing context.");
9656     bool IsBigEndian =
9657         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9658     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9659     uint64_t Offset = Shift / 8;
9660     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9661     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9662            "The size of the original loaded type is not a multiple of a"
9663            " byte.");
9664     // If Offset is bigger than TySizeInBytes, it means we are loading all
9665     // zeros. This should have been optimized before in the process.
9666     assert(TySizeInBytes > Offset &&
9667            "Invalid shift amount for given loaded size");
9668     if (IsBigEndian)
9669       Offset = TySizeInBytes - Offset - getLoadedSize();
9670     return Offset;
9671   }
9672
9673   /// \brief Generate the sequence of instructions to load the slice
9674   /// represented by this object and redirect the uses of this slice to
9675   /// this new sequence of instructions.
9676   /// \pre this->Inst && this->Origin are valid Instructions and this
9677   /// object passed the legal check: LoadedSlice::isLegal returned true.
9678   /// \return The last instruction of the sequence used to load the slice.
9679   SDValue loadSlice() const {
9680     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9681     const SDValue &OldBaseAddr = Origin->getBasePtr();
9682     SDValue BaseAddr = OldBaseAddr;
9683     // Get the offset in that chunk of bytes w.r.t. the endianess.
9684     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9685     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9686     if (Offset) {
9687       // BaseAddr = BaseAddr + Offset.
9688       EVT ArithType = BaseAddr.getValueType();
9689       SDLoc DL(Origin);
9690       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9691                               DAG->getConstant(Offset, DL, ArithType));
9692     }
9693
9694     // Create the type of the loaded slice according to its size.
9695     EVT SliceType = getLoadedType();
9696
9697     // Create the load for the slice.
9698     SDValue LastInst = DAG->getLoad(
9699         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9700         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9701         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9702     // If the final type is not the same as the loaded type, this means that
9703     // we have to pad with zero. Create a zero extend for that.
9704     EVT FinalType = Inst->getValueType(0);
9705     if (SliceType != FinalType)
9706       LastInst =
9707           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9708     return LastInst;
9709   }
9710
9711   /// \brief Check if this slice can be merged with an expensive cross register
9712   /// bank copy. E.g.,
9713   /// i = load i32
9714   /// f = bitcast i32 i to float
9715   bool canMergeExpensiveCrossRegisterBankCopy() const {
9716     if (!Inst || !Inst->hasOneUse())
9717       return false;
9718     SDNode *Use = *Inst->use_begin();
9719     if (Use->getOpcode() != ISD::BITCAST)
9720       return false;
9721     assert(DAG && "Missing context");
9722     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9723     EVT ResVT = Use->getValueType(0);
9724     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9725     const TargetRegisterClass *ArgRC =
9726         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9727     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9728       return false;
9729
9730     // At this point, we know that we perform a cross-register-bank copy.
9731     // Check if it is expensive.
9732     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9733     // Assume bitcasts are cheap, unless both register classes do not
9734     // explicitly share a common sub class.
9735     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9736       return false;
9737
9738     // Check if it will be merged with the load.
9739     // 1. Check the alignment constraint.
9740     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9741         ResVT.getTypeForEVT(*DAG->getContext()));
9742
9743     if (RequiredAlignment > getAlignment())
9744       return false;
9745
9746     // 2. Check that the load is a legal operation for that type.
9747     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9748       return false;
9749
9750     // 3. Check that we do not have a zext in the way.
9751     if (Inst->getValueType(0) != getLoadedType())
9752       return false;
9753
9754     return true;
9755   }
9756 };
9757 }
9758
9759 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9760 /// \p UsedBits looks like 0..0 1..1 0..0.
9761 static bool areUsedBitsDense(const APInt &UsedBits) {
9762   // If all the bits are one, this is dense!
9763   if (UsedBits.isAllOnesValue())
9764     return true;
9765
9766   // Get rid of the unused bits on the right.
9767   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9768   // Get rid of the unused bits on the left.
9769   if (NarrowedUsedBits.countLeadingZeros())
9770     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9771   // Check that the chunk of bits is completely used.
9772   return NarrowedUsedBits.isAllOnesValue();
9773 }
9774
9775 /// \brief Check whether or not \p First and \p Second are next to each other
9776 /// in memory. This means that there is no hole between the bits loaded
9777 /// by \p First and the bits loaded by \p Second.
9778 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9779                                      const LoadedSlice &Second) {
9780   assert(First.Origin == Second.Origin && First.Origin &&
9781          "Unable to match different memory origins.");
9782   APInt UsedBits = First.getUsedBits();
9783   assert((UsedBits & Second.getUsedBits()) == 0 &&
9784          "Slices are not supposed to overlap.");
9785   UsedBits |= Second.getUsedBits();
9786   return areUsedBitsDense(UsedBits);
9787 }
9788
9789 /// \brief Adjust the \p GlobalLSCost according to the target
9790 /// paring capabilities and the layout of the slices.
9791 /// \pre \p GlobalLSCost should account for at least as many loads as
9792 /// there is in the slices in \p LoadedSlices.
9793 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9794                                  LoadedSlice::Cost &GlobalLSCost) {
9795   unsigned NumberOfSlices = LoadedSlices.size();
9796   // If there is less than 2 elements, no pairing is possible.
9797   if (NumberOfSlices < 2)
9798     return;
9799
9800   // Sort the slices so that elements that are likely to be next to each
9801   // other in memory are next to each other in the list.
9802   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9803             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9804     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9805     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9806   });
9807   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9808   // First (resp. Second) is the first (resp. Second) potentially candidate
9809   // to be placed in a paired load.
9810   const LoadedSlice *First = nullptr;
9811   const LoadedSlice *Second = nullptr;
9812   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9813                 // Set the beginning of the pair.
9814                                                            First = Second) {
9815
9816     Second = &LoadedSlices[CurrSlice];
9817
9818     // If First is NULL, it means we start a new pair.
9819     // Get to the next slice.
9820     if (!First)
9821       continue;
9822
9823     EVT LoadedType = First->getLoadedType();
9824
9825     // If the types of the slices are different, we cannot pair them.
9826     if (LoadedType != Second->getLoadedType())
9827       continue;
9828
9829     // Check if the target supplies paired loads for this type.
9830     unsigned RequiredAlignment = 0;
9831     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9832       // move to the next pair, this type is hopeless.
9833       Second = nullptr;
9834       continue;
9835     }
9836     // Check if we meet the alignment requirement.
9837     if (RequiredAlignment > First->getAlignment())
9838       continue;
9839
9840     // Check that both loads are next to each other in memory.
9841     if (!areSlicesNextToEachOther(*First, *Second))
9842       continue;
9843
9844     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9845     --GlobalLSCost.Loads;
9846     // Move to the next pair.
9847     Second = nullptr;
9848   }
9849 }
9850
9851 /// \brief Check the profitability of all involved LoadedSlice.
9852 /// Currently, it is considered profitable if there is exactly two
9853 /// involved slices (1) which are (2) next to each other in memory, and
9854 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9855 ///
9856 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9857 /// the elements themselves.
9858 ///
9859 /// FIXME: When the cost model will be mature enough, we can relax
9860 /// constraints (1) and (2).
9861 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9862                                 const APInt &UsedBits, bool ForCodeSize) {
9863   unsigned NumberOfSlices = LoadedSlices.size();
9864   if (StressLoadSlicing)
9865     return NumberOfSlices > 1;
9866
9867   // Check (1).
9868   if (NumberOfSlices != 2)
9869     return false;
9870
9871   // Check (2).
9872   if (!areUsedBitsDense(UsedBits))
9873     return false;
9874
9875   // Check (3).
9876   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9877   // The original code has one big load.
9878   OrigCost.Loads = 1;
9879   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9880     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9881     // Accumulate the cost of all the slices.
9882     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9883     GlobalSlicingCost += SliceCost;
9884
9885     // Account as cost in the original configuration the gain obtained
9886     // with the current slices.
9887     OrigCost.addSliceGain(LS);
9888   }
9889
9890   // If the target supports paired load, adjust the cost accordingly.
9891   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9892   return OrigCost > GlobalSlicingCost;
9893 }
9894
9895 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9896 /// operations, split it in the various pieces being extracted.
9897 ///
9898 /// This sort of thing is introduced by SROA.
9899 /// This slicing takes care not to insert overlapping loads.
9900 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9901 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9902   if (Level < AfterLegalizeDAG)
9903     return false;
9904
9905   LoadSDNode *LD = cast<LoadSDNode>(N);
9906   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9907       !LD->getValueType(0).isInteger())
9908     return false;
9909
9910   // Keep track of already used bits to detect overlapping values.
9911   // In that case, we will just abort the transformation.
9912   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9913
9914   SmallVector<LoadedSlice, 4> LoadedSlices;
9915
9916   // Check if this load is used as several smaller chunks of bits.
9917   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9918   // of computation for each trunc.
9919   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9920        UI != UIEnd; ++UI) {
9921     // Skip the uses of the chain.
9922     if (UI.getUse().getResNo() != 0)
9923       continue;
9924
9925     SDNode *User = *UI;
9926     unsigned Shift = 0;
9927
9928     // Check if this is a trunc(lshr).
9929     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9930         isa<ConstantSDNode>(User->getOperand(1))) {
9931       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9932       User = *User->use_begin();
9933     }
9934
9935     // At this point, User is a Truncate, iff we encountered, trunc or
9936     // trunc(lshr).
9937     if (User->getOpcode() != ISD::TRUNCATE)
9938       return false;
9939
9940     // The width of the type must be a power of 2 and greater than 8-bits.
9941     // Otherwise the load cannot be represented in LLVM IR.
9942     // Moreover, if we shifted with a non-8-bits multiple, the slice
9943     // will be across several bytes. We do not support that.
9944     unsigned Width = User->getValueSizeInBits(0);
9945     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9946       return 0;
9947
9948     // Build the slice for this chain of computations.
9949     LoadedSlice LS(User, LD, Shift, &DAG);
9950     APInt CurrentUsedBits = LS.getUsedBits();
9951
9952     // Check if this slice overlaps with another.
9953     if ((CurrentUsedBits & UsedBits) != 0)
9954       return false;
9955     // Update the bits used globally.
9956     UsedBits |= CurrentUsedBits;
9957
9958     // Check if the new slice would be legal.
9959     if (!LS.isLegal())
9960       return false;
9961
9962     // Record the slice.
9963     LoadedSlices.push_back(LS);
9964   }
9965
9966   // Abort slicing if it does not seem to be profitable.
9967   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9968     return false;
9969
9970   ++SlicedLoads;
9971
9972   // Rewrite each chain to use an independent load.
9973   // By construction, each chain can be represented by a unique load.
9974
9975   // Prepare the argument for the new token factor for all the slices.
9976   SmallVector<SDValue, 8> ArgChains;
9977   for (SmallVectorImpl<LoadedSlice>::const_iterator
9978            LSIt = LoadedSlices.begin(),
9979            LSItEnd = LoadedSlices.end();
9980        LSIt != LSItEnd; ++LSIt) {
9981     SDValue SliceInst = LSIt->loadSlice();
9982     CombineTo(LSIt->Inst, SliceInst, true);
9983     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9984       SliceInst = SliceInst.getOperand(0);
9985     assert(SliceInst->getOpcode() == ISD::LOAD &&
9986            "It takes more than a zext to get to the loaded slice!!");
9987     ArgChains.push_back(SliceInst.getValue(1));
9988   }
9989
9990   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9991                               ArgChains);
9992   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9993   return true;
9994 }
9995
9996 /// Check to see if V is (and load (ptr), imm), where the load is having
9997 /// specific bytes cleared out.  If so, return the byte size being masked out
9998 /// and the shift amount.
9999 static std::pair<unsigned, unsigned>
10000 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10001   std::pair<unsigned, unsigned> Result(0, 0);
10002
10003   // Check for the structure we're looking for.
10004   if (V->getOpcode() != ISD::AND ||
10005       !isa<ConstantSDNode>(V->getOperand(1)) ||
10006       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10007     return Result;
10008
10009   // Check the chain and pointer.
10010   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10011   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10012
10013   // The store should be chained directly to the load or be an operand of a
10014   // tokenfactor.
10015   if (LD == Chain.getNode())
10016     ; // ok.
10017   else if (Chain->getOpcode() != ISD::TokenFactor)
10018     return Result; // Fail.
10019   else {
10020     bool isOk = false;
10021     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10022       if (Chain->getOperand(i).getNode() == LD) {
10023         isOk = true;
10024         break;
10025       }
10026     if (!isOk) return Result;
10027   }
10028
10029   // This only handles simple types.
10030   if (V.getValueType() != MVT::i16 &&
10031       V.getValueType() != MVT::i32 &&
10032       V.getValueType() != MVT::i64)
10033     return Result;
10034
10035   // Check the constant mask.  Invert it so that the bits being masked out are
10036   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10037   // follow the sign bit for uniformity.
10038   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10039   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10040   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10041   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10042   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10043   if (NotMaskLZ == 64) return Result;  // All zero mask.
10044
10045   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10046   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10047     return Result;
10048
10049   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10050   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10051     NotMaskLZ -= 64-V.getValueSizeInBits();
10052
10053   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10054   switch (MaskedBytes) {
10055   case 1:
10056   case 2:
10057   case 4: break;
10058   default: return Result; // All one mask, or 5-byte mask.
10059   }
10060
10061   // Verify that the first bit starts at a multiple of mask so that the access
10062   // is aligned the same as the access width.
10063   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10064
10065   Result.first = MaskedBytes;
10066   Result.second = NotMaskTZ/8;
10067   return Result;
10068 }
10069
10070
10071 /// Check to see if IVal is something that provides a value as specified by
10072 /// MaskInfo. If so, replace the specified store with a narrower store of
10073 /// truncated IVal.
10074 static SDNode *
10075 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10076                                 SDValue IVal, StoreSDNode *St,
10077                                 DAGCombiner *DC) {
10078   unsigned NumBytes = MaskInfo.first;
10079   unsigned ByteShift = MaskInfo.second;
10080   SelectionDAG &DAG = DC->getDAG();
10081
10082   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10083   // that uses this.  If not, this is not a replacement.
10084   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10085                                   ByteShift*8, (ByteShift+NumBytes)*8);
10086   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10087
10088   // Check that it is legal on the target to do this.  It is legal if the new
10089   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10090   // legalization.
10091   MVT VT = MVT::getIntegerVT(NumBytes*8);
10092   if (!DC->isTypeLegal(VT))
10093     return nullptr;
10094
10095   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10096   // shifted by ByteShift and truncated down to NumBytes.
10097   if (ByteShift) {
10098     SDLoc DL(IVal);
10099     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10100                        DAG.getConstant(ByteShift*8, DL,
10101                                     DC->getShiftAmountTy(IVal.getValueType())));
10102   }
10103
10104   // Figure out the offset for the store and the alignment of the access.
10105   unsigned StOffset;
10106   unsigned NewAlign = St->getAlignment();
10107
10108   if (DAG.getTargetLoweringInfo().isLittleEndian())
10109     StOffset = ByteShift;
10110   else
10111     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10112
10113   SDValue Ptr = St->getBasePtr();
10114   if (StOffset) {
10115     SDLoc DL(IVal);
10116     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10117                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10118     NewAlign = MinAlign(NewAlign, StOffset);
10119   }
10120
10121   // Truncate down to the new size.
10122   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10123
10124   ++OpsNarrowed;
10125   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10126                       St->getPointerInfo().getWithOffset(StOffset),
10127                       false, false, NewAlign).getNode();
10128 }
10129
10130
10131 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10132 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10133 /// narrowing the load and store if it would end up being a win for performance
10134 /// or code size.
10135 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10136   StoreSDNode *ST  = cast<StoreSDNode>(N);
10137   if (ST->isVolatile())
10138     return SDValue();
10139
10140   SDValue Chain = ST->getChain();
10141   SDValue Value = ST->getValue();
10142   SDValue Ptr   = ST->getBasePtr();
10143   EVT VT = Value.getValueType();
10144
10145   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10146     return SDValue();
10147
10148   unsigned Opc = Value.getOpcode();
10149
10150   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10151   // is a byte mask indicating a consecutive number of bytes, check to see if
10152   // Y is known to provide just those bytes.  If so, we try to replace the
10153   // load + replace + store sequence with a single (narrower) store, which makes
10154   // the load dead.
10155   if (Opc == ISD::OR) {
10156     std::pair<unsigned, unsigned> MaskedLoad;
10157     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10158     if (MaskedLoad.first)
10159       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10160                                                   Value.getOperand(1), ST,this))
10161         return SDValue(NewST, 0);
10162
10163     // Or is commutative, so try swapping X and Y.
10164     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10165     if (MaskedLoad.first)
10166       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10167                                                   Value.getOperand(0), ST,this))
10168         return SDValue(NewST, 0);
10169   }
10170
10171   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10172       Value.getOperand(1).getOpcode() != ISD::Constant)
10173     return SDValue();
10174
10175   SDValue N0 = Value.getOperand(0);
10176   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10177       Chain == SDValue(N0.getNode(), 1)) {
10178     LoadSDNode *LD = cast<LoadSDNode>(N0);
10179     if (LD->getBasePtr() != Ptr ||
10180         LD->getPointerInfo().getAddrSpace() !=
10181         ST->getPointerInfo().getAddrSpace())
10182       return SDValue();
10183
10184     // Find the type to narrow it the load / op / store to.
10185     SDValue N1 = Value.getOperand(1);
10186     unsigned BitWidth = N1.getValueSizeInBits();
10187     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10188     if (Opc == ISD::AND)
10189       Imm ^= APInt::getAllOnesValue(BitWidth);
10190     if (Imm == 0 || Imm.isAllOnesValue())
10191       return SDValue();
10192     unsigned ShAmt = Imm.countTrailingZeros();
10193     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10194     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10195     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10196     // The narrowing should be profitable, the load/store operation should be
10197     // legal (or custom) and the store size should be equal to the NewVT width.
10198     while (NewBW < BitWidth &&
10199            (NewVT.getStoreSizeInBits() != NewBW ||
10200             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10201             !TLI.isNarrowingProfitable(VT, NewVT))) {
10202       NewBW = NextPowerOf2(NewBW);
10203       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10204     }
10205     if (NewBW >= BitWidth)
10206       return SDValue();
10207
10208     // If the lsb changed does not start at the type bitwidth boundary,
10209     // start at the previous one.
10210     if (ShAmt % NewBW)
10211       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10212     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10213                                    std::min(BitWidth, ShAmt + NewBW));
10214     if ((Imm & Mask) == Imm) {
10215       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10216       if (Opc == ISD::AND)
10217         NewImm ^= APInt::getAllOnesValue(NewBW);
10218       uint64_t PtrOff = ShAmt / 8;
10219       // For big endian targets, we need to adjust the offset to the pointer to
10220       // load the correct bytes.
10221       if (TLI.isBigEndian())
10222         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10223
10224       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10225       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10226       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10227         return SDValue();
10228
10229       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10230                                    Ptr.getValueType(), Ptr,
10231                                    DAG.getConstant(PtrOff, SDLoc(LD),
10232                                                    Ptr.getValueType()));
10233       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10234                                   LD->getChain(), NewPtr,
10235                                   LD->getPointerInfo().getWithOffset(PtrOff),
10236                                   LD->isVolatile(), LD->isNonTemporal(),
10237                                   LD->isInvariant(), NewAlign,
10238                                   LD->getAAInfo());
10239       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10240                                    DAG.getConstant(NewImm, SDLoc(Value),
10241                                                    NewVT));
10242       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10243                                    NewVal, NewPtr,
10244                                    ST->getPointerInfo().getWithOffset(PtrOff),
10245                                    false, false, NewAlign);
10246
10247       AddToWorklist(NewPtr.getNode());
10248       AddToWorklist(NewLD.getNode());
10249       AddToWorklist(NewVal.getNode());
10250       WorklistRemover DeadNodes(*this);
10251       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10252       ++OpsNarrowed;
10253       return NewST;
10254     }
10255   }
10256
10257   return SDValue();
10258 }
10259
10260 /// For a given floating point load / store pair, if the load value isn't used
10261 /// by any other operations, then consider transforming the pair to integer
10262 /// load / store operations if the target deems the transformation profitable.
10263 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10264   StoreSDNode *ST  = cast<StoreSDNode>(N);
10265   SDValue Chain = ST->getChain();
10266   SDValue Value = ST->getValue();
10267   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10268       Value.hasOneUse() &&
10269       Chain == SDValue(Value.getNode(), 1)) {
10270     LoadSDNode *LD = cast<LoadSDNode>(Value);
10271     EVT VT = LD->getMemoryVT();
10272     if (!VT.isFloatingPoint() ||
10273         VT != ST->getMemoryVT() ||
10274         LD->isNonTemporal() ||
10275         ST->isNonTemporal() ||
10276         LD->getPointerInfo().getAddrSpace() != 0 ||
10277         ST->getPointerInfo().getAddrSpace() != 0)
10278       return SDValue();
10279
10280     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10281     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10282         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10283         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10284         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10285       return SDValue();
10286
10287     unsigned LDAlign = LD->getAlignment();
10288     unsigned STAlign = ST->getAlignment();
10289     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10290     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10291     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10292       return SDValue();
10293
10294     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10295                                 LD->getChain(), LD->getBasePtr(),
10296                                 LD->getPointerInfo(),
10297                                 false, false, false, LDAlign);
10298
10299     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10300                                  NewLD, ST->getBasePtr(),
10301                                  ST->getPointerInfo(),
10302                                  false, false, STAlign);
10303
10304     AddToWorklist(NewLD.getNode());
10305     AddToWorklist(NewST.getNode());
10306     WorklistRemover DeadNodes(*this);
10307     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10308     ++LdStFP2Int;
10309     return NewST;
10310   }
10311
10312   return SDValue();
10313 }
10314
10315 namespace {
10316 /// Helper struct to parse and store a memory address as base + index + offset.
10317 /// We ignore sign extensions when it is safe to do so.
10318 /// The following two expressions are not equivalent. To differentiate we need
10319 /// to store whether there was a sign extension involved in the index
10320 /// computation.
10321 ///  (load (i64 add (i64 copyfromreg %c)
10322 ///                 (i64 signextend (add (i8 load %index)
10323 ///                                      (i8 1))))
10324 /// vs
10325 ///
10326 /// (load (i64 add (i64 copyfromreg %c)
10327 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10328 ///                                         (i32 1)))))
10329 struct BaseIndexOffset {
10330   SDValue Base;
10331   SDValue Index;
10332   int64_t Offset;
10333   bool IsIndexSignExt;
10334
10335   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10336
10337   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10338                   bool IsIndexSignExt) :
10339     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10340
10341   bool equalBaseIndex(const BaseIndexOffset &Other) {
10342     return Other.Base == Base && Other.Index == Index &&
10343       Other.IsIndexSignExt == IsIndexSignExt;
10344   }
10345
10346   /// Parses tree in Ptr for base, index, offset addresses.
10347   static BaseIndexOffset match(SDValue Ptr) {
10348     bool IsIndexSignExt = false;
10349
10350     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10351     // instruction, then it could be just the BASE or everything else we don't
10352     // know how to handle. Just use Ptr as BASE and give up.
10353     if (Ptr->getOpcode() != ISD::ADD)
10354       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10355
10356     // We know that we have at least an ADD instruction. Try to pattern match
10357     // the simple case of BASE + OFFSET.
10358     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10359       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10360       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10361                               IsIndexSignExt);
10362     }
10363
10364     // Inside a loop the current BASE pointer is calculated using an ADD and a
10365     // MUL instruction. In this case Ptr is the actual BASE pointer.
10366     // (i64 add (i64 %array_ptr)
10367     //          (i64 mul (i64 %induction_var)
10368     //                   (i64 %element_size)))
10369     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10370       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10371
10372     // Look at Base + Index + Offset cases.
10373     SDValue Base = Ptr->getOperand(0);
10374     SDValue IndexOffset = Ptr->getOperand(1);
10375
10376     // Skip signextends.
10377     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10378       IndexOffset = IndexOffset->getOperand(0);
10379       IsIndexSignExt = true;
10380     }
10381
10382     // Either the case of Base + Index (no offset) or something else.
10383     if (IndexOffset->getOpcode() != ISD::ADD)
10384       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10385
10386     // Now we have the case of Base + Index + offset.
10387     SDValue Index = IndexOffset->getOperand(0);
10388     SDValue Offset = IndexOffset->getOperand(1);
10389
10390     if (!isa<ConstantSDNode>(Offset))
10391       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10392
10393     // Ignore signextends.
10394     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10395       Index = Index->getOperand(0);
10396       IsIndexSignExt = true;
10397     } else IsIndexSignExt = false;
10398
10399     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10400     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10401   }
10402 };
10403 } // namespace
10404
10405 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10406                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10407                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10408   // Make sure we have something to merge.
10409   if (NumElem < 2)
10410     return false;
10411
10412   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10413   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10414   unsigned LatestNodeUsed = 0;
10415
10416   for (unsigned i=0; i < NumElem; ++i) {
10417     // Find a chain for the new wide-store operand. Notice that some
10418     // of the store nodes that we found may not be selected for inclusion
10419     // in the wide store. The chain we use needs to be the chain of the
10420     // latest store node which is *used* and replaced by the wide store.
10421     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10422       LatestNodeUsed = i;
10423   }
10424
10425   // The latest Node in the DAG.
10426   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10427   SDLoc DL(StoreNodes[0].MemNode);
10428
10429   SDValue StoredVal;
10430   if (UseVector) {
10431     // Find a legal type for the vector store.
10432     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10433     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10434     if (IsConstantSrc) {
10435       // A vector store with a constant source implies that the constant is
10436       // zero; we only handle merging stores of constant zeros because the zero
10437       // can be materialized without a load.
10438       // It may be beneficial to loosen this restriction to allow non-zero
10439       // store merging.
10440       StoredVal = DAG.getConstant(0, DL, Ty);
10441     } else {
10442       SmallVector<SDValue, 8> Ops;
10443       for (unsigned i = 0; i < NumElem ; ++i) {
10444         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10445         SDValue Val = St->getValue();
10446         // All of the operands of a BUILD_VECTOR must have the same type.
10447         if (Val.getValueType() != MemVT)
10448           return false;
10449         Ops.push_back(Val);
10450       }
10451
10452       // Build the extracted vector elements back into a vector.
10453       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10454     }
10455   } else {
10456     // We should always use a vector store when merging extracted vector
10457     // elements, so this path implies a store of constants.
10458     assert(IsConstantSrc && "Merged vector elements should use vector store");
10459
10460     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10461     APInt StoreInt(StoreBW, 0);
10462
10463     // Construct a single integer constant which is made of the smaller
10464     // constant inputs.
10465     bool IsLE = TLI.isLittleEndian();
10466     for (unsigned i = 0; i < NumElem ; ++i) {
10467       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10468       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10469       SDValue Val = St->getValue();
10470       StoreInt <<= ElementSizeBytes*8;
10471       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10472         StoreInt |= C->getAPIntValue().zext(StoreBW);
10473       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10474         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10475       } else {
10476         llvm_unreachable("Invalid constant element type");
10477       }
10478     }
10479
10480     // Create the new Load and Store operations.
10481     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10482     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10483   }
10484
10485   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10486                                   FirstInChain->getBasePtr(),
10487                                   FirstInChain->getPointerInfo(),
10488                                   false, false,
10489                                   FirstInChain->getAlignment());
10490
10491   // Replace the last store with the new store
10492   CombineTo(LatestOp, NewStore);
10493   // Erase all other stores.
10494   for (unsigned i = 0; i < NumElem ; ++i) {
10495     if (StoreNodes[i].MemNode == LatestOp)
10496       continue;
10497     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10498     // ReplaceAllUsesWith will replace all uses that existed when it was
10499     // called, but graph optimizations may cause new ones to appear. For
10500     // example, the case in pr14333 looks like
10501     //
10502     //  St's chain -> St -> another store -> X
10503     //
10504     // And the only difference from St to the other store is the chain.
10505     // When we change it's chain to be St's chain they become identical,
10506     // get CSEed and the net result is that X is now a use of St.
10507     // Since we know that St is redundant, just iterate.
10508     while (!St->use_empty())
10509       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10510     deleteAndRecombine(St);
10511   }
10512
10513   return true;
10514 }
10515
10516 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10517   if (OptLevel == CodeGenOpt::None)
10518     return false;
10519
10520   EVT MemVT = St->getMemoryVT();
10521   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10522   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10523       Attribute::NoImplicitFloat);
10524
10525   // Don't merge vectors into wider inputs.
10526   if (MemVT.isVector() || !MemVT.isSimple())
10527     return false;
10528
10529   // Perform an early exit check. Do not bother looking at stored values that
10530   // are not constants, loads, or extracted vector elements.
10531   SDValue StoredVal = St->getValue();
10532   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10533   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10534                        isa<ConstantFPSDNode>(StoredVal);
10535   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10536
10537   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10538     return false;
10539
10540   // Only look at ends of store sequences.
10541   SDValue Chain = SDValue(St, 0);
10542   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10543     return false;
10544
10545   // This holds the base pointer, index, and the offset in bytes from the base
10546   // pointer.
10547   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10548
10549   // We must have a base and an offset.
10550   if (!BasePtr.Base.getNode())
10551     return false;
10552
10553   // Do not handle stores to undef base pointers.
10554   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10555     return false;
10556
10557   // Save the LoadSDNodes that we find in the chain.
10558   // We need to make sure that these nodes do not interfere with
10559   // any of the store nodes.
10560   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10561
10562   // Save the StoreSDNodes that we find in the chain.
10563   SmallVector<MemOpLink, 8> StoreNodes;
10564
10565   // Walk up the chain and look for nodes with offsets from the same
10566   // base pointer. Stop when reaching an instruction with a different kind
10567   // or instruction which has a different base pointer.
10568   unsigned Seq = 0;
10569   StoreSDNode *Index = St;
10570   while (Index) {
10571     // If the chain has more than one use, then we can't reorder the mem ops.
10572     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10573       break;
10574
10575     // Find the base pointer and offset for this memory node.
10576     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10577
10578     // Check that the base pointer is the same as the original one.
10579     if (!Ptr.equalBaseIndex(BasePtr))
10580       break;
10581
10582     // Check that the alignment is the same.
10583     if (Index->getAlignment() != St->getAlignment())
10584       break;
10585
10586     // The memory operands must not be volatile.
10587     if (Index->isVolatile() || Index->isIndexed())
10588       break;
10589
10590     // No truncation.
10591     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10592       if (St->isTruncatingStore())
10593         break;
10594
10595     // The stored memory type must be the same.
10596     if (Index->getMemoryVT() != MemVT)
10597       break;
10598
10599     // We do not allow unaligned stores because we want to prevent overriding
10600     // stores.
10601     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10602       break;
10603
10604     // We found a potential memory operand to merge.
10605     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10606
10607     // Find the next memory operand in the chain. If the next operand in the
10608     // chain is a store then move up and continue the scan with the next
10609     // memory operand. If the next operand is a load save it and use alias
10610     // information to check if it interferes with anything.
10611     SDNode *NextInChain = Index->getChain().getNode();
10612     while (1) {
10613       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10614         // We found a store node. Use it for the next iteration.
10615         Index = STn;
10616         break;
10617       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10618         if (Ldn->isVolatile()) {
10619           Index = nullptr;
10620           break;
10621         }
10622
10623         // Save the load node for later. Continue the scan.
10624         AliasLoadNodes.push_back(Ldn);
10625         NextInChain = Ldn->getChain().getNode();
10626         continue;
10627       } else {
10628         Index = nullptr;
10629         break;
10630       }
10631     }
10632   }
10633
10634   // Check if there is anything to merge.
10635   if (StoreNodes.size() < 2)
10636     return false;
10637
10638   // Sort the memory operands according to their distance from the base pointer.
10639   std::sort(StoreNodes.begin(), StoreNodes.end(),
10640             [](MemOpLink LHS, MemOpLink RHS) {
10641     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10642            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10643             LHS.SequenceNum > RHS.SequenceNum);
10644   });
10645
10646   // Scan the memory operations on the chain and find the first non-consecutive
10647   // store memory address.
10648   unsigned LastConsecutiveStore = 0;
10649   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10650   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10651
10652     // Check that the addresses are consecutive starting from the second
10653     // element in the list of stores.
10654     if (i > 0) {
10655       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10656       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10657         break;
10658     }
10659
10660     bool Alias = false;
10661     // Check if this store interferes with any of the loads that we found.
10662     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10663       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10664         Alias = true;
10665         break;
10666       }
10667     // We found a load that alias with this store. Stop the sequence.
10668     if (Alias)
10669       break;
10670
10671     // Mark this node as useful.
10672     LastConsecutiveStore = i;
10673   }
10674
10675   // The node with the lowest store address.
10676   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10677
10678   // Store the constants into memory as one consecutive store.
10679   if (IsConstantSrc) {
10680     unsigned LastLegalType = 0;
10681     unsigned LastLegalVectorType = 0;
10682     bool NonZero = false;
10683     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10684       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10685       SDValue StoredVal = St->getValue();
10686
10687       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10688         NonZero |= !C->isNullValue();
10689       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10690         NonZero |= !C->getConstantFPValue()->isNullValue();
10691       } else {
10692         // Non-constant.
10693         break;
10694       }
10695
10696       // Find a legal type for the constant store.
10697       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10698       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10699       if (TLI.isTypeLegal(StoreTy))
10700         LastLegalType = i+1;
10701       // Or check whether a truncstore is legal.
10702       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10703                TargetLowering::TypePromoteInteger) {
10704         EVT LegalizedStoredValueTy =
10705           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10706         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10707           LastLegalType = i+1;
10708       }
10709
10710       // Find a legal type for the vector store.
10711       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10712       if (TLI.isTypeLegal(Ty))
10713         LastLegalVectorType = i + 1;
10714     }
10715
10716     // We only use vectors if the constant is known to be zero and the
10717     // function is not marked with the noimplicitfloat attribute.
10718     if (NonZero || NoVectors)
10719       LastLegalVectorType = 0;
10720
10721     // Check if we found a legal integer type to store.
10722     if (LastLegalType == 0 && LastLegalVectorType == 0)
10723       return false;
10724
10725     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10726     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10727
10728     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10729                                            true, UseVector);
10730   }
10731
10732   // When extracting multiple vector elements, try to store them
10733   // in one vector store rather than a sequence of scalar stores.
10734   if (IsExtractVecEltSrc) {
10735     unsigned NumElem = 0;
10736     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10737       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10738       SDValue StoredVal = St->getValue();
10739       // This restriction could be loosened.
10740       // Bail out if any stored values are not elements extracted from a vector.
10741       // It should be possible to handle mixed sources, but load sources need
10742       // more careful handling (see the block of code below that handles
10743       // consecutive loads).
10744       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10745         return false;
10746
10747       // Find a legal type for the vector store.
10748       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10749       if (TLI.isTypeLegal(Ty))
10750         NumElem = i + 1;
10751     }
10752
10753     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10754                                            false, true);
10755   }
10756
10757   // Below we handle the case of multiple consecutive stores that
10758   // come from multiple consecutive loads. We merge them into a single
10759   // wide load and a single wide store.
10760
10761   // Look for load nodes which are used by the stored values.
10762   SmallVector<MemOpLink, 8> LoadNodes;
10763
10764   // Find acceptable loads. Loads need to have the same chain (token factor),
10765   // must not be zext, volatile, indexed, and they must be consecutive.
10766   BaseIndexOffset LdBasePtr;
10767   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10768     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10769     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10770     if (!Ld) break;
10771
10772     // Loads must only have one use.
10773     if (!Ld->hasNUsesOfValue(1, 0))
10774       break;
10775
10776     // Check that the alignment is the same as the stores.
10777     if (Ld->getAlignment() != St->getAlignment())
10778       break;
10779
10780     // The memory operands must not be volatile.
10781     if (Ld->isVolatile() || Ld->isIndexed())
10782       break;
10783
10784     // We do not accept ext loads.
10785     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10786       break;
10787
10788     // The stored memory type must be the same.
10789     if (Ld->getMemoryVT() != MemVT)
10790       break;
10791
10792     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10793     // If this is not the first ptr that we check.
10794     if (LdBasePtr.Base.getNode()) {
10795       // The base ptr must be the same.
10796       if (!LdPtr.equalBaseIndex(LdBasePtr))
10797         break;
10798     } else {
10799       // Check that all other base pointers are the same as this one.
10800       LdBasePtr = LdPtr;
10801     }
10802
10803     // We found a potential memory operand to merge.
10804     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10805   }
10806
10807   if (LoadNodes.size() < 2)
10808     return false;
10809
10810   // If we have load/store pair instructions and we only have two values,
10811   // don't bother.
10812   unsigned RequiredAlignment;
10813   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10814       St->getAlignment() >= RequiredAlignment)
10815     return false;
10816
10817   // Scan the memory operations on the chain and find the first non-consecutive
10818   // load memory address. These variables hold the index in the store node
10819   // array.
10820   unsigned LastConsecutiveLoad = 0;
10821   // This variable refers to the size and not index in the array.
10822   unsigned LastLegalVectorType = 0;
10823   unsigned LastLegalIntegerType = 0;
10824   StartAddress = LoadNodes[0].OffsetFromBase;
10825   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10826   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10827     // All loads much share the same chain.
10828     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10829       break;
10830
10831     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10832     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10833       break;
10834     LastConsecutiveLoad = i;
10835
10836     // Find a legal type for the vector store.
10837     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10838     if (TLI.isTypeLegal(StoreTy))
10839       LastLegalVectorType = i + 1;
10840
10841     // Find a legal type for the integer store.
10842     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10843     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10844     if (TLI.isTypeLegal(StoreTy))
10845       LastLegalIntegerType = i + 1;
10846     // Or check whether a truncstore and extload is legal.
10847     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10848              TargetLowering::TypePromoteInteger) {
10849       EVT LegalizedStoredValueTy =
10850         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10851       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10852           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10853           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10854           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10855         LastLegalIntegerType = i+1;
10856     }
10857   }
10858
10859   // Only use vector types if the vector type is larger than the integer type.
10860   // If they are the same, use integers.
10861   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10862   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10863
10864   // We add +1 here because the LastXXX variables refer to location while
10865   // the NumElem refers to array/index size.
10866   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10867   NumElem = std::min(LastLegalType, NumElem);
10868
10869   if (NumElem < 2)
10870     return false;
10871
10872   // The latest Node in the DAG.
10873   unsigned LatestNodeUsed = 0;
10874   for (unsigned i=1; i<NumElem; ++i) {
10875     // Find a chain for the new wide-store operand. Notice that some
10876     // of the store nodes that we found may not be selected for inclusion
10877     // in the wide store. The chain we use needs to be the chain of the
10878     // latest store node which is *used* and replaced by the wide store.
10879     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10880       LatestNodeUsed = i;
10881   }
10882
10883   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10884
10885   // Find if it is better to use vectors or integers to load and store
10886   // to memory.
10887   EVT JointMemOpVT;
10888   if (UseVectorTy) {
10889     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10890   } else {
10891     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10892     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10893   }
10894
10895   SDLoc LoadDL(LoadNodes[0].MemNode);
10896   SDLoc StoreDL(StoreNodes[0].MemNode);
10897
10898   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10899   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10900                                 FirstLoad->getChain(),
10901                                 FirstLoad->getBasePtr(),
10902                                 FirstLoad->getPointerInfo(),
10903                                 false, false, false,
10904                                 FirstLoad->getAlignment());
10905
10906   SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
10907                                   FirstInChain->getBasePtr(),
10908                                   FirstInChain->getPointerInfo(), false, false,
10909                                   FirstInChain->getAlignment());
10910
10911   // Replace one of the loads with the new load.
10912   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10913   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10914                                 SDValue(NewLoad.getNode(), 1));
10915
10916   // Remove the rest of the load chains.
10917   for (unsigned i = 1; i < NumElem ; ++i) {
10918     // Replace all chain users of the old load nodes with the chain of the new
10919     // load node.
10920     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10921     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10922   }
10923
10924   // Replace the last store with the new store.
10925   CombineTo(LatestOp, NewStore);
10926   // Erase all other stores.
10927   for (unsigned i = 0; i < NumElem ; ++i) {
10928     // Remove all Store nodes.
10929     if (StoreNodes[i].MemNode == LatestOp)
10930       continue;
10931     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10932     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10933     deleteAndRecombine(St);
10934   }
10935
10936   return true;
10937 }
10938
10939 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10940   StoreSDNode *ST  = cast<StoreSDNode>(N);
10941   SDValue Chain = ST->getChain();
10942   SDValue Value = ST->getValue();
10943   SDValue Ptr   = ST->getBasePtr();
10944
10945   // If this is a store of a bit convert, store the input value if the
10946   // resultant store does not need a higher alignment than the original.
10947   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10948       ST->isUnindexed()) {
10949     unsigned OrigAlign = ST->getAlignment();
10950     EVT SVT = Value.getOperand(0).getValueType();
10951     unsigned Align = TLI.getDataLayout()->
10952       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10953     if (Align <= OrigAlign &&
10954         ((!LegalOperations && !ST->isVolatile()) ||
10955          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10956       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10957                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10958                           ST->isNonTemporal(), OrigAlign,
10959                           ST->getAAInfo());
10960   }
10961
10962   // Turn 'store undef, Ptr' -> nothing.
10963   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10964     return Chain;
10965
10966   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10967   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10968     // NOTE: If the original store is volatile, this transform must not increase
10969     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10970     // processor operation but an i64 (which is not legal) requires two.  So the
10971     // transform should not be done in this case.
10972     if (Value.getOpcode() != ISD::TargetConstantFP) {
10973       SDValue Tmp;
10974       switch (CFP->getSimpleValueType(0).SimpleTy) {
10975       default: llvm_unreachable("Unknown FP type");
10976       case MVT::f16:    // We don't do this for these yet.
10977       case MVT::f80:
10978       case MVT::f128:
10979       case MVT::ppcf128:
10980         break;
10981       case MVT::f32:
10982         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10983             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10984           ;
10985           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10986                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
10987                               MVT::i32);
10988           return DAG.getStore(Chain, SDLoc(N), Tmp,
10989                               Ptr, ST->getMemOperand());
10990         }
10991         break;
10992       case MVT::f64:
10993         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10994              !ST->isVolatile()) ||
10995             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10996           ;
10997           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10998                                 getZExtValue(), SDLoc(CFP), MVT::i64);
10999           return DAG.getStore(Chain, SDLoc(N), Tmp,
11000                               Ptr, ST->getMemOperand());
11001         }
11002
11003         if (!ST->isVolatile() &&
11004             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11005           // Many FP stores are not made apparent until after legalize, e.g. for
11006           // argument passing.  Since this is so common, custom legalize the
11007           // 64-bit integer store into two 32-bit stores.
11008           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11009           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11010           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11011           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11012
11013           unsigned Alignment = ST->getAlignment();
11014           bool isVolatile = ST->isVolatile();
11015           bool isNonTemporal = ST->isNonTemporal();
11016           AAMDNodes AAInfo = ST->getAAInfo();
11017
11018           SDLoc DL(N);
11019
11020           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11021                                      Ptr, ST->getPointerInfo(),
11022                                      isVolatile, isNonTemporal,
11023                                      ST->getAlignment(), AAInfo);
11024           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11025                             DAG.getConstant(4, DL, Ptr.getValueType()));
11026           Alignment = MinAlign(Alignment, 4U);
11027           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11028                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11029                                      isVolatile, isNonTemporal,
11030                                      Alignment, AAInfo);
11031           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11032                              St0, St1);
11033         }
11034
11035         break;
11036       }
11037     }
11038   }
11039
11040   // Try to infer better alignment information than the store already has.
11041   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11042     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11043       if (Align > ST->getAlignment()) {
11044         SDValue NewStore =
11045                DAG.getTruncStore(Chain, SDLoc(N), Value,
11046                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11047                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11048                                  ST->getAAInfo());
11049         if (NewStore.getNode() != N)
11050           return CombineTo(ST, NewStore, true);
11051       }
11052     }
11053   }
11054
11055   // Try transforming a pair floating point load / store ops to integer
11056   // load / store ops.
11057   SDValue NewST = TransformFPLoadStorePair(N);
11058   if (NewST.getNode())
11059     return NewST;
11060
11061   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11062                                                   : DAG.getSubtarget().useAA();
11063 #ifndef NDEBUG
11064   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11065       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11066     UseAA = false;
11067 #endif
11068   if (UseAA && ST->isUnindexed()) {
11069     // Walk up chain skipping non-aliasing memory nodes.
11070     SDValue BetterChain = FindBetterChain(N, Chain);
11071
11072     // If there is a better chain.
11073     if (Chain != BetterChain) {
11074       SDValue ReplStore;
11075
11076       // Replace the chain to avoid dependency.
11077       if (ST->isTruncatingStore()) {
11078         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11079                                       ST->getMemoryVT(), ST->getMemOperand());
11080       } else {
11081         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11082                                  ST->getMemOperand());
11083       }
11084
11085       // Create token to keep both nodes around.
11086       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11087                                   MVT::Other, Chain, ReplStore);
11088
11089       // Make sure the new and old chains are cleaned up.
11090       AddToWorklist(Token.getNode());
11091
11092       // Don't add users to work list.
11093       return CombineTo(N, Token, false);
11094     }
11095   }
11096
11097   // Try transforming N to an indexed store.
11098   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11099     return SDValue(N, 0);
11100
11101   // FIXME: is there such a thing as a truncating indexed store?
11102   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11103       Value.getValueType().isInteger()) {
11104     // See if we can simplify the input to this truncstore with knowledge that
11105     // only the low bits are being used.  For example:
11106     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11107     SDValue Shorter =
11108       GetDemandedBits(Value,
11109                       APInt::getLowBitsSet(
11110                         Value.getValueType().getScalarType().getSizeInBits(),
11111                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11112     AddToWorklist(Value.getNode());
11113     if (Shorter.getNode())
11114       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11115                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11116
11117     // Otherwise, see if we can simplify the operation with
11118     // SimplifyDemandedBits, which only works if the value has a single use.
11119     if (SimplifyDemandedBits(Value,
11120                         APInt::getLowBitsSet(
11121                           Value.getValueType().getScalarType().getSizeInBits(),
11122                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11123       return SDValue(N, 0);
11124   }
11125
11126   // If this is a load followed by a store to the same location, then the store
11127   // is dead/noop.
11128   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11129     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11130         ST->isUnindexed() && !ST->isVolatile() &&
11131         // There can't be any side effects between the load and store, such as
11132         // a call or store.
11133         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11134       // The store is dead, remove it.
11135       return Chain;
11136     }
11137   }
11138
11139   // If this is a store followed by a store with the same value to the same
11140   // location, then the store is dead/noop.
11141   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11142     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11143         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11144         ST1->isUnindexed() && !ST1->isVolatile()) {
11145       // The store is dead, remove it.
11146       return Chain;
11147     }
11148   }
11149
11150   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11151   // truncating store.  We can do this even if this is already a truncstore.
11152   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11153       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11154       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11155                             ST->getMemoryVT())) {
11156     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11157                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11158   }
11159
11160   // Only perform this optimization before the types are legal, because we
11161   // don't want to perform this optimization on every DAGCombine invocation.
11162   if (!LegalTypes) {
11163     bool EverChanged = false;
11164
11165     do {
11166       // There can be multiple store sequences on the same chain.
11167       // Keep trying to merge store sequences until we are unable to do so
11168       // or until we merge the last store on the chain.
11169       bool Changed = MergeConsecutiveStores(ST);
11170       EverChanged |= Changed;
11171       if (!Changed) break;
11172     } while (ST->getOpcode() != ISD::DELETED_NODE);
11173
11174     if (EverChanged)
11175       return SDValue(N, 0);
11176   }
11177
11178   return ReduceLoadOpStoreWidth(N);
11179 }
11180
11181 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11182   SDValue InVec = N->getOperand(0);
11183   SDValue InVal = N->getOperand(1);
11184   SDValue EltNo = N->getOperand(2);
11185   SDLoc dl(N);
11186
11187   // If the inserted element is an UNDEF, just use the input vector.
11188   if (InVal.getOpcode() == ISD::UNDEF)
11189     return InVec;
11190
11191   EVT VT = InVec.getValueType();
11192
11193   // If we can't generate a legal BUILD_VECTOR, exit
11194   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11195     return SDValue();
11196
11197   // Check that we know which element is being inserted
11198   if (!isa<ConstantSDNode>(EltNo))
11199     return SDValue();
11200   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11201
11202   // Canonicalize insert_vector_elt dag nodes.
11203   // Example:
11204   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11205   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11206   //
11207   // Do this only if the child insert_vector node has one use; also
11208   // do this only if indices are both constants and Idx1 < Idx0.
11209   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11210       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11211     unsigned OtherElt =
11212       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11213     if (Elt < OtherElt) {
11214       // Swap nodes.
11215       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11216                                   InVec.getOperand(0), InVal, EltNo);
11217       AddToWorklist(NewOp.getNode());
11218       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11219                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11220     }
11221   }
11222
11223   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11224   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11225   // vector elements.
11226   SmallVector<SDValue, 8> Ops;
11227   // Do not combine these two vectors if the output vector will not replace
11228   // the input vector.
11229   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11230     Ops.append(InVec.getNode()->op_begin(),
11231                InVec.getNode()->op_end());
11232   } else if (InVec.getOpcode() == ISD::UNDEF) {
11233     unsigned NElts = VT.getVectorNumElements();
11234     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11235   } else {
11236     return SDValue();
11237   }
11238
11239   // Insert the element
11240   if (Elt < Ops.size()) {
11241     // All the operands of BUILD_VECTOR must have the same type;
11242     // we enforce that here.
11243     EVT OpVT = Ops[0].getValueType();
11244     if (InVal.getValueType() != OpVT)
11245       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11246                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11247                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11248     Ops[Elt] = InVal;
11249   }
11250
11251   // Return the new vector
11252   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11253 }
11254
11255 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11256     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11257   EVT ResultVT = EVE->getValueType(0);
11258   EVT VecEltVT = InVecVT.getVectorElementType();
11259   unsigned Align = OriginalLoad->getAlignment();
11260   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11261       VecEltVT.getTypeForEVT(*DAG.getContext()));
11262
11263   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11264     return SDValue();
11265
11266   Align = NewAlign;
11267
11268   SDValue NewPtr = OriginalLoad->getBasePtr();
11269   SDValue Offset;
11270   EVT PtrType = NewPtr.getValueType();
11271   MachinePointerInfo MPI;
11272   SDLoc DL(EVE);
11273   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11274     int Elt = ConstEltNo->getZExtValue();
11275     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11276     if (TLI.isBigEndian())
11277       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
11278     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11279     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11280   } else {
11281     Offset = DAG.getNode(
11282         ISD::MUL, DL, EltNo.getValueType(), EltNo,
11283         DAG.getConstant(VecEltVT.getStoreSize(), DL, EltNo.getValueType()));
11284     if (TLI.isBigEndian())
11285       Offset = DAG.getNode(
11286           ISD::SUB, DL, EltNo.getValueType(),
11287           DAG.getConstant(InVecVT.getStoreSize(), DL, EltNo.getValueType()),
11288           Offset);
11289     MPI = OriginalLoad->getPointerInfo();
11290   }
11291   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11292
11293   // The replacement we need to do here is a little tricky: we need to
11294   // replace an extractelement of a load with a load.
11295   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11296   // Note that this replacement assumes that the extractvalue is the only
11297   // use of the load; that's okay because we don't want to perform this
11298   // transformation in other cases anyway.
11299   SDValue Load;
11300   SDValue Chain;
11301   if (ResultVT.bitsGT(VecEltVT)) {
11302     // If the result type of vextract is wider than the load, then issue an
11303     // extending load instead.
11304     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11305                                                   VecEltVT)
11306                                    ? ISD::ZEXTLOAD
11307                                    : ISD::EXTLOAD;
11308     Load = DAG.getExtLoad(
11309         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11310         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11311         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11312     Chain = Load.getValue(1);
11313   } else {
11314     Load = DAG.getLoad(
11315         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11316         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11317         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11318     Chain = Load.getValue(1);
11319     if (ResultVT.bitsLT(VecEltVT))
11320       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11321     else
11322       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11323   }
11324   WorklistRemover DeadNodes(*this);
11325   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11326   SDValue To[] = { Load, Chain };
11327   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11328   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11329   // worklist explicitly as well.
11330   AddToWorklist(Load.getNode());
11331   AddUsersToWorklist(Load.getNode()); // Add users too
11332   // Make sure to revisit this node to clean it up; it will usually be dead.
11333   AddToWorklist(EVE);
11334   ++OpsNarrowed;
11335   return SDValue(EVE, 0);
11336 }
11337
11338 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11339   // (vextract (scalar_to_vector val, 0) -> val
11340   SDValue InVec = N->getOperand(0);
11341   EVT VT = InVec.getValueType();
11342   EVT NVT = N->getValueType(0);
11343
11344   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11345     // Check if the result type doesn't match the inserted element type. A
11346     // SCALAR_TO_VECTOR may truncate the inserted element and the
11347     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11348     SDValue InOp = InVec.getOperand(0);
11349     if (InOp.getValueType() != NVT) {
11350       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11351       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11352     }
11353     return InOp;
11354   }
11355
11356   SDValue EltNo = N->getOperand(1);
11357   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11358
11359   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11360   // We only perform this optimization before the op legalization phase because
11361   // we may introduce new vector instructions which are not backed by TD
11362   // patterns. For example on AVX, extracting elements from a wide vector
11363   // without using extract_subvector. However, if we can find an underlying
11364   // scalar value, then we can always use that.
11365   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11366       && ConstEltNo) {
11367     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11368     int NumElem = VT.getVectorNumElements();
11369     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11370     // Find the new index to extract from.
11371     int OrigElt = SVOp->getMaskElt(Elt);
11372
11373     // Extracting an undef index is undef.
11374     if (OrigElt == -1)
11375       return DAG.getUNDEF(NVT);
11376
11377     // Select the right vector half to extract from.
11378     SDValue SVInVec;
11379     if (OrigElt < NumElem) {
11380       SVInVec = InVec->getOperand(0);
11381     } else {
11382       SVInVec = InVec->getOperand(1);
11383       OrigElt -= NumElem;
11384     }
11385
11386     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11387       SDValue InOp = SVInVec.getOperand(OrigElt);
11388       if (InOp.getValueType() != NVT) {
11389         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11390         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11391       }
11392
11393       return InOp;
11394     }
11395
11396     // FIXME: We should handle recursing on other vector shuffles and
11397     // scalar_to_vector here as well.
11398
11399     if (!LegalOperations) {
11400       EVT IndexTy = TLI.getVectorIdxTy();
11401       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11402                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11403     }
11404   }
11405
11406   bool BCNumEltsChanged = false;
11407   EVT ExtVT = VT.getVectorElementType();
11408   EVT LVT = ExtVT;
11409
11410   // If the result of load has to be truncated, then it's not necessarily
11411   // profitable.
11412   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11413     return SDValue();
11414
11415   if (InVec.getOpcode() == ISD::BITCAST) {
11416     // Don't duplicate a load with other uses.
11417     if (!InVec.hasOneUse())
11418       return SDValue();
11419
11420     EVT BCVT = InVec.getOperand(0).getValueType();
11421     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11422       return SDValue();
11423     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11424       BCNumEltsChanged = true;
11425     InVec = InVec.getOperand(0);
11426     ExtVT = BCVT.getVectorElementType();
11427   }
11428
11429   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11430   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11431       ISD::isNormalLoad(InVec.getNode()) &&
11432       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11433     SDValue Index = N->getOperand(1);
11434     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11435       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11436                                                            OrigLoad);
11437   }
11438
11439   // Perform only after legalization to ensure build_vector / vector_shuffle
11440   // optimizations have already been done.
11441   if (!LegalOperations) return SDValue();
11442
11443   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11444   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11445   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11446
11447   if (ConstEltNo) {
11448     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11449
11450     LoadSDNode *LN0 = nullptr;
11451     const ShuffleVectorSDNode *SVN = nullptr;
11452     if (ISD::isNormalLoad(InVec.getNode())) {
11453       LN0 = cast<LoadSDNode>(InVec);
11454     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11455                InVec.getOperand(0).getValueType() == ExtVT &&
11456                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11457       // Don't duplicate a load with other uses.
11458       if (!InVec.hasOneUse())
11459         return SDValue();
11460
11461       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11462     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11463       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11464       // =>
11465       // (load $addr+1*size)
11466
11467       // Don't duplicate a load with other uses.
11468       if (!InVec.hasOneUse())
11469         return SDValue();
11470
11471       // If the bit convert changed the number of elements, it is unsafe
11472       // to examine the mask.
11473       if (BCNumEltsChanged)
11474         return SDValue();
11475
11476       // Select the input vector, guarding against out of range extract vector.
11477       unsigned NumElems = VT.getVectorNumElements();
11478       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11479       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11480
11481       if (InVec.getOpcode() == ISD::BITCAST) {
11482         // Don't duplicate a load with other uses.
11483         if (!InVec.hasOneUse())
11484           return SDValue();
11485
11486         InVec = InVec.getOperand(0);
11487       }
11488       if (ISD::isNormalLoad(InVec.getNode())) {
11489         LN0 = cast<LoadSDNode>(InVec);
11490         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11491         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11492       }
11493     }
11494
11495     // Make sure we found a non-volatile load and the extractelement is
11496     // the only use.
11497     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11498       return SDValue();
11499
11500     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11501     if (Elt == -1)
11502       return DAG.getUNDEF(LVT);
11503
11504     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11505   }
11506
11507   return SDValue();
11508 }
11509
11510 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11511 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11512   // We perform this optimization post type-legalization because
11513   // the type-legalizer often scalarizes integer-promoted vectors.
11514   // Performing this optimization before may create bit-casts which
11515   // will be type-legalized to complex code sequences.
11516   // We perform this optimization only before the operation legalizer because we
11517   // may introduce illegal operations.
11518   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11519     return SDValue();
11520
11521   unsigned NumInScalars = N->getNumOperands();
11522   SDLoc dl(N);
11523   EVT VT = N->getValueType(0);
11524
11525   // Check to see if this is a BUILD_VECTOR of a bunch of values
11526   // which come from any_extend or zero_extend nodes. If so, we can create
11527   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11528   // optimizations. We do not handle sign-extend because we can't fill the sign
11529   // using shuffles.
11530   EVT SourceType = MVT::Other;
11531   bool AllAnyExt = true;
11532
11533   for (unsigned i = 0; i != NumInScalars; ++i) {
11534     SDValue In = N->getOperand(i);
11535     // Ignore undef inputs.
11536     if (In.getOpcode() == ISD::UNDEF) continue;
11537
11538     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11539     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11540
11541     // Abort if the element is not an extension.
11542     if (!ZeroExt && !AnyExt) {
11543       SourceType = MVT::Other;
11544       break;
11545     }
11546
11547     // The input is a ZeroExt or AnyExt. Check the original type.
11548     EVT InTy = In.getOperand(0).getValueType();
11549
11550     // Check that all of the widened source types are the same.
11551     if (SourceType == MVT::Other)
11552       // First time.
11553       SourceType = InTy;
11554     else if (InTy != SourceType) {
11555       // Multiple income types. Abort.
11556       SourceType = MVT::Other;
11557       break;
11558     }
11559
11560     // Check if all of the extends are ANY_EXTENDs.
11561     AllAnyExt &= AnyExt;
11562   }
11563
11564   // In order to have valid types, all of the inputs must be extended from the
11565   // same source type and all of the inputs must be any or zero extend.
11566   // Scalar sizes must be a power of two.
11567   EVT OutScalarTy = VT.getScalarType();
11568   bool ValidTypes = SourceType != MVT::Other &&
11569                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11570                  isPowerOf2_32(SourceType.getSizeInBits());
11571
11572   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11573   // turn into a single shuffle instruction.
11574   if (!ValidTypes)
11575     return SDValue();
11576
11577   bool isLE = TLI.isLittleEndian();
11578   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11579   assert(ElemRatio > 1 && "Invalid element size ratio");
11580   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11581                                DAG.getConstant(0, SDLoc(N), SourceType);
11582
11583   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11584   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11585
11586   // Populate the new build_vector
11587   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11588     SDValue Cast = N->getOperand(i);
11589     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11590             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11591             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11592     SDValue In;
11593     if (Cast.getOpcode() == ISD::UNDEF)
11594       In = DAG.getUNDEF(SourceType);
11595     else
11596       In = Cast->getOperand(0);
11597     unsigned Index = isLE ? (i * ElemRatio) :
11598                             (i * ElemRatio + (ElemRatio - 1));
11599
11600     assert(Index < Ops.size() && "Invalid index");
11601     Ops[Index] = In;
11602   }
11603
11604   // The type of the new BUILD_VECTOR node.
11605   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11606   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11607          "Invalid vector size");
11608   // Check if the new vector type is legal.
11609   if (!isTypeLegal(VecVT)) return SDValue();
11610
11611   // Make the new BUILD_VECTOR.
11612   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11613
11614   // The new BUILD_VECTOR node has the potential to be further optimized.
11615   AddToWorklist(BV.getNode());
11616   // Bitcast to the desired type.
11617   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11618 }
11619
11620 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11621   EVT VT = N->getValueType(0);
11622
11623   unsigned NumInScalars = N->getNumOperands();
11624   SDLoc dl(N);
11625
11626   EVT SrcVT = MVT::Other;
11627   unsigned Opcode = ISD::DELETED_NODE;
11628   unsigned NumDefs = 0;
11629
11630   for (unsigned i = 0; i != NumInScalars; ++i) {
11631     SDValue In = N->getOperand(i);
11632     unsigned Opc = In.getOpcode();
11633
11634     if (Opc == ISD::UNDEF)
11635       continue;
11636
11637     // If all scalar values are floats and converted from integers.
11638     if (Opcode == ISD::DELETED_NODE &&
11639         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11640       Opcode = Opc;
11641     }
11642
11643     if (Opc != Opcode)
11644       return SDValue();
11645
11646     EVT InVT = In.getOperand(0).getValueType();
11647
11648     // If all scalar values are typed differently, bail out. It's chosen to
11649     // simplify BUILD_VECTOR of integer types.
11650     if (SrcVT == MVT::Other)
11651       SrcVT = InVT;
11652     if (SrcVT != InVT)
11653       return SDValue();
11654     NumDefs++;
11655   }
11656
11657   // If the vector has just one element defined, it's not worth to fold it into
11658   // a vectorized one.
11659   if (NumDefs < 2)
11660     return SDValue();
11661
11662   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11663          && "Should only handle conversion from integer to float.");
11664   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11665
11666   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11667
11668   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11669     return SDValue();
11670
11671   // Just because the floating-point vector type is legal does not necessarily
11672   // mean that the corresponding integer vector type is.
11673   if (!isTypeLegal(NVT))
11674     return SDValue();
11675
11676   SmallVector<SDValue, 8> Opnds;
11677   for (unsigned i = 0; i != NumInScalars; ++i) {
11678     SDValue In = N->getOperand(i);
11679
11680     if (In.getOpcode() == ISD::UNDEF)
11681       Opnds.push_back(DAG.getUNDEF(SrcVT));
11682     else
11683       Opnds.push_back(In.getOperand(0));
11684   }
11685   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11686   AddToWorklist(BV.getNode());
11687
11688   return DAG.getNode(Opcode, dl, VT, BV);
11689 }
11690
11691 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11692   unsigned NumInScalars = N->getNumOperands();
11693   SDLoc dl(N);
11694   EVT VT = N->getValueType(0);
11695
11696   // A vector built entirely of undefs is undef.
11697   if (ISD::allOperandsUndef(N))
11698     return DAG.getUNDEF(VT);
11699
11700   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11701     return V;
11702
11703   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11704     return V;
11705
11706   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11707   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11708   // at most two distinct vectors, turn this into a shuffle node.
11709
11710   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11711   if (!isTypeLegal(VT))
11712     return SDValue();
11713
11714   // May only combine to shuffle after legalize if shuffle is legal.
11715   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11716     return SDValue();
11717
11718   SDValue VecIn1, VecIn2;
11719   bool UsesZeroVector = false;
11720   for (unsigned i = 0; i != NumInScalars; ++i) {
11721     SDValue Op = N->getOperand(i);
11722     // Ignore undef inputs.
11723     if (Op.getOpcode() == ISD::UNDEF) continue;
11724
11725     // See if we can combine this build_vector into a blend with a zero vector.
11726     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11727         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11728         (Op.getOpcode() == ISD::ConstantFP &&
11729         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11730       UsesZeroVector = true;
11731       continue;
11732     }
11733
11734     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11735     // constant index, bail out.
11736     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11737         !isa<ConstantSDNode>(Op.getOperand(1))) {
11738       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11739       break;
11740     }
11741
11742     // We allow up to two distinct input vectors.
11743     SDValue ExtractedFromVec = Op.getOperand(0);
11744     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11745       continue;
11746
11747     if (!VecIn1.getNode()) {
11748       VecIn1 = ExtractedFromVec;
11749     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11750       VecIn2 = ExtractedFromVec;
11751     } else {
11752       // Too many inputs.
11753       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11754       break;
11755     }
11756   }
11757
11758   // If everything is good, we can make a shuffle operation.
11759   if (VecIn1.getNode()) {
11760     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11761     SmallVector<int, 8> Mask;
11762     for (unsigned i = 0; i != NumInScalars; ++i) {
11763       unsigned Opcode = N->getOperand(i).getOpcode();
11764       if (Opcode == ISD::UNDEF) {
11765         Mask.push_back(-1);
11766         continue;
11767       }
11768
11769       // Operands can also be zero.
11770       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11771         assert(UsesZeroVector &&
11772                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11773                "Unexpected node found!");
11774         Mask.push_back(NumInScalars+i);
11775         continue;
11776       }
11777
11778       // If extracting from the first vector, just use the index directly.
11779       SDValue Extract = N->getOperand(i);
11780       SDValue ExtVal = Extract.getOperand(1);
11781       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11782       if (Extract.getOperand(0) == VecIn1) {
11783         Mask.push_back(ExtIndex);
11784         continue;
11785       }
11786
11787       // Otherwise, use InIdx + InputVecSize
11788       Mask.push_back(InNumElements + ExtIndex);
11789     }
11790
11791     // Avoid introducing illegal shuffles with zero.
11792     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11793       return SDValue();
11794
11795     // We can't generate a shuffle node with mismatched input and output types.
11796     // Attempt to transform a single input vector to the correct type.
11797     if ((VT != VecIn1.getValueType())) {
11798       // If the input vector type has a different base type to the output
11799       // vector type, bail out.
11800       EVT VTElemType = VT.getVectorElementType();
11801       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11802           (VecIn2.getNode() &&
11803            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11804         return SDValue();
11805
11806       // If the input vector is too small, widen it.
11807       // We only support widening of vectors which are half the size of the
11808       // output registers. For example XMM->YMM widening on X86 with AVX.
11809       EVT VecInT = VecIn1.getValueType();
11810       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11811         // If we only have one small input, widen it by adding undef values.
11812         if (!VecIn2.getNode())
11813           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11814                                DAG.getUNDEF(VecIn1.getValueType()));
11815         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11816           // If we have two small inputs of the same type, try to concat them.
11817           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11818           VecIn2 = SDValue(nullptr, 0);
11819         } else
11820           return SDValue();
11821       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11822         // If the input vector is too large, try to split it.
11823         // We don't support having two input vectors that are too large.
11824         // If the zero vector was used, we can not split the vector,
11825         // since we'd need 3 inputs.
11826         if (UsesZeroVector || VecIn2.getNode())
11827           return SDValue();
11828
11829         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11830           return SDValue();
11831
11832         // Try to replace VecIn1 with two extract_subvectors
11833         // No need to update the masks, they should still be correct.
11834         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11835           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11836         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11837           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11838       } else
11839         return SDValue();
11840     }
11841
11842     if (UsesZeroVector)
11843       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11844                                 DAG.getConstantFP(0.0, dl, VT);
11845     else
11846       // If VecIn2 is unused then change it to undef.
11847       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11848
11849     // Check that we were able to transform all incoming values to the same
11850     // type.
11851     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11852         VecIn1.getValueType() != VT)
11853           return SDValue();
11854
11855     // Return the new VECTOR_SHUFFLE node.
11856     SDValue Ops[2];
11857     Ops[0] = VecIn1;
11858     Ops[1] = VecIn2;
11859     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11860   }
11861
11862   return SDValue();
11863 }
11864
11865 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
11866   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11867   EVT OpVT = N->getOperand(0).getValueType();
11868
11869   // If the operands are legal vectors, leave them alone.
11870   if (TLI.isTypeLegal(OpVT))
11871     return SDValue();
11872
11873   SDLoc DL(N);
11874   EVT VT = N->getValueType(0);
11875   SmallVector<SDValue, 8> Ops;
11876
11877   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
11878   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11879
11880   // Keep track of what we encounter.
11881   bool AnyInteger = false;
11882   bool AnyFP = false;
11883   for (const SDValue &Op : N->ops()) {
11884     if (ISD::BITCAST == Op.getOpcode() &&
11885         !Op.getOperand(0).getValueType().isVector())
11886       Ops.push_back(Op.getOperand(0));
11887     else if (ISD::UNDEF == Op.getOpcode())
11888       Ops.push_back(ScalarUndef);
11889     else
11890       return SDValue();
11891
11892     // Note whether we encounter an integer or floating point scalar.
11893     // If it's neither, bail out, it could be something weird like x86mmx.
11894     EVT LastOpVT = Ops.back().getValueType();
11895     if (LastOpVT.isFloatingPoint())
11896       AnyFP = true;
11897     else if (LastOpVT.isInteger())
11898       AnyInteger = true;
11899     else
11900       return SDValue();
11901   }
11902
11903   // If any of the operands is a floating point scalar bitcast to a vector,
11904   // use floating point types throughout, and bitcast everything.  
11905   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
11906   if (AnyFP) {
11907     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
11908     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11909     if (AnyInteger) {
11910       for (SDValue &Op : Ops) {
11911         if (Op.getValueType() == SVT)
11912           continue;
11913         if (Op.getOpcode() == ISD::UNDEF)
11914           Op = ScalarUndef;
11915         else
11916           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
11917       }
11918     }
11919   }
11920
11921   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
11922                                VT.getSizeInBits() / SVT.getSizeInBits());
11923   return DAG.getNode(ISD::BITCAST, DL, VT,
11924                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
11925 }
11926
11927 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11928   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11929   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11930   // inputs come from at most two distinct vectors, turn this into a shuffle
11931   // node.
11932
11933   // If we only have one input vector, we don't need to do any concatenation.
11934   if (N->getNumOperands() == 1)
11935     return N->getOperand(0);
11936
11937   // Check if all of the operands are undefs.
11938   EVT VT = N->getValueType(0);
11939   if (ISD::allOperandsUndef(N))
11940     return DAG.getUNDEF(VT);
11941
11942   // Optimize concat_vectors where all but the first of the vectors are undef.
11943   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
11944         return Op.getOpcode() == ISD::UNDEF;
11945       })) {
11946     SDValue In = N->getOperand(0);
11947     assert(In.getValueType().isVector() && "Must concat vectors");
11948
11949     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11950     if (In->getOpcode() == ISD::BITCAST &&
11951         !In->getOperand(0)->getValueType(0).isVector()) {
11952       SDValue Scalar = In->getOperand(0);
11953
11954       // If the bitcast type isn't legal, it might be a trunc of a legal type;
11955       // look through the trunc so we can still do the transform:
11956       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
11957       if (Scalar->getOpcode() == ISD::TRUNCATE &&
11958           !TLI.isTypeLegal(Scalar.getValueType()) &&
11959           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
11960         Scalar = Scalar->getOperand(0);
11961
11962       EVT SclTy = Scalar->getValueType(0);
11963
11964       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11965         return SDValue();
11966
11967       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11968                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11969       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11970         return SDValue();
11971
11972       SDLoc dl = SDLoc(N);
11973       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11974       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11975     }
11976   }
11977
11978   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11979   // We have already tested above for an UNDEF only concatenation.
11980   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11981   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11982   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11983     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11984   };
11985   bool AllBuildVectorsOrUndefs =
11986       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11987   if (AllBuildVectorsOrUndefs) {
11988     SmallVector<SDValue, 8> Opnds;
11989     EVT SVT = VT.getScalarType();
11990
11991     EVT MinVT = SVT;
11992     if (!SVT.isFloatingPoint()) {
11993       // If BUILD_VECTOR are from built from integer, they may have different
11994       // operand types. Get the smallest type and truncate all operands to it.
11995       bool FoundMinVT = false;
11996       for (const SDValue &Op : N->ops())
11997         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11998           EVT OpSVT = Op.getOperand(0)->getValueType(0);
11999           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12000           FoundMinVT = true;
12001         }
12002       assert(FoundMinVT && "Concat vector type mismatch");
12003     }
12004
12005     for (const SDValue &Op : N->ops()) {
12006       EVT OpVT = Op.getValueType();
12007       unsigned NumElts = OpVT.getVectorNumElements();
12008
12009       if (ISD::UNDEF == Op.getOpcode())
12010         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12011
12012       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12013         if (SVT.isFloatingPoint()) {
12014           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12015           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12016         } else {
12017           for (unsigned i = 0; i != NumElts; ++i)
12018             Opnds.push_back(
12019                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12020         }
12021       }
12022     }
12023
12024     assert(VT.getVectorNumElements() == Opnds.size() &&
12025            "Concat vector type mismatch");
12026     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12027   }
12028
12029   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12030   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12031     return V;
12032
12033   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12034   // nodes often generate nop CONCAT_VECTOR nodes.
12035   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12036   // place the incoming vectors at the exact same location.
12037   SDValue SingleSource = SDValue();
12038   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12039
12040   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12041     SDValue Op = N->getOperand(i);
12042
12043     if (Op.getOpcode() == ISD::UNDEF)
12044       continue;
12045
12046     // Check if this is the identity extract:
12047     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12048       return SDValue();
12049
12050     // Find the single incoming vector for the extract_subvector.
12051     if (SingleSource.getNode()) {
12052       if (Op.getOperand(0) != SingleSource)
12053         return SDValue();
12054     } else {
12055       SingleSource = Op.getOperand(0);
12056
12057       // Check the source type is the same as the type of the result.
12058       // If not, this concat may extend the vector, so we can not
12059       // optimize it away.
12060       if (SingleSource.getValueType() != N->getValueType(0))
12061         return SDValue();
12062     }
12063
12064     unsigned IdentityIndex = i * PartNumElem;
12065     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12066     // The extract index must be constant.
12067     if (!CS)
12068       return SDValue();
12069
12070     // Check that we are reading from the identity index.
12071     if (CS->getZExtValue() != IdentityIndex)
12072       return SDValue();
12073   }
12074
12075   if (SingleSource.getNode())
12076     return SingleSource;
12077
12078   return SDValue();
12079 }
12080
12081 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12082   EVT NVT = N->getValueType(0);
12083   SDValue V = N->getOperand(0);
12084
12085   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12086     // Combine:
12087     //    (extract_subvec (concat V1, V2, ...), i)
12088     // Into:
12089     //    Vi if possible
12090     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12091     // type.
12092     if (V->getOperand(0).getValueType() != NVT)
12093       return SDValue();
12094     unsigned Idx = N->getConstantOperandVal(1);
12095     unsigned NumElems = NVT.getVectorNumElements();
12096     assert((Idx % NumElems) == 0 &&
12097            "IDX in concat is not a multiple of the result vector length.");
12098     return V->getOperand(Idx / NumElems);
12099   }
12100
12101   // Skip bitcasting
12102   if (V->getOpcode() == ISD::BITCAST)
12103     V = V.getOperand(0);
12104
12105   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12106     SDLoc dl(N);
12107     // Handle only simple case where vector being inserted and vector
12108     // being extracted are of same type, and are half size of larger vectors.
12109     EVT BigVT = V->getOperand(0).getValueType();
12110     EVT SmallVT = V->getOperand(1).getValueType();
12111     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12112       return SDValue();
12113
12114     // Only handle cases where both indexes are constants with the same type.
12115     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12116     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12117
12118     if (InsIdx && ExtIdx &&
12119         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12120         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12121       // Combine:
12122       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12123       // Into:
12124       //    indices are equal or bit offsets are equal => V1
12125       //    otherwise => (extract_subvec V1, ExtIdx)
12126       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12127           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12128         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12129       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12130                          DAG.getNode(ISD::BITCAST, dl,
12131                                      N->getOperand(0).getValueType(),
12132                                      V->getOperand(0)), N->getOperand(1));
12133     }
12134   }
12135
12136   return SDValue();
12137 }
12138
12139 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12140                                                  SDValue V, SelectionDAG &DAG) {
12141   SDLoc DL(V);
12142   EVT VT = V.getValueType();
12143
12144   switch (V.getOpcode()) {
12145   default:
12146     return V;
12147
12148   case ISD::CONCAT_VECTORS: {
12149     EVT OpVT = V->getOperand(0).getValueType();
12150     int OpSize = OpVT.getVectorNumElements();
12151     SmallBitVector OpUsedElements(OpSize, false);
12152     bool FoundSimplification = false;
12153     SmallVector<SDValue, 4> NewOps;
12154     NewOps.reserve(V->getNumOperands());
12155     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12156       SDValue Op = V->getOperand(i);
12157       bool OpUsed = false;
12158       for (int j = 0; j < OpSize; ++j)
12159         if (UsedElements[i * OpSize + j]) {
12160           OpUsedElements[j] = true;
12161           OpUsed = true;
12162         }
12163       NewOps.push_back(
12164           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12165                  : DAG.getUNDEF(OpVT));
12166       FoundSimplification |= Op == NewOps.back();
12167       OpUsedElements.reset();
12168     }
12169     if (FoundSimplification)
12170       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12171     return V;
12172   }
12173
12174   case ISD::INSERT_SUBVECTOR: {
12175     SDValue BaseV = V->getOperand(0);
12176     SDValue SubV = V->getOperand(1);
12177     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12178     if (!IdxN)
12179       return V;
12180
12181     int SubSize = SubV.getValueType().getVectorNumElements();
12182     int Idx = IdxN->getZExtValue();
12183     bool SubVectorUsed = false;
12184     SmallBitVector SubUsedElements(SubSize, false);
12185     for (int i = 0; i < SubSize; ++i)
12186       if (UsedElements[i + Idx]) {
12187         SubVectorUsed = true;
12188         SubUsedElements[i] = true;
12189         UsedElements[i + Idx] = false;
12190       }
12191
12192     // Now recurse on both the base and sub vectors.
12193     SDValue SimplifiedSubV =
12194         SubVectorUsed
12195             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12196             : DAG.getUNDEF(SubV.getValueType());
12197     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12198     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12199       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12200                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12201     return V;
12202   }
12203   }
12204 }
12205
12206 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12207                                        SDValue N1, SelectionDAG &DAG) {
12208   EVT VT = SVN->getValueType(0);
12209   int NumElts = VT.getVectorNumElements();
12210   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12211   for (int M : SVN->getMask())
12212     if (M >= 0 && M < NumElts)
12213       N0UsedElements[M] = true;
12214     else if (M >= NumElts)
12215       N1UsedElements[M - NumElts] = true;
12216
12217   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12218   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12219   if (S0 == N0 && S1 == N1)
12220     return SDValue();
12221
12222   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12223 }
12224
12225 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12226 // or turn a shuffle of a single concat into simpler shuffle then concat.
12227 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12228   EVT VT = N->getValueType(0);
12229   unsigned NumElts = VT.getVectorNumElements();
12230
12231   SDValue N0 = N->getOperand(0);
12232   SDValue N1 = N->getOperand(1);
12233   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12234
12235   SmallVector<SDValue, 4> Ops;
12236   EVT ConcatVT = N0.getOperand(0).getValueType();
12237   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12238   unsigned NumConcats = NumElts / NumElemsPerConcat;
12239
12240   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12241   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12242   // half vector elements.
12243   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12244       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12245                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12246     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12247                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12248     N1 = DAG.getUNDEF(ConcatVT);
12249     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12250   }
12251
12252   // Look at every vector that's inserted. We're looking for exact
12253   // subvector-sized copies from a concatenated vector
12254   for (unsigned I = 0; I != NumConcats; ++I) {
12255     // Make sure we're dealing with a copy.
12256     unsigned Begin = I * NumElemsPerConcat;
12257     bool AllUndef = true, NoUndef = true;
12258     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12259       if (SVN->getMaskElt(J) >= 0)
12260         AllUndef = false;
12261       else
12262         NoUndef = false;
12263     }
12264
12265     if (NoUndef) {
12266       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12267         return SDValue();
12268
12269       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12270         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12271           return SDValue();
12272
12273       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12274       if (FirstElt < N0.getNumOperands())
12275         Ops.push_back(N0.getOperand(FirstElt));
12276       else
12277         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12278
12279     } else if (AllUndef) {
12280       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12281     } else { // Mixed with general masks and undefs, can't do optimization.
12282       return SDValue();
12283     }
12284   }
12285
12286   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12287 }
12288
12289 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12290   EVT VT = N->getValueType(0);
12291   unsigned NumElts = VT.getVectorNumElements();
12292
12293   SDValue N0 = N->getOperand(0);
12294   SDValue N1 = N->getOperand(1);
12295
12296   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12297
12298   // Canonicalize shuffle undef, undef -> undef
12299   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12300     return DAG.getUNDEF(VT);
12301
12302   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12303
12304   // Canonicalize shuffle v, v -> v, undef
12305   if (N0 == N1) {
12306     SmallVector<int, 8> NewMask;
12307     for (unsigned i = 0; i != NumElts; ++i) {
12308       int Idx = SVN->getMaskElt(i);
12309       if (Idx >= (int)NumElts) Idx -= NumElts;
12310       NewMask.push_back(Idx);
12311     }
12312     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12313                                 &NewMask[0]);
12314   }
12315
12316   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12317   if (N0.getOpcode() == ISD::UNDEF) {
12318     SmallVector<int, 8> NewMask;
12319     for (unsigned i = 0; i != NumElts; ++i) {
12320       int Idx = SVN->getMaskElt(i);
12321       if (Idx >= 0) {
12322         if (Idx >= (int)NumElts)
12323           Idx -= NumElts;
12324         else
12325           Idx = -1; // remove reference to lhs
12326       }
12327       NewMask.push_back(Idx);
12328     }
12329     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12330                                 &NewMask[0]);
12331   }
12332
12333   // Remove references to rhs if it is undef
12334   if (N1.getOpcode() == ISD::UNDEF) {
12335     bool Changed = false;
12336     SmallVector<int, 8> NewMask;
12337     for (unsigned i = 0; i != NumElts; ++i) {
12338       int Idx = SVN->getMaskElt(i);
12339       if (Idx >= (int)NumElts) {
12340         Idx = -1;
12341         Changed = true;
12342       }
12343       NewMask.push_back(Idx);
12344     }
12345     if (Changed)
12346       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12347   }
12348
12349   // If it is a splat, check if the argument vector is another splat or a
12350   // build_vector.
12351   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12352     SDNode *V = N0.getNode();
12353
12354     // If this is a bit convert that changes the element type of the vector but
12355     // not the number of vector elements, look through it.  Be careful not to
12356     // look though conversions that change things like v4f32 to v2f64.
12357     if (V->getOpcode() == ISD::BITCAST) {
12358       SDValue ConvInput = V->getOperand(0);
12359       if (ConvInput.getValueType().isVector() &&
12360           ConvInput.getValueType().getVectorNumElements() == NumElts)
12361         V = ConvInput.getNode();
12362     }
12363
12364     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12365       assert(V->getNumOperands() == NumElts &&
12366              "BUILD_VECTOR has wrong number of operands");
12367       SDValue Base;
12368       bool AllSame = true;
12369       for (unsigned i = 0; i != NumElts; ++i) {
12370         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12371           Base = V->getOperand(i);
12372           break;
12373         }
12374       }
12375       // Splat of <u, u, u, u>, return <u, u, u, u>
12376       if (!Base.getNode())
12377         return N0;
12378       for (unsigned i = 0; i != NumElts; ++i) {
12379         if (V->getOperand(i) != Base) {
12380           AllSame = false;
12381           break;
12382         }
12383       }
12384       // Splat of <x, x, x, x>, return <x, x, x, x>
12385       if (AllSame)
12386         return N0;
12387
12388       // Canonicalize any other splat as a build_vector.
12389       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12390       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12391       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12392                                   V->getValueType(0), Ops);
12393
12394       // We may have jumped through bitcasts, so the type of the
12395       // BUILD_VECTOR may not match the type of the shuffle.
12396       if (V->getValueType(0) != VT)
12397         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12398       return NewBV;
12399     }
12400   }
12401
12402   // There are various patterns used to build up a vector from smaller vectors,
12403   // subvectors, or elements. Scan chains of these and replace unused insertions
12404   // or components with undef.
12405   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12406     return S;
12407
12408   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12409       Level < AfterLegalizeVectorOps &&
12410       (N1.getOpcode() == ISD::UNDEF ||
12411       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12412        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12413     SDValue V = partitionShuffleOfConcats(N, DAG);
12414
12415     if (V.getNode())
12416       return V;
12417   }
12418
12419   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12420   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12421   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12422     SmallVector<SDValue, 8> Ops;
12423     for (int M : SVN->getMask()) {
12424       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12425       if (M >= 0) {
12426         int Idx = M % NumElts;
12427         SDValue &S = (M < (int)NumElts ? N0 : N1);
12428         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12429           Op = S.getOperand(Idx);
12430         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12431           if (Idx == 0)
12432             Op = S.getOperand(0);
12433         } else {
12434           // Operand can't be combined - bail out.
12435           break;
12436         }
12437       }
12438       Ops.push_back(Op);
12439     }
12440     if (Ops.size() == VT.getVectorNumElements()) {
12441       // BUILD_VECTOR requires all inputs to be of the same type, find the
12442       // maximum type and extend them all.
12443       EVT SVT = VT.getScalarType();
12444       if (SVT.isInteger())
12445         for (SDValue &Op : Ops)
12446           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12447       if (SVT != VT.getScalarType())
12448         for (SDValue &Op : Ops)
12449           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12450                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12451                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12452       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12453     }
12454   }
12455
12456   // If this shuffle only has a single input that is a bitcasted shuffle,
12457   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12458   // back to their original types.
12459   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12460       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12461       TLI.isTypeLegal(VT)) {
12462
12463     // Peek through the bitcast only if there is one user.
12464     SDValue BC0 = N0;
12465     while (BC0.getOpcode() == ISD::BITCAST) {
12466       if (!BC0.hasOneUse())
12467         break;
12468       BC0 = BC0.getOperand(0);
12469     }
12470
12471     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12472       if (Scale == 1)
12473         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12474
12475       SmallVector<int, 8> NewMask;
12476       for (int M : Mask)
12477         for (int s = 0; s != Scale; ++s)
12478           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12479       return NewMask;
12480     };
12481
12482     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12483       EVT SVT = VT.getScalarType();
12484       EVT InnerVT = BC0->getValueType(0);
12485       EVT InnerSVT = InnerVT.getScalarType();
12486
12487       // Determine which shuffle works with the smaller scalar type.
12488       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12489       EVT ScaleSVT = ScaleVT.getScalarType();
12490
12491       if (TLI.isTypeLegal(ScaleVT) &&
12492           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12493           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12494
12495         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12496         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12497
12498         // Scale the shuffle masks to the smaller scalar type.
12499         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12500         SmallVector<int, 8> InnerMask =
12501             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12502         SmallVector<int, 8> OuterMask =
12503             ScaleShuffleMask(SVN->getMask(), OuterScale);
12504
12505         // Merge the shuffle masks.
12506         SmallVector<int, 8> NewMask;
12507         for (int M : OuterMask)
12508           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12509
12510         // Test for shuffle mask legality over both commutations.
12511         SDValue SV0 = BC0->getOperand(0);
12512         SDValue SV1 = BC0->getOperand(1);
12513         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12514         if (!LegalMask) {
12515           std::swap(SV0, SV1);
12516           ShuffleVectorSDNode::commuteMask(NewMask);
12517           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12518         }
12519
12520         if (LegalMask) {
12521           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12522           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12523           return DAG.getNode(
12524               ISD::BITCAST, SDLoc(N), VT,
12525               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12526         }
12527       }
12528     }
12529   }
12530
12531   // Canonicalize shuffles according to rules:
12532   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12533   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12534   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12535   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12536       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12537       TLI.isTypeLegal(VT)) {
12538     // The incoming shuffle must be of the same type as the result of the
12539     // current shuffle.
12540     assert(N1->getOperand(0).getValueType() == VT &&
12541            "Shuffle types don't match");
12542
12543     SDValue SV0 = N1->getOperand(0);
12544     SDValue SV1 = N1->getOperand(1);
12545     bool HasSameOp0 = N0 == SV0;
12546     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12547     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12548       // Commute the operands of this shuffle so that next rule
12549       // will trigger.
12550       return DAG.getCommutedVectorShuffle(*SVN);
12551   }
12552
12553   // Try to fold according to rules:
12554   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12555   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12556   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12557   // Don't try to fold shuffles with illegal type.
12558   // Only fold if this shuffle is the only user of the other shuffle.
12559   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12560       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12561     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12562
12563     // The incoming shuffle must be of the same type as the result of the
12564     // current shuffle.
12565     assert(OtherSV->getOperand(0).getValueType() == VT &&
12566            "Shuffle types don't match");
12567
12568     SDValue SV0, SV1;
12569     SmallVector<int, 4> Mask;
12570     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12571     // operand, and SV1 as the second operand.
12572     for (unsigned i = 0; i != NumElts; ++i) {
12573       int Idx = SVN->getMaskElt(i);
12574       if (Idx < 0) {
12575         // Propagate Undef.
12576         Mask.push_back(Idx);
12577         continue;
12578       }
12579
12580       SDValue CurrentVec;
12581       if (Idx < (int)NumElts) {
12582         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12583         // shuffle mask to identify which vector is actually referenced.
12584         Idx = OtherSV->getMaskElt(Idx);
12585         if (Idx < 0) {
12586           // Propagate Undef.
12587           Mask.push_back(Idx);
12588           continue;
12589         }
12590
12591         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12592                                            : OtherSV->getOperand(1);
12593       } else {
12594         // This shuffle index references an element within N1.
12595         CurrentVec = N1;
12596       }
12597
12598       // Simple case where 'CurrentVec' is UNDEF.
12599       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12600         Mask.push_back(-1);
12601         continue;
12602       }
12603
12604       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12605       // will be the first or second operand of the combined shuffle.
12606       Idx = Idx % NumElts;
12607       if (!SV0.getNode() || SV0 == CurrentVec) {
12608         // Ok. CurrentVec is the left hand side.
12609         // Update the mask accordingly.
12610         SV0 = CurrentVec;
12611         Mask.push_back(Idx);
12612         continue;
12613       }
12614
12615       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12616       if (SV1.getNode() && SV1 != CurrentVec)
12617         return SDValue();
12618
12619       // Ok. CurrentVec is the right hand side.
12620       // Update the mask accordingly.
12621       SV1 = CurrentVec;
12622       Mask.push_back(Idx + NumElts);
12623     }
12624
12625     // Check if all indices in Mask are Undef. In case, propagate Undef.
12626     bool isUndefMask = true;
12627     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12628       isUndefMask &= Mask[i] < 0;
12629
12630     if (isUndefMask)
12631       return DAG.getUNDEF(VT);
12632
12633     if (!SV0.getNode())
12634       SV0 = DAG.getUNDEF(VT);
12635     if (!SV1.getNode())
12636       SV1 = DAG.getUNDEF(VT);
12637
12638     // Avoid introducing shuffles with illegal mask.
12639     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12640       ShuffleVectorSDNode::commuteMask(Mask);
12641
12642       if (!TLI.isShuffleMaskLegal(Mask, VT))
12643         return SDValue();
12644
12645       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12646       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12647       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12648       std::swap(SV0, SV1);
12649     }
12650
12651     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12652     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12653     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12654     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12655   }
12656
12657   return SDValue();
12658 }
12659
12660 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12661   SDValue InVal = N->getOperand(0);
12662   EVT VT = N->getValueType(0);
12663
12664   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12665   // with a VECTOR_SHUFFLE.
12666   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12667     SDValue InVec = InVal->getOperand(0);
12668     SDValue EltNo = InVal->getOperand(1);
12669
12670     // FIXME: We could support implicit truncation if the shuffle can be
12671     // scaled to a smaller vector scalar type.
12672     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12673     if (C0 && VT == InVec.getValueType() &&
12674         VT.getScalarType() == InVal.getValueType()) {
12675       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12676       int Elt = C0->getZExtValue();
12677       NewMask[0] = Elt;
12678
12679       if (TLI.isShuffleMaskLegal(NewMask, VT))
12680         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12681                                     NewMask);
12682     }
12683   }
12684
12685   return SDValue();
12686 }
12687
12688 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12689   SDValue N0 = N->getOperand(0);
12690   SDValue N2 = N->getOperand(2);
12691
12692   // If the input vector is a concatenation, and the insert replaces
12693   // one of the halves, we can optimize into a single concat_vectors.
12694   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12695       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12696     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12697     EVT VT = N->getValueType(0);
12698
12699     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12700     // (concat_vectors Z, Y)
12701     if (InsIdx == 0)
12702       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12703                          N->getOperand(1), N0.getOperand(1));
12704
12705     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12706     // (concat_vectors X, Z)
12707     if (InsIdx == VT.getVectorNumElements()/2)
12708       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12709                          N0.getOperand(0), N->getOperand(1));
12710   }
12711
12712   return SDValue();
12713 }
12714
12715 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12716   SDValue N0 = N->getOperand(0);
12717
12718   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12719   if (N0->getOpcode() == ISD::FP16_TO_FP)
12720     return N0->getOperand(0);
12721
12722   return SDValue();
12723 }
12724
12725 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12726 /// with the destination vector and a zero vector.
12727 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12728 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12729 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12730   EVT VT = N->getValueType(0);
12731   SDValue LHS = N->getOperand(0);
12732   SDValue RHS = N->getOperand(1);
12733   SDLoc dl(N);
12734
12735   // Make sure we're not running after operation legalization where it 
12736   // may have custom lowered the vector shuffles.
12737   if (LegalOperations)
12738     return SDValue();
12739
12740   if (N->getOpcode() != ISD::AND)
12741     return SDValue();
12742
12743   if (RHS.getOpcode() == ISD::BITCAST)
12744     RHS = RHS.getOperand(0);
12745
12746   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12747     SmallVector<int, 8> Indices;
12748     unsigned NumElts = RHS.getNumOperands();
12749
12750     for (unsigned i = 0; i != NumElts; ++i) {
12751       SDValue Elt = RHS.getOperand(i);
12752       if (!isa<ConstantSDNode>(Elt))
12753         return SDValue();
12754
12755       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12756         Indices.push_back(i);
12757       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12758         Indices.push_back(NumElts+i);
12759       else
12760         return SDValue();
12761     }
12762
12763     // Let's see if the target supports this vector_shuffle.
12764     EVT RVT = RHS.getValueType();
12765     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12766       return SDValue();
12767
12768     // Return the new VECTOR_SHUFFLE node.
12769     EVT EltVT = RVT.getVectorElementType();
12770     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12771                                    DAG.getConstant(0, dl, EltVT));
12772     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12773     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12774     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12775     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12776   }
12777
12778   return SDValue();
12779 }
12780
12781 /// Visit a binary vector operation, like ADD.
12782 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12783   assert(N->getValueType(0).isVector() &&
12784          "SimplifyVBinOp only works on vectors!");
12785
12786   SDValue LHS = N->getOperand(0);
12787   SDValue RHS = N->getOperand(1);
12788
12789   if (SDValue Shuffle = XformToShuffleWithZero(N))
12790     return Shuffle;
12791
12792   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12793   // this operation.
12794   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12795       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12796     // Check if both vectors are constants. If not bail out.
12797     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12798           cast<BuildVectorSDNode>(RHS)->isConstant()))
12799       return SDValue();
12800
12801     SmallVector<SDValue, 8> Ops;
12802     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12803       SDValue LHSOp = LHS.getOperand(i);
12804       SDValue RHSOp = RHS.getOperand(i);
12805
12806       // Can't fold divide by zero.
12807       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12808           N->getOpcode() == ISD::FDIV) {
12809         if ((RHSOp.getOpcode() == ISD::Constant &&
12810              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12811             (RHSOp.getOpcode() == ISD::ConstantFP &&
12812              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12813           break;
12814       }
12815
12816       EVT VT = LHSOp.getValueType();
12817       EVT RVT = RHSOp.getValueType();
12818       if (RVT != VT) {
12819         // Integer BUILD_VECTOR operands may have types larger than the element
12820         // size (e.g., when the element type is not legal).  Prior to type
12821         // legalization, the types may not match between the two BUILD_VECTORS.
12822         // Truncate one of the operands to make them match.
12823         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12824           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12825         } else {
12826           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12827           VT = RVT;
12828         }
12829       }
12830       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12831                                    LHSOp, RHSOp);
12832       if (FoldOp.getOpcode() != ISD::UNDEF &&
12833           FoldOp.getOpcode() != ISD::Constant &&
12834           FoldOp.getOpcode() != ISD::ConstantFP)
12835         break;
12836       Ops.push_back(FoldOp);
12837       AddToWorklist(FoldOp.getNode());
12838     }
12839
12840     if (Ops.size() == LHS.getNumOperands())
12841       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12842   }
12843
12844   // Type legalization might introduce new shuffles in the DAG.
12845   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12846   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12847   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12848       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12849       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12850       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12851     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12852     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12853
12854     if (SVN0->getMask().equals(SVN1->getMask())) {
12855       EVT VT = N->getValueType(0);
12856       SDValue UndefVector = LHS.getOperand(1);
12857       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12858                                      LHS.getOperand(0), RHS.getOperand(0));
12859       AddUsersToWorklist(N);
12860       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12861                                   &SVN0->getMask()[0]);
12862     }
12863   }
12864
12865   return SDValue();
12866 }
12867
12868 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12869                                     SDValue N1, SDValue N2){
12870   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12871
12872   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12873                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12874
12875   // If we got a simplified select_cc node back from SimplifySelectCC, then
12876   // break it down into a new SETCC node, and a new SELECT node, and then return
12877   // the SELECT node, since we were called with a SELECT node.
12878   if (SCC.getNode()) {
12879     // Check to see if we got a select_cc back (to turn into setcc/select).
12880     // Otherwise, just return whatever node we got back, like fabs.
12881     if (SCC.getOpcode() == ISD::SELECT_CC) {
12882       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12883                                   N0.getValueType(),
12884                                   SCC.getOperand(0), SCC.getOperand(1),
12885                                   SCC.getOperand(4));
12886       AddToWorklist(SETCC.getNode());
12887       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12888                            SCC.getOperand(2), SCC.getOperand(3));
12889     }
12890
12891     return SCC;
12892   }
12893   return SDValue();
12894 }
12895
12896 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12897 /// being selected between, see if we can simplify the select.  Callers of this
12898 /// should assume that TheSelect is deleted if this returns true.  As such, they
12899 /// should return the appropriate thing (e.g. the node) back to the top-level of
12900 /// the DAG combiner loop to avoid it being looked at.
12901 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12902                                     SDValue RHS) {
12903
12904   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12905   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
12906   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
12907     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
12908       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
12909       SDValue Sqrt = RHS;
12910       ISD::CondCode CC;
12911       SDValue CmpLHS;
12912       const ConstantFPSDNode *NegZero = nullptr;
12913
12914       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
12915         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
12916         CmpLHS = TheSelect->getOperand(0);
12917         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
12918       } else {
12919         // SELECT or VSELECT
12920         SDValue Cmp = TheSelect->getOperand(0);
12921         if (Cmp.getOpcode() == ISD::SETCC) {
12922           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
12923           CmpLHS = Cmp.getOperand(0);
12924           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
12925         }
12926       }
12927       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
12928           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
12929           CC == ISD::SETULT || CC == ISD::SETLT)) {
12930         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12931         CombineTo(TheSelect, Sqrt);
12932         return true;
12933       }
12934     }
12935   }
12936   // Cannot simplify select with vector condition
12937   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12938
12939   // If this is a select from two identical things, try to pull the operation
12940   // through the select.
12941   if (LHS.getOpcode() != RHS.getOpcode() ||
12942       !LHS.hasOneUse() || !RHS.hasOneUse())
12943     return false;
12944
12945   // If this is a load and the token chain is identical, replace the select
12946   // of two loads with a load through a select of the address to load from.
12947   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12948   // constants have been dropped into the constant pool.
12949   if (LHS.getOpcode() == ISD::LOAD) {
12950     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12951     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12952
12953     // Token chains must be identical.
12954     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12955         // Do not let this transformation reduce the number of volatile loads.
12956         LLD->isVolatile() || RLD->isVolatile() ||
12957         // FIXME: If either is a pre/post inc/dec load,
12958         // we'd need to split out the address adjustment.
12959         LLD->isIndexed() || RLD->isIndexed() ||
12960         // If this is an EXTLOAD, the VT's must match.
12961         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12962         // If this is an EXTLOAD, the kind of extension must match.
12963         (LLD->getExtensionType() != RLD->getExtensionType() &&
12964          // The only exception is if one of the extensions is anyext.
12965          LLD->getExtensionType() != ISD::EXTLOAD &&
12966          RLD->getExtensionType() != ISD::EXTLOAD) ||
12967         // FIXME: this discards src value information.  This is
12968         // over-conservative. It would be beneficial to be able to remember
12969         // both potential memory locations.  Since we are discarding
12970         // src value info, don't do the transformation if the memory
12971         // locations are not in the default address space.
12972         LLD->getPointerInfo().getAddrSpace() != 0 ||
12973         RLD->getPointerInfo().getAddrSpace() != 0 ||
12974         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12975                                       LLD->getBasePtr().getValueType()))
12976       return false;
12977
12978     // Check that the select condition doesn't reach either load.  If so,
12979     // folding this will induce a cycle into the DAG.  If not, this is safe to
12980     // xform, so create a select of the addresses.
12981     SDValue Addr;
12982     if (TheSelect->getOpcode() == ISD::SELECT) {
12983       SDNode *CondNode = TheSelect->getOperand(0).getNode();
12984       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12985           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12986         return false;
12987       // The loads must not depend on one another.
12988       if (LLD->isPredecessorOf(RLD) ||
12989           RLD->isPredecessorOf(LLD))
12990         return false;
12991       Addr = DAG.getSelect(SDLoc(TheSelect),
12992                            LLD->getBasePtr().getValueType(),
12993                            TheSelect->getOperand(0), LLD->getBasePtr(),
12994                            RLD->getBasePtr());
12995     } else {  // Otherwise SELECT_CC
12996       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12997       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12998
12999       if ((LLD->hasAnyUseOfValue(1) &&
13000            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13001           (RLD->hasAnyUseOfValue(1) &&
13002            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13003         return false;
13004
13005       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13006                          LLD->getBasePtr().getValueType(),
13007                          TheSelect->getOperand(0),
13008                          TheSelect->getOperand(1),
13009                          LLD->getBasePtr(), RLD->getBasePtr(),
13010                          TheSelect->getOperand(4));
13011     }
13012
13013     SDValue Load;
13014     // It is safe to replace the two loads if they have different alignments,
13015     // but the new load must be the minimum (most restrictive) alignment of the
13016     // inputs.
13017     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13018     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13019     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13020       Load = DAG.getLoad(TheSelect->getValueType(0),
13021                          SDLoc(TheSelect),
13022                          // FIXME: Discards pointer and AA info.
13023                          LLD->getChain(), Addr, MachinePointerInfo(),
13024                          LLD->isVolatile(), LLD->isNonTemporal(),
13025                          isInvariant, Alignment);
13026     } else {
13027       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13028                             RLD->getExtensionType() : LLD->getExtensionType(),
13029                             SDLoc(TheSelect),
13030                             TheSelect->getValueType(0),
13031                             // FIXME: Discards pointer and AA info.
13032                             LLD->getChain(), Addr, MachinePointerInfo(),
13033                             LLD->getMemoryVT(), LLD->isVolatile(),
13034                             LLD->isNonTemporal(), isInvariant, Alignment);
13035     }
13036
13037     // Users of the select now use the result of the load.
13038     CombineTo(TheSelect, Load);
13039
13040     // Users of the old loads now use the new load's chain.  We know the
13041     // old-load value is dead now.
13042     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13043     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13044     return true;
13045   }
13046
13047   return false;
13048 }
13049
13050 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13051 /// where 'cond' is the comparison specified by CC.
13052 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13053                                       SDValue N2, SDValue N3,
13054                                       ISD::CondCode CC, bool NotExtCompare) {
13055   // (x ? y : y) -> y.
13056   if (N2 == N3) return N2;
13057
13058   EVT VT = N2.getValueType();
13059   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13060   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13061   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
13062
13063   // Determine if the condition we're dealing with is constant
13064   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13065                               N0, N1, CC, DL, false);
13066   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13067   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
13068
13069   // fold select_cc true, x, y -> x
13070   if (SCCC && !SCCC->isNullValue())
13071     return N2;
13072   // fold select_cc false, x, y -> y
13073   if (SCCC && SCCC->isNullValue())
13074     return N3;
13075
13076   // Check to see if we can simplify the select into an fabs node
13077   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13078     // Allow either -0.0 or 0.0
13079     if (CFP->getValueAPF().isZero()) {
13080       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13081       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13082           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13083           N2 == N3.getOperand(0))
13084         return DAG.getNode(ISD::FABS, DL, VT, N0);
13085
13086       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13087       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13088           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13089           N2.getOperand(0) == N3)
13090         return DAG.getNode(ISD::FABS, DL, VT, N3);
13091     }
13092   }
13093
13094   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13095   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13096   // in it.  This is a win when the constant is not otherwise available because
13097   // it replaces two constant pool loads with one.  We only do this if the FP
13098   // type is known to be legal, because if it isn't, then we are before legalize
13099   // types an we want the other legalization to happen first (e.g. to avoid
13100   // messing with soft float) and if the ConstantFP is not legal, because if
13101   // it is legal, we may not need to store the FP constant in a constant pool.
13102   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13103     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13104       if (TLI.isTypeLegal(N2.getValueType()) &&
13105           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13106                TargetLowering::Legal &&
13107            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13108            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13109           // If both constants have multiple uses, then we won't need to do an
13110           // extra load, they are likely around in registers for other users.
13111           (TV->hasOneUse() || FV->hasOneUse())) {
13112         Constant *Elts[] = {
13113           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13114           const_cast<ConstantFP*>(TV->getConstantFPValue())
13115         };
13116         Type *FPTy = Elts[0]->getType();
13117         const DataLayout &TD = *TLI.getDataLayout();
13118
13119         // Create a ConstantArray of the two constants.
13120         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13121         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13122                                             TD.getPrefTypeAlignment(FPTy));
13123         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13124
13125         // Get the offsets to the 0 and 1 element of the array so that we can
13126         // select between them.
13127         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13128         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13129         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13130
13131         SDValue Cond = DAG.getSetCC(DL,
13132                                     getSetCCResultType(N0.getValueType()),
13133                                     N0, N1, CC);
13134         AddToWorklist(Cond.getNode());
13135         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13136                                           Cond, One, Zero);
13137         AddToWorklist(CstOffset.getNode());
13138         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13139                             CstOffset);
13140         AddToWorklist(CPIdx.getNode());
13141         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13142                            MachinePointerInfo::getConstantPool(), false,
13143                            false, false, Alignment);
13144       }
13145     }
13146
13147   // Check to see if we can perform the "gzip trick", transforming
13148   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13149   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13150       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
13151        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
13152     EVT XType = N0.getValueType();
13153     EVT AType = N2.getValueType();
13154     if (XType.bitsGE(AType)) {
13155       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13156       // single-bit constant.
13157       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13158         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13159         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13160         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13161                                        getShiftAmountTy(N0.getValueType()));
13162         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13163                                     XType, N0, ShCt);
13164         AddToWorklist(Shift.getNode());
13165
13166         if (XType.bitsGT(AType)) {
13167           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13168           AddToWorklist(Shift.getNode());
13169         }
13170
13171         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13172       }
13173
13174       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13175                                   XType, N0,
13176                                   DAG.getConstant(XType.getSizeInBits() - 1,
13177                                                   SDLoc(N0),
13178                                          getShiftAmountTy(N0.getValueType())));
13179       AddToWorklist(Shift.getNode());
13180
13181       if (XType.bitsGT(AType)) {
13182         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13183         AddToWorklist(Shift.getNode());
13184       }
13185
13186       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13187     }
13188   }
13189
13190   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13191   // where y is has a single bit set.
13192   // A plaintext description would be, we can turn the SELECT_CC into an AND
13193   // when the condition can be materialized as an all-ones register.  Any
13194   // single bit-test can be materialized as an all-ones register with
13195   // shift-left and shift-right-arith.
13196   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13197       N0->getValueType(0) == VT &&
13198       N1C && N1C->isNullValue() &&
13199       N2C && N2C->isNullValue()) {
13200     SDValue AndLHS = N0->getOperand(0);
13201     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13202     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13203       // Shift the tested bit over the sign bit.
13204       APInt AndMask = ConstAndRHS->getAPIntValue();
13205       SDValue ShlAmt =
13206         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13207                         getShiftAmountTy(AndLHS.getValueType()));
13208       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13209
13210       // Now arithmetic right shift it all the way over, so the result is either
13211       // all-ones, or zero.
13212       SDValue ShrAmt =
13213         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13214                         getShiftAmountTy(Shl.getValueType()));
13215       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13216
13217       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13218     }
13219   }
13220
13221   // fold select C, 16, 0 -> shl C, 4
13222   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13223       TLI.getBooleanContents(N0.getValueType()) ==
13224           TargetLowering::ZeroOrOneBooleanContent) {
13225
13226     // If the caller doesn't want us to simplify this into a zext of a compare,
13227     // don't do it.
13228     if (NotExtCompare && N2C->getAPIntValue() == 1)
13229       return SDValue();
13230
13231     // Get a SetCC of the condition
13232     // NOTE: Don't create a SETCC if it's not legal on this target.
13233     if (!LegalOperations ||
13234         TLI.isOperationLegal(ISD::SETCC,
13235           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13236       SDValue Temp, SCC;
13237       // cast from setcc result type to select result type
13238       if (LegalTypes) {
13239         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13240                             N0, N1, CC);
13241         if (N2.getValueType().bitsLT(SCC.getValueType()))
13242           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13243                                         N2.getValueType());
13244         else
13245           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13246                              N2.getValueType(), SCC);
13247       } else {
13248         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13249         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13250                            N2.getValueType(), SCC);
13251       }
13252
13253       AddToWorklist(SCC.getNode());
13254       AddToWorklist(Temp.getNode());
13255
13256       if (N2C->getAPIntValue() == 1)
13257         return Temp;
13258
13259       // shl setcc result by log2 n2c
13260       return DAG.getNode(
13261           ISD::SHL, DL, N2.getValueType(), Temp,
13262           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13263                           getShiftAmountTy(Temp.getValueType())));
13264     }
13265   }
13266
13267   // Check to see if this is the equivalent of setcc
13268   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13269   // otherwise, go ahead with the folds.
13270   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13271     EVT XType = N0.getValueType();
13272     if (!LegalOperations ||
13273         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13274       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13275       if (Res.getValueType() != VT)
13276         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13277       return Res;
13278     }
13279
13280     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13281     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13282         (!LegalOperations ||
13283          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13284       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13285       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13286                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13287                                          SDLoc(Ctlz),
13288                                        getShiftAmountTy(Ctlz.getValueType())));
13289     }
13290     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13291     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13292       SDLoc DL(N0);
13293       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13294                                   XType, DAG.getConstant(0, DL, XType), N0);
13295       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13296       return DAG.getNode(ISD::SRL, DL, XType,
13297                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13298                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13299                                          getShiftAmountTy(XType)));
13300     }
13301     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13302     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13303       SDLoc DL(N0);
13304       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13305                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13306                                          getShiftAmountTy(N0.getValueType())));
13307       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13308                                                                     XType));
13309     }
13310   }
13311
13312   // Check to see if this is an integer abs.
13313   // select_cc setg[te] X,  0,  X, -X ->
13314   // select_cc setgt    X, -1,  X, -X ->
13315   // select_cc setl[te] X,  0, -X,  X ->
13316   // select_cc setlt    X,  1, -X,  X ->
13317   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13318   if (N1C) {
13319     ConstantSDNode *SubC = nullptr;
13320     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13321          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13322         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13323       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13324     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13325               (N1C->isOne() && CC == ISD::SETLT)) &&
13326              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13327       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13328
13329     EVT XType = N0.getValueType();
13330     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13331       SDLoc DL(N0);
13332       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13333                                   N0,
13334                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13335                                          getShiftAmountTy(N0.getValueType())));
13336       SDValue Add = DAG.getNode(ISD::ADD, DL,
13337                                 XType, N0, Shift);
13338       AddToWorklist(Shift.getNode());
13339       AddToWorklist(Add.getNode());
13340       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13341     }
13342   }
13343
13344   return SDValue();
13345 }
13346
13347 /// This is a stub for TargetLowering::SimplifySetCC.
13348 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13349                                    SDValue N1, ISD::CondCode Cond,
13350                                    SDLoc DL, bool foldBooleans) {
13351   TargetLowering::DAGCombinerInfo
13352     DagCombineInfo(DAG, Level, false, this);
13353   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13354 }
13355
13356 /// Given an ISD::SDIV node expressing a divide by constant, return
13357 /// a DAG expression to select that will generate the same value by multiplying
13358 /// by a magic number.
13359 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13360 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13361   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13362   if (!C)
13363     return SDValue();
13364
13365   // Avoid division by zero.
13366   if (!C->getAPIntValue())
13367     return SDValue();
13368
13369   std::vector<SDNode*> Built;
13370   SDValue S =
13371       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13372
13373   for (SDNode *N : Built)
13374     AddToWorklist(N);
13375   return S;
13376 }
13377
13378 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13379 /// DAG expression that will generate the same value by right shifting.
13380 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13381   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13382   if (!C)
13383     return SDValue();
13384
13385   // Avoid division by zero.
13386   if (!C->getAPIntValue())
13387     return SDValue();
13388
13389   std::vector<SDNode *> Built;
13390   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13391
13392   for (SDNode *N : Built)
13393     AddToWorklist(N);
13394   return S;
13395 }
13396
13397 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13398 /// expression that will generate the same value by multiplying by a magic
13399 /// number.
13400 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13401 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13402   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13403   if (!C)
13404     return SDValue();
13405
13406   // Avoid division by zero.
13407   if (!C->getAPIntValue())
13408     return SDValue();
13409
13410   std::vector<SDNode*> Built;
13411   SDValue S =
13412       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13413
13414   for (SDNode *N : Built)
13415     AddToWorklist(N);
13416   return S;
13417 }
13418
13419 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13420   if (Level >= AfterLegalizeDAG)
13421     return SDValue();
13422
13423   // Expose the DAG combiner to the target combiner implementations.
13424   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13425
13426   unsigned Iterations = 0;
13427   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13428     if (Iterations) {
13429       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13430       // For the reciprocal, we need to find the zero of the function:
13431       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13432       //     =>
13433       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13434       //     does not require additional intermediate precision]
13435       EVT VT = Op.getValueType();
13436       SDLoc DL(Op);
13437       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13438
13439       AddToWorklist(Est.getNode());
13440
13441       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13442       for (unsigned i = 0; i < Iterations; ++i) {
13443         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13444         AddToWorklist(NewEst.getNode());
13445
13446         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13447         AddToWorklist(NewEst.getNode());
13448
13449         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13450         AddToWorklist(NewEst.getNode());
13451
13452         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13453         AddToWorklist(Est.getNode());
13454       }
13455     }
13456     return Est;
13457   }
13458
13459   return SDValue();
13460 }
13461
13462 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13463 /// For the reciprocal sqrt, we need to find the zero of the function:
13464 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13465 ///     =>
13466 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13467 /// As a result, we precompute A/2 prior to the iteration loop.
13468 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13469                                           unsigned Iterations) {
13470   EVT VT = Arg.getValueType();
13471   SDLoc DL(Arg);
13472   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13473
13474   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13475   // this entire sequence requires only one FP constant.
13476   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13477   AddToWorklist(HalfArg.getNode());
13478
13479   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13480   AddToWorklist(HalfArg.getNode());
13481
13482   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13483   for (unsigned i = 0; i < Iterations; ++i) {
13484     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13485     AddToWorklist(NewEst.getNode());
13486
13487     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13488     AddToWorklist(NewEst.getNode());
13489
13490     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13491     AddToWorklist(NewEst.getNode());
13492
13493     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13494     AddToWorklist(Est.getNode());
13495   }
13496   return Est;
13497 }
13498
13499 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13500 /// For the reciprocal sqrt, we need to find the zero of the function:
13501 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13502 ///     =>
13503 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13504 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13505                                           unsigned Iterations) {
13506   EVT VT = Arg.getValueType();
13507   SDLoc DL(Arg);
13508   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13509   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13510
13511   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13512   for (unsigned i = 0; i < Iterations; ++i) {
13513     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13514     AddToWorklist(HalfEst.getNode());
13515
13516     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13517     AddToWorklist(Est.getNode());
13518
13519     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13520     AddToWorklist(Est.getNode());
13521
13522     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13523     AddToWorklist(Est.getNode());
13524
13525     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13526     AddToWorklist(Est.getNode());
13527   }
13528   return Est;
13529 }
13530
13531 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13532   if (Level >= AfterLegalizeDAG)
13533     return SDValue();
13534
13535   // Expose the DAG combiner to the target combiner implementations.
13536   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13537   unsigned Iterations = 0;
13538   bool UseOneConstNR = false;
13539   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13540     AddToWorklist(Est.getNode());
13541     if (Iterations) {
13542       Est = UseOneConstNR ?
13543         BuildRsqrtNROneConst(Op, Est, Iterations) :
13544         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13545     }
13546     return Est;
13547   }
13548
13549   return SDValue();
13550 }
13551
13552 /// Return true if base is a frame index, which is known not to alias with
13553 /// anything but itself.  Provides base object and offset as results.
13554 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13555                            const GlobalValue *&GV, const void *&CV) {
13556   // Assume it is a primitive operation.
13557   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13558
13559   // If it's an adding a simple constant then integrate the offset.
13560   if (Base.getOpcode() == ISD::ADD) {
13561     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13562       Base = Base.getOperand(0);
13563       Offset += C->getZExtValue();
13564     }
13565   }
13566
13567   // Return the underlying GlobalValue, and update the Offset.  Return false
13568   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13569   // by multiple nodes with different offsets.
13570   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13571     GV = G->getGlobal();
13572     Offset += G->getOffset();
13573     return false;
13574   }
13575
13576   // Return the underlying Constant value, and update the Offset.  Return false
13577   // for ConstantSDNodes since the same constant pool entry may be represented
13578   // by multiple nodes with different offsets.
13579   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13580     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13581                                          : (const void *)C->getConstVal();
13582     Offset += C->getOffset();
13583     return false;
13584   }
13585   // If it's any of the following then it can't alias with anything but itself.
13586   return isa<FrameIndexSDNode>(Base);
13587 }
13588
13589 /// Return true if there is any possibility that the two addresses overlap.
13590 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13591   // If they are the same then they must be aliases.
13592   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13593
13594   // If they are both volatile then they cannot be reordered.
13595   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13596
13597   // Gather base node and offset information.
13598   SDValue Base1, Base2;
13599   int64_t Offset1, Offset2;
13600   const GlobalValue *GV1, *GV2;
13601   const void *CV1, *CV2;
13602   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13603                                       Base1, Offset1, GV1, CV1);
13604   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13605                                       Base2, Offset2, GV2, CV2);
13606
13607   // If they have a same base address then check to see if they overlap.
13608   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13609     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13610              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13611
13612   // It is possible for different frame indices to alias each other, mostly
13613   // when tail call optimization reuses return address slots for arguments.
13614   // To catch this case, look up the actual index of frame indices to compute
13615   // the real alias relationship.
13616   if (isFrameIndex1 && isFrameIndex2) {
13617     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13618     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13619     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13620     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13621              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13622   }
13623
13624   // Otherwise, if we know what the bases are, and they aren't identical, then
13625   // we know they cannot alias.
13626   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13627     return false;
13628
13629   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13630   // compared to the size and offset of the access, we may be able to prove they
13631   // do not alias.  This check is conservative for now to catch cases created by
13632   // splitting vector types.
13633   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13634       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13635       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13636        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13637       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13638     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13639     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13640
13641     // There is no overlap between these relatively aligned accesses of similar
13642     // size, return no alias.
13643     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13644         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13645       return false;
13646   }
13647
13648   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13649                    ? CombinerGlobalAA
13650                    : DAG.getSubtarget().useAA();
13651 #ifndef NDEBUG
13652   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13653       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13654     UseAA = false;
13655 #endif
13656   if (UseAA &&
13657       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13658     // Use alias analysis information.
13659     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13660                                  Op1->getSrcValueOffset());
13661     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13662         Op0->getSrcValueOffset() - MinOffset;
13663     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13664         Op1->getSrcValueOffset() - MinOffset;
13665     AliasAnalysis::AliasResult AAResult =
13666         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13667                                          Overlap1,
13668                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13669                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13670                                          Overlap2,
13671                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13672     if (AAResult == AliasAnalysis::NoAlias)
13673       return false;
13674   }
13675
13676   // Otherwise we have to assume they alias.
13677   return true;
13678 }
13679
13680 /// Walk up chain skipping non-aliasing memory nodes,
13681 /// looking for aliasing nodes and adding them to the Aliases vector.
13682 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13683                                    SmallVectorImpl<SDValue> &Aliases) {
13684   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13685   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13686
13687   // Get alias information for node.
13688   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13689
13690   // Starting off.
13691   Chains.push_back(OriginalChain);
13692   unsigned Depth = 0;
13693
13694   // Look at each chain and determine if it is an alias.  If so, add it to the
13695   // aliases list.  If not, then continue up the chain looking for the next
13696   // candidate.
13697   while (!Chains.empty()) {
13698     SDValue Chain = Chains.back();
13699     Chains.pop_back();
13700
13701     // For TokenFactor nodes, look at each operand and only continue up the
13702     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13703     // find more and revert to original chain since the xform is unlikely to be
13704     // profitable.
13705     //
13706     // FIXME: The depth check could be made to return the last non-aliasing
13707     // chain we found before we hit a tokenfactor rather than the original
13708     // chain.
13709     if (Depth > 6 || Aliases.size() == 2) {
13710       Aliases.clear();
13711       Aliases.push_back(OriginalChain);
13712       return;
13713     }
13714
13715     // Don't bother if we've been before.
13716     if (!Visited.insert(Chain.getNode()).second)
13717       continue;
13718
13719     switch (Chain.getOpcode()) {
13720     case ISD::EntryToken:
13721       // Entry token is ideal chain operand, but handled in FindBetterChain.
13722       break;
13723
13724     case ISD::LOAD:
13725     case ISD::STORE: {
13726       // Get alias information for Chain.
13727       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13728           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13729
13730       // If chain is alias then stop here.
13731       if (!(IsLoad && IsOpLoad) &&
13732           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13733         Aliases.push_back(Chain);
13734       } else {
13735         // Look further up the chain.
13736         Chains.push_back(Chain.getOperand(0));
13737         ++Depth;
13738       }
13739       break;
13740     }
13741
13742     case ISD::TokenFactor:
13743       // We have to check each of the operands of the token factor for "small"
13744       // token factors, so we queue them up.  Adding the operands to the queue
13745       // (stack) in reverse order maintains the original order and increases the
13746       // likelihood that getNode will find a matching token factor (CSE.)
13747       if (Chain.getNumOperands() > 16) {
13748         Aliases.push_back(Chain);
13749         break;
13750       }
13751       for (unsigned n = Chain.getNumOperands(); n;)
13752         Chains.push_back(Chain.getOperand(--n));
13753       ++Depth;
13754       break;
13755
13756     default:
13757       // For all other instructions we will just have to take what we can get.
13758       Aliases.push_back(Chain);
13759       break;
13760     }
13761   }
13762
13763   // We need to be careful here to also search for aliases through the
13764   // value operand of a store, etc. Consider the following situation:
13765   //   Token1 = ...
13766   //   L1 = load Token1, %52
13767   //   S1 = store Token1, L1, %51
13768   //   L2 = load Token1, %52+8
13769   //   S2 = store Token1, L2, %51+8
13770   //   Token2 = Token(S1, S2)
13771   //   L3 = load Token2, %53
13772   //   S3 = store Token2, L3, %52
13773   //   L4 = load Token2, %53+8
13774   //   S4 = store Token2, L4, %52+8
13775   // If we search for aliases of S3 (which loads address %52), and we look
13776   // only through the chain, then we'll miss the trivial dependence on L1
13777   // (which also loads from %52). We then might change all loads and
13778   // stores to use Token1 as their chain operand, which could result in
13779   // copying %53 into %52 before copying %52 into %51 (which should
13780   // happen first).
13781   //
13782   // The problem is, however, that searching for such data dependencies
13783   // can become expensive, and the cost is not directly related to the
13784   // chain depth. Instead, we'll rule out such configurations here by
13785   // insisting that we've visited all chain users (except for users
13786   // of the original chain, which is not necessary). When doing this,
13787   // we need to look through nodes we don't care about (otherwise, things
13788   // like register copies will interfere with trivial cases).
13789
13790   SmallVector<const SDNode *, 16> Worklist;
13791   for (const SDNode *N : Visited)
13792     if (N != OriginalChain.getNode())
13793       Worklist.push_back(N);
13794
13795   while (!Worklist.empty()) {
13796     const SDNode *M = Worklist.pop_back_val();
13797
13798     // We have already visited M, and want to make sure we've visited any uses
13799     // of M that we care about. For uses that we've not visisted, and don't
13800     // care about, queue them to the worklist.
13801
13802     for (SDNode::use_iterator UI = M->use_begin(),
13803          UIE = M->use_end(); UI != UIE; ++UI)
13804       if (UI.getUse().getValueType() == MVT::Other &&
13805           Visited.insert(*UI).second) {
13806         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13807           // We've not visited this use, and we care about it (it could have an
13808           // ordering dependency with the original node).
13809           Aliases.clear();
13810           Aliases.push_back(OriginalChain);
13811           return;
13812         }
13813
13814         // We've not visited this use, but we don't care about it. Mark it as
13815         // visited and enqueue it to the worklist.
13816         Worklist.push_back(*UI);
13817       }
13818   }
13819 }
13820
13821 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13822 /// (aliasing node.)
13823 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13824   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13825
13826   // Accumulate all the aliases to this node.
13827   GatherAllAliases(N, OldChain, Aliases);
13828
13829   // If no operands then chain to entry token.
13830   if (Aliases.size() == 0)
13831     return DAG.getEntryNode();
13832
13833   // If a single operand then chain to it.  We don't need to revisit it.
13834   if (Aliases.size() == 1)
13835     return Aliases[0];
13836
13837   // Construct a custom tailored token factor.
13838   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13839 }
13840
13841 /// This is the entry point for the file.
13842 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13843                            CodeGenOpt::Level OptLevel) {
13844   /// This is the main entry point to this class.
13845   DAGCombiner(*this, AA, OptLevel).Run(Level);
13846 }