DAGCombiner: Combine extract_vector_elt from build_vector
[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 visitIMINMAX(SDNode *N);
249     SDValue visitAND(SDNode *N);
250     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
251     SDValue visitOR(SDNode *N);
252     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitXOR(SDNode *N);
254     SDValue SimplifyVBinOp(SDNode *N);
255     SDValue visitSHL(SDNode *N);
256     SDValue visitSRA(SDNode *N);
257     SDValue visitSRL(SDNode *N);
258     SDValue visitRotate(SDNode *N);
259     SDValue visitBSWAP(SDNode *N);
260     SDValue visitCTLZ(SDNode *N);
261     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTTZ(SDNode *N);
263     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
264     SDValue visitCTPOP(SDNode *N);
265     SDValue visitSELECT(SDNode *N);
266     SDValue visitVSELECT(SDNode *N);
267     SDValue visitSELECT_CC(SDNode *N);
268     SDValue visitSETCC(SDNode *N);
269     SDValue visitSIGN_EXTEND(SDNode *N);
270     SDValue visitZERO_EXTEND(SDNode *N);
271     SDValue visitANY_EXTEND(SDNode *N);
272     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
273     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
274     SDValue visitTRUNCATE(SDNode *N);
275     SDValue visitBITCAST(SDNode *N);
276     SDValue visitBUILD_PAIR(SDNode *N);
277     SDValue visitFADD(SDNode *N);
278     SDValue visitFSUB(SDNode *N);
279     SDValue visitFMUL(SDNode *N);
280     SDValue visitFMA(SDNode *N);
281     SDValue visitFDIV(SDNode *N);
282     SDValue visitFREM(SDNode *N);
283     SDValue visitFSQRT(SDNode *N);
284     SDValue visitFCOPYSIGN(SDNode *N);
285     SDValue visitSINT_TO_FP(SDNode *N);
286     SDValue visitUINT_TO_FP(SDNode *N);
287     SDValue visitFP_TO_SINT(SDNode *N);
288     SDValue visitFP_TO_UINT(SDNode *N);
289     SDValue visitFP_ROUND(SDNode *N);
290     SDValue visitFP_ROUND_INREG(SDNode *N);
291     SDValue visitFP_EXTEND(SDNode *N);
292     SDValue visitFNEG(SDNode *N);
293     SDValue visitFABS(SDNode *N);
294     SDValue visitFCEIL(SDNode *N);
295     SDValue visitFTRUNC(SDNode *N);
296     SDValue visitFFLOOR(SDNode *N);
297     SDValue visitFMINNUM(SDNode *N);
298     SDValue visitFMAXNUM(SDNode *N);
299     SDValue visitBRCOND(SDNode *N);
300     SDValue visitBR_CC(SDNode *N);
301     SDValue visitLOAD(SDNode *N);
302
303     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
304     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
305
306     SDValue visitSTORE(SDNode *N);
307     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
308     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
309     SDValue visitBUILD_VECTOR(SDNode *N);
310     SDValue visitCONCAT_VECTORS(SDNode *N);
311     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
312     SDValue visitVECTOR_SHUFFLE(SDNode *N);
313     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
314     SDValue visitINSERT_SUBVECTOR(SDNode *N);
315     SDValue visitMLOAD(SDNode *N);
316     SDValue visitMSTORE(SDNode *N);
317     SDValue visitMGATHER(SDNode *N);
318     SDValue visitMSCATTER(SDNode *N);
319     SDValue visitFP_TO_FP16(SDNode *N);
320     SDValue visitFP16_TO_FP(SDNode *N);
321
322     SDValue visitFADDForFMACombine(SDNode *N);
323     SDValue visitFSUBForFMACombine(SDNode *N);
324     SDValue visitFMULForFMACombine(SDNode *N);
325
326     SDValue XformToShuffleWithZero(SDNode *N);
327     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
328
329     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
330
331     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
332     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
333     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
334     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
335                              SDValue N3, ISD::CondCode CC,
336                              bool NotExtCompare = false);
337     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
338                           SDLoc DL, bool foldBooleans = true);
339
340     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
341                            SDValue &CC) const;
342     bool isOneUseSetCC(SDValue N) const;
343
344     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
345                                          unsigned HiOp);
346     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
347     SDValue CombineExtLoad(SDNode *N);
348     SDValue combineRepeatedFPDivisors(SDNode *N);
349     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
350     SDValue BuildSDIV(SDNode *N);
351     SDValue BuildSDIVPow2(SDNode *N);
352     SDValue BuildUDIV(SDNode *N);
353     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
354     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
355     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
356                                  SDNodeFlags *Flags);
357     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
358                                  SDNodeFlags *Flags);
359     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
360                                bool DemandHighBits = true);
361     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
362     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
363                               SDValue InnerPos, SDValue InnerNeg,
364                               unsigned PosOpcode, unsigned NegOpcode,
365                               SDLoc DL);
366     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
367     SDValue ReduceLoadWidth(SDNode *N);
368     SDValue ReduceLoadOpStoreWidth(SDNode *N);
369     SDValue TransformFPLoadStorePair(SDNode *N);
370     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
371     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
372
373     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
374
375     /// Walk up chain skipping non-aliasing memory nodes,
376     /// looking for aliasing nodes and adding them to the Aliases vector.
377     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
378                           SmallVectorImpl<SDValue> &Aliases);
379
380     /// Return true if there is any possibility that the two addresses overlap.
381     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
382
383     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
384     /// chain (aliasing node.)
385     SDValue FindBetterChain(SDNode *N, SDValue Chain);
386
387     /// Do FindBetterChain for a store and any possibly adjacent stores on
388     /// consecutive chains.
389     bool findBetterNeighborChains(StoreSDNode *St);
390
391     /// Holds a pointer to an LSBaseSDNode as well as information on where it
392     /// is located in a sequence of memory operations connected by a chain.
393     struct MemOpLink {
394       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
395       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
396       // Ptr to the mem node.
397       LSBaseSDNode *MemNode;
398       // Offset from the base ptr.
399       int64_t OffsetFromBase;
400       // What is the sequence number of this mem node.
401       // Lowest mem operand in the DAG starts at zero.
402       unsigned SequenceNum;
403     };
404
405     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
406     /// constant build_vector of the stored constant values in Stores.
407     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
408                                          SDLoc SL,
409                                          ArrayRef<MemOpLink> Stores,
410                                          SmallVectorImpl<SDValue> &Chains,
411                                          EVT Ty) const;
412
413     /// This is a helper function for MergeConsecutiveStores. When the source
414     /// elements of the consecutive stores are all constants or all extracted
415     /// vector elements, try to merge them into one larger store.
416     /// \return True if a merged store was created.
417     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
418                                          EVT MemVT, unsigned NumStores,
419                                          bool IsConstantSrc, bool UseVector);
420
421     /// This is a helper function for MergeConsecutiveStores.
422     /// Stores that may be merged are placed in StoreNodes.
423     /// Loads that may alias with those stores are placed in AliasLoadNodes.
424     void getStoreMergeAndAliasCandidates(
425         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
426         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
427
428     /// Merge consecutive store operations into a wide store.
429     /// This optimization uses wide integers or vectors when possible.
430     /// \return True if some memory operations were changed.
431     bool MergeConsecutiveStores(StoreSDNode *N);
432
433     /// \brief Try to transform a truncation where C is a constant:
434     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
435     ///
436     /// \p N needs to be a truncation and its first operand an AND. Other
437     /// requirements are checked by the function (e.g. that trunc is
438     /// single-use) and if missed an empty SDValue is returned.
439     SDValue distributeTruncateThroughAnd(SDNode *N);
440
441   public:
442     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
443         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
444           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
445       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
446     }
447
448     /// Runs the dag combiner on all nodes in the work list
449     void Run(CombineLevel AtLevel);
450
451     SelectionDAG &getDAG() const { return DAG; }
452
453     /// Returns a type large enough to hold any valid shift amount - before type
454     /// legalization these can be huge.
455     EVT getShiftAmountTy(EVT LHSTy) {
456       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
457       if (LHSTy.isVector())
458         return LHSTy;
459       auto &DL = DAG.getDataLayout();
460       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
461                         : TLI.getPointerTy(DL);
462     }
463
464     /// This method returns true if we are running before type legalization or
465     /// if the specified VT is legal.
466     bool isTypeLegal(const EVT &VT) {
467       if (!LegalTypes) return true;
468       return TLI.isTypeLegal(VT);
469     }
470
471     /// Convenience wrapper around TargetLowering::getSetCCResultType
472     EVT getSetCCResultType(EVT VT) const {
473       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
474     }
475   };
476 }
477
478
479 namespace {
480 /// This class is a DAGUpdateListener that removes any deleted
481 /// nodes from the worklist.
482 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
483   DAGCombiner &DC;
484 public:
485   explicit WorklistRemover(DAGCombiner &dc)
486     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
487
488   void NodeDeleted(SDNode *N, SDNode *E) override {
489     DC.removeFromWorklist(N);
490   }
491 };
492 }
493
494 //===----------------------------------------------------------------------===//
495 //  TargetLowering::DAGCombinerInfo implementation
496 //===----------------------------------------------------------------------===//
497
498 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
499   ((DAGCombiner*)DC)->AddToWorklist(N);
500 }
501
502 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
503   ((DAGCombiner*)DC)->removeFromWorklist(N);
504 }
505
506 SDValue TargetLowering::DAGCombinerInfo::
507 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
508   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
509 }
510
511 SDValue TargetLowering::DAGCombinerInfo::
512 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
513   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
514 }
515
516
517 SDValue TargetLowering::DAGCombinerInfo::
518 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
519   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
520 }
521
522 void TargetLowering::DAGCombinerInfo::
523 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
524   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
525 }
526
527 //===----------------------------------------------------------------------===//
528 // Helper Functions
529 //===----------------------------------------------------------------------===//
530
531 void DAGCombiner::deleteAndRecombine(SDNode *N) {
532   removeFromWorklist(N);
533
534   // If the operands of this node are only used by the node, they will now be
535   // dead. Make sure to re-visit them and recursively delete dead nodes.
536   for (const SDValue &Op : N->ops())
537     // For an operand generating multiple values, one of the values may
538     // become dead allowing further simplification (e.g. split index
539     // arithmetic from an indexed load).
540     if (Op->hasOneUse() || Op->getNumValues() > 1)
541       AddToWorklist(Op.getNode());
542
543   DAG.DeleteNode(N);
544 }
545
546 /// Return 1 if we can compute the negated form of the specified expression for
547 /// the same cost as the expression itself, or 2 if we can compute the negated
548 /// form more cheaply than the expression itself.
549 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
550                                const TargetLowering &TLI,
551                                const TargetOptions *Options,
552                                unsigned Depth = 0) {
553   // fneg is removable even if it has multiple uses.
554   if (Op.getOpcode() == ISD::FNEG) return 2;
555
556   // Don't allow anything with multiple uses.
557   if (!Op.hasOneUse()) return 0;
558
559   // Don't recurse exponentially.
560   if (Depth > 6) return 0;
561
562   switch (Op.getOpcode()) {
563   default: return false;
564   case ISD::ConstantFP:
565     // Don't invert constant FP values after legalize.  The negated constant
566     // isn't necessarily legal.
567     return LegalOperations ? 0 : 1;
568   case ISD::FADD:
569     // FIXME: determine better conditions for this xform.
570     if (!Options->UnsafeFPMath) return 0;
571
572     // After operation legalization, it might not be legal to create new FSUBs.
573     if (LegalOperations &&
574         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
575       return 0;
576
577     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
578     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
579                                     Options, Depth + 1))
580       return V;
581     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
582     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
583                               Depth + 1);
584   case ISD::FSUB:
585     // We can't turn -(A-B) into B-A when we honor signed zeros.
586     if (!Options->UnsafeFPMath) return 0;
587
588     // fold (fneg (fsub A, B)) -> (fsub B, A)
589     return 1;
590
591   case ISD::FMUL:
592   case ISD::FDIV:
593     if (Options->HonorSignDependentRoundingFPMath()) return 0;
594
595     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
596     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
597                                     Options, Depth + 1))
598       return V;
599
600     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
601                               Depth + 1);
602
603   case ISD::FP_EXTEND:
604   case ISD::FP_ROUND:
605   case ISD::FSIN:
606     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
607                               Depth + 1);
608   }
609 }
610
611 /// If isNegatibleForFree returns true, return the newly negated expression.
612 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
613                                     bool LegalOperations, unsigned Depth = 0) {
614   const TargetOptions &Options = DAG.getTarget().Options;
615   // fneg is removable even if it has multiple uses.
616   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
617
618   // Don't allow anything with multiple uses.
619   assert(Op.hasOneUse() && "Unknown reuse!");
620
621   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
622
623   const SDNodeFlags *Flags = Op.getNode()->getFlags();
624
625   switch (Op.getOpcode()) {
626   default: llvm_unreachable("Unknown code");
627   case ISD::ConstantFP: {
628     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
629     V.changeSign();
630     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
631   }
632   case ISD::FADD:
633     // FIXME: determine better conditions for this xform.
634     assert(Options.UnsafeFPMath);
635
636     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
637     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
638                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
639       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
640                          GetNegatedExpression(Op.getOperand(0), DAG,
641                                               LegalOperations, Depth+1),
642                          Op.getOperand(1), Flags);
643     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
644     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
645                        GetNegatedExpression(Op.getOperand(1), DAG,
646                                             LegalOperations, Depth+1),
647                        Op.getOperand(0), Flags);
648   case ISD::FSUB:
649     // We can't turn -(A-B) into B-A when we honor signed zeros.
650     assert(Options.UnsafeFPMath);
651
652     // fold (fneg (fsub 0, B)) -> B
653     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
654       if (N0CFP->isZero())
655         return Op.getOperand(1);
656
657     // fold (fneg (fsub A, B)) -> (fsub B, A)
658     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
659                        Op.getOperand(1), Op.getOperand(0), Flags);
660
661   case ISD::FMUL:
662   case ISD::FDIV:
663     assert(!Options.HonorSignDependentRoundingFPMath());
664
665     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
666     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
667                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
668       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
669                          GetNegatedExpression(Op.getOperand(0), DAG,
670                                               LegalOperations, Depth+1),
671                          Op.getOperand(1), Flags);
672
673     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
674     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
675                        Op.getOperand(0),
676                        GetNegatedExpression(Op.getOperand(1), DAG,
677                                             LegalOperations, Depth+1), Flags);
678
679   case ISD::FP_EXTEND:
680   case ISD::FSIN:
681     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
682                        GetNegatedExpression(Op.getOperand(0), DAG,
683                                             LegalOperations, Depth+1));
684   case ISD::FP_ROUND:
685       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
686                          GetNegatedExpression(Op.getOperand(0), DAG,
687                                               LegalOperations, Depth+1),
688                          Op.getOperand(1));
689   }
690 }
691
692 // Return true if this node is a setcc, or is a select_cc
693 // that selects between the target values used for true and false, making it
694 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
695 // the appropriate nodes based on the type of node we are checking. This
696 // simplifies life a bit for the callers.
697 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
698                                     SDValue &CC) const {
699   if (N.getOpcode() == ISD::SETCC) {
700     LHS = N.getOperand(0);
701     RHS = N.getOperand(1);
702     CC  = N.getOperand(2);
703     return true;
704   }
705
706   if (N.getOpcode() != ISD::SELECT_CC ||
707       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
708       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
709     return false;
710
711   if (TLI.getBooleanContents(N.getValueType()) ==
712       TargetLowering::UndefinedBooleanContent)
713     return false;
714
715   LHS = N.getOperand(0);
716   RHS = N.getOperand(1);
717   CC  = N.getOperand(4);
718   return true;
719 }
720
721 /// Return true if this is a SetCC-equivalent operation with only one use.
722 /// If this is true, it allows the users to invert the operation for free when
723 /// it is profitable to do so.
724 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
725   SDValue N0, N1, N2;
726   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
727     return true;
728   return false;
729 }
730
731 /// Returns true if N is a BUILD_VECTOR node whose
732 /// elements are all the same constant or undefined.
733 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
734   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
735   if (!C)
736     return false;
737
738   APInt SplatUndef;
739   unsigned SplatBitSize;
740   bool HasAnyUndefs;
741   EVT EltVT = N->getValueType(0).getVectorElementType();
742   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
743                              HasAnyUndefs) &&
744           EltVT.getSizeInBits() >= SplatBitSize);
745 }
746
747 // \brief Returns the SDNode if it is a constant integer BuildVector
748 // or constant integer.
749 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
750   if (isa<ConstantSDNode>(N))
751     return N.getNode();
752   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
753     return N.getNode();
754   return nullptr;
755 }
756
757 // \brief Returns the SDNode if it is a constant float BuildVector
758 // or constant float.
759 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
760   if (isa<ConstantFPSDNode>(N))
761     return N.getNode();
762   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
763     return N.getNode();
764   return nullptr;
765 }
766
767 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
768 // int.
769 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
770   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
771     return CN;
772
773   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
774     BitVector UndefElements;
775     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
776
777     // BuildVectors can truncate their operands. Ignore that case here.
778     // FIXME: We blindly ignore splats which include undef which is overly
779     // pessimistic.
780     if (CN && UndefElements.none() &&
781         CN->getValueType(0) == N.getValueType().getScalarType())
782       return CN;
783   }
784
785   return nullptr;
786 }
787
788 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
789 // float.
790 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
791   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
792     return CN;
793
794   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
795     BitVector UndefElements;
796     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
797
798     if (CN && UndefElements.none())
799       return CN;
800   }
801
802   return nullptr;
803 }
804
805 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
806                                     SDValue N0, SDValue N1) {
807   EVT VT = N0.getValueType();
808   if (N0.getOpcode() == Opc) {
809     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
810       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
811         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
812         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
813           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
814         return SDValue();
815       }
816       if (N0.hasOneUse()) {
817         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
818         // use
819         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
820         if (!OpNode.getNode())
821           return SDValue();
822         AddToWorklist(OpNode.getNode());
823         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
824       }
825     }
826   }
827
828   if (N1.getOpcode() == Opc) {
829     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
830       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
831         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
832         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
833           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
834         return SDValue();
835       }
836       if (N1.hasOneUse()) {
837         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
838         // use
839         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
840         if (!OpNode.getNode())
841           return SDValue();
842         AddToWorklist(OpNode.getNode());
843         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
844       }
845     }
846   }
847
848   return SDValue();
849 }
850
851 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
852                                bool AddTo) {
853   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
854   ++NodesCombined;
855   DEBUG(dbgs() << "\nReplacing.1 ";
856         N->dump(&DAG);
857         dbgs() << "\nWith: ";
858         To[0].getNode()->dump(&DAG);
859         dbgs() << " and " << NumTo-1 << " other values\n");
860   for (unsigned i = 0, e = NumTo; i != e; ++i)
861     assert((!To[i].getNode() ||
862             N->getValueType(i) == To[i].getValueType()) &&
863            "Cannot combine value to value of different type!");
864
865   WorklistRemover DeadNodes(*this);
866   DAG.ReplaceAllUsesWith(N, To);
867   if (AddTo) {
868     // Push the new nodes and any users onto the worklist
869     for (unsigned i = 0, e = NumTo; i != e; ++i) {
870       if (To[i].getNode()) {
871         AddToWorklist(To[i].getNode());
872         AddUsersToWorklist(To[i].getNode());
873       }
874     }
875   }
876
877   // Finally, if the node is now dead, remove it from the graph.  The node
878   // may not be dead if the replacement process recursively simplified to
879   // something else needing this node.
880   if (N->use_empty())
881     deleteAndRecombine(N);
882   return SDValue(N, 0);
883 }
884
885 void DAGCombiner::
886 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
887   // Replace all uses.  If any nodes become isomorphic to other nodes and
888   // are deleted, make sure to remove them from our worklist.
889   WorklistRemover DeadNodes(*this);
890   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
891
892   // Push the new node and any (possibly new) users onto the worklist.
893   AddToWorklist(TLO.New.getNode());
894   AddUsersToWorklist(TLO.New.getNode());
895
896   // Finally, if the node is now dead, remove it from the graph.  The node
897   // may not be dead if the replacement process recursively simplified to
898   // something else needing this node.
899   if (TLO.Old.getNode()->use_empty())
900     deleteAndRecombine(TLO.Old.getNode());
901 }
902
903 /// Check the specified integer node value to see if it can be simplified or if
904 /// things it uses can be simplified by bit propagation. If so, return true.
905 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
906   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
907   APInt KnownZero, KnownOne;
908   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
909     return false;
910
911   // Revisit the node.
912   AddToWorklist(Op.getNode());
913
914   // Replace the old value with the new one.
915   ++NodesCombined;
916   DEBUG(dbgs() << "\nReplacing.2 ";
917         TLO.Old.getNode()->dump(&DAG);
918         dbgs() << "\nWith: ";
919         TLO.New.getNode()->dump(&DAG);
920         dbgs() << '\n');
921
922   CommitTargetLoweringOpt(TLO);
923   return true;
924 }
925
926 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
927   SDLoc dl(Load);
928   EVT VT = Load->getValueType(0);
929   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
930
931   DEBUG(dbgs() << "\nReplacing.9 ";
932         Load->dump(&DAG);
933         dbgs() << "\nWith: ";
934         Trunc.getNode()->dump(&DAG);
935         dbgs() << '\n');
936   WorklistRemover DeadNodes(*this);
937   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
938   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
939   deleteAndRecombine(Load);
940   AddToWorklist(Trunc.getNode());
941 }
942
943 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
944   Replace = false;
945   SDLoc dl(Op);
946   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
947     EVT MemVT = LD->getMemoryVT();
948     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
949       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
950                                                        : ISD::EXTLOAD)
951       : LD->getExtensionType();
952     Replace = true;
953     return DAG.getExtLoad(ExtType, dl, PVT,
954                           LD->getChain(), LD->getBasePtr(),
955                           MemVT, LD->getMemOperand());
956   }
957
958   unsigned Opc = Op.getOpcode();
959   switch (Opc) {
960   default: break;
961   case ISD::AssertSext:
962     return DAG.getNode(ISD::AssertSext, dl, PVT,
963                        SExtPromoteOperand(Op.getOperand(0), PVT),
964                        Op.getOperand(1));
965   case ISD::AssertZext:
966     return DAG.getNode(ISD::AssertZext, dl, PVT,
967                        ZExtPromoteOperand(Op.getOperand(0), PVT),
968                        Op.getOperand(1));
969   case ISD::Constant: {
970     unsigned ExtOpc =
971       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
972     return DAG.getNode(ExtOpc, dl, PVT, Op);
973   }
974   }
975
976   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
977     return SDValue();
978   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
979 }
980
981 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
982   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
983     return SDValue();
984   EVT OldVT = Op.getValueType();
985   SDLoc dl(Op);
986   bool Replace = false;
987   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
988   if (!NewOp.getNode())
989     return SDValue();
990   AddToWorklist(NewOp.getNode());
991
992   if (Replace)
993     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
994   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
995                      DAG.getValueType(OldVT));
996 }
997
998 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
999   EVT OldVT = Op.getValueType();
1000   SDLoc dl(Op);
1001   bool Replace = false;
1002   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1003   if (!NewOp.getNode())
1004     return SDValue();
1005   AddToWorklist(NewOp.getNode());
1006
1007   if (Replace)
1008     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1009   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1010 }
1011
1012 /// Promote the specified integer binary operation if the target indicates it is
1013 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1014 /// i32 since i16 instructions are longer.
1015 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1016   if (!LegalOperations)
1017     return SDValue();
1018
1019   EVT VT = Op.getValueType();
1020   if (VT.isVector() || !VT.isInteger())
1021     return SDValue();
1022
1023   // If operation type is 'undesirable', e.g. i16 on x86, consider
1024   // promoting it.
1025   unsigned Opc = Op.getOpcode();
1026   if (TLI.isTypeDesirableForOp(Opc, VT))
1027     return SDValue();
1028
1029   EVT PVT = VT;
1030   // Consult target whether it is a good idea to promote this operation and
1031   // what's the right type to promote it to.
1032   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1033     assert(PVT != VT && "Don't know what type to promote to!");
1034
1035     bool Replace0 = false;
1036     SDValue N0 = Op.getOperand(0);
1037     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1038     if (!NN0.getNode())
1039       return SDValue();
1040
1041     bool Replace1 = false;
1042     SDValue N1 = Op.getOperand(1);
1043     SDValue NN1;
1044     if (N0 == N1)
1045       NN1 = NN0;
1046     else {
1047       NN1 = PromoteOperand(N1, PVT, Replace1);
1048       if (!NN1.getNode())
1049         return SDValue();
1050     }
1051
1052     AddToWorklist(NN0.getNode());
1053     if (NN1.getNode())
1054       AddToWorklist(NN1.getNode());
1055
1056     if (Replace0)
1057       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1058     if (Replace1)
1059       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1060
1061     DEBUG(dbgs() << "\nPromoting ";
1062           Op.getNode()->dump(&DAG));
1063     SDLoc dl(Op);
1064     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1065                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1066   }
1067   return SDValue();
1068 }
1069
1070 /// Promote the specified integer shift operation if the target indicates it is
1071 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1072 /// i32 since i16 instructions are longer.
1073 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1074   if (!LegalOperations)
1075     return SDValue();
1076
1077   EVT VT = Op.getValueType();
1078   if (VT.isVector() || !VT.isInteger())
1079     return SDValue();
1080
1081   // If operation type is 'undesirable', e.g. i16 on x86, consider
1082   // promoting it.
1083   unsigned Opc = Op.getOpcode();
1084   if (TLI.isTypeDesirableForOp(Opc, VT))
1085     return SDValue();
1086
1087   EVT PVT = VT;
1088   // Consult target whether it is a good idea to promote this operation and
1089   // what's the right type to promote it to.
1090   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1091     assert(PVT != VT && "Don't know what type to promote to!");
1092
1093     bool Replace = false;
1094     SDValue N0 = Op.getOperand(0);
1095     if (Opc == ISD::SRA)
1096       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1097     else if (Opc == ISD::SRL)
1098       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1099     else
1100       N0 = PromoteOperand(N0, PVT, Replace);
1101     if (!N0.getNode())
1102       return SDValue();
1103
1104     AddToWorklist(N0.getNode());
1105     if (Replace)
1106       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1107
1108     DEBUG(dbgs() << "\nPromoting ";
1109           Op.getNode()->dump(&DAG));
1110     SDLoc dl(Op);
1111     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1112                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1113   }
1114   return SDValue();
1115 }
1116
1117 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1118   if (!LegalOperations)
1119     return SDValue();
1120
1121   EVT VT = Op.getValueType();
1122   if (VT.isVector() || !VT.isInteger())
1123     return SDValue();
1124
1125   // If operation type is 'undesirable', e.g. i16 on x86, consider
1126   // promoting it.
1127   unsigned Opc = Op.getOpcode();
1128   if (TLI.isTypeDesirableForOp(Opc, VT))
1129     return SDValue();
1130
1131   EVT PVT = VT;
1132   // Consult target whether it is a good idea to promote this operation and
1133   // what's the right type to promote it to.
1134   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1135     assert(PVT != VT && "Don't know what type to promote to!");
1136     // fold (aext (aext x)) -> (aext x)
1137     // fold (aext (zext x)) -> (zext x)
1138     // fold (aext (sext x)) -> (sext x)
1139     DEBUG(dbgs() << "\nPromoting ";
1140           Op.getNode()->dump(&DAG));
1141     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1142   }
1143   return SDValue();
1144 }
1145
1146 bool DAGCombiner::PromoteLoad(SDValue Op) {
1147   if (!LegalOperations)
1148     return false;
1149
1150   EVT VT = Op.getValueType();
1151   if (VT.isVector() || !VT.isInteger())
1152     return false;
1153
1154   // If operation type is 'undesirable', e.g. i16 on x86, consider
1155   // promoting it.
1156   unsigned Opc = Op.getOpcode();
1157   if (TLI.isTypeDesirableForOp(Opc, VT))
1158     return false;
1159
1160   EVT PVT = VT;
1161   // Consult target whether it is a good idea to promote this operation and
1162   // what's the right type to promote it to.
1163   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1164     assert(PVT != VT && "Don't know what type to promote to!");
1165
1166     SDLoc dl(Op);
1167     SDNode *N = Op.getNode();
1168     LoadSDNode *LD = cast<LoadSDNode>(N);
1169     EVT MemVT = LD->getMemoryVT();
1170     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1171       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1172                                                        : ISD::EXTLOAD)
1173       : LD->getExtensionType();
1174     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1175                                    LD->getChain(), LD->getBasePtr(),
1176                                    MemVT, LD->getMemOperand());
1177     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1178
1179     DEBUG(dbgs() << "\nPromoting ";
1180           N->dump(&DAG);
1181           dbgs() << "\nTo: ";
1182           Result.getNode()->dump(&DAG);
1183           dbgs() << '\n');
1184     WorklistRemover DeadNodes(*this);
1185     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1186     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1187     deleteAndRecombine(N);
1188     AddToWorklist(Result.getNode());
1189     return true;
1190   }
1191   return false;
1192 }
1193
1194 /// \brief Recursively delete a node which has no uses and any operands for
1195 /// which it is the only use.
1196 ///
1197 /// Note that this both deletes the nodes and removes them from the worklist.
1198 /// It also adds any nodes who have had a user deleted to the worklist as they
1199 /// may now have only one use and subject to other combines.
1200 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1201   if (!N->use_empty())
1202     return false;
1203
1204   SmallSetVector<SDNode *, 16> Nodes;
1205   Nodes.insert(N);
1206   do {
1207     N = Nodes.pop_back_val();
1208     if (!N)
1209       continue;
1210
1211     if (N->use_empty()) {
1212       for (const SDValue &ChildN : N->op_values())
1213         Nodes.insert(ChildN.getNode());
1214
1215       removeFromWorklist(N);
1216       DAG.DeleteNode(N);
1217     } else {
1218       AddToWorklist(N);
1219     }
1220   } while (!Nodes.empty());
1221   return true;
1222 }
1223
1224 //===----------------------------------------------------------------------===//
1225 //  Main DAG Combiner implementation
1226 //===----------------------------------------------------------------------===//
1227
1228 void DAGCombiner::Run(CombineLevel AtLevel) {
1229   // set the instance variables, so that the various visit routines may use it.
1230   Level = AtLevel;
1231   LegalOperations = Level >= AfterLegalizeVectorOps;
1232   LegalTypes = Level >= AfterLegalizeTypes;
1233
1234   // Add all the dag nodes to the worklist.
1235   for (SDNode &Node : DAG.allnodes())
1236     AddToWorklist(&Node);
1237
1238   // Create a dummy node (which is not added to allnodes), that adds a reference
1239   // to the root node, preventing it from being deleted, and tracking any
1240   // changes of the root.
1241   HandleSDNode Dummy(DAG.getRoot());
1242
1243   // while the worklist isn't empty, find a node and
1244   // try and combine it.
1245   while (!WorklistMap.empty()) {
1246     SDNode *N;
1247     // The Worklist holds the SDNodes in order, but it may contain null entries.
1248     do {
1249       N = Worklist.pop_back_val();
1250     } while (!N);
1251
1252     bool GoodWorklistEntry = WorklistMap.erase(N);
1253     (void)GoodWorklistEntry;
1254     assert(GoodWorklistEntry &&
1255            "Found a worklist entry without a corresponding map entry!");
1256
1257     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1258     // N is deleted from the DAG, since they too may now be dead or may have a
1259     // reduced number of uses, allowing other xforms.
1260     if (recursivelyDeleteUnusedNodes(N))
1261       continue;
1262
1263     WorklistRemover DeadNodes(*this);
1264
1265     // If this combine is running after legalizing the DAG, re-legalize any
1266     // nodes pulled off the worklist.
1267     if (Level == AfterLegalizeDAG) {
1268       SmallSetVector<SDNode *, 16> UpdatedNodes;
1269       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1270
1271       for (SDNode *LN : UpdatedNodes) {
1272         AddToWorklist(LN);
1273         AddUsersToWorklist(LN);
1274       }
1275       if (!NIsValid)
1276         continue;
1277     }
1278
1279     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1280
1281     // Add any operands of the new node which have not yet been combined to the
1282     // worklist as well. Because the worklist uniques things already, this
1283     // won't repeatedly process the same operand.
1284     CombinedNodes.insert(N);
1285     for (const SDValue &ChildN : N->op_values())
1286       if (!CombinedNodes.count(ChildN.getNode()))
1287         AddToWorklist(ChildN.getNode());
1288
1289     SDValue RV = combine(N);
1290
1291     if (!RV.getNode())
1292       continue;
1293
1294     ++NodesCombined;
1295
1296     // If we get back the same node we passed in, rather than a new node or
1297     // zero, we know that the node must have defined multiple values and
1298     // CombineTo was used.  Since CombineTo takes care of the worklist
1299     // mechanics for us, we have no work to do in this case.
1300     if (RV.getNode() == N)
1301       continue;
1302
1303     assert(N->getOpcode() != ISD::DELETED_NODE &&
1304            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1305            "Node was deleted but visit returned new node!");
1306
1307     DEBUG(dbgs() << " ... into: ";
1308           RV.getNode()->dump(&DAG));
1309
1310     // Transfer debug value.
1311     DAG.TransferDbgValues(SDValue(N, 0), RV);
1312     if (N->getNumValues() == RV.getNode()->getNumValues())
1313       DAG.ReplaceAllUsesWith(N, RV.getNode());
1314     else {
1315       assert(N->getValueType(0) == RV.getValueType() &&
1316              N->getNumValues() == 1 && "Type mismatch");
1317       SDValue OpV = RV;
1318       DAG.ReplaceAllUsesWith(N, &OpV);
1319     }
1320
1321     // Push the new node and any users onto the worklist
1322     AddToWorklist(RV.getNode());
1323     AddUsersToWorklist(RV.getNode());
1324
1325     // Finally, if the node is now dead, remove it from the graph.  The node
1326     // may not be dead if the replacement process recursively simplified to
1327     // something else needing this node. This will also take care of adding any
1328     // operands which have lost a user to the worklist.
1329     recursivelyDeleteUnusedNodes(N);
1330   }
1331
1332   // If the root changed (e.g. it was a dead load, update the root).
1333   DAG.setRoot(Dummy.getValue());
1334   DAG.RemoveDeadNodes();
1335 }
1336
1337 SDValue DAGCombiner::visit(SDNode *N) {
1338   switch (N->getOpcode()) {
1339   default: break;
1340   case ISD::TokenFactor:        return visitTokenFactor(N);
1341   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1342   case ISD::ADD:                return visitADD(N);
1343   case ISD::SUB:                return visitSUB(N);
1344   case ISD::ADDC:               return visitADDC(N);
1345   case ISD::SUBC:               return visitSUBC(N);
1346   case ISD::ADDE:               return visitADDE(N);
1347   case ISD::SUBE:               return visitSUBE(N);
1348   case ISD::MUL:                return visitMUL(N);
1349   case ISD::SDIV:               return visitSDIV(N);
1350   case ISD::UDIV:               return visitUDIV(N);
1351   case ISD::SREM:               return visitSREM(N);
1352   case ISD::UREM:               return visitUREM(N);
1353   case ISD::MULHU:              return visitMULHU(N);
1354   case ISD::MULHS:              return visitMULHS(N);
1355   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1356   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1357   case ISD::SMULO:              return visitSMULO(N);
1358   case ISD::UMULO:              return visitUMULO(N);
1359   case ISD::SDIVREM:            return visitSDIVREM(N);
1360   case ISD::UDIVREM:            return visitUDIVREM(N);
1361   case ISD::SMIN:
1362   case ISD::SMAX:
1363   case ISD::UMIN:
1364   case ISD::UMAX:               return visitIMINMAX(N);
1365   case ISD::AND:                return visitAND(N);
1366   case ISD::OR:                 return visitOR(N);
1367   case ISD::XOR:                return visitXOR(N);
1368   case ISD::SHL:                return visitSHL(N);
1369   case ISD::SRA:                return visitSRA(N);
1370   case ISD::SRL:                return visitSRL(N);
1371   case ISD::ROTR:
1372   case ISD::ROTL:               return visitRotate(N);
1373   case ISD::BSWAP:              return visitBSWAP(N);
1374   case ISD::CTLZ:               return visitCTLZ(N);
1375   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1376   case ISD::CTTZ:               return visitCTTZ(N);
1377   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1378   case ISD::CTPOP:              return visitCTPOP(N);
1379   case ISD::SELECT:             return visitSELECT(N);
1380   case ISD::VSELECT:            return visitVSELECT(N);
1381   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1382   case ISD::SETCC:              return visitSETCC(N);
1383   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1384   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1385   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1386   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1387   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1388   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1389   case ISD::BITCAST:            return visitBITCAST(N);
1390   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1391   case ISD::FADD:               return visitFADD(N);
1392   case ISD::FSUB:               return visitFSUB(N);
1393   case ISD::FMUL:               return visitFMUL(N);
1394   case ISD::FMA:                return visitFMA(N);
1395   case ISD::FDIV:               return visitFDIV(N);
1396   case ISD::FREM:               return visitFREM(N);
1397   case ISD::FSQRT:              return visitFSQRT(N);
1398   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1399   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1400   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1401   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1402   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1403   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1404   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1405   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1406   case ISD::FNEG:               return visitFNEG(N);
1407   case ISD::FABS:               return visitFABS(N);
1408   case ISD::FFLOOR:             return visitFFLOOR(N);
1409   case ISD::FMINNUM:            return visitFMINNUM(N);
1410   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1411   case ISD::FCEIL:              return visitFCEIL(N);
1412   case ISD::FTRUNC:             return visitFTRUNC(N);
1413   case ISD::BRCOND:             return visitBRCOND(N);
1414   case ISD::BR_CC:              return visitBR_CC(N);
1415   case ISD::LOAD:               return visitLOAD(N);
1416   case ISD::STORE:              return visitSTORE(N);
1417   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1418   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1419   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1420   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1421   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1422   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1423   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1424   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1425   case ISD::MGATHER:            return visitMGATHER(N);
1426   case ISD::MLOAD:              return visitMLOAD(N);
1427   case ISD::MSCATTER:           return visitMSCATTER(N);
1428   case ISD::MSTORE:             return visitMSTORE(N);
1429   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1430   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1431   }
1432   return SDValue();
1433 }
1434
1435 SDValue DAGCombiner::combine(SDNode *N) {
1436   SDValue RV = visit(N);
1437
1438   // If nothing happened, try a target-specific DAG combine.
1439   if (!RV.getNode()) {
1440     assert(N->getOpcode() != ISD::DELETED_NODE &&
1441            "Node was deleted but visit returned NULL!");
1442
1443     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1444         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1445
1446       // Expose the DAG combiner to the target combiner impls.
1447       TargetLowering::DAGCombinerInfo
1448         DagCombineInfo(DAG, Level, false, this);
1449
1450       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1451     }
1452   }
1453
1454   // If nothing happened still, try promoting the operation.
1455   if (!RV.getNode()) {
1456     switch (N->getOpcode()) {
1457     default: break;
1458     case ISD::ADD:
1459     case ISD::SUB:
1460     case ISD::MUL:
1461     case ISD::AND:
1462     case ISD::OR:
1463     case ISD::XOR:
1464       RV = PromoteIntBinOp(SDValue(N, 0));
1465       break;
1466     case ISD::SHL:
1467     case ISD::SRA:
1468     case ISD::SRL:
1469       RV = PromoteIntShiftOp(SDValue(N, 0));
1470       break;
1471     case ISD::SIGN_EXTEND:
1472     case ISD::ZERO_EXTEND:
1473     case ISD::ANY_EXTEND:
1474       RV = PromoteExtend(SDValue(N, 0));
1475       break;
1476     case ISD::LOAD:
1477       if (PromoteLoad(SDValue(N, 0)))
1478         RV = SDValue(N, 0);
1479       break;
1480     }
1481   }
1482
1483   // If N is a commutative binary node, try commuting it to enable more
1484   // sdisel CSE.
1485   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1486       N->getNumValues() == 1) {
1487     SDValue N0 = N->getOperand(0);
1488     SDValue N1 = N->getOperand(1);
1489
1490     // Constant operands are canonicalized to RHS.
1491     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1492       SDValue Ops[] = {N1, N0};
1493       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1494                                             N->getFlags());
1495       if (CSENode)
1496         return SDValue(CSENode, 0);
1497     }
1498   }
1499
1500   return RV;
1501 }
1502
1503 /// Given a node, return its input chain if it has one, otherwise return a null
1504 /// sd operand.
1505 static SDValue getInputChainForNode(SDNode *N) {
1506   if (unsigned NumOps = N->getNumOperands()) {
1507     if (N->getOperand(0).getValueType() == MVT::Other)
1508       return N->getOperand(0);
1509     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1510       return N->getOperand(NumOps-1);
1511     for (unsigned i = 1; i < NumOps-1; ++i)
1512       if (N->getOperand(i).getValueType() == MVT::Other)
1513         return N->getOperand(i);
1514   }
1515   return SDValue();
1516 }
1517
1518 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1519   // If N has two operands, where one has an input chain equal to the other,
1520   // the 'other' chain is redundant.
1521   if (N->getNumOperands() == 2) {
1522     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1523       return N->getOperand(0);
1524     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1525       return N->getOperand(1);
1526   }
1527
1528   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1529   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1530   SmallPtrSet<SDNode*, 16> SeenOps;
1531   bool Changed = false;             // If we should replace this token factor.
1532
1533   // Start out with this token factor.
1534   TFs.push_back(N);
1535
1536   // Iterate through token factors.  The TFs grows when new token factors are
1537   // encountered.
1538   for (unsigned i = 0; i < TFs.size(); ++i) {
1539     SDNode *TF = TFs[i];
1540
1541     // Check each of the operands.
1542     for (const SDValue &Op : TF->op_values()) {
1543
1544       switch (Op.getOpcode()) {
1545       case ISD::EntryToken:
1546         // Entry tokens don't need to be added to the list. They are
1547         // redundant.
1548         Changed = true;
1549         break;
1550
1551       case ISD::TokenFactor:
1552         if (Op.hasOneUse() &&
1553             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1554           // Queue up for processing.
1555           TFs.push_back(Op.getNode());
1556           // Clean up in case the token factor is removed.
1557           AddToWorklist(Op.getNode());
1558           Changed = true;
1559           break;
1560         }
1561         // Fall thru
1562
1563       default:
1564         // Only add if it isn't already in the list.
1565         if (SeenOps.insert(Op.getNode()).second)
1566           Ops.push_back(Op);
1567         else
1568           Changed = true;
1569         break;
1570       }
1571     }
1572   }
1573
1574   SDValue Result;
1575
1576   // If we've changed things around then replace token factor.
1577   if (Changed) {
1578     if (Ops.empty()) {
1579       // The entry token is the only possible outcome.
1580       Result = DAG.getEntryNode();
1581     } else {
1582       // New and improved token factor.
1583       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1584     }
1585
1586     // Add users to worklist if AA is enabled, since it may introduce
1587     // a lot of new chained token factors while removing memory deps.
1588     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1589       : DAG.getSubtarget().useAA();
1590     return CombineTo(N, Result, UseAA /*add to worklist*/);
1591   }
1592
1593   return Result;
1594 }
1595
1596 /// MERGE_VALUES can always be eliminated.
1597 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1598   WorklistRemover DeadNodes(*this);
1599   // Replacing results may cause a different MERGE_VALUES to suddenly
1600   // be CSE'd with N, and carry its uses with it. Iterate until no
1601   // uses remain, to ensure that the node can be safely deleted.
1602   // First add the users of this node to the work list so that they
1603   // can be tried again once they have new operands.
1604   AddUsersToWorklist(N);
1605   do {
1606     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1607       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1608   } while (!N->use_empty());
1609   deleteAndRecombine(N);
1610   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1611 }
1612
1613 static bool isNullConstant(SDValue V) {
1614   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1615   return Const != nullptr && Const->isNullValue();
1616 }
1617
1618 static bool isNullFPConstant(SDValue V) {
1619   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1620   return Const != nullptr && Const->isZero() && !Const->isNegative();
1621 }
1622
1623 static bool isAllOnesConstant(SDValue V) {
1624   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1625   return Const != nullptr && Const->isAllOnesValue();
1626 }
1627
1628 static bool isOneConstant(SDValue V) {
1629   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1630   return Const != nullptr && Const->isOne();
1631 }
1632
1633 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1634 /// ContantSDNode pointer else nullptr.
1635 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1636   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1637   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1638 }
1639
1640 SDValue DAGCombiner::visitADD(SDNode *N) {
1641   SDValue N0 = N->getOperand(0);
1642   SDValue N1 = N->getOperand(1);
1643   EVT VT = N0.getValueType();
1644
1645   // fold vector ops
1646   if (VT.isVector()) {
1647     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1648       return FoldedVOp;
1649
1650     // fold (add x, 0) -> x, vector edition
1651     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1652       return N0;
1653     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1654       return N1;
1655   }
1656
1657   // fold (add x, undef) -> undef
1658   if (N0.getOpcode() == ISD::UNDEF)
1659     return N0;
1660   if (N1.getOpcode() == ISD::UNDEF)
1661     return N1;
1662   // fold (add c1, c2) -> c1+c2
1663   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1664   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1665   if (N0C && N1C)
1666     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1667   // canonicalize constant to RHS
1668   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1669      !isConstantIntBuildVectorOrConstantInt(N1))
1670     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1671   // fold (add x, 0) -> x
1672   if (isNullConstant(N1))
1673     return N0;
1674   // fold (add Sym, c) -> Sym+c
1675   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1676     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1677         GA->getOpcode() == ISD::GlobalAddress)
1678       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1679                                   GA->getOffset() +
1680                                     (uint64_t)N1C->getSExtValue());
1681   // fold ((c1-A)+c2) -> (c1+c2)-A
1682   if (N1C && N0.getOpcode() == ISD::SUB)
1683     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1684       SDLoc DL(N);
1685       return DAG.getNode(ISD::SUB, DL, VT,
1686                          DAG.getConstant(N1C->getAPIntValue()+
1687                                          N0C->getAPIntValue(), DL, VT),
1688                          N0.getOperand(1));
1689     }
1690   // reassociate add
1691   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1692     return RADD;
1693   // fold ((0-A) + B) -> B-A
1694   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1695     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1696   // fold (A + (0-B)) -> A-B
1697   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1698     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1699   // fold (A+(B-A)) -> B
1700   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1701     return N1.getOperand(0);
1702   // fold ((B-A)+A) -> B
1703   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1704     return N0.getOperand(0);
1705   // fold (A+(B-(A+C))) to (B-C)
1706   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1707       N0 == N1.getOperand(1).getOperand(0))
1708     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1709                        N1.getOperand(1).getOperand(1));
1710   // fold (A+(B-(C+A))) to (B-C)
1711   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1712       N0 == N1.getOperand(1).getOperand(1))
1713     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1714                        N1.getOperand(1).getOperand(0));
1715   // fold (A+((B-A)+or-C)) to (B+or-C)
1716   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1717       N1.getOperand(0).getOpcode() == ISD::SUB &&
1718       N0 == N1.getOperand(0).getOperand(1))
1719     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1720                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1721
1722   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1723   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1724     SDValue N00 = N0.getOperand(0);
1725     SDValue N01 = N0.getOperand(1);
1726     SDValue N10 = N1.getOperand(0);
1727     SDValue N11 = N1.getOperand(1);
1728
1729     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1730       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1731                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1732                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1733   }
1734
1735   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1736     return SDValue(N, 0);
1737
1738   // fold (a+b) -> (a|b) iff a and b share no bits.
1739   if (VT.isInteger() && !VT.isVector()) {
1740     APInt LHSZero, LHSOne;
1741     APInt RHSZero, RHSOne;
1742     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1743
1744     if (LHSZero.getBoolValue()) {
1745       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1746
1747       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1748       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1749       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1750         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1751           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1752       }
1753     }
1754   }
1755
1756   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1757   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1758       isNullConstant(N1.getOperand(0).getOperand(0)))
1759     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1760                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1761                                    N1.getOperand(0).getOperand(1),
1762                                    N1.getOperand(1)));
1763   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1764       isNullConstant(N0.getOperand(0).getOperand(0)))
1765     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1766                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1767                                    N0.getOperand(0).getOperand(1),
1768                                    N0.getOperand(1)));
1769
1770   if (N1.getOpcode() == ISD::AND) {
1771     SDValue AndOp0 = N1.getOperand(0);
1772     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1773     unsigned DestBits = VT.getScalarType().getSizeInBits();
1774
1775     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1776     // and similar xforms where the inner op is either ~0 or 0.
1777     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1778       SDLoc DL(N);
1779       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1780     }
1781   }
1782
1783   // add (sext i1), X -> sub X, (zext i1)
1784   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1785       N0.getOperand(0).getValueType() == MVT::i1 &&
1786       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1787     SDLoc DL(N);
1788     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1789     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1790   }
1791
1792   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1793   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1794     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1795     if (TN->getVT() == MVT::i1) {
1796       SDLoc DL(N);
1797       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1798                                  DAG.getConstant(1, DL, VT));
1799       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1800     }
1801   }
1802
1803   return SDValue();
1804 }
1805
1806 SDValue DAGCombiner::visitADDC(SDNode *N) {
1807   SDValue N0 = N->getOperand(0);
1808   SDValue N1 = N->getOperand(1);
1809   EVT VT = N0.getValueType();
1810
1811   // If the flag result is dead, turn this into an ADD.
1812   if (!N->hasAnyUseOfValue(1))
1813     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1814                      DAG.getNode(ISD::CARRY_FALSE,
1815                                  SDLoc(N), MVT::Glue));
1816
1817   // canonicalize constant to RHS.
1818   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1819   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1820   if (N0C && !N1C)
1821     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1822
1823   // fold (addc x, 0) -> x + no carry out
1824   if (isNullConstant(N1))
1825     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1826                                         SDLoc(N), MVT::Glue));
1827
1828   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1829   APInt LHSZero, LHSOne;
1830   APInt RHSZero, RHSOne;
1831   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1832
1833   if (LHSZero.getBoolValue()) {
1834     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1835
1836     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1837     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1838     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1839       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1840                        DAG.getNode(ISD::CARRY_FALSE,
1841                                    SDLoc(N), MVT::Glue));
1842   }
1843
1844   return SDValue();
1845 }
1846
1847 SDValue DAGCombiner::visitADDE(SDNode *N) {
1848   SDValue N0 = N->getOperand(0);
1849   SDValue N1 = N->getOperand(1);
1850   SDValue CarryIn = N->getOperand(2);
1851
1852   // canonicalize constant to RHS
1853   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1854   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1855   if (N0C && !N1C)
1856     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1857                        N1, N0, CarryIn);
1858
1859   // fold (adde x, y, false) -> (addc x, y)
1860   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1861     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1862
1863   return SDValue();
1864 }
1865
1866 // Since it may not be valid to emit a fold to zero for vector initializers
1867 // check if we can before folding.
1868 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1869                              SelectionDAG &DAG,
1870                              bool LegalOperations, bool LegalTypes) {
1871   if (!VT.isVector())
1872     return DAG.getConstant(0, DL, VT);
1873   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1874     return DAG.getConstant(0, DL, VT);
1875   return SDValue();
1876 }
1877
1878 SDValue DAGCombiner::visitSUB(SDNode *N) {
1879   SDValue N0 = N->getOperand(0);
1880   SDValue N1 = N->getOperand(1);
1881   EVT VT = N0.getValueType();
1882
1883   // fold vector ops
1884   if (VT.isVector()) {
1885     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1886       return FoldedVOp;
1887
1888     // fold (sub x, 0) -> x, vector edition
1889     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1890       return N0;
1891   }
1892
1893   // fold (sub x, x) -> 0
1894   // FIXME: Refactor this and xor and other similar operations together.
1895   if (N0 == N1)
1896     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1897   // fold (sub c1, c2) -> c1-c2
1898   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1899   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1900   if (N0C && N1C)
1901     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1902   // fold (sub x, c) -> (add x, -c)
1903   if (N1C) {
1904     SDLoc DL(N);
1905     return DAG.getNode(ISD::ADD, DL, VT, N0,
1906                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1907   }
1908   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1909   if (isAllOnesConstant(N0))
1910     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1911   // fold A-(A-B) -> B
1912   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1913     return N1.getOperand(1);
1914   // fold (A+B)-A -> B
1915   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1916     return N0.getOperand(1);
1917   // fold (A+B)-B -> A
1918   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1919     return N0.getOperand(0);
1920   // fold C2-(A+C1) -> (C2-C1)-A
1921   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1922     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1923   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1924     SDLoc DL(N);
1925     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1926                                    DL, VT);
1927     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1928                        N1.getOperand(0));
1929   }
1930   // fold ((A+(B+or-C))-B) -> A+or-C
1931   if (N0.getOpcode() == ISD::ADD &&
1932       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1933        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1934       N0.getOperand(1).getOperand(0) == N1)
1935     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1936                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1937   // fold ((A+(C+B))-B) -> A+C
1938   if (N0.getOpcode() == ISD::ADD &&
1939       N0.getOperand(1).getOpcode() == ISD::ADD &&
1940       N0.getOperand(1).getOperand(1) == N1)
1941     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1942                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1943   // fold ((A-(B-C))-C) -> A-B
1944   if (N0.getOpcode() == ISD::SUB &&
1945       N0.getOperand(1).getOpcode() == ISD::SUB &&
1946       N0.getOperand(1).getOperand(1) == N1)
1947     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1948                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1949
1950   // If either operand of a sub is undef, the result is undef
1951   if (N0.getOpcode() == ISD::UNDEF)
1952     return N0;
1953   if (N1.getOpcode() == ISD::UNDEF)
1954     return N1;
1955
1956   // If the relocation model supports it, consider symbol offsets.
1957   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1958     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1959       // fold (sub Sym, c) -> Sym-c
1960       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1961         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1962                                     GA->getOffset() -
1963                                       (uint64_t)N1C->getSExtValue());
1964       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1965       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1966         if (GA->getGlobal() == GB->getGlobal())
1967           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1968                                  SDLoc(N), VT);
1969     }
1970
1971   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1972   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1973     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1974     if (TN->getVT() == MVT::i1) {
1975       SDLoc DL(N);
1976       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1977                                  DAG.getConstant(1, DL, VT));
1978       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1979     }
1980   }
1981
1982   return SDValue();
1983 }
1984
1985 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1986   SDValue N0 = N->getOperand(0);
1987   SDValue N1 = N->getOperand(1);
1988   EVT VT = N0.getValueType();
1989
1990   // If the flag result is dead, turn this into an SUB.
1991   if (!N->hasAnyUseOfValue(1))
1992     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1993                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1994                                  MVT::Glue));
1995
1996   // fold (subc x, x) -> 0 + no borrow
1997   if (N0 == N1) {
1998     SDLoc DL(N);
1999     return CombineTo(N, DAG.getConstant(0, DL, VT),
2000                      DAG.getNode(ISD::CARRY_FALSE, DL,
2001                                  MVT::Glue));
2002   }
2003
2004   // fold (subc x, 0) -> x + no borrow
2005   if (isNullConstant(N1))
2006     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2007                                         MVT::Glue));
2008
2009   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2010   if (isAllOnesConstant(N0))
2011     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2012                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2013                                  MVT::Glue));
2014
2015   return SDValue();
2016 }
2017
2018 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2019   SDValue N0 = N->getOperand(0);
2020   SDValue N1 = N->getOperand(1);
2021   SDValue CarryIn = N->getOperand(2);
2022
2023   // fold (sube x, y, false) -> (subc x, y)
2024   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2025     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2026
2027   return SDValue();
2028 }
2029
2030 SDValue DAGCombiner::visitMUL(SDNode *N) {
2031   SDValue N0 = N->getOperand(0);
2032   SDValue N1 = N->getOperand(1);
2033   EVT VT = N0.getValueType();
2034
2035   // fold (mul x, undef) -> 0
2036   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2037     return DAG.getConstant(0, SDLoc(N), VT);
2038
2039   bool N0IsConst = false;
2040   bool N1IsConst = false;
2041   bool N1IsOpaqueConst = false;
2042   bool N0IsOpaqueConst = false;
2043   APInt ConstValue0, ConstValue1;
2044   // fold vector ops
2045   if (VT.isVector()) {
2046     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2047       return FoldedVOp;
2048
2049     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2050     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2051   } else {
2052     N0IsConst = isa<ConstantSDNode>(N0);
2053     if (N0IsConst) {
2054       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2055       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2056     }
2057     N1IsConst = isa<ConstantSDNode>(N1);
2058     if (N1IsConst) {
2059       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2060       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2061     }
2062   }
2063
2064   // fold (mul c1, c2) -> c1*c2
2065   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2066     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2067                                       N0.getNode(), N1.getNode());
2068
2069   // canonicalize constant to RHS (vector doesn't have to splat)
2070   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2071      !isConstantIntBuildVectorOrConstantInt(N1))
2072     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2073   // fold (mul x, 0) -> 0
2074   if (N1IsConst && ConstValue1 == 0)
2075     return N1;
2076   // We require a splat of the entire scalar bit width for non-contiguous
2077   // bit patterns.
2078   bool IsFullSplat =
2079     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2080   // fold (mul x, 1) -> x
2081   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2082     return N0;
2083   // fold (mul x, -1) -> 0-x
2084   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2085     SDLoc DL(N);
2086     return DAG.getNode(ISD::SUB, DL, VT,
2087                        DAG.getConstant(0, DL, VT), N0);
2088   }
2089   // fold (mul x, (1 << c)) -> x << c
2090   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2091       IsFullSplat) {
2092     SDLoc DL(N);
2093     return DAG.getNode(ISD::SHL, DL, VT, N0,
2094                        DAG.getConstant(ConstValue1.logBase2(), DL,
2095                                        getShiftAmountTy(N0.getValueType())));
2096   }
2097   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2098   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2099       IsFullSplat) {
2100     unsigned Log2Val = (-ConstValue1).logBase2();
2101     SDLoc DL(N);
2102     // FIXME: If the input is something that is easily negated (e.g. a
2103     // single-use add), we should put the negate there.
2104     return DAG.getNode(ISD::SUB, DL, VT,
2105                        DAG.getConstant(0, DL, VT),
2106                        DAG.getNode(ISD::SHL, DL, VT, N0,
2107                             DAG.getConstant(Log2Val, DL,
2108                                       getShiftAmountTy(N0.getValueType()))));
2109   }
2110
2111   APInt Val;
2112   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2113   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2114       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2115                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2116     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2117                              N1, N0.getOperand(1));
2118     AddToWorklist(C3.getNode());
2119     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2120                        N0.getOperand(0), C3);
2121   }
2122
2123   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2124   // use.
2125   {
2126     SDValue Sh(nullptr,0), Y(nullptr,0);
2127     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2128     if (N0.getOpcode() == ISD::SHL &&
2129         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2130                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2131         N0.getNode()->hasOneUse()) {
2132       Sh = N0; Y = N1;
2133     } else if (N1.getOpcode() == ISD::SHL &&
2134                isa<ConstantSDNode>(N1.getOperand(1)) &&
2135                N1.getNode()->hasOneUse()) {
2136       Sh = N1; Y = N0;
2137     }
2138
2139     if (Sh.getNode()) {
2140       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2141                                 Sh.getOperand(0), Y);
2142       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2143                          Mul, Sh.getOperand(1));
2144     }
2145   }
2146
2147   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2148   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2149       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2150                      isa<ConstantSDNode>(N0.getOperand(1))))
2151     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2152                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2153                                    N0.getOperand(0), N1),
2154                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2155                                    N0.getOperand(1), N1));
2156
2157   // reassociate mul
2158   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2159     return RMUL;
2160
2161   return SDValue();
2162 }
2163
2164 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2165   SDValue N0 = N->getOperand(0);
2166   SDValue N1 = N->getOperand(1);
2167   EVT VT = N->getValueType(0);
2168
2169   // fold vector ops
2170   if (VT.isVector())
2171     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2172       return FoldedVOp;
2173
2174   // fold (sdiv c1, c2) -> c1/c2
2175   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2176   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2177   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2178     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2179   // fold (sdiv X, 1) -> X
2180   if (N1C && N1C->isOne())
2181     return N0;
2182   // fold (sdiv X, -1) -> 0-X
2183   if (N1C && N1C->isAllOnesValue()) {
2184     SDLoc DL(N);
2185     return DAG.getNode(ISD::SUB, DL, VT,
2186                        DAG.getConstant(0, DL, VT), N0);
2187   }
2188   // If we know the sign bits of both operands are zero, strength reduce to a
2189   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2190   if (!VT.isVector()) {
2191     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2192       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2193                          N0, N1);
2194   }
2195
2196   // fold (sdiv X, pow2) -> simple ops after legalize
2197   // FIXME: We check for the exact bit here because the generic lowering gives
2198   // better results in that case. The target-specific lowering should learn how
2199   // to handle exact sdivs efficiently.
2200   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2201       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2202       (N1C->getAPIntValue().isPowerOf2() ||
2203        (-N1C->getAPIntValue()).isPowerOf2())) {
2204     // Target-specific implementation of sdiv x, pow2.
2205     if (SDValue Res = BuildSDIVPow2(N))
2206       return Res;
2207
2208     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2209     SDLoc DL(N);
2210
2211     // Splat the sign bit into the register
2212     SDValue SGN =
2213         DAG.getNode(ISD::SRA, DL, VT, N0,
2214                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2215                                     getShiftAmountTy(N0.getValueType())));
2216     AddToWorklist(SGN.getNode());
2217
2218     // Add (N0 < 0) ? abs2 - 1 : 0;
2219     SDValue SRL =
2220         DAG.getNode(ISD::SRL, DL, VT, SGN,
2221                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2222                                     getShiftAmountTy(SGN.getValueType())));
2223     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2224     AddToWorklist(SRL.getNode());
2225     AddToWorklist(ADD.getNode());    // Divide by pow2
2226     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2227                   DAG.getConstant(lg2, DL,
2228                                   getShiftAmountTy(ADD.getValueType())));
2229
2230     // If we're dividing by a positive value, we're done.  Otherwise, we must
2231     // negate the result.
2232     if (N1C->getAPIntValue().isNonNegative())
2233       return SRA;
2234
2235     AddToWorklist(SRA.getNode());
2236     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2237   }
2238
2239   // If integer divide is expensive and we satisfy the requirements, emit an
2240   // alternate sequence.  Targets may check function attributes for size/speed
2241   // trade-offs.
2242   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2243   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2244     if (SDValue Op = BuildSDIV(N))
2245       return Op;
2246
2247   // undef / X -> 0
2248   if (N0.getOpcode() == ISD::UNDEF)
2249     return DAG.getConstant(0, SDLoc(N), VT);
2250   // X / undef -> undef
2251   if (N1.getOpcode() == ISD::UNDEF)
2252     return N1;
2253
2254   return SDValue();
2255 }
2256
2257 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2258   SDValue N0 = N->getOperand(0);
2259   SDValue N1 = N->getOperand(1);
2260   EVT VT = N->getValueType(0);
2261
2262   // fold vector ops
2263   if (VT.isVector())
2264     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2265       return FoldedVOp;
2266
2267   // fold (udiv c1, c2) -> c1/c2
2268   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2269   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2270   if (N0C && N1C)
2271     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2272                                                     N0C, N1C))
2273       return Folded;
2274   // fold (udiv x, (1 << c)) -> x >>u c
2275   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2276     SDLoc DL(N);
2277     return DAG.getNode(ISD::SRL, DL, VT, N0,
2278                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2279                                        getShiftAmountTy(N0.getValueType())));
2280   }
2281   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2282   if (N1.getOpcode() == ISD::SHL) {
2283     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2284       if (SHC->getAPIntValue().isPowerOf2()) {
2285         EVT ADDVT = N1.getOperand(1).getValueType();
2286         SDLoc DL(N);
2287         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2288                                   N1.getOperand(1),
2289                                   DAG.getConstant(SHC->getAPIntValue()
2290                                                                   .logBase2(),
2291                                                   DL, ADDVT));
2292         AddToWorklist(Add.getNode());
2293         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2294       }
2295     }
2296   }
2297
2298   // fold (udiv x, c) -> alternate
2299   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2300   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2301     if (SDValue Op = BuildUDIV(N))
2302       return Op;
2303
2304   // undef / X -> 0
2305   if (N0.getOpcode() == ISD::UNDEF)
2306     return DAG.getConstant(0, SDLoc(N), VT);
2307   // X / undef -> undef
2308   if (N1.getOpcode() == ISD::UNDEF)
2309     return N1;
2310
2311   return SDValue();
2312 }
2313
2314 SDValue DAGCombiner::visitSREM(SDNode *N) {
2315   SDValue N0 = N->getOperand(0);
2316   SDValue N1 = N->getOperand(1);
2317   EVT VT = N->getValueType(0);
2318
2319   // fold (srem c1, c2) -> c1%c2
2320   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2321   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2322   if (N0C && N1C)
2323     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2324                                                     N0C, N1C))
2325       return Folded;
2326   // If we know the sign bits of both operands are zero, strength reduce to a
2327   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2328   if (!VT.isVector()) {
2329     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2330       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2331   }
2332
2333   // If X/C can be simplified by the division-by-constant logic, lower
2334   // X%C to the equivalent of X-X/C*C.
2335   if (N1C && !N1C->isNullValue()) {
2336     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2337     AddToWorklist(Div.getNode());
2338     SDValue OptimizedDiv = combine(Div.getNode());
2339     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2340       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2341                                 OptimizedDiv, N1);
2342       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2343       AddToWorklist(Mul.getNode());
2344       return Sub;
2345     }
2346   }
2347
2348   // undef % X -> 0
2349   if (N0.getOpcode() == ISD::UNDEF)
2350     return DAG.getConstant(0, SDLoc(N), VT);
2351   // X % undef -> undef
2352   if (N1.getOpcode() == ISD::UNDEF)
2353     return N1;
2354
2355   return SDValue();
2356 }
2357
2358 SDValue DAGCombiner::visitUREM(SDNode *N) {
2359   SDValue N0 = N->getOperand(0);
2360   SDValue N1 = N->getOperand(1);
2361   EVT VT = N->getValueType(0);
2362
2363   // fold (urem c1, c2) -> c1%c2
2364   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2365   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2366   if (N0C && N1C)
2367     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2368                                                     N0C, N1C))
2369       return Folded;
2370   // fold (urem x, pow2) -> (and x, pow2-1)
2371   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2372       N1C->getAPIntValue().isPowerOf2()) {
2373     SDLoc DL(N);
2374     return DAG.getNode(ISD::AND, DL, VT, N0,
2375                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2376   }
2377   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2378   if (N1.getOpcode() == ISD::SHL) {
2379     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2380       if (SHC->getAPIntValue().isPowerOf2()) {
2381         SDLoc DL(N);
2382         SDValue Add =
2383           DAG.getNode(ISD::ADD, DL, VT, N1,
2384                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2385                                  VT));
2386         AddToWorklist(Add.getNode());
2387         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2388       }
2389     }
2390   }
2391
2392   // If X/C can be simplified by the division-by-constant logic, lower
2393   // X%C to the equivalent of X-X/C*C.
2394   if (N1C && !N1C->isNullValue()) {
2395     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2396     AddToWorklist(Div.getNode());
2397     SDValue OptimizedDiv = combine(Div.getNode());
2398     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2399       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2400                                 OptimizedDiv, N1);
2401       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2402       AddToWorklist(Mul.getNode());
2403       return Sub;
2404     }
2405   }
2406
2407   // undef % X -> 0
2408   if (N0.getOpcode() == ISD::UNDEF)
2409     return DAG.getConstant(0, SDLoc(N), VT);
2410   // X % undef -> undef
2411   if (N1.getOpcode() == ISD::UNDEF)
2412     return N1;
2413
2414   return SDValue();
2415 }
2416
2417 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2418   SDValue N0 = N->getOperand(0);
2419   SDValue N1 = N->getOperand(1);
2420   EVT VT = N->getValueType(0);
2421   SDLoc DL(N);
2422
2423   // fold (mulhs x, 0) -> 0
2424   if (isNullConstant(N1))
2425     return N1;
2426   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2427   if (isOneConstant(N1)) {
2428     SDLoc DL(N);
2429     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2430                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2431                                        DL,
2432                                        getShiftAmountTy(N0.getValueType())));
2433   }
2434   // fold (mulhs x, undef) -> 0
2435   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2436     return DAG.getConstant(0, SDLoc(N), VT);
2437
2438   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2439   // plus a shift.
2440   if (VT.isSimple() && !VT.isVector()) {
2441     MVT Simple = VT.getSimpleVT();
2442     unsigned SimpleSize = Simple.getSizeInBits();
2443     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2444     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2445       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2446       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2447       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2448       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2449             DAG.getConstant(SimpleSize, DL,
2450                             getShiftAmountTy(N1.getValueType())));
2451       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2452     }
2453   }
2454
2455   return SDValue();
2456 }
2457
2458 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2459   SDValue N0 = N->getOperand(0);
2460   SDValue N1 = N->getOperand(1);
2461   EVT VT = N->getValueType(0);
2462   SDLoc DL(N);
2463
2464   // fold (mulhu x, 0) -> 0
2465   if (isNullConstant(N1))
2466     return N1;
2467   // fold (mulhu x, 1) -> 0
2468   if (isOneConstant(N1))
2469     return DAG.getConstant(0, DL, N0.getValueType());
2470   // fold (mulhu x, undef) -> 0
2471   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2472     return DAG.getConstant(0, DL, VT);
2473
2474   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2475   // plus a shift.
2476   if (VT.isSimple() && !VT.isVector()) {
2477     MVT Simple = VT.getSimpleVT();
2478     unsigned SimpleSize = Simple.getSizeInBits();
2479     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2480     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2481       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2482       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2483       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2484       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2485             DAG.getConstant(SimpleSize, DL,
2486                             getShiftAmountTy(N1.getValueType())));
2487       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2488     }
2489   }
2490
2491   return SDValue();
2492 }
2493
2494 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2495 /// give the opcodes for the two computations that are being performed. Return
2496 /// true if a simplification was made.
2497 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2498                                                 unsigned HiOp) {
2499   // If the high half is not needed, just compute the low half.
2500   bool HiExists = N->hasAnyUseOfValue(1);
2501   if (!HiExists &&
2502       (!LegalOperations ||
2503        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2504     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2505     return CombineTo(N, Res, Res);
2506   }
2507
2508   // If the low half is not needed, just compute the high half.
2509   bool LoExists = N->hasAnyUseOfValue(0);
2510   if (!LoExists &&
2511       (!LegalOperations ||
2512        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2513     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2514     return CombineTo(N, Res, Res);
2515   }
2516
2517   // If both halves are used, return as it is.
2518   if (LoExists && HiExists)
2519     return SDValue();
2520
2521   // If the two computed results can be simplified separately, separate them.
2522   if (LoExists) {
2523     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2524     AddToWorklist(Lo.getNode());
2525     SDValue LoOpt = combine(Lo.getNode());
2526     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2527         (!LegalOperations ||
2528          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2529       return CombineTo(N, LoOpt, LoOpt);
2530   }
2531
2532   if (HiExists) {
2533     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2534     AddToWorklist(Hi.getNode());
2535     SDValue HiOpt = combine(Hi.getNode());
2536     if (HiOpt.getNode() && HiOpt != Hi &&
2537         (!LegalOperations ||
2538          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2539       return CombineTo(N, HiOpt, HiOpt);
2540   }
2541
2542   return SDValue();
2543 }
2544
2545 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2546   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2547     return Res;
2548
2549   EVT VT = N->getValueType(0);
2550   SDLoc DL(N);
2551
2552   // If the type is twice as wide is legal, transform the mulhu to a wider
2553   // multiply plus a shift.
2554   if (VT.isSimple() && !VT.isVector()) {
2555     MVT Simple = VT.getSimpleVT();
2556     unsigned SimpleSize = Simple.getSizeInBits();
2557     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2558     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2559       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2560       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2561       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2562       // Compute the high part as N1.
2563       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2564             DAG.getConstant(SimpleSize, DL,
2565                             getShiftAmountTy(Lo.getValueType())));
2566       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2567       // Compute the low part as N0.
2568       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2569       return CombineTo(N, Lo, Hi);
2570     }
2571   }
2572
2573   return SDValue();
2574 }
2575
2576 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2577   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2578     return Res;
2579
2580   EVT VT = N->getValueType(0);
2581   SDLoc DL(N);
2582
2583   // If the type is twice as wide is legal, transform the mulhu to a wider
2584   // multiply plus a shift.
2585   if (VT.isSimple() && !VT.isVector()) {
2586     MVT Simple = VT.getSimpleVT();
2587     unsigned SimpleSize = Simple.getSizeInBits();
2588     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2589     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2590       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2591       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2592       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2593       // Compute the high part as N1.
2594       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2595             DAG.getConstant(SimpleSize, DL,
2596                             getShiftAmountTy(Lo.getValueType())));
2597       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2598       // Compute the low part as N0.
2599       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2600       return CombineTo(N, Lo, Hi);
2601     }
2602   }
2603
2604   return SDValue();
2605 }
2606
2607 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2608   // (smulo x, 2) -> (saddo x, x)
2609   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2610     if (C2->getAPIntValue() == 2)
2611       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2612                          N->getOperand(0), N->getOperand(0));
2613
2614   return SDValue();
2615 }
2616
2617 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2618   // (umulo x, 2) -> (uaddo x, x)
2619   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2620     if (C2->getAPIntValue() == 2)
2621       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2622                          N->getOperand(0), N->getOperand(0));
2623
2624   return SDValue();
2625 }
2626
2627 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2628   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2629     return Res;
2630
2631   return SDValue();
2632 }
2633
2634 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2635   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2636     return Res;
2637
2638   return SDValue();
2639 }
2640
2641 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2642   SDValue N0 = N->getOperand(0);
2643   SDValue N1 = N->getOperand(1);
2644   EVT VT = N0.getValueType();
2645
2646   // fold vector ops
2647   if (VT.isVector())
2648     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2649       return FoldedVOp;
2650
2651   // fold (add c1, c2) -> c1+c2
2652   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2653   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2654   if (N0C && N1C)
2655     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2656
2657   // canonicalize constant to RHS
2658   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2659      !isConstantIntBuildVectorOrConstantInt(N1))
2660     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2661
2662   return SDValue();
2663 }
2664
2665 /// If this is a binary operator with two operands of the same opcode, try to
2666 /// simplify it.
2667 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2668   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2669   EVT VT = N0.getValueType();
2670   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2671
2672   // Bail early if none of these transforms apply.
2673   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2674
2675   // For each of OP in AND/OR/XOR:
2676   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2677   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2678   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2679   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2680   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2681   //
2682   // do not sink logical op inside of a vector extend, since it may combine
2683   // into a vsetcc.
2684   EVT Op0VT = N0.getOperand(0).getValueType();
2685   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2686        N0.getOpcode() == ISD::SIGN_EXTEND ||
2687        N0.getOpcode() == ISD::BSWAP ||
2688        // Avoid infinite looping with PromoteIntBinOp.
2689        (N0.getOpcode() == ISD::ANY_EXTEND &&
2690         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2691        (N0.getOpcode() == ISD::TRUNCATE &&
2692         (!TLI.isZExtFree(VT, Op0VT) ||
2693          !TLI.isTruncateFree(Op0VT, VT)) &&
2694         TLI.isTypeLegal(Op0VT))) &&
2695       !VT.isVector() &&
2696       Op0VT == N1.getOperand(0).getValueType() &&
2697       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2698     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2699                                  N0.getOperand(0).getValueType(),
2700                                  N0.getOperand(0), N1.getOperand(0));
2701     AddToWorklist(ORNode.getNode());
2702     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2703   }
2704
2705   // For each of OP in SHL/SRL/SRA/AND...
2706   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2707   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2708   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2709   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2710        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2711       N0.getOperand(1) == N1.getOperand(1)) {
2712     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2713                                  N0.getOperand(0).getValueType(),
2714                                  N0.getOperand(0), N1.getOperand(0));
2715     AddToWorklist(ORNode.getNode());
2716     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2717                        ORNode, N0.getOperand(1));
2718   }
2719
2720   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2721   // Only perform this optimization after type legalization and before
2722   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2723   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2724   // we don't want to undo this promotion.
2725   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2726   // on scalars.
2727   if ((N0.getOpcode() == ISD::BITCAST ||
2728        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2729       Level == AfterLegalizeTypes) {
2730     SDValue In0 = N0.getOperand(0);
2731     SDValue In1 = N1.getOperand(0);
2732     EVT In0Ty = In0.getValueType();
2733     EVT In1Ty = In1.getValueType();
2734     SDLoc DL(N);
2735     // If both incoming values are integers, and the original types are the
2736     // same.
2737     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2738       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2739       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2740       AddToWorklist(Op.getNode());
2741       return BC;
2742     }
2743   }
2744
2745   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2746   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2747   // If both shuffles use the same mask, and both shuffle within a single
2748   // vector, then it is worthwhile to move the swizzle after the operation.
2749   // The type-legalizer generates this pattern when loading illegal
2750   // vector types from memory. In many cases this allows additional shuffle
2751   // optimizations.
2752   // There are other cases where moving the shuffle after the xor/and/or
2753   // is profitable even if shuffles don't perform a swizzle.
2754   // If both shuffles use the same mask, and both shuffles have the same first
2755   // or second operand, then it might still be profitable to move the shuffle
2756   // after the xor/and/or operation.
2757   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2758     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2759     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2760
2761     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2762            "Inputs to shuffles are not the same type");
2763
2764     // Check that both shuffles use the same mask. The masks are known to be of
2765     // the same length because the result vector type is the same.
2766     // Check also that shuffles have only one use to avoid introducing extra
2767     // instructions.
2768     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2769         SVN0->getMask().equals(SVN1->getMask())) {
2770       SDValue ShOp = N0->getOperand(1);
2771
2772       // Don't try to fold this node if it requires introducing a
2773       // build vector of all zeros that might be illegal at this stage.
2774       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2775         if (!LegalTypes)
2776           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2777         else
2778           ShOp = SDValue();
2779       }
2780
2781       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2782       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2783       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2784       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2785         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2786                                       N0->getOperand(0), N1->getOperand(0));
2787         AddToWorklist(NewNode.getNode());
2788         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2789                                     &SVN0->getMask()[0]);
2790       }
2791
2792       // Don't try to fold this node if it requires introducing a
2793       // build vector of all zeros that might be illegal at this stage.
2794       ShOp = N0->getOperand(0);
2795       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2796         if (!LegalTypes)
2797           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2798         else
2799           ShOp = SDValue();
2800       }
2801
2802       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2803       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2804       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2805       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2806         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2807                                       N0->getOperand(1), N1->getOperand(1));
2808         AddToWorklist(NewNode.getNode());
2809         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2810                                     &SVN0->getMask()[0]);
2811       }
2812     }
2813   }
2814
2815   return SDValue();
2816 }
2817
2818 /// This contains all DAGCombine rules which reduce two values combined by
2819 /// an And operation to a single value. This makes them reusable in the context
2820 /// of visitSELECT(). Rules involving constants are not included as
2821 /// visitSELECT() already handles those cases.
2822 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2823                                   SDNode *LocReference) {
2824   EVT VT = N1.getValueType();
2825
2826   // fold (and x, undef) -> 0
2827   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2828     return DAG.getConstant(0, SDLoc(LocReference), VT);
2829   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2830   SDValue LL, LR, RL, RR, CC0, CC1;
2831   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2832     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2833     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2834
2835     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2836         LL.getValueType().isInteger()) {
2837       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2838       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2839         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2840                                      LR.getValueType(), LL, RL);
2841         AddToWorklist(ORNode.getNode());
2842         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2843       }
2844       if (isAllOnesConstant(LR)) {
2845         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2846         if (Op1 == ISD::SETEQ) {
2847           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2848                                         LR.getValueType(), LL, RL);
2849           AddToWorklist(ANDNode.getNode());
2850           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2851         }
2852         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2853         if (Op1 == ISD::SETGT) {
2854           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2855                                        LR.getValueType(), LL, RL);
2856           AddToWorklist(ORNode.getNode());
2857           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2858         }
2859       }
2860     }
2861     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2862     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2863         Op0 == Op1 && LL.getValueType().isInteger() &&
2864       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2865                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2866       SDLoc DL(N0);
2867       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2868                                     LL, DAG.getConstant(1, DL,
2869                                                         LL.getValueType()));
2870       AddToWorklist(ADDNode.getNode());
2871       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2872                           DAG.getConstant(2, DL, LL.getValueType()),
2873                           ISD::SETUGE);
2874     }
2875     // canonicalize equivalent to ll == rl
2876     if (LL == RR && LR == RL) {
2877       Op1 = ISD::getSetCCSwappedOperands(Op1);
2878       std::swap(RL, RR);
2879     }
2880     if (LL == RL && LR == RR) {
2881       bool isInteger = LL.getValueType().isInteger();
2882       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2883       if (Result != ISD::SETCC_INVALID &&
2884           (!LegalOperations ||
2885            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2886             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2887         EVT CCVT = getSetCCResultType(LL.getValueType());
2888         if (N0.getValueType() == CCVT ||
2889             (!LegalOperations && N0.getValueType() == MVT::i1))
2890           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2891                               LL, LR, Result);
2892       }
2893     }
2894   }
2895
2896   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2897       VT.getSizeInBits() <= 64) {
2898     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2899       APInt ADDC = ADDI->getAPIntValue();
2900       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2901         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2902         // immediate for an add, but it is legal if its top c2 bits are set,
2903         // transform the ADD so the immediate doesn't need to be materialized
2904         // in a register.
2905         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2906           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2907                                              SRLI->getZExtValue());
2908           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2909             ADDC |= Mask;
2910             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2911               SDLoc DL(N0);
2912               SDValue NewAdd =
2913                 DAG.getNode(ISD::ADD, DL, VT,
2914                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2915               CombineTo(N0.getNode(), NewAdd);
2916               // Return N so it doesn't get rechecked!
2917               return SDValue(LocReference, 0);
2918             }
2919           }
2920         }
2921       }
2922     }
2923   }
2924
2925   return SDValue();
2926 }
2927
2928 SDValue DAGCombiner::visitAND(SDNode *N) {
2929   SDValue N0 = N->getOperand(0);
2930   SDValue N1 = N->getOperand(1);
2931   EVT VT = N1.getValueType();
2932
2933   // fold vector ops
2934   if (VT.isVector()) {
2935     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2936       return FoldedVOp;
2937
2938     // fold (and x, 0) -> 0, vector edition
2939     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2940       // do not return N0, because undef node may exist in N0
2941       return DAG.getConstant(
2942           APInt::getNullValue(
2943               N0.getValueType().getScalarType().getSizeInBits()),
2944           SDLoc(N), N0.getValueType());
2945     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2946       // do not return N1, because undef node may exist in N1
2947       return DAG.getConstant(
2948           APInt::getNullValue(
2949               N1.getValueType().getScalarType().getSizeInBits()),
2950           SDLoc(N), N1.getValueType());
2951
2952     // fold (and x, -1) -> x, vector edition
2953     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2954       return N1;
2955     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2956       return N0;
2957   }
2958
2959   // fold (and c1, c2) -> c1&c2
2960   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2961   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2962   if (N0C && N1C && !N1C->isOpaque())
2963     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2964   // canonicalize constant to RHS
2965   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2966      !isConstantIntBuildVectorOrConstantInt(N1))
2967     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2968   // fold (and x, -1) -> x
2969   if (isAllOnesConstant(N1))
2970     return N0;
2971   // if (and x, c) is known to be zero, return 0
2972   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2973   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2974                                    APInt::getAllOnesValue(BitWidth)))
2975     return DAG.getConstant(0, SDLoc(N), VT);
2976   // reassociate and
2977   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2978     return RAND;
2979   // fold (and (or x, C), D) -> D if (C & D) == D
2980   if (N1C && N0.getOpcode() == ISD::OR)
2981     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2982       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2983         return N1;
2984   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2985   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2986     SDValue N0Op0 = N0.getOperand(0);
2987     APInt Mask = ~N1C->getAPIntValue();
2988     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2989     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2990       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2991                                  N0.getValueType(), N0Op0);
2992
2993       // Replace uses of the AND with uses of the Zero extend node.
2994       CombineTo(N, Zext);
2995
2996       // We actually want to replace all uses of the any_extend with the
2997       // zero_extend, to avoid duplicating things.  This will later cause this
2998       // AND to be folded.
2999       CombineTo(N0.getNode(), Zext);
3000       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3001     }
3002   }
3003   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3004   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3005   // already be zero by virtue of the width of the base type of the load.
3006   //
3007   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3008   // more cases.
3009   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3010        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3011       N0.getOpcode() == ISD::LOAD) {
3012     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3013                                          N0 : N0.getOperand(0) );
3014
3015     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3016     // This can be a pure constant or a vector splat, in which case we treat the
3017     // vector as a scalar and use the splat value.
3018     APInt Constant = APInt::getNullValue(1);
3019     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3020       Constant = C->getAPIntValue();
3021     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3022       APInt SplatValue, SplatUndef;
3023       unsigned SplatBitSize;
3024       bool HasAnyUndefs;
3025       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3026                                              SplatBitSize, HasAnyUndefs);
3027       if (IsSplat) {
3028         // Undef bits can contribute to a possible optimisation if set, so
3029         // set them.
3030         SplatValue |= SplatUndef;
3031
3032         // The splat value may be something like "0x00FFFFFF", which means 0 for
3033         // the first vector value and FF for the rest, repeating. We need a mask
3034         // that will apply equally to all members of the vector, so AND all the
3035         // lanes of the constant together.
3036         EVT VT = Vector->getValueType(0);
3037         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3038
3039         // If the splat value has been compressed to a bitlength lower
3040         // than the size of the vector lane, we need to re-expand it to
3041         // the lane size.
3042         if (BitWidth > SplatBitSize)
3043           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3044                SplatBitSize < BitWidth;
3045                SplatBitSize = SplatBitSize * 2)
3046             SplatValue |= SplatValue.shl(SplatBitSize);
3047
3048         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3049         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3050         if (SplatBitSize % BitWidth == 0) {
3051           Constant = APInt::getAllOnesValue(BitWidth);
3052           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3053             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3054         }
3055       }
3056     }
3057
3058     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3059     // actually legal and isn't going to get expanded, else this is a false
3060     // optimisation.
3061     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3062                                                     Load->getValueType(0),
3063                                                     Load->getMemoryVT());
3064
3065     // Resize the constant to the same size as the original memory access before
3066     // extension. If it is still the AllOnesValue then this AND is completely
3067     // unneeded.
3068     Constant =
3069       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3070
3071     bool B;
3072     switch (Load->getExtensionType()) {
3073     default: B = false; break;
3074     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3075     case ISD::ZEXTLOAD:
3076     case ISD::NON_EXTLOAD: B = true; break;
3077     }
3078
3079     if (B && Constant.isAllOnesValue()) {
3080       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3081       // preserve semantics once we get rid of the AND.
3082       SDValue NewLoad(Load, 0);
3083       if (Load->getExtensionType() == ISD::EXTLOAD) {
3084         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3085                               Load->getValueType(0), SDLoc(Load),
3086                               Load->getChain(), Load->getBasePtr(),
3087                               Load->getOffset(), Load->getMemoryVT(),
3088                               Load->getMemOperand());
3089         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3090         if (Load->getNumValues() == 3) {
3091           // PRE/POST_INC loads have 3 values.
3092           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3093                            NewLoad.getValue(2) };
3094           CombineTo(Load, To, 3, true);
3095         } else {
3096           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3097         }
3098       }
3099
3100       // Fold the AND away, taking care not to fold to the old load node if we
3101       // replaced it.
3102       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3103
3104       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3105     }
3106   }
3107
3108   // fold (and (load x), 255) -> (zextload x, i8)
3109   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3110   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3111   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3112               (N0.getOpcode() == ISD::ANY_EXTEND &&
3113                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3114     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3115     LoadSDNode *LN0 = HasAnyExt
3116       ? cast<LoadSDNode>(N0.getOperand(0))
3117       : cast<LoadSDNode>(N0);
3118     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3119         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3120       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3121       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3122         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3123         EVT LoadedVT = LN0->getMemoryVT();
3124         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3125
3126         if (ExtVT == LoadedVT &&
3127             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3128                                                     ExtVT))) {
3129
3130           SDValue NewLoad =
3131             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3132                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3133                            LN0->getMemOperand());
3134           AddToWorklist(N);
3135           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3136           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3137         }
3138
3139         // Do not change the width of a volatile load.
3140         // Do not generate loads of non-round integer types since these can
3141         // be expensive (and would be wrong if the type is not byte sized).
3142         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3143             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3144                                                     ExtVT))) {
3145           EVT PtrType = LN0->getOperand(1).getValueType();
3146
3147           unsigned Alignment = LN0->getAlignment();
3148           SDValue NewPtr = LN0->getBasePtr();
3149
3150           // For big endian targets, we need to add an offset to the pointer
3151           // to load the correct bytes.  For little endian systems, we merely
3152           // need to read fewer bytes from the same pointer.
3153           if (DAG.getDataLayout().isBigEndian()) {
3154             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3155             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3156             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3157             SDLoc DL(LN0);
3158             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3159                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3160             Alignment = MinAlign(Alignment, PtrOff);
3161           }
3162
3163           AddToWorklist(NewPtr.getNode());
3164
3165           SDValue Load =
3166             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3167                            LN0->getChain(), NewPtr,
3168                            LN0->getPointerInfo(),
3169                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3170                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3171           AddToWorklist(N);
3172           CombineTo(LN0, Load, Load.getValue(1));
3173           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3174         }
3175       }
3176     }
3177   }
3178
3179   if (SDValue Combined = visitANDLike(N0, N1, N))
3180     return Combined;
3181
3182   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3183   if (N0.getOpcode() == N1.getOpcode())
3184     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3185       return Tmp;
3186
3187   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3188   // fold (and (sra)) -> (and (srl)) when possible.
3189   if (!VT.isVector() &&
3190       SimplifyDemandedBits(SDValue(N, 0)))
3191     return SDValue(N, 0);
3192
3193   // fold (zext_inreg (extload x)) -> (zextload x)
3194   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3195     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3196     EVT MemVT = LN0->getMemoryVT();
3197     // If we zero all the possible extended bits, then we can turn this into
3198     // a zextload if we are running before legalize or the operation is legal.
3199     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3200     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3201                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3202         ((!LegalOperations && !LN0->isVolatile()) ||
3203          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3204       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3205                                        LN0->getChain(), LN0->getBasePtr(),
3206                                        MemVT, LN0->getMemOperand());
3207       AddToWorklist(N);
3208       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3209       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3210     }
3211   }
3212   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3213   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3214       N0.hasOneUse()) {
3215     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3216     EVT MemVT = LN0->getMemoryVT();
3217     // If we zero all the possible extended bits, then we can turn this into
3218     // a zextload if we are running before legalize or the operation is legal.
3219     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3220     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3221                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3222         ((!LegalOperations && !LN0->isVolatile()) ||
3223          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3224       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3225                                        LN0->getChain(), LN0->getBasePtr(),
3226                                        MemVT, LN0->getMemOperand());
3227       AddToWorklist(N);
3228       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3229       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3230     }
3231   }
3232   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3233   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3234     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3235                                        N0.getOperand(1), false);
3236     if (BSwap.getNode())
3237       return BSwap;
3238   }
3239
3240   return SDValue();
3241 }
3242
3243 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3244 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3245                                         bool DemandHighBits) {
3246   if (!LegalOperations)
3247     return SDValue();
3248
3249   EVT VT = N->getValueType(0);
3250   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3251     return SDValue();
3252   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3253     return SDValue();
3254
3255   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3256   bool LookPassAnd0 = false;
3257   bool LookPassAnd1 = false;
3258   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3259       std::swap(N0, N1);
3260   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3261       std::swap(N0, N1);
3262   if (N0.getOpcode() == ISD::AND) {
3263     if (!N0.getNode()->hasOneUse())
3264       return SDValue();
3265     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3266     if (!N01C || N01C->getZExtValue() != 0xFF00)
3267       return SDValue();
3268     N0 = N0.getOperand(0);
3269     LookPassAnd0 = true;
3270   }
3271
3272   if (N1.getOpcode() == ISD::AND) {
3273     if (!N1.getNode()->hasOneUse())
3274       return SDValue();
3275     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3276     if (!N11C || N11C->getZExtValue() != 0xFF)
3277       return SDValue();
3278     N1 = N1.getOperand(0);
3279     LookPassAnd1 = true;
3280   }
3281
3282   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3283     std::swap(N0, N1);
3284   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3285     return SDValue();
3286   if (!N0.getNode()->hasOneUse() ||
3287       !N1.getNode()->hasOneUse())
3288     return SDValue();
3289
3290   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3291   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3292   if (!N01C || !N11C)
3293     return SDValue();
3294   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3295     return SDValue();
3296
3297   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3298   SDValue N00 = N0->getOperand(0);
3299   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3300     if (!N00.getNode()->hasOneUse())
3301       return SDValue();
3302     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3303     if (!N001C || N001C->getZExtValue() != 0xFF)
3304       return SDValue();
3305     N00 = N00.getOperand(0);
3306     LookPassAnd0 = true;
3307   }
3308
3309   SDValue N10 = N1->getOperand(0);
3310   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3311     if (!N10.getNode()->hasOneUse())
3312       return SDValue();
3313     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3314     if (!N101C || N101C->getZExtValue() != 0xFF00)
3315       return SDValue();
3316     N10 = N10.getOperand(0);
3317     LookPassAnd1 = true;
3318   }
3319
3320   if (N00 != N10)
3321     return SDValue();
3322
3323   // Make sure everything beyond the low halfword gets set to zero since the SRL
3324   // 16 will clear the top bits.
3325   unsigned OpSizeInBits = VT.getSizeInBits();
3326   if (DemandHighBits && OpSizeInBits > 16) {
3327     // If the left-shift isn't masked out then the only way this is a bswap is
3328     // if all bits beyond the low 8 are 0. In that case the entire pattern
3329     // reduces to a left shift anyway: leave it for other parts of the combiner.
3330     if (!LookPassAnd0)
3331       return SDValue();
3332
3333     // However, if the right shift isn't masked out then it might be because
3334     // it's not needed. See if we can spot that too.
3335     if (!LookPassAnd1 &&
3336         !DAG.MaskedValueIsZero(
3337             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3338       return SDValue();
3339   }
3340
3341   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3342   if (OpSizeInBits > 16) {
3343     SDLoc DL(N);
3344     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3345                       DAG.getConstant(OpSizeInBits - 16, DL,
3346                                       getShiftAmountTy(VT)));
3347   }
3348   return Res;
3349 }
3350
3351 /// Return true if the specified node is an element that makes up a 32-bit
3352 /// packed halfword byteswap.
3353 /// ((x & 0x000000ff) << 8) |
3354 /// ((x & 0x0000ff00) >> 8) |
3355 /// ((x & 0x00ff0000) << 8) |
3356 /// ((x & 0xff000000) >> 8)
3357 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3358   if (!N.getNode()->hasOneUse())
3359     return false;
3360
3361   unsigned Opc = N.getOpcode();
3362   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3363     return false;
3364
3365   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3366   if (!N1C)
3367     return false;
3368
3369   unsigned Num;
3370   switch (N1C->getZExtValue()) {
3371   default:
3372     return false;
3373   case 0xFF:       Num = 0; break;
3374   case 0xFF00:     Num = 1; break;
3375   case 0xFF0000:   Num = 2; break;
3376   case 0xFF000000: Num = 3; break;
3377   }
3378
3379   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3380   SDValue N0 = N.getOperand(0);
3381   if (Opc == ISD::AND) {
3382     if (Num == 0 || Num == 2) {
3383       // (x >> 8) & 0xff
3384       // (x >> 8) & 0xff0000
3385       if (N0.getOpcode() != ISD::SRL)
3386         return false;
3387       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3388       if (!C || C->getZExtValue() != 8)
3389         return false;
3390     } else {
3391       // (x << 8) & 0xff00
3392       // (x << 8) & 0xff000000
3393       if (N0.getOpcode() != ISD::SHL)
3394         return false;
3395       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3396       if (!C || C->getZExtValue() != 8)
3397         return false;
3398     }
3399   } else if (Opc == ISD::SHL) {
3400     // (x & 0xff) << 8
3401     // (x & 0xff0000) << 8
3402     if (Num != 0 && Num != 2)
3403       return false;
3404     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3405     if (!C || C->getZExtValue() != 8)
3406       return false;
3407   } else { // Opc == ISD::SRL
3408     // (x & 0xff00) >> 8
3409     // (x & 0xff000000) >> 8
3410     if (Num != 1 && Num != 3)
3411       return false;
3412     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3413     if (!C || C->getZExtValue() != 8)
3414       return false;
3415   }
3416
3417   if (Parts[Num])
3418     return false;
3419
3420   Parts[Num] = N0.getOperand(0).getNode();
3421   return true;
3422 }
3423
3424 /// Match a 32-bit packed halfword bswap. That is
3425 /// ((x & 0x000000ff) << 8) |
3426 /// ((x & 0x0000ff00) >> 8) |
3427 /// ((x & 0x00ff0000) << 8) |
3428 /// ((x & 0xff000000) >> 8)
3429 /// => (rotl (bswap x), 16)
3430 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3431   if (!LegalOperations)
3432     return SDValue();
3433
3434   EVT VT = N->getValueType(0);
3435   if (VT != MVT::i32)
3436     return SDValue();
3437   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3438     return SDValue();
3439
3440   // Look for either
3441   // (or (or (and), (and)), (or (and), (and)))
3442   // (or (or (or (and), (and)), (and)), (and))
3443   if (N0.getOpcode() != ISD::OR)
3444     return SDValue();
3445   SDValue N00 = N0.getOperand(0);
3446   SDValue N01 = N0.getOperand(1);
3447   SDNode *Parts[4] = {};
3448
3449   if (N1.getOpcode() == ISD::OR &&
3450       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3451     // (or (or (and), (and)), (or (and), (and)))
3452     SDValue N000 = N00.getOperand(0);
3453     if (!isBSwapHWordElement(N000, Parts))
3454       return SDValue();
3455
3456     SDValue N001 = N00.getOperand(1);
3457     if (!isBSwapHWordElement(N001, Parts))
3458       return SDValue();
3459     SDValue N010 = N01.getOperand(0);
3460     if (!isBSwapHWordElement(N010, Parts))
3461       return SDValue();
3462     SDValue N011 = N01.getOperand(1);
3463     if (!isBSwapHWordElement(N011, Parts))
3464       return SDValue();
3465   } else {
3466     // (or (or (or (and), (and)), (and)), (and))
3467     if (!isBSwapHWordElement(N1, Parts))
3468       return SDValue();
3469     if (!isBSwapHWordElement(N01, Parts))
3470       return SDValue();
3471     if (N00.getOpcode() != ISD::OR)
3472       return SDValue();
3473     SDValue N000 = N00.getOperand(0);
3474     if (!isBSwapHWordElement(N000, Parts))
3475       return SDValue();
3476     SDValue N001 = N00.getOperand(1);
3477     if (!isBSwapHWordElement(N001, Parts))
3478       return SDValue();
3479   }
3480
3481   // Make sure the parts are all coming from the same node.
3482   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3483     return SDValue();
3484
3485   SDLoc DL(N);
3486   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3487                               SDValue(Parts[0], 0));
3488
3489   // Result of the bswap should be rotated by 16. If it's not legal, then
3490   // do  (x << 16) | (x >> 16).
3491   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3492   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3493     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3494   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3495     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3496   return DAG.getNode(ISD::OR, DL, VT,
3497                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3498                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3499 }
3500
3501 /// This contains all DAGCombine rules which reduce two values combined by
3502 /// an Or operation to a single value \see visitANDLike().
3503 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3504   EVT VT = N1.getValueType();
3505   // fold (or x, undef) -> -1
3506   if (!LegalOperations &&
3507       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3508     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3509     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3510                            SDLoc(LocReference), VT);
3511   }
3512   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3513   SDValue LL, LR, RL, RR, CC0, CC1;
3514   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3515     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3516     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3517
3518     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3519       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3520       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3521       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3522         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3523                                      LR.getValueType(), LL, RL);
3524         AddToWorklist(ORNode.getNode());
3525         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3526       }
3527       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3528       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3529       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3530         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3531                                       LR.getValueType(), LL, RL);
3532         AddToWorklist(ANDNode.getNode());
3533         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3534       }
3535     }
3536     // canonicalize equivalent to ll == rl
3537     if (LL == RR && LR == RL) {
3538       Op1 = ISD::getSetCCSwappedOperands(Op1);
3539       std::swap(RL, RR);
3540     }
3541     if (LL == RL && LR == RR) {
3542       bool isInteger = LL.getValueType().isInteger();
3543       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3544       if (Result != ISD::SETCC_INVALID &&
3545           (!LegalOperations ||
3546            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3547             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3548         EVT CCVT = getSetCCResultType(LL.getValueType());
3549         if (N0.getValueType() == CCVT ||
3550             (!LegalOperations && N0.getValueType() == MVT::i1))
3551           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3552                               LL, LR, Result);
3553       }
3554     }
3555   }
3556
3557   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3558   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3559       // Don't increase # computations.
3560       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3561     // We can only do this xform if we know that bits from X that are set in C2
3562     // but not in C1 are already zero.  Likewise for Y.
3563     if (const ConstantSDNode *N0O1C =
3564         getAsNonOpaqueConstant(N0.getOperand(1))) {
3565       if (const ConstantSDNode *N1O1C =
3566           getAsNonOpaqueConstant(N1.getOperand(1))) {
3567         // We can only do this xform if we know that bits from X that are set in
3568         // C2 but not in C1 are already zero.  Likewise for Y.
3569         const APInt &LHSMask = N0O1C->getAPIntValue();
3570         const APInt &RHSMask = N1O1C->getAPIntValue();
3571
3572         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3573             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3574           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3575                                   N0.getOperand(0), N1.getOperand(0));
3576           SDLoc DL(LocReference);
3577           return DAG.getNode(ISD::AND, DL, VT, X,
3578                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3579         }
3580       }
3581     }
3582   }
3583
3584   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3585   if (N0.getOpcode() == ISD::AND &&
3586       N1.getOpcode() == ISD::AND &&
3587       N0.getOperand(0) == N1.getOperand(0) &&
3588       // Don't increase # computations.
3589       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3590     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3591                             N0.getOperand(1), N1.getOperand(1));
3592     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3593   }
3594
3595   return SDValue();
3596 }
3597
3598 SDValue DAGCombiner::visitOR(SDNode *N) {
3599   SDValue N0 = N->getOperand(0);
3600   SDValue N1 = N->getOperand(1);
3601   EVT VT = N1.getValueType();
3602
3603   // fold vector ops
3604   if (VT.isVector()) {
3605     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3606       return FoldedVOp;
3607
3608     // fold (or x, 0) -> x, vector edition
3609     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3610       return N1;
3611     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3612       return N0;
3613
3614     // fold (or x, -1) -> -1, vector edition
3615     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3616       // do not return N0, because undef node may exist in N0
3617       return DAG.getConstant(
3618           APInt::getAllOnesValue(
3619               N0.getValueType().getScalarType().getSizeInBits()),
3620           SDLoc(N), N0.getValueType());
3621     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3622       // do not return N1, because undef node may exist in N1
3623       return DAG.getConstant(
3624           APInt::getAllOnesValue(
3625               N1.getValueType().getScalarType().getSizeInBits()),
3626           SDLoc(N), N1.getValueType());
3627
3628     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3629     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3630     // Do this only if the resulting shuffle is legal.
3631     if (isa<ShuffleVectorSDNode>(N0) &&
3632         isa<ShuffleVectorSDNode>(N1) &&
3633         // Avoid folding a node with illegal type.
3634         TLI.isTypeLegal(VT) &&
3635         N0->getOperand(1) == N1->getOperand(1) &&
3636         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3637       bool CanFold = true;
3638       unsigned NumElts = VT.getVectorNumElements();
3639       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3640       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3641       // We construct two shuffle masks:
3642       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3643       // and N1 as the second operand.
3644       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3645       // and N0 as the second operand.
3646       // We do this because OR is commutable and therefore there might be
3647       // two ways to fold this node into a shuffle.
3648       SmallVector<int,4> Mask1;
3649       SmallVector<int,4> Mask2;
3650
3651       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3652         int M0 = SV0->getMaskElt(i);
3653         int M1 = SV1->getMaskElt(i);
3654
3655         // Both shuffle indexes are undef. Propagate Undef.
3656         if (M0 < 0 && M1 < 0) {
3657           Mask1.push_back(M0);
3658           Mask2.push_back(M0);
3659           continue;
3660         }
3661
3662         if (M0 < 0 || M1 < 0 ||
3663             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3664             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3665           CanFold = false;
3666           break;
3667         }
3668
3669         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3670         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3671       }
3672
3673       if (CanFold) {
3674         // Fold this sequence only if the resulting shuffle is 'legal'.
3675         if (TLI.isShuffleMaskLegal(Mask1, VT))
3676           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3677                                       N1->getOperand(0), &Mask1[0]);
3678         if (TLI.isShuffleMaskLegal(Mask2, VT))
3679           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3680                                       N0->getOperand(0), &Mask2[0]);
3681       }
3682     }
3683   }
3684
3685   // fold (or c1, c2) -> c1|c2
3686   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3687   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3688   if (N0C && N1C && !N1C->isOpaque())
3689     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3690   // canonicalize constant to RHS
3691   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3692      !isConstantIntBuildVectorOrConstantInt(N1))
3693     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3694   // fold (or x, 0) -> x
3695   if (isNullConstant(N1))
3696     return N0;
3697   // fold (or x, -1) -> -1
3698   if (isAllOnesConstant(N1))
3699     return N1;
3700   // fold (or x, c) -> c iff (x & ~c) == 0
3701   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3702     return N1;
3703
3704   if (SDValue Combined = visitORLike(N0, N1, N))
3705     return Combined;
3706
3707   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3708   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3709     return BSwap;
3710   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3711     return BSwap;
3712
3713   // reassociate or
3714   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3715     return ROR;
3716   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3717   // iff (c1 & c2) == 0.
3718   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3719              isa<ConstantSDNode>(N0.getOperand(1))) {
3720     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3721     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3722       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3723                                                    N1C, C1))
3724         return DAG.getNode(
3725             ISD::AND, SDLoc(N), VT,
3726             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3727       return SDValue();
3728     }
3729   }
3730   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3731   if (N0.getOpcode() == N1.getOpcode())
3732     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3733       return Tmp;
3734
3735   // See if this is some rotate idiom.
3736   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3737     return SDValue(Rot, 0);
3738
3739   // Simplify the operands using demanded-bits information.
3740   if (!VT.isVector() &&
3741       SimplifyDemandedBits(SDValue(N, 0)))
3742     return SDValue(N, 0);
3743
3744   return SDValue();
3745 }
3746
3747 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3748 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3749   if (Op.getOpcode() == ISD::AND) {
3750     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3751       Mask = Op.getOperand(1);
3752       Op = Op.getOperand(0);
3753     } else {
3754       return false;
3755     }
3756   }
3757
3758   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3759     Shift = Op;
3760     return true;
3761   }
3762
3763   return false;
3764 }
3765
3766 // Return true if we can prove that, whenever Neg and Pos are both in the
3767 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3768 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3769 //
3770 //     (or (shift1 X, Neg), (shift2 X, Pos))
3771 //
3772 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3773 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3774 // to consider shift amounts with defined behavior.
3775 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3776   // If OpSize is a power of 2 then:
3777   //
3778   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3779   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3780   //
3781   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3782   // for the stronger condition:
3783   //
3784   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3785   //
3786   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3787   // we can just replace Neg with Neg' for the rest of the function.
3788   //
3789   // In other cases we check for the even stronger condition:
3790   //
3791   //     Neg == OpSize - Pos                                    [B]
3792   //
3793   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3794   // behavior if Pos == 0 (and consequently Neg == OpSize).
3795   //
3796   // We could actually use [A] whenever OpSize is a power of 2, but the
3797   // only extra cases that it would match are those uninteresting ones
3798   // where Neg and Pos are never in range at the same time.  E.g. for
3799   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3800   // as well as (sub 32, Pos), but:
3801   //
3802   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3803   //
3804   // always invokes undefined behavior for 32-bit X.
3805   //
3806   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3807   unsigned MaskLoBits = 0;
3808   if (Neg.getOpcode() == ISD::AND &&
3809       isPowerOf2_64(OpSize) &&
3810       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3811       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3812     Neg = Neg.getOperand(0);
3813     MaskLoBits = Log2_64(OpSize);
3814   }
3815
3816   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3817   if (Neg.getOpcode() != ISD::SUB)
3818     return 0;
3819   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3820   if (!NegC)
3821     return 0;
3822   SDValue NegOp1 = Neg.getOperand(1);
3823
3824   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3825   // Pos'.  The truncation is redundant for the purpose of the equality.
3826   if (MaskLoBits &&
3827       Pos.getOpcode() == ISD::AND &&
3828       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3829       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3830     Pos = Pos.getOperand(0);
3831
3832   // The condition we need is now:
3833   //
3834   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3835   //
3836   // If NegOp1 == Pos then we need:
3837   //
3838   //              OpSize & Mask == NegC & Mask
3839   //
3840   // (because "x & Mask" is a truncation and distributes through subtraction).
3841   APInt Width;
3842   if (Pos == NegOp1)
3843     Width = NegC->getAPIntValue();
3844   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3845   // Then the condition we want to prove becomes:
3846   //
3847   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3848   //
3849   // which, again because "x & Mask" is a truncation, becomes:
3850   //
3851   //                NegC & Mask == (OpSize - PosC) & Mask
3852   //              OpSize & Mask == (NegC + PosC) & Mask
3853   else if (Pos.getOpcode() == ISD::ADD &&
3854            Pos.getOperand(0) == NegOp1 &&
3855            Pos.getOperand(1).getOpcode() == ISD::Constant)
3856     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3857              NegC->getAPIntValue());
3858   else
3859     return false;
3860
3861   // Now we just need to check that OpSize & Mask == Width & Mask.
3862   if (MaskLoBits)
3863     // Opsize & Mask is 0 since Mask is Opsize - 1.
3864     return Width.getLoBits(MaskLoBits) == 0;
3865   return Width == OpSize;
3866 }
3867
3868 // A subroutine of MatchRotate used once we have found an OR of two opposite
3869 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3870 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3871 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3872 // Neg with outer conversions stripped away.
3873 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3874                                        SDValue Neg, SDValue InnerPos,
3875                                        SDValue InnerNeg, unsigned PosOpcode,
3876                                        unsigned NegOpcode, SDLoc DL) {
3877   // fold (or (shl x, (*ext y)),
3878   //          (srl x, (*ext (sub 32, y)))) ->
3879   //   (rotl x, y) or (rotr x, (sub 32, y))
3880   //
3881   // fold (or (shl x, (*ext (sub 32, y))),
3882   //          (srl x, (*ext y))) ->
3883   //   (rotr x, y) or (rotl x, (sub 32, y))
3884   EVT VT = Shifted.getValueType();
3885   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3886     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3887     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3888                        HasPos ? Pos : Neg).getNode();
3889   }
3890
3891   return nullptr;
3892 }
3893
3894 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3895 // idioms for rotate, and if the target supports rotation instructions, generate
3896 // a rot[lr].
3897 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3898   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3899   EVT VT = LHS.getValueType();
3900   if (!TLI.isTypeLegal(VT)) return nullptr;
3901
3902   // The target must have at least one rotate flavor.
3903   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3904   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3905   if (!HasROTL && !HasROTR) return nullptr;
3906
3907   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3908   SDValue LHSShift;   // The shift.
3909   SDValue LHSMask;    // AND value if any.
3910   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3911     return nullptr; // Not part of a rotate.
3912
3913   SDValue RHSShift;   // The shift.
3914   SDValue RHSMask;    // AND value if any.
3915   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3916     return nullptr; // Not part of a rotate.
3917
3918   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3919     return nullptr;   // Not shifting the same value.
3920
3921   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3922     return nullptr;   // Shifts must disagree.
3923
3924   // Canonicalize shl to left side in a shl/srl pair.
3925   if (RHSShift.getOpcode() == ISD::SHL) {
3926     std::swap(LHS, RHS);
3927     std::swap(LHSShift, RHSShift);
3928     std::swap(LHSMask , RHSMask );
3929   }
3930
3931   unsigned OpSizeInBits = VT.getSizeInBits();
3932   SDValue LHSShiftArg = LHSShift.getOperand(0);
3933   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3934   SDValue RHSShiftArg = RHSShift.getOperand(0);
3935   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3936
3937   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3938   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3939   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3940       RHSShiftAmt.getOpcode() == ISD::Constant) {
3941     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3942     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3943     if ((LShVal + RShVal) != OpSizeInBits)
3944       return nullptr;
3945
3946     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3947                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3948
3949     // If there is an AND of either shifted operand, apply it to the result.
3950     if (LHSMask.getNode() || RHSMask.getNode()) {
3951       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3952
3953       if (LHSMask.getNode()) {
3954         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3955         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3956       }
3957       if (RHSMask.getNode()) {
3958         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3959         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3960       }
3961
3962       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3963     }
3964
3965     return Rot.getNode();
3966   }
3967
3968   // If there is a mask here, and we have a variable shift, we can't be sure
3969   // that we're masking out the right stuff.
3970   if (LHSMask.getNode() || RHSMask.getNode())
3971     return nullptr;
3972
3973   // If the shift amount is sign/zext/any-extended just peel it off.
3974   SDValue LExtOp0 = LHSShiftAmt;
3975   SDValue RExtOp0 = RHSShiftAmt;
3976   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3977        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3978        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3979        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3980       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3981        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3982        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3983        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3984     LExtOp0 = LHSShiftAmt.getOperand(0);
3985     RExtOp0 = RHSShiftAmt.getOperand(0);
3986   }
3987
3988   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3989                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3990   if (TryL)
3991     return TryL;
3992
3993   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3994                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3995   if (TryR)
3996     return TryR;
3997
3998   return nullptr;
3999 }
4000
4001 SDValue DAGCombiner::visitXOR(SDNode *N) {
4002   SDValue N0 = N->getOperand(0);
4003   SDValue N1 = N->getOperand(1);
4004   EVT VT = N0.getValueType();
4005
4006   // fold vector ops
4007   if (VT.isVector()) {
4008     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4009       return FoldedVOp;
4010
4011     // fold (xor x, 0) -> x, vector edition
4012     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4013       return N1;
4014     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4015       return N0;
4016   }
4017
4018   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4019   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4020     return DAG.getConstant(0, SDLoc(N), VT);
4021   // fold (xor x, undef) -> undef
4022   if (N0.getOpcode() == ISD::UNDEF)
4023     return N0;
4024   if (N1.getOpcode() == ISD::UNDEF)
4025     return N1;
4026   // fold (xor c1, c2) -> c1^c2
4027   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4028   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4029   if (N0C && N1C)
4030     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4031   // canonicalize constant to RHS
4032   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4033      !isConstantIntBuildVectorOrConstantInt(N1))
4034     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4035   // fold (xor x, 0) -> x
4036   if (isNullConstant(N1))
4037     return N0;
4038   // reassociate xor
4039   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4040     return RXOR;
4041
4042   // fold !(x cc y) -> (x !cc y)
4043   SDValue LHS, RHS, CC;
4044   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4045     bool isInt = LHS.getValueType().isInteger();
4046     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4047                                                isInt);
4048
4049     if (!LegalOperations ||
4050         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4051       switch (N0.getOpcode()) {
4052       default:
4053         llvm_unreachable("Unhandled SetCC Equivalent!");
4054       case ISD::SETCC:
4055         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4056       case ISD::SELECT_CC:
4057         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4058                                N0.getOperand(3), NotCC);
4059       }
4060     }
4061   }
4062
4063   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4064   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4065       N0.getNode()->hasOneUse() &&
4066       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4067     SDValue V = N0.getOperand(0);
4068     SDLoc DL(N0);
4069     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4070                     DAG.getConstant(1, DL, V.getValueType()));
4071     AddToWorklist(V.getNode());
4072     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4073   }
4074
4075   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4076   if (isOneConstant(N1) && VT == MVT::i1 &&
4077       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4078     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4079     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4080       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4081       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4082       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4083       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4084       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4085     }
4086   }
4087   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4088   if (isAllOnesConstant(N1) &&
4089       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4090     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4091     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4092       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4093       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4094       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4095       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4096       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4097     }
4098   }
4099   // fold (xor (and x, y), y) -> (and (not x), y)
4100   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4101       N0->getOperand(1) == N1) {
4102     SDValue X = N0->getOperand(0);
4103     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4104     AddToWorklist(NotX.getNode());
4105     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4106   }
4107   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4108   if (N1C && N0.getOpcode() == ISD::XOR) {
4109     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4110       SDLoc DL(N);
4111       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4112                          DAG.getConstant(N1C->getAPIntValue() ^
4113                                          N00C->getAPIntValue(), DL, VT));
4114     }
4115     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4116       SDLoc DL(N);
4117       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4118                          DAG.getConstant(N1C->getAPIntValue() ^
4119                                          N01C->getAPIntValue(), DL, VT));
4120     }
4121   }
4122   // fold (xor x, x) -> 0
4123   if (N0 == N1)
4124     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4125
4126   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4127   // Here is a concrete example of this equivalence:
4128   // i16   x ==  14
4129   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4130   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4131   //
4132   // =>
4133   //
4134   // i16     ~1      == 0b1111111111111110
4135   // i16 rol(~1, 14) == 0b1011111111111111
4136   //
4137   // Some additional tips to help conceptualize this transform:
4138   // - Try to see the operation as placing a single zero in a value of all ones.
4139   // - There exists no value for x which would allow the result to contain zero.
4140   // - Values of x larger than the bitwidth are undefined and do not require a
4141   //   consistent result.
4142   // - Pushing the zero left requires shifting one bits in from the right.
4143   // A rotate left of ~1 is a nice way of achieving the desired result.
4144   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4145       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4146     SDLoc DL(N);
4147     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4148                        N0.getOperand(1));
4149   }
4150
4151   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4152   if (N0.getOpcode() == N1.getOpcode())
4153     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4154       return Tmp;
4155
4156   // Simplify the expression using non-local knowledge.
4157   if (!VT.isVector() &&
4158       SimplifyDemandedBits(SDValue(N, 0)))
4159     return SDValue(N, 0);
4160
4161   return SDValue();
4162 }
4163
4164 /// Handle transforms common to the three shifts, when the shift amount is a
4165 /// constant.
4166 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4167   SDNode *LHS = N->getOperand(0).getNode();
4168   if (!LHS->hasOneUse()) return SDValue();
4169
4170   // We want to pull some binops through shifts, so that we have (and (shift))
4171   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4172   // thing happens with address calculations, so it's important to canonicalize
4173   // it.
4174   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4175
4176   switch (LHS->getOpcode()) {
4177   default: return SDValue();
4178   case ISD::OR:
4179   case ISD::XOR:
4180     HighBitSet = false; // We can only transform sra if the high bit is clear.
4181     break;
4182   case ISD::AND:
4183     HighBitSet = true;  // We can only transform sra if the high bit is set.
4184     break;
4185   case ISD::ADD:
4186     if (N->getOpcode() != ISD::SHL)
4187       return SDValue(); // only shl(add) not sr[al](add).
4188     HighBitSet = false; // We can only transform sra if the high bit is clear.
4189     break;
4190   }
4191
4192   // We require the RHS of the binop to be a constant and not opaque as well.
4193   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4194   if (!BinOpCst) return SDValue();
4195
4196   // FIXME: disable this unless the input to the binop is a shift by a constant.
4197   // If it is not a shift, it pessimizes some common cases like:
4198   //
4199   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4200   //    int bar(int *X, int i) { return X[i & 255]; }
4201   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4202   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4203        BinOpLHSVal->getOpcode() != ISD::SRA &&
4204        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4205       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4206     return SDValue();
4207
4208   EVT VT = N->getValueType(0);
4209
4210   // If this is a signed shift right, and the high bit is modified by the
4211   // logical operation, do not perform the transformation. The highBitSet
4212   // boolean indicates the value of the high bit of the constant which would
4213   // cause it to be modified for this operation.
4214   if (N->getOpcode() == ISD::SRA) {
4215     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4216     if (BinOpRHSSignSet != HighBitSet)
4217       return SDValue();
4218   }
4219
4220   if (!TLI.isDesirableToCommuteWithShift(LHS))
4221     return SDValue();
4222
4223   // Fold the constants, shifting the binop RHS by the shift amount.
4224   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4225                                N->getValueType(0),
4226                                LHS->getOperand(1), N->getOperand(1));
4227   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4228
4229   // Create the new shift.
4230   SDValue NewShift = DAG.getNode(N->getOpcode(),
4231                                  SDLoc(LHS->getOperand(0)),
4232                                  VT, LHS->getOperand(0), N->getOperand(1));
4233
4234   // Create the new binop.
4235   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4236 }
4237
4238 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4239   assert(N->getOpcode() == ISD::TRUNCATE);
4240   assert(N->getOperand(0).getOpcode() == ISD::AND);
4241
4242   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4243   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4244     SDValue N01 = N->getOperand(0).getOperand(1);
4245
4246     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4247       if (!N01C->isOpaque()) {
4248         EVT TruncVT = N->getValueType(0);
4249         SDValue N00 = N->getOperand(0).getOperand(0);
4250         APInt TruncC = N01C->getAPIntValue();
4251         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4252         SDLoc DL(N);
4253
4254         return DAG.getNode(ISD::AND, DL, TruncVT,
4255                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4256                            DAG.getConstant(TruncC, DL, TruncVT));
4257       }
4258     }
4259   }
4260
4261   return SDValue();
4262 }
4263
4264 SDValue DAGCombiner::visitRotate(SDNode *N) {
4265   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4266   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4267       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4268     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4269     if (NewOp1.getNode())
4270       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4271                          N->getOperand(0), NewOp1);
4272   }
4273   return SDValue();
4274 }
4275
4276 SDValue DAGCombiner::visitSHL(SDNode *N) {
4277   SDValue N0 = N->getOperand(0);
4278   SDValue N1 = N->getOperand(1);
4279   EVT VT = N0.getValueType();
4280   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4281
4282   // fold vector ops
4283   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4284   if (VT.isVector()) {
4285     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4286       return FoldedVOp;
4287
4288     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4289     // If setcc produces all-one true value then:
4290     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4291     if (N1CV && N1CV->isConstant()) {
4292       if (N0.getOpcode() == ISD::AND) {
4293         SDValue N00 = N0->getOperand(0);
4294         SDValue N01 = N0->getOperand(1);
4295         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4296
4297         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4298             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4299                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4300           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4301                                                      N01CV, N1CV))
4302             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4303         }
4304       } else {
4305         N1C = isConstOrConstSplat(N1);
4306       }
4307     }
4308   }
4309
4310   // fold (shl c1, c2) -> c1<<c2
4311   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4312   if (N0C && N1C && !N1C->isOpaque())
4313     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4314   // fold (shl 0, x) -> 0
4315   if (isNullConstant(N0))
4316     return N0;
4317   // fold (shl x, c >= size(x)) -> undef
4318   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4319     return DAG.getUNDEF(VT);
4320   // fold (shl x, 0) -> x
4321   if (N1C && N1C->isNullValue())
4322     return N0;
4323   // fold (shl undef, x) -> 0
4324   if (N0.getOpcode() == ISD::UNDEF)
4325     return DAG.getConstant(0, SDLoc(N), VT);
4326   // if (shl x, c) is known to be zero, return 0
4327   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4328                             APInt::getAllOnesValue(OpSizeInBits)))
4329     return DAG.getConstant(0, SDLoc(N), VT);
4330   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4331   if (N1.getOpcode() == ISD::TRUNCATE &&
4332       N1.getOperand(0).getOpcode() == ISD::AND) {
4333     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4334     if (NewOp1.getNode())
4335       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4336   }
4337
4338   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4339     return SDValue(N, 0);
4340
4341   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4342   if (N1C && N0.getOpcode() == ISD::SHL) {
4343     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4344       uint64_t c1 = N0C1->getZExtValue();
4345       uint64_t c2 = N1C->getZExtValue();
4346       SDLoc DL(N);
4347       if (c1 + c2 >= OpSizeInBits)
4348         return DAG.getConstant(0, DL, VT);
4349       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4350                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4351     }
4352   }
4353
4354   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4355   // For this to be valid, the second form must not preserve any of the bits
4356   // that are shifted out by the inner shift in the first form.  This means
4357   // the outer shift size must be >= the number of bits added by the ext.
4358   // As a corollary, we don't care what kind of ext it is.
4359   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4360               N0.getOpcode() == ISD::ANY_EXTEND ||
4361               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4362       N0.getOperand(0).getOpcode() == ISD::SHL) {
4363     SDValue N0Op0 = N0.getOperand(0);
4364     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4365       uint64_t c1 = N0Op0C1->getZExtValue();
4366       uint64_t c2 = N1C->getZExtValue();
4367       EVT InnerShiftVT = N0Op0.getValueType();
4368       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4369       if (c2 >= OpSizeInBits - InnerShiftSize) {
4370         SDLoc DL(N0);
4371         if (c1 + c2 >= OpSizeInBits)
4372           return DAG.getConstant(0, DL, VT);
4373         return DAG.getNode(ISD::SHL, DL, VT,
4374                            DAG.getNode(N0.getOpcode(), DL, VT,
4375                                        N0Op0->getOperand(0)),
4376                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4377       }
4378     }
4379   }
4380
4381   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4382   // Only fold this if the inner zext has no other uses to avoid increasing
4383   // the total number of instructions.
4384   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4385       N0.getOperand(0).getOpcode() == ISD::SRL) {
4386     SDValue N0Op0 = N0.getOperand(0);
4387     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4388       uint64_t c1 = N0Op0C1->getZExtValue();
4389       if (c1 < VT.getScalarSizeInBits()) {
4390         uint64_t c2 = N1C->getZExtValue();
4391         if (c1 == c2) {
4392           SDValue NewOp0 = N0.getOperand(0);
4393           EVT CountVT = NewOp0.getOperand(1).getValueType();
4394           SDLoc DL(N);
4395           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4396                                        NewOp0,
4397                                        DAG.getConstant(c2, DL, CountVT));
4398           AddToWorklist(NewSHL.getNode());
4399           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4400         }
4401       }
4402     }
4403   }
4404
4405   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4406   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4407   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4408       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4409     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4410       uint64_t C1 = N0C1->getZExtValue();
4411       uint64_t C2 = N1C->getZExtValue();
4412       SDLoc DL(N);
4413       if (C1 <= C2)
4414         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4415                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4416       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4417                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4418     }
4419   }
4420
4421   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4422   //                               (and (srl x, (sub c1, c2), MASK)
4423   // Only fold this if the inner shift has no other uses -- if it does, folding
4424   // this will increase the total number of instructions.
4425   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4426     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4427       uint64_t c1 = N0C1->getZExtValue();
4428       if (c1 < OpSizeInBits) {
4429         uint64_t c2 = N1C->getZExtValue();
4430         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4431         SDValue Shift;
4432         if (c2 > c1) {
4433           Mask = Mask.shl(c2 - c1);
4434           SDLoc DL(N);
4435           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4436                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4437         } else {
4438           Mask = Mask.lshr(c1 - c2);
4439           SDLoc DL(N);
4440           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4441                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4442         }
4443         SDLoc DL(N0);
4444         return DAG.getNode(ISD::AND, DL, VT, Shift,
4445                            DAG.getConstant(Mask, DL, VT));
4446       }
4447     }
4448   }
4449   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4450   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4451     unsigned BitSize = VT.getScalarSizeInBits();
4452     SDLoc DL(N);
4453     SDValue HiBitsMask =
4454       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4455                                             BitSize - N1C->getZExtValue()),
4456                       DL, VT);
4457     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4458                        HiBitsMask);
4459   }
4460
4461   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4462   // Variant of version done on multiply, except mul by a power of 2 is turned
4463   // into a shift.
4464   APInt Val;
4465   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4466       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4467        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4468     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4469     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4470     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4471   }
4472
4473   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4474   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4475     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4476       if (SDValue Folded =
4477               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4478         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4479     }
4480   }
4481
4482   if (N1C && !N1C->isOpaque())
4483     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4484       return NewSHL;
4485
4486   return SDValue();
4487 }
4488
4489 SDValue DAGCombiner::visitSRA(SDNode *N) {
4490   SDValue N0 = N->getOperand(0);
4491   SDValue N1 = N->getOperand(1);
4492   EVT VT = N0.getValueType();
4493   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4494
4495   // fold vector ops
4496   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4497   if (VT.isVector()) {
4498     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4499       return FoldedVOp;
4500
4501     N1C = isConstOrConstSplat(N1);
4502   }
4503
4504   // fold (sra c1, c2) -> (sra c1, c2)
4505   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4506   if (N0C && N1C && !N1C->isOpaque())
4507     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4508   // fold (sra 0, x) -> 0
4509   if (isNullConstant(N0))
4510     return N0;
4511   // fold (sra -1, x) -> -1
4512   if (isAllOnesConstant(N0))
4513     return N0;
4514   // fold (sra x, (setge c, size(x))) -> undef
4515   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4516     return DAG.getUNDEF(VT);
4517   // fold (sra x, 0) -> x
4518   if (N1C && N1C->isNullValue())
4519     return N0;
4520   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4521   // sext_inreg.
4522   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4523     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4524     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4525     if (VT.isVector())
4526       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4527                                ExtVT, VT.getVectorNumElements());
4528     if ((!LegalOperations ||
4529          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4530       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4531                          N0.getOperand(0), DAG.getValueType(ExtVT));
4532   }
4533
4534   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4535   if (N1C && N0.getOpcode() == ISD::SRA) {
4536     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4537       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4538       if (Sum >= OpSizeInBits)
4539         Sum = OpSizeInBits - 1;
4540       SDLoc DL(N);
4541       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4542                          DAG.getConstant(Sum, DL, N1.getValueType()));
4543     }
4544   }
4545
4546   // fold (sra (shl X, m), (sub result_size, n))
4547   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4548   // result_size - n != m.
4549   // If truncate is free for the target sext(shl) is likely to result in better
4550   // code.
4551   if (N0.getOpcode() == ISD::SHL && N1C) {
4552     // Get the two constanst of the shifts, CN0 = m, CN = n.
4553     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4554     if (N01C) {
4555       LLVMContext &Ctx = *DAG.getContext();
4556       // Determine what the truncate's result bitsize and type would be.
4557       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4558
4559       if (VT.isVector())
4560         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4561
4562       // Determine the residual right-shift amount.
4563       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4564
4565       // If the shift is not a no-op (in which case this should be just a sign
4566       // extend already), the truncated to type is legal, sign_extend is legal
4567       // on that type, and the truncate to that type is both legal and free,
4568       // perform the transform.
4569       if ((ShiftAmt > 0) &&
4570           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4571           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4572           TLI.isTruncateFree(VT, TruncVT)) {
4573
4574         SDLoc DL(N);
4575         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4576             getShiftAmountTy(N0.getOperand(0).getValueType()));
4577         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4578                                     N0.getOperand(0), Amt);
4579         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4580                                     Shift);
4581         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4582                            N->getValueType(0), Trunc);
4583       }
4584     }
4585   }
4586
4587   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4588   if (N1.getOpcode() == ISD::TRUNCATE &&
4589       N1.getOperand(0).getOpcode() == ISD::AND) {
4590     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4591     if (NewOp1.getNode())
4592       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4593   }
4594
4595   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4596   //      if c1 is equal to the number of bits the trunc removes
4597   if (N0.getOpcode() == ISD::TRUNCATE &&
4598       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4599        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4600       N0.getOperand(0).hasOneUse() &&
4601       N0.getOperand(0).getOperand(1).hasOneUse() &&
4602       N1C) {
4603     SDValue N0Op0 = N0.getOperand(0);
4604     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4605       unsigned LargeShiftVal = LargeShift->getZExtValue();
4606       EVT LargeVT = N0Op0.getValueType();
4607
4608       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4609         SDLoc DL(N);
4610         SDValue Amt =
4611           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4612                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4613         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4614                                   N0Op0.getOperand(0), Amt);
4615         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4616       }
4617     }
4618   }
4619
4620   // Simplify, based on bits shifted out of the LHS.
4621   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4622     return SDValue(N, 0);
4623
4624
4625   // If the sign bit is known to be zero, switch this to a SRL.
4626   if (DAG.SignBitIsZero(N0))
4627     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4628
4629   if (N1C && !N1C->isOpaque())
4630     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4631       return NewSRA;
4632
4633   return SDValue();
4634 }
4635
4636 SDValue DAGCombiner::visitSRL(SDNode *N) {
4637   SDValue N0 = N->getOperand(0);
4638   SDValue N1 = N->getOperand(1);
4639   EVT VT = N0.getValueType();
4640   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4641
4642   // fold vector ops
4643   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4644   if (VT.isVector()) {
4645     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4646       return FoldedVOp;
4647
4648     N1C = isConstOrConstSplat(N1);
4649   }
4650
4651   // fold (srl c1, c2) -> c1 >>u c2
4652   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4653   if (N0C && N1C && !N1C->isOpaque())
4654     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4655   // fold (srl 0, x) -> 0
4656   if (isNullConstant(N0))
4657     return N0;
4658   // fold (srl x, c >= size(x)) -> undef
4659   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4660     return DAG.getUNDEF(VT);
4661   // fold (srl x, 0) -> x
4662   if (N1C && N1C->isNullValue())
4663     return N0;
4664   // if (srl x, c) is known to be zero, return 0
4665   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4666                                    APInt::getAllOnesValue(OpSizeInBits)))
4667     return DAG.getConstant(0, SDLoc(N), VT);
4668
4669   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4670   if (N1C && N0.getOpcode() == ISD::SRL) {
4671     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4672       uint64_t c1 = N01C->getZExtValue();
4673       uint64_t c2 = N1C->getZExtValue();
4674       SDLoc DL(N);
4675       if (c1 + c2 >= OpSizeInBits)
4676         return DAG.getConstant(0, DL, VT);
4677       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4678                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4679     }
4680   }
4681
4682   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4683   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4684       N0.getOperand(0).getOpcode() == ISD::SRL &&
4685       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4686     uint64_t c1 =
4687       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4688     uint64_t c2 = N1C->getZExtValue();
4689     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4690     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4691     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4692     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4693     if (c1 + OpSizeInBits == InnerShiftSize) {
4694       SDLoc DL(N0);
4695       if (c1 + c2 >= InnerShiftSize)
4696         return DAG.getConstant(0, DL, VT);
4697       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4698                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4699                                      N0.getOperand(0)->getOperand(0),
4700                                      DAG.getConstant(c1 + c2, DL,
4701                                                      ShiftCountVT)));
4702     }
4703   }
4704
4705   // fold (srl (shl x, c), c) -> (and x, cst2)
4706   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4707     unsigned BitSize = N0.getScalarValueSizeInBits();
4708     if (BitSize <= 64) {
4709       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4710       SDLoc DL(N);
4711       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4712                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4713     }
4714   }
4715
4716   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4717   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4718     // Shifting in all undef bits?
4719     EVT SmallVT = N0.getOperand(0).getValueType();
4720     unsigned BitSize = SmallVT.getScalarSizeInBits();
4721     if (N1C->getZExtValue() >= BitSize)
4722       return DAG.getUNDEF(VT);
4723
4724     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4725       uint64_t ShiftAmt = N1C->getZExtValue();
4726       SDLoc DL0(N0);
4727       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4728                                        N0.getOperand(0),
4729                           DAG.getConstant(ShiftAmt, DL0,
4730                                           getShiftAmountTy(SmallVT)));
4731       AddToWorklist(SmallShift.getNode());
4732       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4733       SDLoc DL(N);
4734       return DAG.getNode(ISD::AND, DL, VT,
4735                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4736                          DAG.getConstant(Mask, DL, VT));
4737     }
4738   }
4739
4740   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4741   // bit, which is unmodified by sra.
4742   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4743     if (N0.getOpcode() == ISD::SRA)
4744       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4745   }
4746
4747   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4748   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4749       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4750     APInt KnownZero, KnownOne;
4751     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4752
4753     // If any of the input bits are KnownOne, then the input couldn't be all
4754     // zeros, thus the result of the srl will always be zero.
4755     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4756
4757     // If all of the bits input the to ctlz node are known to be zero, then
4758     // the result of the ctlz is "32" and the result of the shift is one.
4759     APInt UnknownBits = ~KnownZero;
4760     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4761
4762     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4763     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4764       // Okay, we know that only that the single bit specified by UnknownBits
4765       // could be set on input to the CTLZ node. If this bit is set, the SRL
4766       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4767       // to an SRL/XOR pair, which is likely to simplify more.
4768       unsigned ShAmt = UnknownBits.countTrailingZeros();
4769       SDValue Op = N0.getOperand(0);
4770
4771       if (ShAmt) {
4772         SDLoc DL(N0);
4773         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4774                   DAG.getConstant(ShAmt, DL,
4775                                   getShiftAmountTy(Op.getValueType())));
4776         AddToWorklist(Op.getNode());
4777       }
4778
4779       SDLoc DL(N);
4780       return DAG.getNode(ISD::XOR, DL, VT,
4781                          Op, DAG.getConstant(1, DL, VT));
4782     }
4783   }
4784
4785   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4786   if (N1.getOpcode() == ISD::TRUNCATE &&
4787       N1.getOperand(0).getOpcode() == ISD::AND) {
4788     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4789       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4790   }
4791
4792   // fold operands of srl based on knowledge that the low bits are not
4793   // demanded.
4794   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4795     return SDValue(N, 0);
4796
4797   if (N1C && !N1C->isOpaque())
4798     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4799       return NewSRL;
4800
4801   // Attempt to convert a srl of a load into a narrower zero-extending load.
4802   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4803     return NarrowLoad;
4804
4805   // Here is a common situation. We want to optimize:
4806   //
4807   //   %a = ...
4808   //   %b = and i32 %a, 2
4809   //   %c = srl i32 %b, 1
4810   //   brcond i32 %c ...
4811   //
4812   // into
4813   //
4814   //   %a = ...
4815   //   %b = and %a, 2
4816   //   %c = setcc eq %b, 0
4817   //   brcond %c ...
4818   //
4819   // However when after the source operand of SRL is optimized into AND, the SRL
4820   // itself may not be optimized further. Look for it and add the BRCOND into
4821   // the worklist.
4822   if (N->hasOneUse()) {
4823     SDNode *Use = *N->use_begin();
4824     if (Use->getOpcode() == ISD::BRCOND)
4825       AddToWorklist(Use);
4826     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4827       // Also look pass the truncate.
4828       Use = *Use->use_begin();
4829       if (Use->getOpcode() == ISD::BRCOND)
4830         AddToWorklist(Use);
4831     }
4832   }
4833
4834   return SDValue();
4835 }
4836
4837 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4838   SDValue N0 = N->getOperand(0);
4839   EVT VT = N->getValueType(0);
4840
4841   // fold (bswap c1) -> c2
4842   if (isConstantIntBuildVectorOrConstantInt(N0))
4843     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4844   // fold (bswap (bswap x)) -> x
4845   if (N0.getOpcode() == ISD::BSWAP)
4846     return N0->getOperand(0);
4847   return SDValue();
4848 }
4849
4850 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4851   SDValue N0 = N->getOperand(0);
4852   EVT VT = N->getValueType(0);
4853
4854   // fold (ctlz c1) -> c2
4855   if (isConstantIntBuildVectorOrConstantInt(N0))
4856     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4857   return SDValue();
4858 }
4859
4860 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4861   SDValue N0 = N->getOperand(0);
4862   EVT VT = N->getValueType(0);
4863
4864   // fold (ctlz_zero_undef c1) -> c2
4865   if (isConstantIntBuildVectorOrConstantInt(N0))
4866     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4867   return SDValue();
4868 }
4869
4870 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4871   SDValue N0 = N->getOperand(0);
4872   EVT VT = N->getValueType(0);
4873
4874   // fold (cttz c1) -> c2
4875   if (isConstantIntBuildVectorOrConstantInt(N0))
4876     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4877   return SDValue();
4878 }
4879
4880 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4881   SDValue N0 = N->getOperand(0);
4882   EVT VT = N->getValueType(0);
4883
4884   // fold (cttz_zero_undef c1) -> c2
4885   if (isConstantIntBuildVectorOrConstantInt(N0))
4886     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4887   return SDValue();
4888 }
4889
4890 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4891   SDValue N0 = N->getOperand(0);
4892   EVT VT = N->getValueType(0);
4893
4894   // fold (ctpop c1) -> c2
4895   if (isConstantIntBuildVectorOrConstantInt(N0))
4896     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4897   return SDValue();
4898 }
4899
4900
4901 /// \brief Generate Min/Max node
4902 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4903                                    SDValue True, SDValue False,
4904                                    ISD::CondCode CC, const TargetLowering &TLI,
4905                                    SelectionDAG &DAG) {
4906   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4907     return SDValue();
4908
4909   switch (CC) {
4910   case ISD::SETOLT:
4911   case ISD::SETOLE:
4912   case ISD::SETLT:
4913   case ISD::SETLE:
4914   case ISD::SETULT:
4915   case ISD::SETULE: {
4916     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4917     if (TLI.isOperationLegal(Opcode, VT))
4918       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4919     return SDValue();
4920   }
4921   case ISD::SETOGT:
4922   case ISD::SETOGE:
4923   case ISD::SETGT:
4924   case ISD::SETGE:
4925   case ISD::SETUGT:
4926   case ISD::SETUGE: {
4927     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4928     if (TLI.isOperationLegal(Opcode, VT))
4929       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4930     return SDValue();
4931   }
4932   default:
4933     return SDValue();
4934   }
4935 }
4936
4937 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4938   SDValue N0 = N->getOperand(0);
4939   SDValue N1 = N->getOperand(1);
4940   SDValue N2 = N->getOperand(2);
4941   EVT VT = N->getValueType(0);
4942   EVT VT0 = N0.getValueType();
4943
4944   // fold (select C, X, X) -> X
4945   if (N1 == N2)
4946     return N1;
4947   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4948     // fold (select true, X, Y) -> X
4949     // fold (select false, X, Y) -> Y
4950     return !N0C->isNullValue() ? N1 : N2;
4951   }
4952   // fold (select C, 1, X) -> (or C, X)
4953   if (VT == MVT::i1 && isOneConstant(N1))
4954     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4955   // fold (select C, 0, 1) -> (xor C, 1)
4956   // We can't do this reliably if integer based booleans have different contents
4957   // to floating point based booleans. This is because we can't tell whether we
4958   // have an integer-based boolean or a floating-point-based boolean unless we
4959   // can find the SETCC that produced it and inspect its operands. This is
4960   // fairly easy if C is the SETCC node, but it can potentially be
4961   // undiscoverable (or not reasonably discoverable). For example, it could be
4962   // in another basic block or it could require searching a complicated
4963   // expression.
4964   if (VT.isInteger() &&
4965       (VT0 == MVT::i1 || (VT0.isInteger() &&
4966                           TLI.getBooleanContents(false, false) ==
4967                               TLI.getBooleanContents(false, true) &&
4968                           TLI.getBooleanContents(false, false) ==
4969                               TargetLowering::ZeroOrOneBooleanContent)) &&
4970       isNullConstant(N1) && isOneConstant(N2)) {
4971     SDValue XORNode;
4972     if (VT == VT0) {
4973       SDLoc DL(N);
4974       return DAG.getNode(ISD::XOR, DL, VT0,
4975                          N0, DAG.getConstant(1, DL, VT0));
4976     }
4977     SDLoc DL0(N0);
4978     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4979                           N0, DAG.getConstant(1, DL0, VT0));
4980     AddToWorklist(XORNode.getNode());
4981     if (VT.bitsGT(VT0))
4982       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4983     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4984   }
4985   // fold (select C, 0, X) -> (and (not C), X)
4986   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4987     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4988     AddToWorklist(NOTNode.getNode());
4989     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4990   }
4991   // fold (select C, X, 1) -> (or (not C), X)
4992   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4993     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4994     AddToWorklist(NOTNode.getNode());
4995     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4996   }
4997   // fold (select C, X, 0) -> (and C, X)
4998   if (VT == MVT::i1 && isNullConstant(N2))
4999     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5000   // fold (select X, X, Y) -> (or X, Y)
5001   // fold (select X, 1, Y) -> (or X, Y)
5002   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5003     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5004   // fold (select X, Y, X) -> (and X, Y)
5005   // fold (select X, Y, 0) -> (and X, Y)
5006   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5007     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5008
5009   // If we can fold this based on the true/false value, do so.
5010   if (SimplifySelectOps(N, N1, N2))
5011     return SDValue(N, 0);  // Don't revisit N.
5012
5013   if (VT0 == MVT::i1) {
5014     // The code in this block deals with the following 2 equivalences:
5015     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5016     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5017     // The target can specify its prefered form with the
5018     // shouldNormalizeToSelectSequence() callback. However we always transform
5019     // to the right anyway if we find the inner select exists in the DAG anyway
5020     // and we always transform to the left side if we know that we can further
5021     // optimize the combination of the conditions.
5022     bool normalizeToSequence
5023       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5024     // select (and Cond0, Cond1), X, Y
5025     //   -> select Cond0, (select Cond1, X, Y), Y
5026     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5027       SDValue Cond0 = N0->getOperand(0);
5028       SDValue Cond1 = N0->getOperand(1);
5029       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5030                                         N1.getValueType(), Cond1, N1, N2);
5031       if (normalizeToSequence || !InnerSelect.use_empty())
5032         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5033                            InnerSelect, N2);
5034     }
5035     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5036     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5037       SDValue Cond0 = N0->getOperand(0);
5038       SDValue Cond1 = N0->getOperand(1);
5039       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5040                                         N1.getValueType(), Cond1, N1, N2);
5041       if (normalizeToSequence || !InnerSelect.use_empty())
5042         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5043                            InnerSelect);
5044     }
5045
5046     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5047     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5048       SDValue N1_0 = N1->getOperand(0);
5049       SDValue N1_1 = N1->getOperand(1);
5050       SDValue N1_2 = N1->getOperand(2);
5051       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5052         // Create the actual and node if we can generate good code for it.
5053         if (!normalizeToSequence) {
5054           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5055                                     N0, N1_0);
5056           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5057                              N1_1, N2);
5058         }
5059         // Otherwise see if we can optimize the "and" to a better pattern.
5060         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5061           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5062                              N1_1, N2);
5063       }
5064     }
5065     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5066     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5067       SDValue N2_0 = N2->getOperand(0);
5068       SDValue N2_1 = N2->getOperand(1);
5069       SDValue N2_2 = N2->getOperand(2);
5070       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5071         // Create the actual or node if we can generate good code for it.
5072         if (!normalizeToSequence) {
5073           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5074                                    N0, N2_0);
5075           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5076                              N1, N2_2);
5077         }
5078         // Otherwise see if we can optimize to a better pattern.
5079         if (SDValue Combined = visitORLike(N0, N2_0, N))
5080           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5081                              N1, N2_2);
5082       }
5083     }
5084   }
5085
5086   // fold selects based on a setcc into other things, such as min/max/abs
5087   if (N0.getOpcode() == ISD::SETCC) {
5088     // select x, y (fcmp lt x, y) -> fminnum x, y
5089     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5090     //
5091     // This is OK if we don't care about what happens if either operand is a
5092     // NaN.
5093     //
5094
5095     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5096     // no signed zeros as well as no nans.
5097     const TargetOptions &Options = DAG.getTarget().Options;
5098     if (Options.UnsafeFPMath &&
5099         VT.isFloatingPoint() && N0.hasOneUse() &&
5100         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5101       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5102
5103       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5104                                                 N0.getOperand(1), N1, N2, CC,
5105                                                 TLI, DAG))
5106         return FMinMax;
5107     }
5108
5109     if ((!LegalOperations &&
5110          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5111         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5112       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5113                          N0.getOperand(0), N0.getOperand(1),
5114                          N1, N2, N0.getOperand(2));
5115     return SimplifySelect(SDLoc(N), N0, N1, N2);
5116   }
5117
5118   return SDValue();
5119 }
5120
5121 static
5122 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5123   SDLoc DL(N);
5124   EVT LoVT, HiVT;
5125   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5126
5127   // Split the inputs.
5128   SDValue Lo, Hi, LL, LH, RL, RH;
5129   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5130   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5131
5132   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5133   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5134
5135   return std::make_pair(Lo, Hi);
5136 }
5137
5138 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5139 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5140 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5141   SDLoc dl(N);
5142   SDValue Cond = N->getOperand(0);
5143   SDValue LHS = N->getOperand(1);
5144   SDValue RHS = N->getOperand(2);
5145   EVT VT = N->getValueType(0);
5146   int NumElems = VT.getVectorNumElements();
5147   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5148          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5149          Cond.getOpcode() == ISD::BUILD_VECTOR);
5150
5151   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5152   // binary ones here.
5153   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5154     return SDValue();
5155
5156   // We're sure we have an even number of elements due to the
5157   // concat_vectors we have as arguments to vselect.
5158   // Skip BV elements until we find one that's not an UNDEF
5159   // After we find an UNDEF element, keep looping until we get to half the
5160   // length of the BV and see if all the non-undef nodes are the same.
5161   ConstantSDNode *BottomHalf = nullptr;
5162   for (int i = 0; i < NumElems / 2; ++i) {
5163     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5164       continue;
5165
5166     if (BottomHalf == nullptr)
5167       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5168     else if (Cond->getOperand(i).getNode() != BottomHalf)
5169       return SDValue();
5170   }
5171
5172   // Do the same for the second half of the BuildVector
5173   ConstantSDNode *TopHalf = nullptr;
5174   for (int i = NumElems / 2; i < NumElems; ++i) {
5175     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5176       continue;
5177
5178     if (TopHalf == nullptr)
5179       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5180     else if (Cond->getOperand(i).getNode() != TopHalf)
5181       return SDValue();
5182   }
5183
5184   assert(TopHalf && BottomHalf &&
5185          "One half of the selector was all UNDEFs and the other was all the "
5186          "same value. This should have been addressed before this function.");
5187   return DAG.getNode(
5188       ISD::CONCAT_VECTORS, dl, VT,
5189       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5190       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5191 }
5192
5193 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5194
5195   if (Level >= AfterLegalizeTypes)
5196     return SDValue();
5197
5198   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5199   SDValue Mask = MSC->getMask();
5200   SDValue Data  = MSC->getValue();
5201   SDLoc DL(N);
5202
5203   // If the MSCATTER data type requires splitting and the mask is provided by a
5204   // SETCC, then split both nodes and its operands before legalization. This
5205   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5206   // and enables future optimizations (e.g. min/max pattern matching on X86).
5207   if (Mask.getOpcode() != ISD::SETCC)
5208     return SDValue();
5209
5210   // Check if any splitting is required.
5211   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5212       TargetLowering::TypeSplitVector)
5213     return SDValue();
5214   SDValue MaskLo, MaskHi, Lo, Hi;
5215   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5216
5217   EVT LoVT, HiVT;
5218   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5219
5220   SDValue Chain = MSC->getChain();
5221
5222   EVT MemoryVT = MSC->getMemoryVT();
5223   unsigned Alignment = MSC->getOriginalAlignment();
5224
5225   EVT LoMemVT, HiMemVT;
5226   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5227
5228   SDValue DataLo, DataHi;
5229   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5230
5231   SDValue BasePtr = MSC->getBasePtr();
5232   SDValue IndexLo, IndexHi;
5233   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5234
5235   MachineMemOperand *MMO = DAG.getMachineFunction().
5236     getMachineMemOperand(MSC->getPointerInfo(),
5237                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5238                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5239
5240   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5241   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5242                             DL, OpsLo, MMO);
5243
5244   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5245   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5246                             DL, OpsHi, MMO);
5247
5248   AddToWorklist(Lo.getNode());
5249   AddToWorklist(Hi.getNode());
5250
5251   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5252 }
5253
5254 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5255
5256   if (Level >= AfterLegalizeTypes)
5257     return SDValue();
5258
5259   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5260   SDValue Mask = MST->getMask();
5261   SDValue Data  = MST->getValue();
5262   SDLoc DL(N);
5263
5264   // If the MSTORE data type requires splitting and the mask is provided by a
5265   // SETCC, then split both nodes and its operands before legalization. This
5266   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5267   // and enables future optimizations (e.g. min/max pattern matching on X86).
5268   if (Mask.getOpcode() == ISD::SETCC) {
5269
5270     // Check if any splitting is required.
5271     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5272         TargetLowering::TypeSplitVector)
5273       return SDValue();
5274
5275     SDValue MaskLo, MaskHi, Lo, Hi;
5276     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5277
5278     EVT LoVT, HiVT;
5279     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5280
5281     SDValue Chain = MST->getChain();
5282     SDValue Ptr   = MST->getBasePtr();
5283
5284     EVT MemoryVT = MST->getMemoryVT();
5285     unsigned Alignment = MST->getOriginalAlignment();
5286
5287     // if Alignment is equal to the vector size,
5288     // take the half of it for the second part
5289     unsigned SecondHalfAlignment =
5290       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5291          Alignment/2 : Alignment;
5292
5293     EVT LoMemVT, HiMemVT;
5294     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5295
5296     SDValue DataLo, DataHi;
5297     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5298
5299     MachineMemOperand *MMO = DAG.getMachineFunction().
5300       getMachineMemOperand(MST->getPointerInfo(),
5301                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5302                            Alignment, MST->getAAInfo(), MST->getRanges());
5303
5304     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5305                             MST->isTruncatingStore());
5306
5307     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5308     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5309                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5310
5311     MMO = DAG.getMachineFunction().
5312       getMachineMemOperand(MST->getPointerInfo(),
5313                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5314                            SecondHalfAlignment, MST->getAAInfo(),
5315                            MST->getRanges());
5316
5317     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5318                             MST->isTruncatingStore());
5319
5320     AddToWorklist(Lo.getNode());
5321     AddToWorklist(Hi.getNode());
5322
5323     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5324   }
5325   return SDValue();
5326 }
5327
5328 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5329
5330   if (Level >= AfterLegalizeTypes)
5331     return SDValue();
5332
5333   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5334   SDValue Mask = MGT->getMask();
5335   SDLoc DL(N);
5336
5337   // If the MGATHER result requires splitting and the mask is provided by a
5338   // SETCC, then split both nodes and its operands before legalization. This
5339   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5340   // and enables future optimizations (e.g. min/max pattern matching on X86).
5341
5342   if (Mask.getOpcode() != ISD::SETCC)
5343     return SDValue();
5344
5345   EVT VT = N->getValueType(0);
5346
5347   // Check if any splitting is required.
5348   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5349       TargetLowering::TypeSplitVector)
5350     return SDValue();
5351
5352   SDValue MaskLo, MaskHi, Lo, Hi;
5353   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5354
5355   SDValue Src0 = MGT->getValue();
5356   SDValue Src0Lo, Src0Hi;
5357   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5358
5359   EVT LoVT, HiVT;
5360   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5361
5362   SDValue Chain = MGT->getChain();
5363   EVT MemoryVT = MGT->getMemoryVT();
5364   unsigned Alignment = MGT->getOriginalAlignment();
5365
5366   EVT LoMemVT, HiMemVT;
5367   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5368
5369   SDValue BasePtr = MGT->getBasePtr();
5370   SDValue Index = MGT->getIndex();
5371   SDValue IndexLo, IndexHi;
5372   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5373
5374   MachineMemOperand *MMO = DAG.getMachineFunction().
5375     getMachineMemOperand(MGT->getPointerInfo(),
5376                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5377                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5378
5379   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5380   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5381                             MMO);
5382
5383   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5384   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5385                             MMO);
5386
5387   AddToWorklist(Lo.getNode());
5388   AddToWorklist(Hi.getNode());
5389
5390   // Build a factor node to remember that this load is independent of the
5391   // other one.
5392   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5393                       Hi.getValue(1));
5394
5395   // Legalized the chain result - switch anything that used the old chain to
5396   // use the new one.
5397   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5398
5399   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5400
5401   SDValue RetOps[] = { GatherRes, Chain };
5402   return DAG.getMergeValues(RetOps, DL);
5403 }
5404
5405 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5406
5407   if (Level >= AfterLegalizeTypes)
5408     return SDValue();
5409
5410   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5411   SDValue Mask = MLD->getMask();
5412   SDLoc DL(N);
5413
5414   // If the MLOAD result requires splitting and the mask is provided by a
5415   // SETCC, then split both nodes and its operands before legalization. This
5416   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5417   // and enables future optimizations (e.g. min/max pattern matching on X86).
5418
5419   if (Mask.getOpcode() == ISD::SETCC) {
5420     EVT VT = N->getValueType(0);
5421
5422     // Check if any splitting is required.
5423     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5424         TargetLowering::TypeSplitVector)
5425       return SDValue();
5426
5427     SDValue MaskLo, MaskHi, Lo, Hi;
5428     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5429
5430     SDValue Src0 = MLD->getSrc0();
5431     SDValue Src0Lo, Src0Hi;
5432     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5433
5434     EVT LoVT, HiVT;
5435     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5436
5437     SDValue Chain = MLD->getChain();
5438     SDValue Ptr   = MLD->getBasePtr();
5439     EVT MemoryVT = MLD->getMemoryVT();
5440     unsigned Alignment = MLD->getOriginalAlignment();
5441
5442     // if Alignment is equal to the vector size,
5443     // take the half of it for the second part
5444     unsigned SecondHalfAlignment =
5445       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5446          Alignment/2 : Alignment;
5447
5448     EVT LoMemVT, HiMemVT;
5449     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5450
5451     MachineMemOperand *MMO = DAG.getMachineFunction().
5452     getMachineMemOperand(MLD->getPointerInfo(),
5453                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5454                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5455
5456     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5457                            ISD::NON_EXTLOAD);
5458
5459     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5460     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5461                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5462
5463     MMO = DAG.getMachineFunction().
5464     getMachineMemOperand(MLD->getPointerInfo(),
5465                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5466                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5467
5468     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5469                            ISD::NON_EXTLOAD);
5470
5471     AddToWorklist(Lo.getNode());
5472     AddToWorklist(Hi.getNode());
5473
5474     // Build a factor node to remember that this load is independent of the
5475     // other one.
5476     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5477                         Hi.getValue(1));
5478
5479     // Legalized the chain result - switch anything that used the old chain to
5480     // use the new one.
5481     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5482
5483     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5484
5485     SDValue RetOps[] = { LoadRes, Chain };
5486     return DAG.getMergeValues(RetOps, DL);
5487   }
5488   return SDValue();
5489 }
5490
5491 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5492   SDValue N0 = N->getOperand(0);
5493   SDValue N1 = N->getOperand(1);
5494   SDValue N2 = N->getOperand(2);
5495   SDLoc DL(N);
5496
5497   // Canonicalize integer abs.
5498   // vselect (setg[te] X,  0),  X, -X ->
5499   // vselect (setgt    X, -1),  X, -X ->
5500   // vselect (setl[te] X,  0), -X,  X ->
5501   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5502   if (N0.getOpcode() == ISD::SETCC) {
5503     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5504     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5505     bool isAbs = false;
5506     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5507
5508     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5509          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5510         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5511       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5512     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5513              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5514       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5515
5516     if (isAbs) {
5517       EVT VT = LHS.getValueType();
5518       SDValue Shift = DAG.getNode(
5519           ISD::SRA, DL, VT, LHS,
5520           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5521       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5522       AddToWorklist(Shift.getNode());
5523       AddToWorklist(Add.getNode());
5524       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5525     }
5526   }
5527
5528   if (SimplifySelectOps(N, N1, N2))
5529     return SDValue(N, 0);  // Don't revisit N.
5530
5531   // If the VSELECT result requires splitting and the mask is provided by a
5532   // SETCC, then split both nodes and its operands before legalization. This
5533   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5534   // and enables future optimizations (e.g. min/max pattern matching on X86).
5535   if (N0.getOpcode() == ISD::SETCC) {
5536     EVT VT = N->getValueType(0);
5537
5538     // Check if any splitting is required.
5539     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5540         TargetLowering::TypeSplitVector)
5541       return SDValue();
5542
5543     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5544     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5545     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5546     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5547
5548     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5549     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5550
5551     // Add the new VSELECT nodes to the work list in case they need to be split
5552     // again.
5553     AddToWorklist(Lo.getNode());
5554     AddToWorklist(Hi.getNode());
5555
5556     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5557   }
5558
5559   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5560   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5561     return N1;
5562   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5563   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5564     return N2;
5565
5566   // The ConvertSelectToConcatVector function is assuming both the above
5567   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5568   // and addressed.
5569   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5570       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5571       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5572     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5573       return CV;
5574   }
5575
5576   return SDValue();
5577 }
5578
5579 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5580   SDValue N0 = N->getOperand(0);
5581   SDValue N1 = N->getOperand(1);
5582   SDValue N2 = N->getOperand(2);
5583   SDValue N3 = N->getOperand(3);
5584   SDValue N4 = N->getOperand(4);
5585   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5586
5587   // fold select_cc lhs, rhs, x, x, cc -> x
5588   if (N2 == N3)
5589     return N2;
5590
5591   // Determine if the condition we're dealing with is constant
5592   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5593                               N0, N1, CC, SDLoc(N), false);
5594   if (SCC.getNode()) {
5595     AddToWorklist(SCC.getNode());
5596
5597     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5598       if (!SCCC->isNullValue())
5599         return N2;    // cond always true -> true val
5600       else
5601         return N3;    // cond always false -> false val
5602     } else if (SCC->getOpcode() == ISD::UNDEF) {
5603       // When the condition is UNDEF, just return the first operand. This is
5604       // coherent the DAG creation, no setcc node is created in this case
5605       return N2;
5606     } else if (SCC.getOpcode() == ISD::SETCC) {
5607       // Fold to a simpler select_cc
5608       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5609                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5610                          SCC.getOperand(2));
5611     }
5612   }
5613
5614   // If we can fold this based on the true/false value, do so.
5615   if (SimplifySelectOps(N, N2, N3))
5616     return SDValue(N, 0);  // Don't revisit N.
5617
5618   // fold select_cc into other things, such as min/max/abs
5619   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5620 }
5621
5622 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5623   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5624                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5625                        SDLoc(N));
5626 }
5627
5628 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5629 /// a build_vector of constants.
5630 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5631 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5632 /// Vector extends are not folded if operations are legal; this is to
5633 /// avoid introducing illegal build_vector dag nodes.
5634 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5635                                          SelectionDAG &DAG, bool LegalTypes,
5636                                          bool LegalOperations) {
5637   unsigned Opcode = N->getOpcode();
5638   SDValue N0 = N->getOperand(0);
5639   EVT VT = N->getValueType(0);
5640
5641   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5642          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5643          && "Expected EXTEND dag node in input!");
5644
5645   // fold (sext c1) -> c1
5646   // fold (zext c1) -> c1
5647   // fold (aext c1) -> c1
5648   if (isa<ConstantSDNode>(N0))
5649     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5650
5651   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5652   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5653   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5654   EVT SVT = VT.getScalarType();
5655   if (!(VT.isVector() &&
5656       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5657       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5658     return nullptr;
5659
5660   // We can fold this node into a build_vector.
5661   unsigned VTBits = SVT.getSizeInBits();
5662   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5663   SmallVector<SDValue, 8> Elts;
5664   unsigned NumElts = VT.getVectorNumElements();
5665   SDLoc DL(N);
5666
5667   for (unsigned i=0; i != NumElts; ++i) {
5668     SDValue Op = N0->getOperand(i);
5669     if (Op->getOpcode() == ISD::UNDEF) {
5670       Elts.push_back(DAG.getUNDEF(SVT));
5671       continue;
5672     }
5673
5674     SDLoc DL(Op);
5675     // Get the constant value and if needed trunc it to the size of the type.
5676     // Nodes like build_vector might have constants wider than the scalar type.
5677     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5678     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5679       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5680     else
5681       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5682   }
5683
5684   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5685 }
5686
5687 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5688 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5689 // transformation. Returns true if extension are possible and the above
5690 // mentioned transformation is profitable.
5691 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5692                                     unsigned ExtOpc,
5693                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5694                                     const TargetLowering &TLI) {
5695   bool HasCopyToRegUses = false;
5696   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5697   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5698                             UE = N0.getNode()->use_end();
5699        UI != UE; ++UI) {
5700     SDNode *User = *UI;
5701     if (User == N)
5702       continue;
5703     if (UI.getUse().getResNo() != N0.getResNo())
5704       continue;
5705     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5706     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5707       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5708       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5709         // Sign bits will be lost after a zext.
5710         return false;
5711       bool Add = false;
5712       for (unsigned i = 0; i != 2; ++i) {
5713         SDValue UseOp = User->getOperand(i);
5714         if (UseOp == N0)
5715           continue;
5716         if (!isa<ConstantSDNode>(UseOp))
5717           return false;
5718         Add = true;
5719       }
5720       if (Add)
5721         ExtendNodes.push_back(User);
5722       continue;
5723     }
5724     // If truncates aren't free and there are users we can't
5725     // extend, it isn't worthwhile.
5726     if (!isTruncFree)
5727       return false;
5728     // Remember if this value is live-out.
5729     if (User->getOpcode() == ISD::CopyToReg)
5730       HasCopyToRegUses = true;
5731   }
5732
5733   if (HasCopyToRegUses) {
5734     bool BothLiveOut = false;
5735     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5736          UI != UE; ++UI) {
5737       SDUse &Use = UI.getUse();
5738       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5739         BothLiveOut = true;
5740         break;
5741       }
5742     }
5743     if (BothLiveOut)
5744       // Both unextended and extended values are live out. There had better be
5745       // a good reason for the transformation.
5746       return ExtendNodes.size();
5747   }
5748   return true;
5749 }
5750
5751 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5752                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5753                                   ISD::NodeType ExtType) {
5754   // Extend SetCC uses if necessary.
5755   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5756     SDNode *SetCC = SetCCs[i];
5757     SmallVector<SDValue, 4> Ops;
5758
5759     for (unsigned j = 0; j != 2; ++j) {
5760       SDValue SOp = SetCC->getOperand(j);
5761       if (SOp == Trunc)
5762         Ops.push_back(ExtLoad);
5763       else
5764         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5765     }
5766
5767     Ops.push_back(SetCC->getOperand(2));
5768     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5769   }
5770 }
5771
5772 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5773 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5774   SDValue N0 = N->getOperand(0);
5775   EVT DstVT = N->getValueType(0);
5776   EVT SrcVT = N0.getValueType();
5777
5778   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5779           N->getOpcode() == ISD::ZERO_EXTEND) &&
5780          "Unexpected node type (not an extend)!");
5781
5782   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5783   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5784   //   (v8i32 (sext (v8i16 (load x))))
5785   // into:
5786   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5787   //                          (v4i32 (sextload (x + 16)))))
5788   // Where uses of the original load, i.e.:
5789   //   (v8i16 (load x))
5790   // are replaced with:
5791   //   (v8i16 (truncate
5792   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5793   //                            (v4i32 (sextload (x + 16)))))))
5794   //
5795   // This combine is only applicable to illegal, but splittable, vectors.
5796   // All legal types, and illegal non-vector types, are handled elsewhere.
5797   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5798   //
5799   if (N0->getOpcode() != ISD::LOAD)
5800     return SDValue();
5801
5802   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5803
5804   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5805       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5806       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5807     return SDValue();
5808
5809   SmallVector<SDNode *, 4> SetCCs;
5810   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5811     return SDValue();
5812
5813   ISD::LoadExtType ExtType =
5814       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5815
5816   // Try to split the vector types to get down to legal types.
5817   EVT SplitSrcVT = SrcVT;
5818   EVT SplitDstVT = DstVT;
5819   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5820          SplitSrcVT.getVectorNumElements() > 1) {
5821     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5822     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5823   }
5824
5825   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5826     return SDValue();
5827
5828   SDLoc DL(N);
5829   const unsigned NumSplits =
5830       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5831   const unsigned Stride = SplitSrcVT.getStoreSize();
5832   SmallVector<SDValue, 4> Loads;
5833   SmallVector<SDValue, 4> Chains;
5834
5835   SDValue BasePtr = LN0->getBasePtr();
5836   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5837     const unsigned Offset = Idx * Stride;
5838     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5839
5840     SDValue SplitLoad = DAG.getExtLoad(
5841         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5842         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5843         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5844         Align, LN0->getAAInfo());
5845
5846     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5847                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5848
5849     Loads.push_back(SplitLoad.getValue(0));
5850     Chains.push_back(SplitLoad.getValue(1));
5851   }
5852
5853   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5854   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5855
5856   CombineTo(N, NewValue);
5857
5858   // Replace uses of the original load (before extension)
5859   // with a truncate of the concatenated sextloaded vectors.
5860   SDValue Trunc =
5861       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5862   CombineTo(N0.getNode(), Trunc, NewChain);
5863   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5864                   (ISD::NodeType)N->getOpcode());
5865   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5866 }
5867
5868 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5869   SDValue N0 = N->getOperand(0);
5870   EVT VT = N->getValueType(0);
5871
5872   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5873                                               LegalOperations))
5874     return SDValue(Res, 0);
5875
5876   // fold (sext (sext x)) -> (sext x)
5877   // fold (sext (aext x)) -> (sext x)
5878   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5879     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5880                        N0.getOperand(0));
5881
5882   if (N0.getOpcode() == ISD::TRUNCATE) {
5883     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5884     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5885     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5886       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5887       if (NarrowLoad.getNode() != N0.getNode()) {
5888         CombineTo(N0.getNode(), NarrowLoad);
5889         // CombineTo deleted the truncate, if needed, but not what's under it.
5890         AddToWorklist(oye);
5891       }
5892       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5893     }
5894
5895     // See if the value being truncated is already sign extended.  If so, just
5896     // eliminate the trunc/sext pair.
5897     SDValue Op = N0.getOperand(0);
5898     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5899     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5900     unsigned DestBits = VT.getScalarType().getSizeInBits();
5901     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5902
5903     if (OpBits == DestBits) {
5904       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5905       // bits, it is already ready.
5906       if (NumSignBits > DestBits-MidBits)
5907         return Op;
5908     } else if (OpBits < DestBits) {
5909       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5910       // bits, just sext from i32.
5911       if (NumSignBits > OpBits-MidBits)
5912         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5913     } else {
5914       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5915       // bits, just truncate to i32.
5916       if (NumSignBits > OpBits-MidBits)
5917         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5918     }
5919
5920     // fold (sext (truncate x)) -> (sextinreg x).
5921     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5922                                                  N0.getValueType())) {
5923       if (OpBits < DestBits)
5924         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5925       else if (OpBits > DestBits)
5926         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5927       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5928                          DAG.getValueType(N0.getValueType()));
5929     }
5930   }
5931
5932   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5933   // Only generate vector extloads when 1) they're legal, and 2) they are
5934   // deemed desirable by the target.
5935   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5936       ((!LegalOperations && !VT.isVector() &&
5937         !cast<LoadSDNode>(N0)->isVolatile()) ||
5938        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5939     bool DoXform = true;
5940     SmallVector<SDNode*, 4> SetCCs;
5941     if (!N0.hasOneUse())
5942       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5943     if (VT.isVector())
5944       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5945     if (DoXform) {
5946       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5947       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5948                                        LN0->getChain(),
5949                                        LN0->getBasePtr(), N0.getValueType(),
5950                                        LN0->getMemOperand());
5951       CombineTo(N, ExtLoad);
5952       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5953                                   N0.getValueType(), ExtLoad);
5954       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5955       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5956                       ISD::SIGN_EXTEND);
5957       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5958     }
5959   }
5960
5961   // fold (sext (load x)) to multiple smaller sextloads.
5962   // Only on illegal but splittable vectors.
5963   if (SDValue ExtLoad = CombineExtLoad(N))
5964     return ExtLoad;
5965
5966   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5967   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5968   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5969       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5970     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5971     EVT MemVT = LN0->getMemoryVT();
5972     if ((!LegalOperations && !LN0->isVolatile()) ||
5973         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5974       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5975                                        LN0->getChain(),
5976                                        LN0->getBasePtr(), MemVT,
5977                                        LN0->getMemOperand());
5978       CombineTo(N, ExtLoad);
5979       CombineTo(N0.getNode(),
5980                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5981                             N0.getValueType(), ExtLoad),
5982                 ExtLoad.getValue(1));
5983       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5984     }
5985   }
5986
5987   // fold (sext (and/or/xor (load x), cst)) ->
5988   //      (and/or/xor (sextload x), (sext cst))
5989   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5990        N0.getOpcode() == ISD::XOR) &&
5991       isa<LoadSDNode>(N0.getOperand(0)) &&
5992       N0.getOperand(1).getOpcode() == ISD::Constant &&
5993       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5994       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5995     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5996     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5997       bool DoXform = true;
5998       SmallVector<SDNode*, 4> SetCCs;
5999       if (!N0.hasOneUse())
6000         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6001                                           SetCCs, TLI);
6002       if (DoXform) {
6003         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6004                                          LN0->getChain(), LN0->getBasePtr(),
6005                                          LN0->getMemoryVT(),
6006                                          LN0->getMemOperand());
6007         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6008         Mask = Mask.sext(VT.getSizeInBits());
6009         SDLoc DL(N);
6010         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6011                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6012         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6013                                     SDLoc(N0.getOperand(0)),
6014                                     N0.getOperand(0).getValueType(), ExtLoad);
6015         CombineTo(N, And);
6016         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6017         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6018                         ISD::SIGN_EXTEND);
6019         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6020       }
6021     }
6022   }
6023
6024   if (N0.getOpcode() == ISD::SETCC) {
6025     EVT N0VT = N0.getOperand(0).getValueType();
6026     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6027     // Only do this before legalize for now.
6028     if (VT.isVector() && !LegalOperations &&
6029         TLI.getBooleanContents(N0VT) ==
6030             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6031       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6032       // of the same size as the compared operands. Only optimize sext(setcc())
6033       // if this is the case.
6034       EVT SVT = getSetCCResultType(N0VT);
6035
6036       // We know that the # elements of the results is the same as the
6037       // # elements of the compare (and the # elements of the compare result
6038       // for that matter).  Check to see that they are the same size.  If so,
6039       // we know that the element size of the sext'd result matches the
6040       // element size of the compare operands.
6041       if (VT.getSizeInBits() == SVT.getSizeInBits())
6042         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6043                              N0.getOperand(1),
6044                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6045
6046       // If the desired elements are smaller or larger than the source
6047       // elements we can use a matching integer vector type and then
6048       // truncate/sign extend
6049       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6050       if (SVT == MatchingVectorType) {
6051         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6052                                N0.getOperand(0), N0.getOperand(1),
6053                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6054         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6055       }
6056     }
6057
6058     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6059     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6060     SDLoc DL(N);
6061     SDValue NegOne =
6062       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6063     SDValue SCC =
6064       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6065                        NegOne, DAG.getConstant(0, DL, VT),
6066                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6067     if (SCC.getNode()) return SCC;
6068
6069     if (!VT.isVector()) {
6070       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6071       if (!LegalOperations ||
6072           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6073         SDLoc DL(N);
6074         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6075         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6076                                      N0.getOperand(0), N0.getOperand(1), CC);
6077         return DAG.getSelect(DL, VT, SetCC,
6078                              NegOne, DAG.getConstant(0, DL, VT));
6079       }
6080     }
6081   }
6082
6083   // fold (sext x) -> (zext x) if the sign bit is known zero.
6084   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6085       DAG.SignBitIsZero(N0))
6086     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6087
6088   return SDValue();
6089 }
6090
6091 // isTruncateOf - If N is a truncate of some other value, return true, record
6092 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6093 // This function computes KnownZero to avoid a duplicated call to
6094 // computeKnownBits in the caller.
6095 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6096                          APInt &KnownZero) {
6097   APInt KnownOne;
6098   if (N->getOpcode() == ISD::TRUNCATE) {
6099     Op = N->getOperand(0);
6100     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6101     return true;
6102   }
6103
6104   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6105       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6106     return false;
6107
6108   SDValue Op0 = N->getOperand(0);
6109   SDValue Op1 = N->getOperand(1);
6110   assert(Op0.getValueType() == Op1.getValueType());
6111
6112   if (isNullConstant(Op0))
6113     Op = Op1;
6114   else if (isNullConstant(Op1))
6115     Op = Op0;
6116   else
6117     return false;
6118
6119   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6120
6121   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6122     return false;
6123
6124   return true;
6125 }
6126
6127 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6128   SDValue N0 = N->getOperand(0);
6129   EVT VT = N->getValueType(0);
6130
6131   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6132                                               LegalOperations))
6133     return SDValue(Res, 0);
6134
6135   // fold (zext (zext x)) -> (zext x)
6136   // fold (zext (aext x)) -> (zext x)
6137   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6138     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6139                        N0.getOperand(0));
6140
6141   // fold (zext (truncate x)) -> (zext x) or
6142   //      (zext (truncate x)) -> (truncate x)
6143   // This is valid when the truncated bits of x are already zero.
6144   // FIXME: We should extend this to work for vectors too.
6145   SDValue Op;
6146   APInt KnownZero;
6147   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6148     APInt TruncatedBits =
6149       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6150       APInt(Op.getValueSizeInBits(), 0) :
6151       APInt::getBitsSet(Op.getValueSizeInBits(),
6152                         N0.getValueSizeInBits(),
6153                         std::min(Op.getValueSizeInBits(),
6154                                  VT.getSizeInBits()));
6155     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6156       if (VT.bitsGT(Op.getValueType()))
6157         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6158       if (VT.bitsLT(Op.getValueType()))
6159         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6160
6161       return Op;
6162     }
6163   }
6164
6165   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6166   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6167   if (N0.getOpcode() == ISD::TRUNCATE) {
6168     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6169       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6170       if (NarrowLoad.getNode() != N0.getNode()) {
6171         CombineTo(N0.getNode(), NarrowLoad);
6172         // CombineTo deleted the truncate, if needed, but not what's under it.
6173         AddToWorklist(oye);
6174       }
6175       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6176     }
6177   }
6178
6179   // fold (zext (truncate x)) -> (and x, mask)
6180   if (N0.getOpcode() == ISD::TRUNCATE) {
6181     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6182     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6183     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6184       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6185       if (NarrowLoad.getNode() != N0.getNode()) {
6186         CombineTo(N0.getNode(), NarrowLoad);
6187         // CombineTo deleted the truncate, if needed, but not what's under it.
6188         AddToWorklist(oye);
6189       }
6190       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6191     }
6192
6193     EVT SrcVT = N0.getOperand(0).getValueType();
6194     EVT MinVT = N0.getValueType();
6195
6196     // Try to mask before the extension to avoid having to generate a larger mask,
6197     // possibly over several sub-vectors.
6198     if (SrcVT.bitsLT(VT)) {
6199       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6200                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6201         SDValue Op = N0.getOperand(0);
6202         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6203         AddToWorklist(Op.getNode());
6204         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6205       }
6206     }
6207
6208     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6209       SDValue Op = N0.getOperand(0);
6210       if (SrcVT.bitsLT(VT)) {
6211         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6212         AddToWorklist(Op.getNode());
6213       } else if (SrcVT.bitsGT(VT)) {
6214         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6215         AddToWorklist(Op.getNode());
6216       }
6217       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6218     }
6219   }
6220
6221   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6222   // if either of the casts is not free.
6223   if (N0.getOpcode() == ISD::AND &&
6224       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6225       N0.getOperand(1).getOpcode() == ISD::Constant &&
6226       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6227                            N0.getValueType()) ||
6228        !TLI.isZExtFree(N0.getValueType(), VT))) {
6229     SDValue X = N0.getOperand(0).getOperand(0);
6230     if (X.getValueType().bitsLT(VT)) {
6231       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6232     } else if (X.getValueType().bitsGT(VT)) {
6233       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6234     }
6235     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6236     Mask = Mask.zext(VT.getSizeInBits());
6237     SDLoc DL(N);
6238     return DAG.getNode(ISD::AND, DL, VT,
6239                        X, DAG.getConstant(Mask, DL, VT));
6240   }
6241
6242   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6243   // Only generate vector extloads when 1) they're legal, and 2) they are
6244   // deemed desirable by the target.
6245   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6246       ((!LegalOperations && !VT.isVector() &&
6247         !cast<LoadSDNode>(N0)->isVolatile()) ||
6248        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6249     bool DoXform = true;
6250     SmallVector<SDNode*, 4> SetCCs;
6251     if (!N0.hasOneUse())
6252       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6253     if (VT.isVector())
6254       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6255     if (DoXform) {
6256       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6257       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6258                                        LN0->getChain(),
6259                                        LN0->getBasePtr(), N0.getValueType(),
6260                                        LN0->getMemOperand());
6261       CombineTo(N, ExtLoad);
6262       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6263                                   N0.getValueType(), ExtLoad);
6264       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6265
6266       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6267                       ISD::ZERO_EXTEND);
6268       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6269     }
6270   }
6271
6272   // fold (zext (load x)) to multiple smaller zextloads.
6273   // Only on illegal but splittable vectors.
6274   if (SDValue ExtLoad = CombineExtLoad(N))
6275     return ExtLoad;
6276
6277   // fold (zext (and/or/xor (load x), cst)) ->
6278   //      (and/or/xor (zextload x), (zext cst))
6279   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6280        N0.getOpcode() == ISD::XOR) &&
6281       isa<LoadSDNode>(N0.getOperand(0)) &&
6282       N0.getOperand(1).getOpcode() == ISD::Constant &&
6283       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6284       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6285     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6286     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6287       bool DoXform = true;
6288       SmallVector<SDNode*, 4> SetCCs;
6289       if (!N0.hasOneUse())
6290         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6291                                           SetCCs, TLI);
6292       if (DoXform) {
6293         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6294                                          LN0->getChain(), LN0->getBasePtr(),
6295                                          LN0->getMemoryVT(),
6296                                          LN0->getMemOperand());
6297         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6298         Mask = Mask.zext(VT.getSizeInBits());
6299         SDLoc DL(N);
6300         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6301                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6302         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6303                                     SDLoc(N0.getOperand(0)),
6304                                     N0.getOperand(0).getValueType(), ExtLoad);
6305         CombineTo(N, And);
6306         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6307         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6308                         ISD::ZERO_EXTEND);
6309         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6310       }
6311     }
6312   }
6313
6314   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6315   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6316   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6317       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6318     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6319     EVT MemVT = LN0->getMemoryVT();
6320     if ((!LegalOperations && !LN0->isVolatile()) ||
6321         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6322       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6323                                        LN0->getChain(),
6324                                        LN0->getBasePtr(), MemVT,
6325                                        LN0->getMemOperand());
6326       CombineTo(N, ExtLoad);
6327       CombineTo(N0.getNode(),
6328                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6329                             ExtLoad),
6330                 ExtLoad.getValue(1));
6331       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6332     }
6333   }
6334
6335   if (N0.getOpcode() == ISD::SETCC) {
6336     if (!LegalOperations && VT.isVector() &&
6337         N0.getValueType().getVectorElementType() == MVT::i1) {
6338       EVT N0VT = N0.getOperand(0).getValueType();
6339       if (getSetCCResultType(N0VT) == N0.getValueType())
6340         return SDValue();
6341
6342       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6343       // Only do this before legalize for now.
6344       EVT EltVT = VT.getVectorElementType();
6345       SDLoc DL(N);
6346       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6347                                     DAG.getConstant(1, DL, EltVT));
6348       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6349         // We know that the # elements of the results is the same as the
6350         // # elements of the compare (and the # elements of the compare result
6351         // for that matter).  Check to see that they are the same size.  If so,
6352         // we know that the element size of the sext'd result matches the
6353         // element size of the compare operands.
6354         return DAG.getNode(ISD::AND, DL, VT,
6355                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6356                                          N0.getOperand(1),
6357                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6358                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6359                                        OneOps));
6360
6361       // If the desired elements are smaller or larger than the source
6362       // elements we can use a matching integer vector type and then
6363       // truncate/sign extend
6364       EVT MatchingElementType =
6365         EVT::getIntegerVT(*DAG.getContext(),
6366                           N0VT.getScalarType().getSizeInBits());
6367       EVT MatchingVectorType =
6368         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6369                          N0VT.getVectorNumElements());
6370       SDValue VsetCC =
6371         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6372                       N0.getOperand(1),
6373                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6374       return DAG.getNode(ISD::AND, DL, VT,
6375                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6376                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6377     }
6378
6379     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6380     SDLoc DL(N);
6381     SDValue SCC =
6382       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6383                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6384                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6385     if (SCC.getNode()) return SCC;
6386   }
6387
6388   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6389   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6390       isa<ConstantSDNode>(N0.getOperand(1)) &&
6391       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6392       N0.hasOneUse()) {
6393     SDValue ShAmt = N0.getOperand(1);
6394     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6395     if (N0.getOpcode() == ISD::SHL) {
6396       SDValue InnerZExt = N0.getOperand(0);
6397       // If the original shl may be shifting out bits, do not perform this
6398       // transformation.
6399       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6400         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6401       if (ShAmtVal > KnownZeroBits)
6402         return SDValue();
6403     }
6404
6405     SDLoc DL(N);
6406
6407     // Ensure that the shift amount is wide enough for the shifted value.
6408     if (VT.getSizeInBits() >= 256)
6409       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6410
6411     return DAG.getNode(N0.getOpcode(), DL, VT,
6412                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6413                        ShAmt);
6414   }
6415
6416   return SDValue();
6417 }
6418
6419 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6420   SDValue N0 = N->getOperand(0);
6421   EVT VT = N->getValueType(0);
6422
6423   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6424                                               LegalOperations))
6425     return SDValue(Res, 0);
6426
6427   // fold (aext (aext x)) -> (aext x)
6428   // fold (aext (zext x)) -> (zext x)
6429   // fold (aext (sext x)) -> (sext x)
6430   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6431       N0.getOpcode() == ISD::ZERO_EXTEND ||
6432       N0.getOpcode() == ISD::SIGN_EXTEND)
6433     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6434
6435   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6436   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6437   if (N0.getOpcode() == ISD::TRUNCATE) {
6438     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6439       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6440       if (NarrowLoad.getNode() != N0.getNode()) {
6441         CombineTo(N0.getNode(), NarrowLoad);
6442         // CombineTo deleted the truncate, if needed, but not what's under it.
6443         AddToWorklist(oye);
6444       }
6445       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6446     }
6447   }
6448
6449   // fold (aext (truncate x))
6450   if (N0.getOpcode() == ISD::TRUNCATE) {
6451     SDValue TruncOp = N0.getOperand(0);
6452     if (TruncOp.getValueType() == VT)
6453       return TruncOp; // x iff x size == zext size.
6454     if (TruncOp.getValueType().bitsGT(VT))
6455       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6456     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6457   }
6458
6459   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6460   // if the trunc is not free.
6461   if (N0.getOpcode() == ISD::AND &&
6462       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6463       N0.getOperand(1).getOpcode() == ISD::Constant &&
6464       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6465                           N0.getValueType())) {
6466     SDValue X = N0.getOperand(0).getOperand(0);
6467     if (X.getValueType().bitsLT(VT)) {
6468       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6469     } else if (X.getValueType().bitsGT(VT)) {
6470       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6471     }
6472     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6473     Mask = Mask.zext(VT.getSizeInBits());
6474     SDLoc DL(N);
6475     return DAG.getNode(ISD::AND, DL, VT,
6476                        X, DAG.getConstant(Mask, DL, VT));
6477   }
6478
6479   // fold (aext (load x)) -> (aext (truncate (extload x)))
6480   // None of the supported targets knows how to perform load and any_ext
6481   // on vectors in one instruction.  We only perform this transformation on
6482   // scalars.
6483   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6484       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6485       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6486     bool DoXform = true;
6487     SmallVector<SDNode*, 4> SetCCs;
6488     if (!N0.hasOneUse())
6489       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6490     if (DoXform) {
6491       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6492       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6493                                        LN0->getChain(),
6494                                        LN0->getBasePtr(), N0.getValueType(),
6495                                        LN0->getMemOperand());
6496       CombineTo(N, ExtLoad);
6497       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6498                                   N0.getValueType(), ExtLoad);
6499       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6500       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6501                       ISD::ANY_EXTEND);
6502       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6503     }
6504   }
6505
6506   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6507   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6508   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6509   if (N0.getOpcode() == ISD::LOAD &&
6510       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6511       N0.hasOneUse()) {
6512     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6513     ISD::LoadExtType ExtType = LN0->getExtensionType();
6514     EVT MemVT = LN0->getMemoryVT();
6515     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6516       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6517                                        VT, LN0->getChain(), LN0->getBasePtr(),
6518                                        MemVT, LN0->getMemOperand());
6519       CombineTo(N, ExtLoad);
6520       CombineTo(N0.getNode(),
6521                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6522                             N0.getValueType(), ExtLoad),
6523                 ExtLoad.getValue(1));
6524       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6525     }
6526   }
6527
6528   if (N0.getOpcode() == ISD::SETCC) {
6529     // For vectors:
6530     // aext(setcc) -> vsetcc
6531     // aext(setcc) -> truncate(vsetcc)
6532     // aext(setcc) -> aext(vsetcc)
6533     // Only do this before legalize for now.
6534     if (VT.isVector() && !LegalOperations) {
6535       EVT N0VT = N0.getOperand(0).getValueType();
6536         // We know that the # elements of the results is the same as the
6537         // # elements of the compare (and the # elements of the compare result
6538         // for that matter).  Check to see that they are the same size.  If so,
6539         // we know that the element size of the sext'd result matches the
6540         // element size of the compare operands.
6541       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6542         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6543                              N0.getOperand(1),
6544                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6545       // If the desired elements are smaller or larger than the source
6546       // elements we can use a matching integer vector type and then
6547       // truncate/any extend
6548       else {
6549         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6550         SDValue VsetCC =
6551           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6552                         N0.getOperand(1),
6553                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6554         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6555       }
6556     }
6557
6558     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6559     SDLoc DL(N);
6560     SDValue SCC =
6561       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6562                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6563                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6564     if (SCC.getNode())
6565       return SCC;
6566   }
6567
6568   return SDValue();
6569 }
6570
6571 /// See if the specified operand can be simplified with the knowledge that only
6572 /// the bits specified by Mask are used.  If so, return the simpler operand,
6573 /// otherwise return a null SDValue.
6574 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6575   switch (V.getOpcode()) {
6576   default: break;
6577   case ISD::Constant: {
6578     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6579     assert(CV && "Const value should be ConstSDNode.");
6580     const APInt &CVal = CV->getAPIntValue();
6581     APInt NewVal = CVal & Mask;
6582     if (NewVal != CVal)
6583       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6584     break;
6585   }
6586   case ISD::OR:
6587   case ISD::XOR:
6588     // If the LHS or RHS don't contribute bits to the or, drop them.
6589     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6590       return V.getOperand(1);
6591     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6592       return V.getOperand(0);
6593     break;
6594   case ISD::SRL:
6595     // Only look at single-use SRLs.
6596     if (!V.getNode()->hasOneUse())
6597       break;
6598     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6599       // See if we can recursively simplify the LHS.
6600       unsigned Amt = RHSC->getZExtValue();
6601
6602       // Watch out for shift count overflow though.
6603       if (Amt >= Mask.getBitWidth()) break;
6604       APInt NewMask = Mask << Amt;
6605       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6606         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6607                            SimplifyLHS, V.getOperand(1));
6608     }
6609   }
6610   return SDValue();
6611 }
6612
6613 /// If the result of a wider load is shifted to right of N  bits and then
6614 /// truncated to a narrower type and where N is a multiple of number of bits of
6615 /// the narrower type, transform it to a narrower load from address + N / num of
6616 /// bits of new type. If the result is to be extended, also fold the extension
6617 /// to form a extending load.
6618 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6619   unsigned Opc = N->getOpcode();
6620
6621   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6622   SDValue N0 = N->getOperand(0);
6623   EVT VT = N->getValueType(0);
6624   EVT ExtVT = VT;
6625
6626   // This transformation isn't valid for vector loads.
6627   if (VT.isVector())
6628     return SDValue();
6629
6630   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6631   // extended to VT.
6632   if (Opc == ISD::SIGN_EXTEND_INREG) {
6633     ExtType = ISD::SEXTLOAD;
6634     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6635   } else if (Opc == ISD::SRL) {
6636     // Another special-case: SRL is basically zero-extending a narrower value.
6637     ExtType = ISD::ZEXTLOAD;
6638     N0 = SDValue(N, 0);
6639     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6640     if (!N01) return SDValue();
6641     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6642                               VT.getSizeInBits() - N01->getZExtValue());
6643   }
6644   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6645     return SDValue();
6646
6647   unsigned EVTBits = ExtVT.getSizeInBits();
6648
6649   // Do not generate loads of non-round integer types since these can
6650   // be expensive (and would be wrong if the type is not byte sized).
6651   if (!ExtVT.isRound())
6652     return SDValue();
6653
6654   unsigned ShAmt = 0;
6655   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6656     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6657       ShAmt = N01->getZExtValue();
6658       // Is the shift amount a multiple of size of VT?
6659       if ((ShAmt & (EVTBits-1)) == 0) {
6660         N0 = N0.getOperand(0);
6661         // Is the load width a multiple of size of VT?
6662         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6663           return SDValue();
6664       }
6665
6666       // At this point, we must have a load or else we can't do the transform.
6667       if (!isa<LoadSDNode>(N0)) return SDValue();
6668
6669       // Because a SRL must be assumed to *need* to zero-extend the high bits
6670       // (as opposed to anyext the high bits), we can't combine the zextload
6671       // lowering of SRL and an sextload.
6672       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6673         return SDValue();
6674
6675       // If the shift amount is larger than the input type then we're not
6676       // accessing any of the loaded bytes.  If the load was a zextload/extload
6677       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6678       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6679         return SDValue();
6680     }
6681   }
6682
6683   // If the load is shifted left (and the result isn't shifted back right),
6684   // we can fold the truncate through the shift.
6685   unsigned ShLeftAmt = 0;
6686   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6687       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6688     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6689       ShLeftAmt = N01->getZExtValue();
6690       N0 = N0.getOperand(0);
6691     }
6692   }
6693
6694   // If we haven't found a load, we can't narrow it.  Don't transform one with
6695   // multiple uses, this would require adding a new load.
6696   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6697     return SDValue();
6698
6699   // Don't change the width of a volatile load.
6700   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6701   if (LN0->isVolatile())
6702     return SDValue();
6703
6704   // Verify that we are actually reducing a load width here.
6705   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6706     return SDValue();
6707
6708   // For the transform to be legal, the load must produce only two values
6709   // (the value loaded and the chain).  Don't transform a pre-increment
6710   // load, for example, which produces an extra value.  Otherwise the
6711   // transformation is not equivalent, and the downstream logic to replace
6712   // uses gets things wrong.
6713   if (LN0->getNumValues() > 2)
6714     return SDValue();
6715
6716   // If the load that we're shrinking is an extload and we're not just
6717   // discarding the extension we can't simply shrink the load. Bail.
6718   // TODO: It would be possible to merge the extensions in some cases.
6719   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6720       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6721     return SDValue();
6722
6723   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6724     return SDValue();
6725
6726   EVT PtrType = N0.getOperand(1).getValueType();
6727
6728   if (PtrType == MVT::Untyped || PtrType.isExtended())
6729     // It's not possible to generate a constant of extended or untyped type.
6730     return SDValue();
6731
6732   // For big endian targets, we need to adjust the offset to the pointer to
6733   // load the correct bytes.
6734   if (DAG.getDataLayout().isBigEndian()) {
6735     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6736     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6737     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6738   }
6739
6740   uint64_t PtrOff = ShAmt / 8;
6741   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6742   SDLoc DL(LN0);
6743   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6744                                PtrType, LN0->getBasePtr(),
6745                                DAG.getConstant(PtrOff, DL, PtrType));
6746   AddToWorklist(NewPtr.getNode());
6747
6748   SDValue Load;
6749   if (ExtType == ISD::NON_EXTLOAD)
6750     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6751                         LN0->getPointerInfo().getWithOffset(PtrOff),
6752                         LN0->isVolatile(), LN0->isNonTemporal(),
6753                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6754   else
6755     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6756                           LN0->getPointerInfo().getWithOffset(PtrOff),
6757                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6758                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6759
6760   // Replace the old load's chain with the new load's chain.
6761   WorklistRemover DeadNodes(*this);
6762   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6763
6764   // Shift the result left, if we've swallowed a left shift.
6765   SDValue Result = Load;
6766   if (ShLeftAmt != 0) {
6767     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6768     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6769       ShImmTy = VT;
6770     // If the shift amount is as large as the result size (but, presumably,
6771     // no larger than the source) then the useful bits of the result are
6772     // zero; we can't simply return the shortened shift, because the result
6773     // of that operation is undefined.
6774     SDLoc DL(N0);
6775     if (ShLeftAmt >= VT.getSizeInBits())
6776       Result = DAG.getConstant(0, DL, VT);
6777     else
6778       Result = DAG.getNode(ISD::SHL, DL, VT,
6779                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6780   }
6781
6782   // Return the new loaded value.
6783   return Result;
6784 }
6785
6786 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6787   SDValue N0 = N->getOperand(0);
6788   SDValue N1 = N->getOperand(1);
6789   EVT VT = N->getValueType(0);
6790   EVT EVT = cast<VTSDNode>(N1)->getVT();
6791   unsigned VTBits = VT.getScalarType().getSizeInBits();
6792   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6793
6794   if (N0.isUndef())
6795     return DAG.getUNDEF(VT);
6796
6797   // fold (sext_in_reg c1) -> c1
6798   if (isConstantIntBuildVectorOrConstantInt(N0))
6799     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6800
6801   // If the input is already sign extended, just drop the extension.
6802   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6803     return N0;
6804
6805   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6806   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6807       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6808     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6809                        N0.getOperand(0), N1);
6810
6811   // fold (sext_in_reg (sext x)) -> (sext x)
6812   // fold (sext_in_reg (aext x)) -> (sext x)
6813   // if x is small enough.
6814   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6815     SDValue N00 = N0.getOperand(0);
6816     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6817         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6818       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6819   }
6820
6821   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6822   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6823     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6824
6825   // fold operands of sext_in_reg based on knowledge that the top bits are not
6826   // demanded.
6827   if (SimplifyDemandedBits(SDValue(N, 0)))
6828     return SDValue(N, 0);
6829
6830   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6831   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6832   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6833     return NarrowLoad;
6834
6835   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6836   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6837   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6838   if (N0.getOpcode() == ISD::SRL) {
6839     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6840       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6841         // We can turn this into an SRA iff the input to the SRL is already sign
6842         // extended enough.
6843         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6844         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6845           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6846                              N0.getOperand(0), N0.getOperand(1));
6847       }
6848   }
6849
6850   // fold (sext_inreg (extload x)) -> (sextload x)
6851   if (ISD::isEXTLoad(N0.getNode()) &&
6852       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6853       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6854       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6855        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6856     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6857     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6858                                      LN0->getChain(),
6859                                      LN0->getBasePtr(), EVT,
6860                                      LN0->getMemOperand());
6861     CombineTo(N, ExtLoad);
6862     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6863     AddToWorklist(ExtLoad.getNode());
6864     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6865   }
6866   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6867   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6868       N0.hasOneUse() &&
6869       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6870       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6871        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6872     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6873     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6874                                      LN0->getChain(),
6875                                      LN0->getBasePtr(), EVT,
6876                                      LN0->getMemOperand());
6877     CombineTo(N, ExtLoad);
6878     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6879     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6880   }
6881
6882   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6883   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6884     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6885                                        N0.getOperand(1), false);
6886     if (BSwap.getNode())
6887       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6888                          BSwap, N1);
6889   }
6890
6891   return SDValue();
6892 }
6893
6894 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6895   SDValue N0 = N->getOperand(0);
6896   EVT VT = N->getValueType(0);
6897
6898   if (N0.getOpcode() == ISD::UNDEF)
6899     return DAG.getUNDEF(VT);
6900
6901   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6902                                               LegalOperations))
6903     return SDValue(Res, 0);
6904
6905   return SDValue();
6906 }
6907
6908 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6909   SDValue N0 = N->getOperand(0);
6910   EVT VT = N->getValueType(0);
6911   bool isLE = DAG.getDataLayout().isLittleEndian();
6912
6913   // noop truncate
6914   if (N0.getValueType() == N->getValueType(0))
6915     return N0;
6916   // fold (truncate c1) -> c1
6917   if (isConstantIntBuildVectorOrConstantInt(N0))
6918     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6919   // fold (truncate (truncate x)) -> (truncate x)
6920   if (N0.getOpcode() == ISD::TRUNCATE)
6921     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6922   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6923   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6924       N0.getOpcode() == ISD::SIGN_EXTEND ||
6925       N0.getOpcode() == ISD::ANY_EXTEND) {
6926     if (N0.getOperand(0).getValueType().bitsLT(VT))
6927       // if the source is smaller than the dest, we still need an extend
6928       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6929                          N0.getOperand(0));
6930     if (N0.getOperand(0).getValueType().bitsGT(VT))
6931       // if the source is larger than the dest, than we just need the truncate
6932       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6933     // if the source and dest are the same type, we can drop both the extend
6934     // and the truncate.
6935     return N0.getOperand(0);
6936   }
6937
6938   // Fold extract-and-trunc into a narrow extract. For example:
6939   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6940   //   i32 y = TRUNCATE(i64 x)
6941   //        -- becomes --
6942   //   v16i8 b = BITCAST (v2i64 val)
6943   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6944   //
6945   // Note: We only run this optimization after type legalization (which often
6946   // creates this pattern) and before operation legalization after which
6947   // we need to be more careful about the vector instructions that we generate.
6948   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6949       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6950
6951     EVT VecTy = N0.getOperand(0).getValueType();
6952     EVT ExTy = N0.getValueType();
6953     EVT TrTy = N->getValueType(0);
6954
6955     unsigned NumElem = VecTy.getVectorNumElements();
6956     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6957
6958     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6959     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6960
6961     SDValue EltNo = N0->getOperand(1);
6962     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6963       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6964       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6965       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6966
6967       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6968                               NVT, N0.getOperand(0));
6969
6970       SDLoc DL(N);
6971       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6972                          DL, TrTy, V,
6973                          DAG.getConstant(Index, DL, IndexTy));
6974     }
6975   }
6976
6977   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6978   if (N0.getOpcode() == ISD::SELECT) {
6979     EVT SrcVT = N0.getValueType();
6980     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6981         TLI.isTruncateFree(SrcVT, VT)) {
6982       SDLoc SL(N0);
6983       SDValue Cond = N0.getOperand(0);
6984       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6985       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6986       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6987     }
6988   }
6989
6990   // Fold a series of buildvector, bitcast, and truncate if possible.
6991   // For example fold
6992   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6993   //   (2xi32 (buildvector x, y)).
6994   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6995       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6996       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6997       N0.getOperand(0).hasOneUse()) {
6998
6999     SDValue BuildVect = N0.getOperand(0);
7000     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7001     EVT TruncVecEltTy = VT.getVectorElementType();
7002
7003     // Check that the element types match.
7004     if (BuildVectEltTy == TruncVecEltTy) {
7005       // Now we only need to compute the offset of the truncated elements.
7006       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7007       unsigned TruncVecNumElts = VT.getVectorNumElements();
7008       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7009
7010       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7011              "Invalid number of elements");
7012
7013       SmallVector<SDValue, 8> Opnds;
7014       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7015         Opnds.push_back(BuildVect.getOperand(i));
7016
7017       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7018     }
7019   }
7020
7021   // See if we can simplify the input to this truncate through knowledge that
7022   // only the low bits are being used.
7023   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7024   // Currently we only perform this optimization on scalars because vectors
7025   // may have different active low bits.
7026   if (!VT.isVector()) {
7027     SDValue Shorter =
7028       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7029                                                VT.getSizeInBits()));
7030     if (Shorter.getNode())
7031       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7032   }
7033   // fold (truncate (load x)) -> (smaller load x)
7034   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7035   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7036     if (SDValue Reduced = ReduceLoadWidth(N))
7037       return Reduced;
7038
7039     // Handle the case where the load remains an extending load even
7040     // after truncation.
7041     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7042       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7043       if (!LN0->isVolatile() &&
7044           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7045         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7046                                          VT, LN0->getChain(), LN0->getBasePtr(),
7047                                          LN0->getMemoryVT(),
7048                                          LN0->getMemOperand());
7049         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7050         return NewLoad;
7051       }
7052     }
7053   }
7054   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7055   // where ... are all 'undef'.
7056   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7057     SmallVector<EVT, 8> VTs;
7058     SDValue V;
7059     unsigned Idx = 0;
7060     unsigned NumDefs = 0;
7061
7062     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7063       SDValue X = N0.getOperand(i);
7064       if (X.getOpcode() != ISD::UNDEF) {
7065         V = X;
7066         Idx = i;
7067         NumDefs++;
7068       }
7069       // Stop if more than one members are non-undef.
7070       if (NumDefs > 1)
7071         break;
7072       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7073                                      VT.getVectorElementType(),
7074                                      X.getValueType().getVectorNumElements()));
7075     }
7076
7077     if (NumDefs == 0)
7078       return DAG.getUNDEF(VT);
7079
7080     if (NumDefs == 1) {
7081       assert(V.getNode() && "The single defined operand is empty!");
7082       SmallVector<SDValue, 8> Opnds;
7083       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7084         if (i != Idx) {
7085           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7086           continue;
7087         }
7088         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7089         AddToWorklist(NV.getNode());
7090         Opnds.push_back(NV);
7091       }
7092       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7093     }
7094   }
7095
7096   // Simplify the operands using demanded-bits information.
7097   if (!VT.isVector() &&
7098       SimplifyDemandedBits(SDValue(N, 0)))
7099     return SDValue(N, 0);
7100
7101   return SDValue();
7102 }
7103
7104 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7105   SDValue Elt = N->getOperand(i);
7106   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7107     return Elt.getNode();
7108   return Elt.getOperand(Elt.getResNo()).getNode();
7109 }
7110
7111 /// build_pair (load, load) -> load
7112 /// if load locations are consecutive.
7113 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7114   assert(N->getOpcode() == ISD::BUILD_PAIR);
7115
7116   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7117   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7118   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7119       LD1->getAddressSpace() != LD2->getAddressSpace())
7120     return SDValue();
7121   EVT LD1VT = LD1->getValueType(0);
7122
7123   if (ISD::isNON_EXTLoad(LD2) &&
7124       LD2->hasOneUse() &&
7125       // If both are volatile this would reduce the number of volatile loads.
7126       // If one is volatile it might be ok, but play conservative and bail out.
7127       !LD1->isVolatile() &&
7128       !LD2->isVolatile() &&
7129       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7130     unsigned Align = LD1->getAlignment();
7131     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7132         VT.getTypeForEVT(*DAG.getContext()));
7133
7134     if (NewAlign <= Align &&
7135         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7136       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7137                          LD1->getBasePtr(), LD1->getPointerInfo(),
7138                          false, false, false, Align);
7139   }
7140
7141   return SDValue();
7142 }
7143
7144 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7145   SDValue N0 = N->getOperand(0);
7146   EVT VT = N->getValueType(0);
7147
7148   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7149   // Only do this before legalize, since afterward the target may be depending
7150   // on the bitconvert.
7151   // First check to see if this is all constant.
7152   if (!LegalTypes &&
7153       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7154       VT.isVector()) {
7155     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7156
7157     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7158     assert(!DestEltVT.isVector() &&
7159            "Element type of vector ValueType must not be vector!");
7160     if (isSimple)
7161       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7162   }
7163
7164   // If the input is a constant, let getNode fold it.
7165   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7166     // If we can't allow illegal operations, we need to check that this is just
7167     // a fp -> int or int -> conversion and that the resulting operation will
7168     // be legal.
7169     if (!LegalOperations ||
7170         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7171          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7172         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7173          TLI.isOperationLegal(ISD::Constant, VT)))
7174       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7175   }
7176
7177   // (conv (conv x, t1), t2) -> (conv x, t2)
7178   if (N0.getOpcode() == ISD::BITCAST)
7179     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7180                        N0.getOperand(0));
7181
7182   // fold (conv (load x)) -> (load (conv*)x)
7183   // If the resultant load doesn't need a higher alignment than the original!
7184   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7185       // Do not change the width of a volatile load.
7186       !cast<LoadSDNode>(N0)->isVolatile() &&
7187       // Do not remove the cast if the types differ in endian layout.
7188       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7189           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7190       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7191       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7192     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7193     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7194         VT.getTypeForEVT(*DAG.getContext()));
7195     unsigned OrigAlign = LN0->getAlignment();
7196
7197     if (Align <= OrigAlign) {
7198       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7199                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7200                                  LN0->isVolatile(), LN0->isNonTemporal(),
7201                                  LN0->isInvariant(), OrigAlign,
7202                                  LN0->getAAInfo());
7203       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7204       return Load;
7205     }
7206   }
7207
7208   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7209   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7210   // This often reduces constant pool loads.
7211   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7212        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7213       N0.getNode()->hasOneUse() && VT.isInteger() &&
7214       !VT.isVector() && !N0.getValueType().isVector()) {
7215     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7216                                   N0.getOperand(0));
7217     AddToWorklist(NewConv.getNode());
7218
7219     SDLoc DL(N);
7220     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7221     if (N0.getOpcode() == ISD::FNEG)
7222       return DAG.getNode(ISD::XOR, DL, VT,
7223                          NewConv, DAG.getConstant(SignBit, DL, VT));
7224     assert(N0.getOpcode() == ISD::FABS);
7225     return DAG.getNode(ISD::AND, DL, VT,
7226                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7227   }
7228
7229   // fold (bitconvert (fcopysign cst, x)) ->
7230   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7231   // Note that we don't handle (copysign x, cst) because this can always be
7232   // folded to an fneg or fabs.
7233   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7234       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7235       VT.isInteger() && !VT.isVector()) {
7236     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7237     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7238     if (isTypeLegal(IntXVT)) {
7239       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7240                               IntXVT, N0.getOperand(1));
7241       AddToWorklist(X.getNode());
7242
7243       // If X has a different width than the result/lhs, sext it or truncate it.
7244       unsigned VTWidth = VT.getSizeInBits();
7245       if (OrigXWidth < VTWidth) {
7246         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7247         AddToWorklist(X.getNode());
7248       } else if (OrigXWidth > VTWidth) {
7249         // To get the sign bit in the right place, we have to shift it right
7250         // before truncating.
7251         SDLoc DL(X);
7252         X = DAG.getNode(ISD::SRL, DL,
7253                         X.getValueType(), X,
7254                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7255                                         X.getValueType()));
7256         AddToWorklist(X.getNode());
7257         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7258         AddToWorklist(X.getNode());
7259       }
7260
7261       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7262       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7263                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7264       AddToWorklist(X.getNode());
7265
7266       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7267                                 VT, N0.getOperand(0));
7268       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7269                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7270       AddToWorklist(Cst.getNode());
7271
7272       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7273     }
7274   }
7275
7276   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7277   if (N0.getOpcode() == ISD::BUILD_PAIR)
7278     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7279       return CombineLD;
7280
7281   // Remove double bitcasts from shuffles - this is often a legacy of
7282   // XformToShuffleWithZero being used to combine bitmaskings (of
7283   // float vectors bitcast to integer vectors) into shuffles.
7284   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7285   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7286       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7287       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7288       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7289     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7290
7291     // If operands are a bitcast, peek through if it casts the original VT.
7292     // If operands are a constant, just bitcast back to original VT.
7293     auto PeekThroughBitcast = [&](SDValue Op) {
7294       if (Op.getOpcode() == ISD::BITCAST &&
7295           Op.getOperand(0).getValueType() == VT)
7296         return SDValue(Op.getOperand(0));
7297       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7298           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7299         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7300       return SDValue();
7301     };
7302
7303     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7304     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7305     if (!(SV0 && SV1))
7306       return SDValue();
7307
7308     int MaskScale =
7309         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7310     SmallVector<int, 8> NewMask;
7311     for (int M : SVN->getMask())
7312       for (int i = 0; i != MaskScale; ++i)
7313         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7314
7315     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7316     if (!LegalMask) {
7317       std::swap(SV0, SV1);
7318       ShuffleVectorSDNode::commuteMask(NewMask);
7319       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7320     }
7321
7322     if (LegalMask)
7323       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7324   }
7325
7326   return SDValue();
7327 }
7328
7329 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7330   EVT VT = N->getValueType(0);
7331   return CombineConsecutiveLoads(N, VT);
7332 }
7333
7334 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7335 /// operands. DstEltVT indicates the destination element value type.
7336 SDValue DAGCombiner::
7337 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7338   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7339
7340   // If this is already the right type, we're done.
7341   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7342
7343   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7344   unsigned DstBitSize = DstEltVT.getSizeInBits();
7345
7346   // If this is a conversion of N elements of one type to N elements of another
7347   // type, convert each element.  This handles FP<->INT cases.
7348   if (SrcBitSize == DstBitSize) {
7349     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7350                               BV->getValueType(0).getVectorNumElements());
7351
7352     // Due to the FP element handling below calling this routine recursively,
7353     // we can end up with a scalar-to-vector node here.
7354     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7355       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7356                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7357                                      DstEltVT, BV->getOperand(0)));
7358
7359     SmallVector<SDValue, 8> Ops;
7360     for (SDValue Op : BV->op_values()) {
7361       // If the vector element type is not legal, the BUILD_VECTOR operands
7362       // are promoted and implicitly truncated.  Make that explicit here.
7363       if (Op.getValueType() != SrcEltVT)
7364         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7365       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7366                                 DstEltVT, Op));
7367       AddToWorklist(Ops.back().getNode());
7368     }
7369     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7370   }
7371
7372   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7373   // handle annoying details of growing/shrinking FP values, we convert them to
7374   // int first.
7375   if (SrcEltVT.isFloatingPoint()) {
7376     // Convert the input float vector to a int vector where the elements are the
7377     // same sizes.
7378     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7379     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7380     SrcEltVT = IntVT;
7381   }
7382
7383   // Now we know the input is an integer vector.  If the output is a FP type,
7384   // convert to integer first, then to FP of the right size.
7385   if (DstEltVT.isFloatingPoint()) {
7386     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7387     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7388
7389     // Next, convert to FP elements of the same size.
7390     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7391   }
7392
7393   SDLoc DL(BV);
7394
7395   // Okay, we know the src/dst types are both integers of differing types.
7396   // Handling growing first.
7397   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7398   if (SrcBitSize < DstBitSize) {
7399     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7400
7401     SmallVector<SDValue, 8> Ops;
7402     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7403          i += NumInputsPerOutput) {
7404       bool isLE = DAG.getDataLayout().isLittleEndian();
7405       APInt NewBits = APInt(DstBitSize, 0);
7406       bool EltIsUndef = true;
7407       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7408         // Shift the previously computed bits over.
7409         NewBits <<= SrcBitSize;
7410         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7411         if (Op.getOpcode() == ISD::UNDEF) continue;
7412         EltIsUndef = false;
7413
7414         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7415                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7416       }
7417
7418       if (EltIsUndef)
7419         Ops.push_back(DAG.getUNDEF(DstEltVT));
7420       else
7421         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7422     }
7423
7424     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7425     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7426   }
7427
7428   // Finally, this must be the case where we are shrinking elements: each input
7429   // turns into multiple outputs.
7430   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7431   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7432                             NumOutputsPerInput*BV->getNumOperands());
7433   SmallVector<SDValue, 8> Ops;
7434
7435   for (const SDValue &Op : BV->op_values()) {
7436     if (Op.getOpcode() == ISD::UNDEF) {
7437       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7438       continue;
7439     }
7440
7441     APInt OpVal = cast<ConstantSDNode>(Op)->
7442                   getAPIntValue().zextOrTrunc(SrcBitSize);
7443
7444     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7445       APInt ThisVal = OpVal.trunc(DstBitSize);
7446       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7447       OpVal = OpVal.lshr(DstBitSize);
7448     }
7449
7450     // For big endian targets, swap the order of the pieces of each element.
7451     if (DAG.getDataLayout().isBigEndian())
7452       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7453   }
7454
7455   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7456 }
7457
7458 /// Try to perform FMA combining on a given FADD node.
7459 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7460   SDValue N0 = N->getOperand(0);
7461   SDValue N1 = N->getOperand(1);
7462   EVT VT = N->getValueType(0);
7463   SDLoc SL(N);
7464
7465   const TargetOptions &Options = DAG.getTarget().Options;
7466   bool AllowFusion =
7467       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7468
7469   // Floating-point multiply-add with intermediate rounding.
7470   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7471
7472   // Floating-point multiply-add without intermediate rounding.
7473   bool HasFMA =
7474       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7475       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7476
7477   // No valid opcode, do not combine.
7478   if (!HasFMAD && !HasFMA)
7479     return SDValue();
7480
7481   // Always prefer FMAD to FMA for precision.
7482   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7483   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7484   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7485
7486   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7487   // prefer to fold the multiply with fewer uses.
7488   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7489       N1.getOpcode() == ISD::FMUL) {
7490     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7491       std::swap(N0, N1);
7492   }
7493
7494   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7495   if (N0.getOpcode() == ISD::FMUL &&
7496       (Aggressive || N0->hasOneUse())) {
7497     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7498                        N0.getOperand(0), N0.getOperand(1), N1);
7499   }
7500
7501   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7502   // Note: Commutes FADD operands.
7503   if (N1.getOpcode() == ISD::FMUL &&
7504       (Aggressive || N1->hasOneUse())) {
7505     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7506                        N1.getOperand(0), N1.getOperand(1), N0);
7507   }
7508
7509   // Look through FP_EXTEND nodes to do more combining.
7510   if (AllowFusion && LookThroughFPExt) {
7511     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7512     if (N0.getOpcode() == ISD::FP_EXTEND) {
7513       SDValue N00 = N0.getOperand(0);
7514       if (N00.getOpcode() == ISD::FMUL)
7515         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7516                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7517                                        N00.getOperand(0)),
7518                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7519                                        N00.getOperand(1)), N1);
7520     }
7521
7522     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7523     // Note: Commutes FADD operands.
7524     if (N1.getOpcode() == ISD::FP_EXTEND) {
7525       SDValue N10 = N1.getOperand(0);
7526       if (N10.getOpcode() == ISD::FMUL)
7527         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7528                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7529                                        N10.getOperand(0)),
7530                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7531                                        N10.getOperand(1)), N0);
7532     }
7533   }
7534
7535   // More folding opportunities when target permits.
7536   if ((AllowFusion || HasFMAD)  && Aggressive) {
7537     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7538     if (N0.getOpcode() == PreferredFusedOpcode &&
7539         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7540       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7541                          N0.getOperand(0), N0.getOperand(1),
7542                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7543                                      N0.getOperand(2).getOperand(0),
7544                                      N0.getOperand(2).getOperand(1),
7545                                      N1));
7546     }
7547
7548     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7549     if (N1->getOpcode() == PreferredFusedOpcode &&
7550         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7551       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7552                          N1.getOperand(0), N1.getOperand(1),
7553                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7554                                      N1.getOperand(2).getOperand(0),
7555                                      N1.getOperand(2).getOperand(1),
7556                                      N0));
7557     }
7558
7559     if (AllowFusion && LookThroughFPExt) {
7560       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7561       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7562       auto FoldFAddFMAFPExtFMul = [&] (
7563           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7564         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7565                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7566                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7567                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7568                                        Z));
7569       };
7570       if (N0.getOpcode() == PreferredFusedOpcode) {
7571         SDValue N02 = N0.getOperand(2);
7572         if (N02.getOpcode() == ISD::FP_EXTEND) {
7573           SDValue N020 = N02.getOperand(0);
7574           if (N020.getOpcode() == ISD::FMUL)
7575             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7576                                         N020.getOperand(0), N020.getOperand(1),
7577                                         N1);
7578         }
7579       }
7580
7581       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7582       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7583       // FIXME: This turns two single-precision and one double-precision
7584       // operation into two double-precision operations, which might not be
7585       // interesting for all targets, especially GPUs.
7586       auto FoldFAddFPExtFMAFMul = [&] (
7587           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7588         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7589                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7590                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7591                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7592                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7593                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7594                                        Z));
7595       };
7596       if (N0.getOpcode() == ISD::FP_EXTEND) {
7597         SDValue N00 = N0.getOperand(0);
7598         if (N00.getOpcode() == PreferredFusedOpcode) {
7599           SDValue N002 = N00.getOperand(2);
7600           if (N002.getOpcode() == ISD::FMUL)
7601             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7602                                         N002.getOperand(0), N002.getOperand(1),
7603                                         N1);
7604         }
7605       }
7606
7607       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7608       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7609       if (N1.getOpcode() == PreferredFusedOpcode) {
7610         SDValue N12 = N1.getOperand(2);
7611         if (N12.getOpcode() == ISD::FP_EXTEND) {
7612           SDValue N120 = N12.getOperand(0);
7613           if (N120.getOpcode() == ISD::FMUL)
7614             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7615                                         N120.getOperand(0), N120.getOperand(1),
7616                                         N0);
7617         }
7618       }
7619
7620       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7621       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7622       // FIXME: This turns two single-precision and one double-precision
7623       // operation into two double-precision operations, which might not be
7624       // interesting for all targets, especially GPUs.
7625       if (N1.getOpcode() == ISD::FP_EXTEND) {
7626         SDValue N10 = N1.getOperand(0);
7627         if (N10.getOpcode() == PreferredFusedOpcode) {
7628           SDValue N102 = N10.getOperand(2);
7629           if (N102.getOpcode() == ISD::FMUL)
7630             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7631                                         N102.getOperand(0), N102.getOperand(1),
7632                                         N0);
7633         }
7634       }
7635     }
7636   }
7637
7638   return SDValue();
7639 }
7640
7641 /// Try to perform FMA combining on a given FSUB node.
7642 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7643   SDValue N0 = N->getOperand(0);
7644   SDValue N1 = N->getOperand(1);
7645   EVT VT = N->getValueType(0);
7646   SDLoc SL(N);
7647
7648   const TargetOptions &Options = DAG.getTarget().Options;
7649   bool AllowFusion =
7650       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7651
7652   // Floating-point multiply-add with intermediate rounding.
7653   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7654
7655   // Floating-point multiply-add without intermediate rounding.
7656   bool HasFMA =
7657       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7658       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7659
7660   // No valid opcode, do not combine.
7661   if (!HasFMAD && !HasFMA)
7662     return SDValue();
7663
7664   // Always prefer FMAD to FMA for precision.
7665   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7666   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7667   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7668
7669   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7670   if (N0.getOpcode() == ISD::FMUL &&
7671       (Aggressive || N0->hasOneUse())) {
7672     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7673                        N0.getOperand(0), N0.getOperand(1),
7674                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7675   }
7676
7677   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7678   // Note: Commutes FSUB operands.
7679   if (N1.getOpcode() == ISD::FMUL &&
7680       (Aggressive || N1->hasOneUse()))
7681     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7682                        DAG.getNode(ISD::FNEG, SL, VT,
7683                                    N1.getOperand(0)),
7684                        N1.getOperand(1), N0);
7685
7686   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7687   if (N0.getOpcode() == ISD::FNEG &&
7688       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7689       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7690     SDValue N00 = N0.getOperand(0).getOperand(0);
7691     SDValue N01 = N0.getOperand(0).getOperand(1);
7692     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7693                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7694                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7695   }
7696
7697   // Look through FP_EXTEND nodes to do more combining.
7698   if (AllowFusion && LookThroughFPExt) {
7699     // fold (fsub (fpext (fmul x, y)), z)
7700     //   -> (fma (fpext x), (fpext y), (fneg z))
7701     if (N0.getOpcode() == ISD::FP_EXTEND) {
7702       SDValue N00 = N0.getOperand(0);
7703       if (N00.getOpcode() == ISD::FMUL)
7704         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7705                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7706                                        N00.getOperand(0)),
7707                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7708                                        N00.getOperand(1)),
7709                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7710     }
7711
7712     // fold (fsub x, (fpext (fmul y, z)))
7713     //   -> (fma (fneg (fpext y)), (fpext z), x)
7714     // Note: Commutes FSUB operands.
7715     if (N1.getOpcode() == ISD::FP_EXTEND) {
7716       SDValue N10 = N1.getOperand(0);
7717       if (N10.getOpcode() == ISD::FMUL)
7718         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7719                            DAG.getNode(ISD::FNEG, SL, VT,
7720                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7721                                                    N10.getOperand(0))),
7722                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7723                                        N10.getOperand(1)),
7724                            N0);
7725     }
7726
7727     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7728     //   -> (fneg (fma (fpext x), (fpext y), z))
7729     // Note: This could be removed with appropriate canonicalization of the
7730     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7731     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7732     // from implementing the canonicalization in visitFSUB.
7733     if (N0.getOpcode() == ISD::FP_EXTEND) {
7734       SDValue N00 = N0.getOperand(0);
7735       if (N00.getOpcode() == ISD::FNEG) {
7736         SDValue N000 = N00.getOperand(0);
7737         if (N000.getOpcode() == ISD::FMUL) {
7738           return DAG.getNode(ISD::FNEG, SL, VT,
7739                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7740                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7741                                                      N000.getOperand(0)),
7742                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7743                                                      N000.getOperand(1)),
7744                                          N1));
7745         }
7746       }
7747     }
7748
7749     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7750     //   -> (fneg (fma (fpext x)), (fpext y), z)
7751     // Note: This could be removed with appropriate canonicalization of the
7752     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7753     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7754     // from implementing the canonicalization in visitFSUB.
7755     if (N0.getOpcode() == ISD::FNEG) {
7756       SDValue N00 = N0.getOperand(0);
7757       if (N00.getOpcode() == ISD::FP_EXTEND) {
7758         SDValue N000 = N00.getOperand(0);
7759         if (N000.getOpcode() == ISD::FMUL) {
7760           return DAG.getNode(ISD::FNEG, SL, VT,
7761                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7762                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7763                                                      N000.getOperand(0)),
7764                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7765                                                      N000.getOperand(1)),
7766                                          N1));
7767         }
7768       }
7769     }
7770
7771   }
7772
7773   // More folding opportunities when target permits.
7774   if ((AllowFusion || HasFMAD) && Aggressive) {
7775     // fold (fsub (fma x, y, (fmul u, v)), z)
7776     //   -> (fma x, y (fma u, v, (fneg z)))
7777     if (N0.getOpcode() == PreferredFusedOpcode &&
7778         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7779       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7780                          N0.getOperand(0), N0.getOperand(1),
7781                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7782                                      N0.getOperand(2).getOperand(0),
7783                                      N0.getOperand(2).getOperand(1),
7784                                      DAG.getNode(ISD::FNEG, SL, VT,
7785                                                  N1)));
7786     }
7787
7788     // fold (fsub x, (fma y, z, (fmul u, v)))
7789     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7790     if (N1.getOpcode() == PreferredFusedOpcode &&
7791         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7792       SDValue N20 = N1.getOperand(2).getOperand(0);
7793       SDValue N21 = N1.getOperand(2).getOperand(1);
7794       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7795                          DAG.getNode(ISD::FNEG, SL, VT,
7796                                      N1.getOperand(0)),
7797                          N1.getOperand(1),
7798                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7799                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7800
7801                                      N21, N0));
7802     }
7803
7804     if (AllowFusion && LookThroughFPExt) {
7805       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7806       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7807       if (N0.getOpcode() == PreferredFusedOpcode) {
7808         SDValue N02 = N0.getOperand(2);
7809         if (N02.getOpcode() == ISD::FP_EXTEND) {
7810           SDValue N020 = N02.getOperand(0);
7811           if (N020.getOpcode() == ISD::FMUL)
7812             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7813                                N0.getOperand(0), N0.getOperand(1),
7814                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7815                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7816                                                        N020.getOperand(0)),
7817                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7818                                                        N020.getOperand(1)),
7819                                            DAG.getNode(ISD::FNEG, SL, VT,
7820                                                        N1)));
7821         }
7822       }
7823
7824       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7825       //   -> (fma (fpext x), (fpext y),
7826       //           (fma (fpext u), (fpext v), (fneg z)))
7827       // FIXME: This turns two single-precision and one double-precision
7828       // operation into two double-precision operations, which might not be
7829       // interesting for all targets, especially GPUs.
7830       if (N0.getOpcode() == ISD::FP_EXTEND) {
7831         SDValue N00 = N0.getOperand(0);
7832         if (N00.getOpcode() == PreferredFusedOpcode) {
7833           SDValue N002 = N00.getOperand(2);
7834           if (N002.getOpcode() == ISD::FMUL)
7835             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7836                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7837                                            N00.getOperand(0)),
7838                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7839                                            N00.getOperand(1)),
7840                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7841                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7842                                                        N002.getOperand(0)),
7843                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7844                                                        N002.getOperand(1)),
7845                                            DAG.getNode(ISD::FNEG, SL, VT,
7846                                                        N1)));
7847         }
7848       }
7849
7850       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7851       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7852       if (N1.getOpcode() == PreferredFusedOpcode &&
7853         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7854         SDValue N120 = N1.getOperand(2).getOperand(0);
7855         if (N120.getOpcode() == ISD::FMUL) {
7856           SDValue N1200 = N120.getOperand(0);
7857           SDValue N1201 = N120.getOperand(1);
7858           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7859                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7860                              N1.getOperand(1),
7861                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7862                                          DAG.getNode(ISD::FNEG, SL, VT,
7863                                              DAG.getNode(ISD::FP_EXTEND, SL,
7864                                                          VT, N1200)),
7865                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7866                                                      N1201),
7867                                          N0));
7868         }
7869       }
7870
7871       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7872       //   -> (fma (fneg (fpext y)), (fpext z),
7873       //           (fma (fneg (fpext u)), (fpext v), x))
7874       // FIXME: This turns two single-precision and one double-precision
7875       // operation into two double-precision operations, which might not be
7876       // interesting for all targets, especially GPUs.
7877       if (N1.getOpcode() == ISD::FP_EXTEND &&
7878         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7879         SDValue N100 = N1.getOperand(0).getOperand(0);
7880         SDValue N101 = N1.getOperand(0).getOperand(1);
7881         SDValue N102 = N1.getOperand(0).getOperand(2);
7882         if (N102.getOpcode() == ISD::FMUL) {
7883           SDValue N1020 = N102.getOperand(0);
7884           SDValue N1021 = N102.getOperand(1);
7885           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7886                              DAG.getNode(ISD::FNEG, SL, VT,
7887                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7888                                                      N100)),
7889                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7890                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7891                                          DAG.getNode(ISD::FNEG, SL, VT,
7892                                              DAG.getNode(ISD::FP_EXTEND, SL,
7893                                                          VT, N1020)),
7894                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7895                                                      N1021),
7896                                          N0));
7897         }
7898       }
7899     }
7900   }
7901
7902   return SDValue();
7903 }
7904
7905 /// Try to perform FMA combining on a given FMUL node.
7906 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7907   SDValue N0 = N->getOperand(0);
7908   SDValue N1 = N->getOperand(1);
7909   EVT VT = N->getValueType(0);
7910   SDLoc SL(N);
7911
7912   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7913
7914   const TargetOptions &Options = DAG.getTarget().Options;
7915   bool AllowFusion =
7916       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7917
7918   // Floating-point multiply-add with intermediate rounding.
7919   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7920
7921   // Floating-point multiply-add without intermediate rounding.
7922   bool HasFMA =
7923       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7924       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7925
7926   // No valid opcode, do not combine.
7927   if (!HasFMAD && !HasFMA)
7928     return SDValue();
7929
7930   // Always prefer FMAD to FMA for precision.
7931   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7932   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7933
7934   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
7935   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
7936   auto FuseFADD = [&](SDValue X, SDValue Y) {
7937     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
7938       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7939       if (XC1 && XC1->isExactlyValue(+1.0))
7940         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7941       if (XC1 && XC1->isExactlyValue(-1.0))
7942         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7943                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7944     }
7945     return SDValue();
7946   };
7947
7948   if (SDValue FMA = FuseFADD(N0, N1))
7949     return FMA;
7950   if (SDValue FMA = FuseFADD(N1, N0))
7951     return FMA;
7952
7953   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
7954   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
7955   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
7956   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
7957   auto FuseFSUB = [&](SDValue X, SDValue Y) {
7958     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
7959       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
7960       if (XC0 && XC0->isExactlyValue(+1.0))
7961         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7962                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
7963                            Y);
7964       if (XC0 && XC0->isExactlyValue(-1.0))
7965         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7966                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
7967                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7968
7969       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7970       if (XC1 && XC1->isExactlyValue(+1.0))
7971         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7972                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7973       if (XC1 && XC1->isExactlyValue(-1.0))
7974         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7975     }
7976     return SDValue();
7977   };
7978
7979   if (SDValue FMA = FuseFSUB(N0, N1))
7980     return FMA;
7981   if (SDValue FMA = FuseFSUB(N1, N0))
7982     return FMA;
7983
7984   return SDValue();
7985 }
7986
7987 SDValue DAGCombiner::visitFADD(SDNode *N) {
7988   SDValue N0 = N->getOperand(0);
7989   SDValue N1 = N->getOperand(1);
7990   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
7991   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
7992   EVT VT = N->getValueType(0);
7993   SDLoc DL(N);
7994   const TargetOptions &Options = DAG.getTarget().Options;
7995   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
7996
7997   // fold vector ops
7998   if (VT.isVector())
7999     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8000       return FoldedVOp;
8001
8002   // fold (fadd c1, c2) -> c1 + c2
8003   if (N0CFP && N1CFP)
8004     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8005
8006   // canonicalize constant to RHS
8007   if (N0CFP && !N1CFP)
8008     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8009
8010   // fold (fadd A, (fneg B)) -> (fsub A, B)
8011   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8012       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8013     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8014                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8015
8016   // fold (fadd (fneg A), B) -> (fsub B, A)
8017   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8018       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8019     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8020                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8021
8022   // If 'unsafe math' is enabled, fold lots of things.
8023   if (Options.UnsafeFPMath) {
8024     // No FP constant should be created after legalization as Instruction
8025     // Selection pass has a hard time dealing with FP constants.
8026     bool AllowNewConst = (Level < AfterLegalizeDAG);
8027
8028     // fold (fadd A, 0) -> A
8029     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8030       if (N1C->isZero())
8031         return N0;
8032
8033     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8034     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8035         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8036       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8037                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8038                                      Flags),
8039                          Flags);
8040
8041     // If allowed, fold (fadd (fneg x), x) -> 0.0
8042     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8043       return DAG.getConstantFP(0.0, DL, VT);
8044
8045     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8046     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8047       return DAG.getConstantFP(0.0, DL, VT);
8048
8049     // We can fold chains of FADD's of the same value into multiplications.
8050     // This transform is not safe in general because we are reducing the number
8051     // of rounding steps.
8052     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8053       if (N0.getOpcode() == ISD::FMUL) {
8054         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8055         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8056
8057         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8058         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8059           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8060                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8061           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8062         }
8063
8064         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8065         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8066             N1.getOperand(0) == N1.getOperand(1) &&
8067             N0.getOperand(0) == N1.getOperand(0)) {
8068           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8069                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8070           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8071         }
8072       }
8073
8074       if (N1.getOpcode() == ISD::FMUL) {
8075         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8076         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8077
8078         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8079         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8080           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8081                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8082           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8083         }
8084
8085         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8086         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8087             N0.getOperand(0) == N0.getOperand(1) &&
8088             N1.getOperand(0) == N0.getOperand(0)) {
8089           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8090                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8091           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8092         }
8093       }
8094
8095       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8096         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8097         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8098         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8099             (N0.getOperand(0) == N1)) {
8100           return DAG.getNode(ISD::FMUL, DL, VT,
8101                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8102         }
8103       }
8104
8105       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8106         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8107         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8108         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8109             N1.getOperand(0) == N0) {
8110           return DAG.getNode(ISD::FMUL, DL, VT,
8111                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8112         }
8113       }
8114
8115       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8116       if (AllowNewConst &&
8117           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8118           N0.getOperand(0) == N0.getOperand(1) &&
8119           N1.getOperand(0) == N1.getOperand(1) &&
8120           N0.getOperand(0) == N1.getOperand(0)) {
8121         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8122                            DAG.getConstantFP(4.0, DL, VT), Flags);
8123       }
8124     }
8125   } // enable-unsafe-fp-math
8126
8127   // FADD -> FMA combines:
8128   if (SDValue Fused = visitFADDForFMACombine(N)) {
8129     AddToWorklist(Fused.getNode());
8130     return Fused;
8131   }
8132
8133   return SDValue();
8134 }
8135
8136 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8137   SDValue N0 = N->getOperand(0);
8138   SDValue N1 = N->getOperand(1);
8139   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8140   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8141   EVT VT = N->getValueType(0);
8142   SDLoc dl(N);
8143   const TargetOptions &Options = DAG.getTarget().Options;
8144   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8145
8146   // fold vector ops
8147   if (VT.isVector())
8148     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8149       return FoldedVOp;
8150
8151   // fold (fsub c1, c2) -> c1-c2
8152   if (N0CFP && N1CFP)
8153     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8154
8155   // fold (fsub A, (fneg B)) -> (fadd A, B)
8156   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8157     return DAG.getNode(ISD::FADD, dl, VT, N0,
8158                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8159
8160   // If 'unsafe math' is enabled, fold lots of things.
8161   if (Options.UnsafeFPMath) {
8162     // (fsub A, 0) -> A
8163     if (N1CFP && N1CFP->isZero())
8164       return N0;
8165
8166     // (fsub 0, B) -> -B
8167     if (N0CFP && N0CFP->isZero()) {
8168       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8169         return GetNegatedExpression(N1, DAG, LegalOperations);
8170       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8171         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8172     }
8173
8174     // (fsub x, x) -> 0.0
8175     if (N0 == N1)
8176       return DAG.getConstantFP(0.0f, dl, VT);
8177
8178     // (fsub x, (fadd x, y)) -> (fneg y)
8179     // (fsub x, (fadd y, x)) -> (fneg y)
8180     if (N1.getOpcode() == ISD::FADD) {
8181       SDValue N10 = N1->getOperand(0);
8182       SDValue N11 = N1->getOperand(1);
8183
8184       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8185         return GetNegatedExpression(N11, DAG, LegalOperations);
8186
8187       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8188         return GetNegatedExpression(N10, DAG, LegalOperations);
8189     }
8190   }
8191
8192   // FSUB -> FMA combines:
8193   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8194     AddToWorklist(Fused.getNode());
8195     return Fused;
8196   }
8197
8198   return SDValue();
8199 }
8200
8201 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8202   SDValue N0 = N->getOperand(0);
8203   SDValue N1 = N->getOperand(1);
8204   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8205   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8206   EVT VT = N->getValueType(0);
8207   SDLoc DL(N);
8208   const TargetOptions &Options = DAG.getTarget().Options;
8209   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8210
8211   // fold vector ops
8212   if (VT.isVector()) {
8213     // This just handles C1 * C2 for vectors. Other vector folds are below.
8214     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8215       return FoldedVOp;
8216   }
8217
8218   // fold (fmul c1, c2) -> c1*c2
8219   if (N0CFP && N1CFP)
8220     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8221
8222   // canonicalize constant to RHS
8223   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8224      !isConstantFPBuildVectorOrConstantFP(N1))
8225     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8226
8227   // fold (fmul A, 1.0) -> A
8228   if (N1CFP && N1CFP->isExactlyValue(1.0))
8229     return N0;
8230
8231   if (Options.UnsafeFPMath) {
8232     // fold (fmul A, 0) -> 0
8233     if (N1CFP && N1CFP->isZero())
8234       return N1;
8235
8236     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8237     if (N0.getOpcode() == ISD::FMUL) {
8238       // Fold scalars or any vector constants (not just splats).
8239       // This fold is done in general by InstCombine, but extra fmul insts
8240       // may have been generated during lowering.
8241       SDValue N00 = N0.getOperand(0);
8242       SDValue N01 = N0.getOperand(1);
8243       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8244       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8245       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8246
8247       // Check 1: Make sure that the first operand of the inner multiply is NOT
8248       // a constant. Otherwise, we may induce infinite looping.
8249       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8250         // Check 2: Make sure that the second operand of the inner multiply and
8251         // the second operand of the outer multiply are constants.
8252         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8253             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8254           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8255           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8256         }
8257       }
8258     }
8259
8260     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8261     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8262     // during an early run of DAGCombiner can prevent folding with fmuls
8263     // inserted during lowering.
8264     if (N0.getOpcode() == ISD::FADD &&
8265         (N0.getOperand(0) == N0.getOperand(1)) &&
8266         N0.hasOneUse()) {
8267       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8268       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8269       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8270     }
8271   }
8272
8273   // fold (fmul X, 2.0) -> (fadd X, X)
8274   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8275     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8276
8277   // fold (fmul X, -1.0) -> (fneg X)
8278   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8279     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8280       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8281
8282   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8283   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8284     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8285       // Both can be negated for free, check to see if at least one is cheaper
8286       // negated.
8287       if (LHSNeg == 2 || RHSNeg == 2)
8288         return DAG.getNode(ISD::FMUL, DL, VT,
8289                            GetNegatedExpression(N0, DAG, LegalOperations),
8290                            GetNegatedExpression(N1, DAG, LegalOperations),
8291                            Flags);
8292     }
8293   }
8294
8295   // FMUL -> FMA combines:
8296   if (SDValue Fused = visitFMULForFMACombine(N)) {
8297     AddToWorklist(Fused.getNode());
8298     return Fused;
8299   }
8300
8301   return SDValue();
8302 }
8303
8304 SDValue DAGCombiner::visitFMA(SDNode *N) {
8305   SDValue N0 = N->getOperand(0);
8306   SDValue N1 = N->getOperand(1);
8307   SDValue N2 = N->getOperand(2);
8308   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8309   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8310   EVT VT = N->getValueType(0);
8311   SDLoc dl(N);
8312   const TargetOptions &Options = DAG.getTarget().Options;
8313
8314   // Constant fold FMA.
8315   if (isa<ConstantFPSDNode>(N0) &&
8316       isa<ConstantFPSDNode>(N1) &&
8317       isa<ConstantFPSDNode>(N2)) {
8318     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8319   }
8320
8321   if (Options.UnsafeFPMath) {
8322     if (N0CFP && N0CFP->isZero())
8323       return N2;
8324     if (N1CFP && N1CFP->isZero())
8325       return N2;
8326   }
8327   // TODO: The FMA node should have flags that propagate to these nodes.
8328   if (N0CFP && N0CFP->isExactlyValue(1.0))
8329     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8330   if (N1CFP && N1CFP->isExactlyValue(1.0))
8331     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8332
8333   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8334   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8335      !isConstantFPBuildVectorOrConstantFP(N1))
8336     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8337
8338   // TODO: FMA nodes should have flags that propagate to the created nodes.
8339   // For now, create a Flags object for use with all unsafe math transforms.
8340   SDNodeFlags Flags;
8341   Flags.setUnsafeAlgebra(true);
8342
8343   if (Options.UnsafeFPMath) {
8344     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8345     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8346         isConstantFPBuildVectorOrConstantFP(N1) &&
8347         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8348       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8349                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8350                                      &Flags), &Flags);
8351     }
8352
8353     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8354     if (N0.getOpcode() == ISD::FMUL &&
8355         isConstantFPBuildVectorOrConstantFP(N1) &&
8356         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8357       return DAG.getNode(ISD::FMA, dl, VT,
8358                          N0.getOperand(0),
8359                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8360                                      &Flags),
8361                          N2);
8362     }
8363   }
8364
8365   // (fma x, 1, y) -> (fadd x, y)
8366   // (fma x, -1, y) -> (fadd (fneg x), y)
8367   if (N1CFP) {
8368     if (N1CFP->isExactlyValue(1.0))
8369       // TODO: The FMA node should have flags that propagate to this node.
8370       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8371
8372     if (N1CFP->isExactlyValue(-1.0) &&
8373         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8374       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8375       AddToWorklist(RHSNeg.getNode());
8376       // TODO: The FMA node should have flags that propagate to this node.
8377       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8378     }
8379   }
8380
8381   if (Options.UnsafeFPMath) {
8382     // (fma x, c, x) -> (fmul x, (c+1))
8383     if (N1CFP && N0 == N2) {
8384     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8385                          DAG.getNode(ISD::FADD, dl, VT,
8386                                      N1, DAG.getConstantFP(1.0, dl, VT),
8387                                      &Flags), &Flags);
8388     }
8389
8390     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8391     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8392       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8393                          DAG.getNode(ISD::FADD, dl, VT,
8394                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8395                                      &Flags), &Flags);
8396     }
8397   }
8398
8399   return SDValue();
8400 }
8401
8402 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8403 // reciprocal.
8404 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8405 // Notice that this is not always beneficial. One reason is different target
8406 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8407 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8408 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8409 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8410   if (!DAG.getTarget().Options.UnsafeFPMath)
8411     return SDValue();
8412
8413   // Skip if current node is a reciprocal.
8414   SDValue N0 = N->getOperand(0);
8415   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8416   if (N0CFP && N0CFP->isExactlyValue(1.0))
8417     return SDValue();
8418
8419   // Exit early if the target does not want this transform or if there can't
8420   // possibly be enough uses of the divisor to make the transform worthwhile.
8421   SDValue N1 = N->getOperand(1);
8422   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8423   if (!MinUses || N1->use_size() < MinUses)
8424     return SDValue();
8425
8426   // Find all FDIV users of the same divisor.
8427   // Use a set because duplicates may be present in the user list.
8428   SetVector<SDNode *> Users;
8429   for (auto *U : N1->uses())
8430     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8431       Users.insert(U);
8432
8433   // Now that we have the actual number of divisor uses, make sure it meets
8434   // the minimum threshold specified by the target.
8435   if (Users.size() < MinUses)
8436     return SDValue();
8437
8438   EVT VT = N->getValueType(0);
8439   SDLoc DL(N);
8440   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8441   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8442   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8443
8444   // Dividend / Divisor -> Dividend * Reciprocal
8445   for (auto *U : Users) {
8446     SDValue Dividend = U->getOperand(0);
8447     if (Dividend != FPOne) {
8448       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8449                                     Reciprocal, Flags);
8450       CombineTo(U, NewNode);
8451     } else if (U != Reciprocal.getNode()) {
8452       // In the absence of fast-math-flags, this user node is always the
8453       // same node as Reciprocal, but with FMF they may be different nodes.
8454       CombineTo(U, Reciprocal);
8455     }
8456   }
8457   return SDValue(N, 0);  // N was replaced.
8458 }
8459
8460 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8461   SDValue N0 = N->getOperand(0);
8462   SDValue N1 = N->getOperand(1);
8463   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8464   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8465   EVT VT = N->getValueType(0);
8466   SDLoc DL(N);
8467   const TargetOptions &Options = DAG.getTarget().Options;
8468   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8469
8470   // fold vector ops
8471   if (VT.isVector())
8472     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8473       return FoldedVOp;
8474
8475   // fold (fdiv c1, c2) -> c1/c2
8476   if (N0CFP && N1CFP)
8477     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8478
8479   if (Options.UnsafeFPMath) {
8480     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8481     if (N1CFP) {
8482       // Compute the reciprocal 1.0 / c2.
8483       APFloat N1APF = N1CFP->getValueAPF();
8484       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8485       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8486       // Only do the transform if the reciprocal is a legal fp immediate that
8487       // isn't too nasty (eg NaN, denormal, ...).
8488       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8489           (!LegalOperations ||
8490            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8491            // backend)... we should handle this gracefully after Legalize.
8492            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8493            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8494            TLI.isFPImmLegal(Recip, VT)))
8495         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8496                            DAG.getConstantFP(Recip, DL, VT), Flags);
8497     }
8498
8499     // If this FDIV is part of a reciprocal square root, it may be folded
8500     // into a target-specific square root estimate instruction.
8501     if (N1.getOpcode() == ISD::FSQRT) {
8502       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8503         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8504       }
8505     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8506                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8507       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8508                                           Flags)) {
8509         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8510         AddToWorklist(RV.getNode());
8511         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8512       }
8513     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8514                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8515       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8516                                           Flags)) {
8517         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8518         AddToWorklist(RV.getNode());
8519         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8520       }
8521     } else if (N1.getOpcode() == ISD::FMUL) {
8522       // Look through an FMUL. Even though this won't remove the FDIV directly,
8523       // it's still worthwhile to get rid of the FSQRT if possible.
8524       SDValue SqrtOp;
8525       SDValue OtherOp;
8526       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8527         SqrtOp = N1.getOperand(0);
8528         OtherOp = N1.getOperand(1);
8529       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8530         SqrtOp = N1.getOperand(1);
8531         OtherOp = N1.getOperand(0);
8532       }
8533       if (SqrtOp.getNode()) {
8534         // We found a FSQRT, so try to make this fold:
8535         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8536         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8537           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8538           AddToWorklist(RV.getNode());
8539           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8540         }
8541       }
8542     }
8543
8544     // Fold into a reciprocal estimate and multiply instead of a real divide.
8545     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8546       AddToWorklist(RV.getNode());
8547       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8548     }
8549   }
8550
8551   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8552   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8553     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8554       // Both can be negated for free, check to see if at least one is cheaper
8555       // negated.
8556       if (LHSNeg == 2 || RHSNeg == 2)
8557         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8558                            GetNegatedExpression(N0, DAG, LegalOperations),
8559                            GetNegatedExpression(N1, DAG, LegalOperations),
8560                            Flags);
8561     }
8562   }
8563
8564   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8565     return CombineRepeatedDivisors;
8566
8567   return SDValue();
8568 }
8569
8570 SDValue DAGCombiner::visitFREM(SDNode *N) {
8571   SDValue N0 = N->getOperand(0);
8572   SDValue N1 = N->getOperand(1);
8573   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8574   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8575   EVT VT = N->getValueType(0);
8576
8577   // fold (frem c1, c2) -> fmod(c1,c2)
8578   if (N0CFP && N1CFP)
8579     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8580                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8581
8582   return SDValue();
8583 }
8584
8585 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8586   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8587     return SDValue();
8588
8589   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8590   // For now, create a Flags object for use with all unsafe math transforms.
8591   SDNodeFlags Flags;
8592   Flags.setUnsafeAlgebra(true);
8593
8594   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8595   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8596   if (!RV)
8597     return SDValue();
8598
8599   EVT VT = RV.getValueType();
8600   SDLoc DL(N);
8601   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8602   AddToWorklist(RV.getNode());
8603
8604   // Unfortunately, RV is now NaN if the input was exactly 0.
8605   // Select out this case and force the answer to 0.
8606   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8607   EVT CCVT = getSetCCResultType(VT);
8608   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8609   AddToWorklist(ZeroCmp.getNode());
8610   AddToWorklist(RV.getNode());
8611
8612   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8613                      ZeroCmp, Zero, RV);
8614 }
8615
8616 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8617   SDValue N0 = N->getOperand(0);
8618   SDValue N1 = N->getOperand(1);
8619   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8620   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8621   EVT VT = N->getValueType(0);
8622
8623   if (N0CFP && N1CFP)  // Constant fold
8624     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8625
8626   if (N1CFP) {
8627     const APFloat& V = N1CFP->getValueAPF();
8628     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8629     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8630     if (!V.isNegative()) {
8631       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8632         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8633     } else {
8634       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8635         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8636                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8637     }
8638   }
8639
8640   // copysign(fabs(x), y) -> copysign(x, y)
8641   // copysign(fneg(x), y) -> copysign(x, y)
8642   // copysign(copysign(x,z), y) -> copysign(x, y)
8643   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8644       N0.getOpcode() == ISD::FCOPYSIGN)
8645     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8646                        N0.getOperand(0), N1);
8647
8648   // copysign(x, abs(y)) -> abs(x)
8649   if (N1.getOpcode() == ISD::FABS)
8650     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8651
8652   // copysign(x, copysign(y,z)) -> copysign(x, z)
8653   if (N1.getOpcode() == ISD::FCOPYSIGN)
8654     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8655                        N0, N1.getOperand(1));
8656
8657   // copysign(x, fp_extend(y)) -> copysign(x, y)
8658   // copysign(x, fp_round(y)) -> copysign(x, y)
8659   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8660     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8661                        N0, N1.getOperand(0));
8662
8663   return SDValue();
8664 }
8665
8666 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8667   SDValue N0 = N->getOperand(0);
8668   EVT VT = N->getValueType(0);
8669   EVT OpVT = N0.getValueType();
8670
8671   // fold (sint_to_fp c1) -> c1fp
8672   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8673       // ...but only if the target supports immediate floating-point values
8674       (!LegalOperations ||
8675        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8676     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8677
8678   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8679   // but UINT_TO_FP is legal on this target, try to convert.
8680   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8681       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8682     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8683     if (DAG.SignBitIsZero(N0))
8684       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8685   }
8686
8687   // The next optimizations are desirable only if SELECT_CC can be lowered.
8688   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8689     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8690     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8691         !VT.isVector() &&
8692         (!LegalOperations ||
8693          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8694       SDLoc DL(N);
8695       SDValue Ops[] =
8696         { N0.getOperand(0), N0.getOperand(1),
8697           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8698           N0.getOperand(2) };
8699       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8700     }
8701
8702     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8703     //      (select_cc x, y, 1.0, 0.0,, cc)
8704     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8705         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8706         (!LegalOperations ||
8707          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8708       SDLoc DL(N);
8709       SDValue Ops[] =
8710         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8711           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8712           N0.getOperand(0).getOperand(2) };
8713       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8714     }
8715   }
8716
8717   return SDValue();
8718 }
8719
8720 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8721   SDValue N0 = N->getOperand(0);
8722   EVT VT = N->getValueType(0);
8723   EVT OpVT = N0.getValueType();
8724
8725   // fold (uint_to_fp c1) -> c1fp
8726   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8727       // ...but only if the target supports immediate floating-point values
8728       (!LegalOperations ||
8729        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8730     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8731
8732   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8733   // but SINT_TO_FP is legal on this target, try to convert.
8734   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8735       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8736     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8737     if (DAG.SignBitIsZero(N0))
8738       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8739   }
8740
8741   // The next optimizations are desirable only if SELECT_CC can be lowered.
8742   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8743     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8744
8745     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8746         (!LegalOperations ||
8747          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8748       SDLoc DL(N);
8749       SDValue Ops[] =
8750         { N0.getOperand(0), N0.getOperand(1),
8751           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8752           N0.getOperand(2) };
8753       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8754     }
8755   }
8756
8757   return SDValue();
8758 }
8759
8760 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8761 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8762   SDValue N0 = N->getOperand(0);
8763   EVT VT = N->getValueType(0);
8764
8765   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8766     return SDValue();
8767
8768   SDValue Src = N0.getOperand(0);
8769   EVT SrcVT = Src.getValueType();
8770   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8771   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8772
8773   // We can safely assume the conversion won't overflow the output range,
8774   // because (for example) (uint8_t)18293.f is undefined behavior.
8775
8776   // Since we can assume the conversion won't overflow, our decision as to
8777   // whether the input will fit in the float should depend on the minimum
8778   // of the input range and output range.
8779
8780   // This means this is also safe for a signed input and unsigned output, since
8781   // a negative input would lead to undefined behavior.
8782   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8783   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8784   unsigned ActualSize = std::min(InputSize, OutputSize);
8785   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8786
8787   // We can only fold away the float conversion if the input range can be
8788   // represented exactly in the float range.
8789   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8790     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8791       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8792                                                        : ISD::ZERO_EXTEND;
8793       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8794     }
8795     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8796       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8797     if (SrcVT == VT)
8798       return Src;
8799     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8800   }
8801   return SDValue();
8802 }
8803
8804 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8805   SDValue N0 = N->getOperand(0);
8806   EVT VT = N->getValueType(0);
8807
8808   // fold (fp_to_sint c1fp) -> c1
8809   if (isConstantFPBuildVectorOrConstantFP(N0))
8810     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8811
8812   return FoldIntToFPToInt(N, DAG);
8813 }
8814
8815 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8816   SDValue N0 = N->getOperand(0);
8817   EVT VT = N->getValueType(0);
8818
8819   // fold (fp_to_uint c1fp) -> c1
8820   if (isConstantFPBuildVectorOrConstantFP(N0))
8821     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8822
8823   return FoldIntToFPToInt(N, DAG);
8824 }
8825
8826 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8827   SDValue N0 = N->getOperand(0);
8828   SDValue N1 = N->getOperand(1);
8829   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8830   EVT VT = N->getValueType(0);
8831
8832   // fold (fp_round c1fp) -> c1fp
8833   if (N0CFP)
8834     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8835
8836   // fold (fp_round (fp_extend x)) -> x
8837   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8838     return N0.getOperand(0);
8839
8840   // fold (fp_round (fp_round x)) -> (fp_round x)
8841   if (N0.getOpcode() == ISD::FP_ROUND) {
8842     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8843     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8844     // If the first fp_round isn't a value preserving truncation, it might
8845     // introduce a tie in the second fp_round, that wouldn't occur in the
8846     // single-step fp_round we want to fold to.
8847     // In other words, double rounding isn't the same as rounding.
8848     // Also, this is a value preserving truncation iff both fp_round's are.
8849     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8850       SDLoc DL(N);
8851       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8852                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8853     }
8854   }
8855
8856   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8857   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8858     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8859                               N0.getOperand(0), N1);
8860     AddToWorklist(Tmp.getNode());
8861     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8862                        Tmp, N0.getOperand(1));
8863   }
8864
8865   return SDValue();
8866 }
8867
8868 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8869   SDValue N0 = N->getOperand(0);
8870   EVT VT = N->getValueType(0);
8871   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8872   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8873
8874   // fold (fp_round_inreg c1fp) -> c1fp
8875   if (N0CFP && isTypeLegal(EVT)) {
8876     SDLoc DL(N);
8877     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8878     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8879   }
8880
8881   return SDValue();
8882 }
8883
8884 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8885   SDValue N0 = N->getOperand(0);
8886   EVT VT = N->getValueType(0);
8887
8888   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8889   if (N->hasOneUse() &&
8890       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8891     return SDValue();
8892
8893   // fold (fp_extend c1fp) -> c1fp
8894   if (isConstantFPBuildVectorOrConstantFP(N0))
8895     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8896
8897   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8898   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8899       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8900     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8901
8902   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8903   // value of X.
8904   if (N0.getOpcode() == ISD::FP_ROUND
8905       && N0.getNode()->getConstantOperandVal(1) == 1) {
8906     SDValue In = N0.getOperand(0);
8907     if (In.getValueType() == VT) return In;
8908     if (VT.bitsLT(In.getValueType()))
8909       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8910                          In, N0.getOperand(1));
8911     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8912   }
8913
8914   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8915   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8916        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8917     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8918     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8919                                      LN0->getChain(),
8920                                      LN0->getBasePtr(), N0.getValueType(),
8921                                      LN0->getMemOperand());
8922     CombineTo(N, ExtLoad);
8923     CombineTo(N0.getNode(),
8924               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8925                           N0.getValueType(), ExtLoad,
8926                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8927               ExtLoad.getValue(1));
8928     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8929   }
8930
8931   return SDValue();
8932 }
8933
8934 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8935   SDValue N0 = N->getOperand(0);
8936   EVT VT = N->getValueType(0);
8937
8938   // fold (fceil c1) -> fceil(c1)
8939   if (isConstantFPBuildVectorOrConstantFP(N0))
8940     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8941
8942   return SDValue();
8943 }
8944
8945 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8946   SDValue N0 = N->getOperand(0);
8947   EVT VT = N->getValueType(0);
8948
8949   // fold (ftrunc c1) -> ftrunc(c1)
8950   if (isConstantFPBuildVectorOrConstantFP(N0))
8951     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8952
8953   return SDValue();
8954 }
8955
8956 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8957   SDValue N0 = N->getOperand(0);
8958   EVT VT = N->getValueType(0);
8959
8960   // fold (ffloor c1) -> ffloor(c1)
8961   if (isConstantFPBuildVectorOrConstantFP(N0))
8962     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8963
8964   return SDValue();
8965 }
8966
8967 // FIXME: FNEG and FABS have a lot in common; refactor.
8968 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8969   SDValue N0 = N->getOperand(0);
8970   EVT VT = N->getValueType(0);
8971
8972   // Constant fold FNEG.
8973   if (isConstantFPBuildVectorOrConstantFP(N0))
8974     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8975
8976   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8977                          &DAG.getTarget().Options))
8978     return GetNegatedExpression(N0, DAG, LegalOperations);
8979
8980   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8981   // constant pool values.
8982   if (!TLI.isFNegFree(VT) &&
8983       N0.getOpcode() == ISD::BITCAST &&
8984       N0.getNode()->hasOneUse()) {
8985     SDValue Int = N0.getOperand(0);
8986     EVT IntVT = Int.getValueType();
8987     if (IntVT.isInteger() && !IntVT.isVector()) {
8988       APInt SignMask;
8989       if (N0.getValueType().isVector()) {
8990         // For a vector, get a mask such as 0x80... per scalar element
8991         // and splat it.
8992         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8993         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8994       } else {
8995         // For a scalar, just generate 0x80...
8996         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8997       }
8998       SDLoc DL0(N0);
8999       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9000                         DAG.getConstant(SignMask, DL0, IntVT));
9001       AddToWorklist(Int.getNode());
9002       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9003     }
9004   }
9005
9006   // (fneg (fmul c, x)) -> (fmul -c, x)
9007   if (N0.getOpcode() == ISD::FMUL &&
9008       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9009     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9010     if (CFP1) {
9011       APFloat CVal = CFP1->getValueAPF();
9012       CVal.changeSign();
9013       if (Level >= AfterLegalizeDAG &&
9014           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
9015            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
9016         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9017                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9018                                        N0.getOperand(1)),
9019                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9020     }
9021   }
9022
9023   return SDValue();
9024 }
9025
9026 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9027   SDValue N0 = N->getOperand(0);
9028   SDValue N1 = N->getOperand(1);
9029   EVT VT = N->getValueType(0);
9030   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9031   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9032
9033   if (N0CFP && N1CFP) {
9034     const APFloat &C0 = N0CFP->getValueAPF();
9035     const APFloat &C1 = N1CFP->getValueAPF();
9036     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9037   }
9038
9039   // Canonicalize to constant on RHS.
9040   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9041      !isConstantFPBuildVectorOrConstantFP(N1))
9042     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9043
9044   return SDValue();
9045 }
9046
9047 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9048   SDValue N0 = N->getOperand(0);
9049   SDValue N1 = N->getOperand(1);
9050   EVT VT = N->getValueType(0);
9051   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9052   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9053
9054   if (N0CFP && N1CFP) {
9055     const APFloat &C0 = N0CFP->getValueAPF();
9056     const APFloat &C1 = N1CFP->getValueAPF();
9057     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9058   }
9059
9060   // Canonicalize to constant on RHS.
9061   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9062      !isConstantFPBuildVectorOrConstantFP(N1))
9063     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9064
9065   return SDValue();
9066 }
9067
9068 SDValue DAGCombiner::visitFABS(SDNode *N) {
9069   SDValue N0 = N->getOperand(0);
9070   EVT VT = N->getValueType(0);
9071
9072   // fold (fabs c1) -> fabs(c1)
9073   if (isConstantFPBuildVectorOrConstantFP(N0))
9074     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9075
9076   // fold (fabs (fabs x)) -> (fabs x)
9077   if (N0.getOpcode() == ISD::FABS)
9078     return N->getOperand(0);
9079
9080   // fold (fabs (fneg x)) -> (fabs x)
9081   // fold (fabs (fcopysign x, y)) -> (fabs x)
9082   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9083     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9084
9085   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9086   // constant pool values.
9087   if (!TLI.isFAbsFree(VT) &&
9088       N0.getOpcode() == ISD::BITCAST &&
9089       N0.getNode()->hasOneUse()) {
9090     SDValue Int = N0.getOperand(0);
9091     EVT IntVT = Int.getValueType();
9092     if (IntVT.isInteger() && !IntVT.isVector()) {
9093       APInt SignMask;
9094       if (N0.getValueType().isVector()) {
9095         // For a vector, get a mask such as 0x7f... per scalar element
9096         // and splat it.
9097         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9098         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9099       } else {
9100         // For a scalar, just generate 0x7f...
9101         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9102       }
9103       SDLoc DL(N0);
9104       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9105                         DAG.getConstant(SignMask, DL, IntVT));
9106       AddToWorklist(Int.getNode());
9107       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9108     }
9109   }
9110
9111   return SDValue();
9112 }
9113
9114 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9115   SDValue Chain = N->getOperand(0);
9116   SDValue N1 = N->getOperand(1);
9117   SDValue N2 = N->getOperand(2);
9118
9119   // If N is a constant we could fold this into a fallthrough or unconditional
9120   // branch. However that doesn't happen very often in normal code, because
9121   // Instcombine/SimplifyCFG should have handled the available opportunities.
9122   // If we did this folding here, it would be necessary to update the
9123   // MachineBasicBlock CFG, which is awkward.
9124
9125   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9126   // on the target.
9127   if (N1.getOpcode() == ISD::SETCC &&
9128       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9129                                    N1.getOperand(0).getValueType())) {
9130     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9131                        Chain, N1.getOperand(2),
9132                        N1.getOperand(0), N1.getOperand(1), N2);
9133   }
9134
9135   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9136       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9137        (N1.getOperand(0).hasOneUse() &&
9138         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9139     SDNode *Trunc = nullptr;
9140     if (N1.getOpcode() == ISD::TRUNCATE) {
9141       // Look pass the truncate.
9142       Trunc = N1.getNode();
9143       N1 = N1.getOperand(0);
9144     }
9145
9146     // Match this pattern so that we can generate simpler code:
9147     //
9148     //   %a = ...
9149     //   %b = and i32 %a, 2
9150     //   %c = srl i32 %b, 1
9151     //   brcond i32 %c ...
9152     //
9153     // into
9154     //
9155     //   %a = ...
9156     //   %b = and i32 %a, 2
9157     //   %c = setcc eq %b, 0
9158     //   brcond %c ...
9159     //
9160     // This applies only when the AND constant value has one bit set and the
9161     // SRL constant is equal to the log2 of the AND constant. The back-end is
9162     // smart enough to convert the result into a TEST/JMP sequence.
9163     SDValue Op0 = N1.getOperand(0);
9164     SDValue Op1 = N1.getOperand(1);
9165
9166     if (Op0.getOpcode() == ISD::AND &&
9167         Op1.getOpcode() == ISD::Constant) {
9168       SDValue AndOp1 = Op0.getOperand(1);
9169
9170       if (AndOp1.getOpcode() == ISD::Constant) {
9171         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9172
9173         if (AndConst.isPowerOf2() &&
9174             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9175           SDLoc DL(N);
9176           SDValue SetCC =
9177             DAG.getSetCC(DL,
9178                          getSetCCResultType(Op0.getValueType()),
9179                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9180                          ISD::SETNE);
9181
9182           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9183                                           MVT::Other, Chain, SetCC, N2);
9184           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9185           // will convert it back to (X & C1) >> C2.
9186           CombineTo(N, NewBRCond, false);
9187           // Truncate is dead.
9188           if (Trunc)
9189             deleteAndRecombine(Trunc);
9190           // Replace the uses of SRL with SETCC
9191           WorklistRemover DeadNodes(*this);
9192           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9193           deleteAndRecombine(N1.getNode());
9194           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9195         }
9196       }
9197     }
9198
9199     if (Trunc)
9200       // Restore N1 if the above transformation doesn't match.
9201       N1 = N->getOperand(1);
9202   }
9203
9204   // Transform br(xor(x, y)) -> br(x != y)
9205   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9206   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9207     SDNode *TheXor = N1.getNode();
9208     SDValue Op0 = TheXor->getOperand(0);
9209     SDValue Op1 = TheXor->getOperand(1);
9210     if (Op0.getOpcode() == Op1.getOpcode()) {
9211       // Avoid missing important xor optimizations.
9212       if (SDValue Tmp = visitXOR(TheXor)) {
9213         if (Tmp.getNode() != TheXor) {
9214           DEBUG(dbgs() << "\nReplacing.8 ";
9215                 TheXor->dump(&DAG);
9216                 dbgs() << "\nWith: ";
9217                 Tmp.getNode()->dump(&DAG);
9218                 dbgs() << '\n');
9219           WorklistRemover DeadNodes(*this);
9220           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9221           deleteAndRecombine(TheXor);
9222           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9223                              MVT::Other, Chain, Tmp, N2);
9224         }
9225
9226         // visitXOR has changed XOR's operands or replaced the XOR completely,
9227         // bail out.
9228         return SDValue(N, 0);
9229       }
9230     }
9231
9232     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9233       bool Equal = false;
9234       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9235           Op0.getOpcode() == ISD::XOR) {
9236         TheXor = Op0.getNode();
9237         Equal = true;
9238       }
9239
9240       EVT SetCCVT = N1.getValueType();
9241       if (LegalTypes)
9242         SetCCVT = getSetCCResultType(SetCCVT);
9243       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9244                                    SetCCVT,
9245                                    Op0, Op1,
9246                                    Equal ? ISD::SETEQ : ISD::SETNE);
9247       // Replace the uses of XOR with SETCC
9248       WorklistRemover DeadNodes(*this);
9249       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9250       deleteAndRecombine(N1.getNode());
9251       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9252                          MVT::Other, Chain, SetCC, N2);
9253     }
9254   }
9255
9256   return SDValue();
9257 }
9258
9259 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9260 //
9261 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9262   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9263   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9264
9265   // If N is a constant we could fold this into a fallthrough or unconditional
9266   // branch. However that doesn't happen very often in normal code, because
9267   // Instcombine/SimplifyCFG should have handled the available opportunities.
9268   // If we did this folding here, it would be necessary to update the
9269   // MachineBasicBlock CFG, which is awkward.
9270
9271   // Use SimplifySetCC to simplify SETCC's.
9272   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9273                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9274                                false);
9275   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9276
9277   // fold to a simpler setcc
9278   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9279     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9280                        N->getOperand(0), Simp.getOperand(2),
9281                        Simp.getOperand(0), Simp.getOperand(1),
9282                        N->getOperand(4));
9283
9284   return SDValue();
9285 }
9286
9287 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9288 /// and that N may be folded in the load / store addressing mode.
9289 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9290                                     SelectionDAG &DAG,
9291                                     const TargetLowering &TLI) {
9292   EVT VT;
9293   unsigned AS;
9294
9295   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9296     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9297       return false;
9298     VT = LD->getMemoryVT();
9299     AS = LD->getAddressSpace();
9300   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9301     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9302       return false;
9303     VT = ST->getMemoryVT();
9304     AS = ST->getAddressSpace();
9305   } else
9306     return false;
9307
9308   TargetLowering::AddrMode AM;
9309   if (N->getOpcode() == ISD::ADD) {
9310     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9311     if (Offset)
9312       // [reg +/- imm]
9313       AM.BaseOffs = Offset->getSExtValue();
9314     else
9315       // [reg +/- reg]
9316       AM.Scale = 1;
9317   } else if (N->getOpcode() == ISD::SUB) {
9318     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9319     if (Offset)
9320       // [reg +/- imm]
9321       AM.BaseOffs = -Offset->getSExtValue();
9322     else
9323       // [reg +/- reg]
9324       AM.Scale = 1;
9325   } else
9326     return false;
9327
9328   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9329                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9330 }
9331
9332 /// Try turning a load/store into a pre-indexed load/store when the base
9333 /// pointer is an add or subtract and it has other uses besides the load/store.
9334 /// After the transformation, the new indexed load/store has effectively folded
9335 /// the add/subtract in and all of its other uses are redirected to the
9336 /// new load/store.
9337 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9338   if (Level < AfterLegalizeDAG)
9339     return false;
9340
9341   bool isLoad = true;
9342   SDValue Ptr;
9343   EVT VT;
9344   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9345     if (LD->isIndexed())
9346       return false;
9347     VT = LD->getMemoryVT();
9348     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9349         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9350       return false;
9351     Ptr = LD->getBasePtr();
9352   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9353     if (ST->isIndexed())
9354       return false;
9355     VT = ST->getMemoryVT();
9356     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9357         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9358       return false;
9359     Ptr = ST->getBasePtr();
9360     isLoad = false;
9361   } else {
9362     return false;
9363   }
9364
9365   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9366   // out.  There is no reason to make this a preinc/predec.
9367   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9368       Ptr.getNode()->hasOneUse())
9369     return false;
9370
9371   // Ask the target to do addressing mode selection.
9372   SDValue BasePtr;
9373   SDValue Offset;
9374   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9375   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9376     return false;
9377
9378   // Backends without true r+i pre-indexed forms may need to pass a
9379   // constant base with a variable offset so that constant coercion
9380   // will work with the patterns in canonical form.
9381   bool Swapped = false;
9382   if (isa<ConstantSDNode>(BasePtr)) {
9383     std::swap(BasePtr, Offset);
9384     Swapped = true;
9385   }
9386
9387   // Don't create a indexed load / store with zero offset.
9388   if (isNullConstant(Offset))
9389     return false;
9390
9391   // Try turning it into a pre-indexed load / store except when:
9392   // 1) The new base ptr is a frame index.
9393   // 2) If N is a store and the new base ptr is either the same as or is a
9394   //    predecessor of the value being stored.
9395   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9396   //    that would create a cycle.
9397   // 4) All uses are load / store ops that use it as old base ptr.
9398
9399   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9400   // (plus the implicit offset) to a register to preinc anyway.
9401   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9402     return false;
9403
9404   // Check #2.
9405   if (!isLoad) {
9406     SDValue Val = cast<StoreSDNode>(N)->getValue();
9407     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9408       return false;
9409   }
9410
9411   // If the offset is a constant, there may be other adds of constants that
9412   // can be folded with this one. We should do this to avoid having to keep
9413   // a copy of the original base pointer.
9414   SmallVector<SDNode *, 16> OtherUses;
9415   if (isa<ConstantSDNode>(Offset))
9416     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9417                               UE = BasePtr.getNode()->use_end();
9418          UI != UE; ++UI) {
9419       SDUse &Use = UI.getUse();
9420       // Skip the use that is Ptr and uses of other results from BasePtr's
9421       // node (important for nodes that return multiple results).
9422       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9423         continue;
9424
9425       if (Use.getUser()->isPredecessorOf(N))
9426         continue;
9427
9428       if (Use.getUser()->getOpcode() != ISD::ADD &&
9429           Use.getUser()->getOpcode() != ISD::SUB) {
9430         OtherUses.clear();
9431         break;
9432       }
9433
9434       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9435       if (!isa<ConstantSDNode>(Op1)) {
9436         OtherUses.clear();
9437         break;
9438       }
9439
9440       // FIXME: In some cases, we can be smarter about this.
9441       if (Op1.getValueType() != Offset.getValueType()) {
9442         OtherUses.clear();
9443         break;
9444       }
9445
9446       OtherUses.push_back(Use.getUser());
9447     }
9448
9449   if (Swapped)
9450     std::swap(BasePtr, Offset);
9451
9452   // Now check for #3 and #4.
9453   bool RealUse = false;
9454
9455   // Caches for hasPredecessorHelper
9456   SmallPtrSet<const SDNode *, 32> Visited;
9457   SmallVector<const SDNode *, 16> Worklist;
9458
9459   for (SDNode *Use : Ptr.getNode()->uses()) {
9460     if (Use == N)
9461       continue;
9462     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9463       return false;
9464
9465     // If Ptr may be folded in addressing mode of other use, then it's
9466     // not profitable to do this transformation.
9467     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9468       RealUse = true;
9469   }
9470
9471   if (!RealUse)
9472     return false;
9473
9474   SDValue Result;
9475   if (isLoad)
9476     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9477                                 BasePtr, Offset, AM);
9478   else
9479     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9480                                  BasePtr, Offset, AM);
9481   ++PreIndexedNodes;
9482   ++NodesCombined;
9483   DEBUG(dbgs() << "\nReplacing.4 ";
9484         N->dump(&DAG);
9485         dbgs() << "\nWith: ";
9486         Result.getNode()->dump(&DAG);
9487         dbgs() << '\n');
9488   WorklistRemover DeadNodes(*this);
9489   if (isLoad) {
9490     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9491     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9492   } else {
9493     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9494   }
9495
9496   // Finally, since the node is now dead, remove it from the graph.
9497   deleteAndRecombine(N);
9498
9499   if (Swapped)
9500     std::swap(BasePtr, Offset);
9501
9502   // Replace other uses of BasePtr that can be updated to use Ptr
9503   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9504     unsigned OffsetIdx = 1;
9505     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9506       OffsetIdx = 0;
9507     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9508            BasePtr.getNode() && "Expected BasePtr operand");
9509
9510     // We need to replace ptr0 in the following expression:
9511     //   x0 * offset0 + y0 * ptr0 = t0
9512     // knowing that
9513     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9514     //
9515     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9516     // indexed load/store and the expresion that needs to be re-written.
9517     //
9518     // Therefore, we have:
9519     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9520
9521     ConstantSDNode *CN =
9522       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9523     int X0, X1, Y0, Y1;
9524     APInt Offset0 = CN->getAPIntValue();
9525     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9526
9527     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9528     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9529     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9530     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9531
9532     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9533
9534     APInt CNV = Offset0;
9535     if (X0 < 0) CNV = -CNV;
9536     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9537     else CNV = CNV - Offset1;
9538
9539     SDLoc DL(OtherUses[i]);
9540
9541     // We can now generate the new expression.
9542     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9543     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9544
9545     SDValue NewUse = DAG.getNode(Opcode,
9546                                  DL,
9547                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9548     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9549     deleteAndRecombine(OtherUses[i]);
9550   }
9551
9552   // Replace the uses of Ptr with uses of the updated base value.
9553   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9554   deleteAndRecombine(Ptr.getNode());
9555
9556   return true;
9557 }
9558
9559 /// Try to combine a load/store with a add/sub of the base pointer node into a
9560 /// post-indexed load/store. The transformation folded the add/subtract into the
9561 /// new indexed load/store effectively and all of its uses are redirected to the
9562 /// new load/store.
9563 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9564   if (Level < AfterLegalizeDAG)
9565     return false;
9566
9567   bool isLoad = true;
9568   SDValue Ptr;
9569   EVT VT;
9570   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9571     if (LD->isIndexed())
9572       return false;
9573     VT = LD->getMemoryVT();
9574     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9575         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9576       return false;
9577     Ptr = LD->getBasePtr();
9578   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9579     if (ST->isIndexed())
9580       return false;
9581     VT = ST->getMemoryVT();
9582     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9583         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9584       return false;
9585     Ptr = ST->getBasePtr();
9586     isLoad = false;
9587   } else {
9588     return false;
9589   }
9590
9591   if (Ptr.getNode()->hasOneUse())
9592     return false;
9593
9594   for (SDNode *Op : Ptr.getNode()->uses()) {
9595     if (Op == N ||
9596         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9597       continue;
9598
9599     SDValue BasePtr;
9600     SDValue Offset;
9601     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9602     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9603       // Don't create a indexed load / store with zero offset.
9604       if (isNullConstant(Offset))
9605         continue;
9606
9607       // Try turning it into a post-indexed load / store except when
9608       // 1) All uses are load / store ops that use it as base ptr (and
9609       //    it may be folded as addressing mmode).
9610       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9611       //    nor a successor of N. Otherwise, if Op is folded that would
9612       //    create a cycle.
9613
9614       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9615         continue;
9616
9617       // Check for #1.
9618       bool TryNext = false;
9619       for (SDNode *Use : BasePtr.getNode()->uses()) {
9620         if (Use == Ptr.getNode())
9621           continue;
9622
9623         // If all the uses are load / store addresses, then don't do the
9624         // transformation.
9625         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9626           bool RealUse = false;
9627           for (SDNode *UseUse : Use->uses()) {
9628             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9629               RealUse = true;
9630           }
9631
9632           if (!RealUse) {
9633             TryNext = true;
9634             break;
9635           }
9636         }
9637       }
9638
9639       if (TryNext)
9640         continue;
9641
9642       // Check for #2
9643       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9644         SDValue Result = isLoad
9645           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9646                                BasePtr, Offset, AM)
9647           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9648                                 BasePtr, Offset, AM);
9649         ++PostIndexedNodes;
9650         ++NodesCombined;
9651         DEBUG(dbgs() << "\nReplacing.5 ";
9652               N->dump(&DAG);
9653               dbgs() << "\nWith: ";
9654               Result.getNode()->dump(&DAG);
9655               dbgs() << '\n');
9656         WorklistRemover DeadNodes(*this);
9657         if (isLoad) {
9658           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9659           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9660         } else {
9661           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9662         }
9663
9664         // Finally, since the node is now dead, remove it from the graph.
9665         deleteAndRecombine(N);
9666
9667         // Replace the uses of Use with uses of the updated base value.
9668         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9669                                       Result.getValue(isLoad ? 1 : 0));
9670         deleteAndRecombine(Op);
9671         return true;
9672       }
9673     }
9674   }
9675
9676   return false;
9677 }
9678
9679 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9680 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9681   ISD::MemIndexedMode AM = LD->getAddressingMode();
9682   assert(AM != ISD::UNINDEXED);
9683   SDValue BP = LD->getOperand(1);
9684   SDValue Inc = LD->getOperand(2);
9685
9686   // Some backends use TargetConstants for load offsets, but don't expect
9687   // TargetConstants in general ADD nodes. We can convert these constants into
9688   // regular Constants (if the constant is not opaque).
9689   assert((Inc.getOpcode() != ISD::TargetConstant ||
9690           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9691          "Cannot split out indexing using opaque target constants");
9692   if (Inc.getOpcode() == ISD::TargetConstant) {
9693     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9694     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9695                           ConstInc->getValueType(0));
9696   }
9697
9698   unsigned Opc =
9699       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9700   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9701 }
9702
9703 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9704   LoadSDNode *LD  = cast<LoadSDNode>(N);
9705   SDValue Chain = LD->getChain();
9706   SDValue Ptr   = LD->getBasePtr();
9707
9708   // If load is not volatile and there are no uses of the loaded value (and
9709   // the updated indexed value in case of indexed loads), change uses of the
9710   // chain value into uses of the chain input (i.e. delete the dead load).
9711   if (!LD->isVolatile()) {
9712     if (N->getValueType(1) == MVT::Other) {
9713       // Unindexed loads.
9714       if (!N->hasAnyUseOfValue(0)) {
9715         // It's not safe to use the two value CombineTo variant here. e.g.
9716         // v1, chain2 = load chain1, loc
9717         // v2, chain3 = load chain2, loc
9718         // v3         = add v2, c
9719         // Now we replace use of chain2 with chain1.  This makes the second load
9720         // isomorphic to the one we are deleting, and thus makes this load live.
9721         DEBUG(dbgs() << "\nReplacing.6 ";
9722               N->dump(&DAG);
9723               dbgs() << "\nWith chain: ";
9724               Chain.getNode()->dump(&DAG);
9725               dbgs() << "\n");
9726         WorklistRemover DeadNodes(*this);
9727         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9728
9729         if (N->use_empty())
9730           deleteAndRecombine(N);
9731
9732         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9733       }
9734     } else {
9735       // Indexed loads.
9736       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9737
9738       // If this load has an opaque TargetConstant offset, then we cannot split
9739       // the indexing into an add/sub directly (that TargetConstant may not be
9740       // valid for a different type of node, and we cannot convert an opaque
9741       // target constant into a regular constant).
9742       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9743                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9744
9745       if (!N->hasAnyUseOfValue(0) &&
9746           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9747         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9748         SDValue Index;
9749         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9750           Index = SplitIndexingFromLoad(LD);
9751           // Try to fold the base pointer arithmetic into subsequent loads and
9752           // stores.
9753           AddUsersToWorklist(N);
9754         } else
9755           Index = DAG.getUNDEF(N->getValueType(1));
9756         DEBUG(dbgs() << "\nReplacing.7 ";
9757               N->dump(&DAG);
9758               dbgs() << "\nWith: ";
9759               Undef.getNode()->dump(&DAG);
9760               dbgs() << " and 2 other values\n");
9761         WorklistRemover DeadNodes(*this);
9762         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9763         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9764         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9765         deleteAndRecombine(N);
9766         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9767       }
9768     }
9769   }
9770
9771   // If this load is directly stored, replace the load value with the stored
9772   // value.
9773   // TODO: Handle store large -> read small portion.
9774   // TODO: Handle TRUNCSTORE/LOADEXT
9775   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9776     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9777       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9778       if (PrevST->getBasePtr() == Ptr &&
9779           PrevST->getValue().getValueType() == N->getValueType(0))
9780       return CombineTo(N, Chain.getOperand(1), Chain);
9781     }
9782   }
9783
9784   // Try to infer better alignment information than the load already has.
9785   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9786     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9787       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9788         SDValue NewLoad =
9789                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9790                               LD->getValueType(0),
9791                               Chain, Ptr, LD->getPointerInfo(),
9792                               LD->getMemoryVT(),
9793                               LD->isVolatile(), LD->isNonTemporal(),
9794                               LD->isInvariant(), Align, LD->getAAInfo());
9795         if (NewLoad.getNode() != N)
9796           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9797       }
9798     }
9799   }
9800
9801   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9802                                                   : DAG.getSubtarget().useAA();
9803 #ifndef NDEBUG
9804   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9805       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9806     UseAA = false;
9807 #endif
9808   if (UseAA && LD->isUnindexed()) {
9809     // Walk up chain skipping non-aliasing memory nodes.
9810     SDValue BetterChain = FindBetterChain(N, Chain);
9811
9812     // If there is a better chain.
9813     if (Chain != BetterChain) {
9814       SDValue ReplLoad;
9815
9816       // Replace the chain to void dependency.
9817       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9818         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9819                                BetterChain, Ptr, LD->getMemOperand());
9820       } else {
9821         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9822                                   LD->getValueType(0),
9823                                   BetterChain, Ptr, LD->getMemoryVT(),
9824                                   LD->getMemOperand());
9825       }
9826
9827       // Create token factor to keep old chain connected.
9828       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9829                                   MVT::Other, Chain, ReplLoad.getValue(1));
9830
9831       // Make sure the new and old chains are cleaned up.
9832       AddToWorklist(Token.getNode());
9833
9834       // Replace uses with load result and token factor. Don't add users
9835       // to work list.
9836       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9837     }
9838   }
9839
9840   // Try transforming N to an indexed load.
9841   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9842     return SDValue(N, 0);
9843
9844   // Try to slice up N to more direct loads if the slices are mapped to
9845   // different register banks or pairing can take place.
9846   if (SliceUpLoad(N))
9847     return SDValue(N, 0);
9848
9849   return SDValue();
9850 }
9851
9852 namespace {
9853 /// \brief Helper structure used to slice a load in smaller loads.
9854 /// Basically a slice is obtained from the following sequence:
9855 /// Origin = load Ty1, Base
9856 /// Shift = srl Ty1 Origin, CstTy Amount
9857 /// Inst = trunc Shift to Ty2
9858 ///
9859 /// Then, it will be rewriten into:
9860 /// Slice = load SliceTy, Base + SliceOffset
9861 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9862 ///
9863 /// SliceTy is deduced from the number of bits that are actually used to
9864 /// build Inst.
9865 struct LoadedSlice {
9866   /// \brief Helper structure used to compute the cost of a slice.
9867   struct Cost {
9868     /// Are we optimizing for code size.
9869     bool ForCodeSize;
9870     /// Various cost.
9871     unsigned Loads;
9872     unsigned Truncates;
9873     unsigned CrossRegisterBanksCopies;
9874     unsigned ZExts;
9875     unsigned Shift;
9876
9877     Cost(bool ForCodeSize = false)
9878         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9879           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9880
9881     /// \brief Get the cost of one isolated slice.
9882     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9883         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9884           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9885       EVT TruncType = LS.Inst->getValueType(0);
9886       EVT LoadedType = LS.getLoadedType();
9887       if (TruncType != LoadedType &&
9888           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9889         ZExts = 1;
9890     }
9891
9892     /// \brief Account for slicing gain in the current cost.
9893     /// Slicing provide a few gains like removing a shift or a
9894     /// truncate. This method allows to grow the cost of the original
9895     /// load with the gain from this slice.
9896     void addSliceGain(const LoadedSlice &LS) {
9897       // Each slice saves a truncate.
9898       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9899       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9900                               LS.Inst->getValueType(0)))
9901         ++Truncates;
9902       // If there is a shift amount, this slice gets rid of it.
9903       if (LS.Shift)
9904         ++Shift;
9905       // If this slice can merge a cross register bank copy, account for it.
9906       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9907         ++CrossRegisterBanksCopies;
9908     }
9909
9910     Cost &operator+=(const Cost &RHS) {
9911       Loads += RHS.Loads;
9912       Truncates += RHS.Truncates;
9913       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9914       ZExts += RHS.ZExts;
9915       Shift += RHS.Shift;
9916       return *this;
9917     }
9918
9919     bool operator==(const Cost &RHS) const {
9920       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9921              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9922              ZExts == RHS.ZExts && Shift == RHS.Shift;
9923     }
9924
9925     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9926
9927     bool operator<(const Cost &RHS) const {
9928       // Assume cross register banks copies are as expensive as loads.
9929       // FIXME: Do we want some more target hooks?
9930       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9931       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9932       // Unless we are optimizing for code size, consider the
9933       // expensive operation first.
9934       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9935         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9936       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9937              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9938     }
9939
9940     bool operator>(const Cost &RHS) const { return RHS < *this; }
9941
9942     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9943
9944     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9945   };
9946   // The last instruction that represent the slice. This should be a
9947   // truncate instruction.
9948   SDNode *Inst;
9949   // The original load instruction.
9950   LoadSDNode *Origin;
9951   // The right shift amount in bits from the original load.
9952   unsigned Shift;
9953   // The DAG from which Origin came from.
9954   // This is used to get some contextual information about legal types, etc.
9955   SelectionDAG *DAG;
9956
9957   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9958               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9959       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9960
9961   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9962   /// \return Result is \p BitWidth and has used bits set to 1 and
9963   ///         not used bits set to 0.
9964   APInt getUsedBits() const {
9965     // Reproduce the trunc(lshr) sequence:
9966     // - Start from the truncated value.
9967     // - Zero extend to the desired bit width.
9968     // - Shift left.
9969     assert(Origin && "No original load to compare against.");
9970     unsigned BitWidth = Origin->getValueSizeInBits(0);
9971     assert(Inst && "This slice is not bound to an instruction");
9972     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9973            "Extracted slice is bigger than the whole type!");
9974     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9975     UsedBits.setAllBits();
9976     UsedBits = UsedBits.zext(BitWidth);
9977     UsedBits <<= Shift;
9978     return UsedBits;
9979   }
9980
9981   /// \brief Get the size of the slice to be loaded in bytes.
9982   unsigned getLoadedSize() const {
9983     unsigned SliceSize = getUsedBits().countPopulation();
9984     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9985     return SliceSize / 8;
9986   }
9987
9988   /// \brief Get the type that will be loaded for this slice.
9989   /// Note: This may not be the final type for the slice.
9990   EVT getLoadedType() const {
9991     assert(DAG && "Missing context");
9992     LLVMContext &Ctxt = *DAG->getContext();
9993     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9994   }
9995
9996   /// \brief Get the alignment of the load used for this slice.
9997   unsigned getAlignment() const {
9998     unsigned Alignment = Origin->getAlignment();
9999     unsigned Offset = getOffsetFromBase();
10000     if (Offset != 0)
10001       Alignment = MinAlign(Alignment, Alignment + Offset);
10002     return Alignment;
10003   }
10004
10005   /// \brief Check if this slice can be rewritten with legal operations.
10006   bool isLegal() const {
10007     // An invalid slice is not legal.
10008     if (!Origin || !Inst || !DAG)
10009       return false;
10010
10011     // Offsets are for indexed load only, we do not handle that.
10012     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10013       return false;
10014
10015     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10016
10017     // Check that the type is legal.
10018     EVT SliceType = getLoadedType();
10019     if (!TLI.isTypeLegal(SliceType))
10020       return false;
10021
10022     // Check that the load is legal for this type.
10023     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10024       return false;
10025
10026     // Check that the offset can be computed.
10027     // 1. Check its type.
10028     EVT PtrType = Origin->getBasePtr().getValueType();
10029     if (PtrType == MVT::Untyped || PtrType.isExtended())
10030       return false;
10031
10032     // 2. Check that it fits in the immediate.
10033     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10034       return false;
10035
10036     // 3. Check that the computation is legal.
10037     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10038       return false;
10039
10040     // Check that the zext is legal if it needs one.
10041     EVT TruncateType = Inst->getValueType(0);
10042     if (TruncateType != SliceType &&
10043         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10044       return false;
10045
10046     return true;
10047   }
10048
10049   /// \brief Get the offset in bytes of this slice in the original chunk of
10050   /// bits.
10051   /// \pre DAG != nullptr.
10052   uint64_t getOffsetFromBase() const {
10053     assert(DAG && "Missing context.");
10054     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10055     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10056     uint64_t Offset = Shift / 8;
10057     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10058     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10059            "The size of the original loaded type is not a multiple of a"
10060            " byte.");
10061     // If Offset is bigger than TySizeInBytes, it means we are loading all
10062     // zeros. This should have been optimized before in the process.
10063     assert(TySizeInBytes > Offset &&
10064            "Invalid shift amount for given loaded size");
10065     if (IsBigEndian)
10066       Offset = TySizeInBytes - Offset - getLoadedSize();
10067     return Offset;
10068   }
10069
10070   /// \brief Generate the sequence of instructions to load the slice
10071   /// represented by this object and redirect the uses of this slice to
10072   /// this new sequence of instructions.
10073   /// \pre this->Inst && this->Origin are valid Instructions and this
10074   /// object passed the legal check: LoadedSlice::isLegal returned true.
10075   /// \return The last instruction of the sequence used to load the slice.
10076   SDValue loadSlice() const {
10077     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10078     const SDValue &OldBaseAddr = Origin->getBasePtr();
10079     SDValue BaseAddr = OldBaseAddr;
10080     // Get the offset in that chunk of bytes w.r.t. the endianess.
10081     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10082     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10083     if (Offset) {
10084       // BaseAddr = BaseAddr + Offset.
10085       EVT ArithType = BaseAddr.getValueType();
10086       SDLoc DL(Origin);
10087       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10088                               DAG->getConstant(Offset, DL, ArithType));
10089     }
10090
10091     // Create the type of the loaded slice according to its size.
10092     EVT SliceType = getLoadedType();
10093
10094     // Create the load for the slice.
10095     SDValue LastInst = DAG->getLoad(
10096         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10097         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10098         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10099     // If the final type is not the same as the loaded type, this means that
10100     // we have to pad with zero. Create a zero extend for that.
10101     EVT FinalType = Inst->getValueType(0);
10102     if (SliceType != FinalType)
10103       LastInst =
10104           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10105     return LastInst;
10106   }
10107
10108   /// \brief Check if this slice can be merged with an expensive cross register
10109   /// bank copy. E.g.,
10110   /// i = load i32
10111   /// f = bitcast i32 i to float
10112   bool canMergeExpensiveCrossRegisterBankCopy() const {
10113     if (!Inst || !Inst->hasOneUse())
10114       return false;
10115     SDNode *Use = *Inst->use_begin();
10116     if (Use->getOpcode() != ISD::BITCAST)
10117       return false;
10118     assert(DAG && "Missing context");
10119     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10120     EVT ResVT = Use->getValueType(0);
10121     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10122     const TargetRegisterClass *ArgRC =
10123         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10124     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10125       return false;
10126
10127     // At this point, we know that we perform a cross-register-bank copy.
10128     // Check if it is expensive.
10129     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10130     // Assume bitcasts are cheap, unless both register classes do not
10131     // explicitly share a common sub class.
10132     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10133       return false;
10134
10135     // Check if it will be merged with the load.
10136     // 1. Check the alignment constraint.
10137     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10138         ResVT.getTypeForEVT(*DAG->getContext()));
10139
10140     if (RequiredAlignment > getAlignment())
10141       return false;
10142
10143     // 2. Check that the load is a legal operation for that type.
10144     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10145       return false;
10146
10147     // 3. Check that we do not have a zext in the way.
10148     if (Inst->getValueType(0) != getLoadedType())
10149       return false;
10150
10151     return true;
10152   }
10153 };
10154 }
10155
10156 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10157 /// \p UsedBits looks like 0..0 1..1 0..0.
10158 static bool areUsedBitsDense(const APInt &UsedBits) {
10159   // If all the bits are one, this is dense!
10160   if (UsedBits.isAllOnesValue())
10161     return true;
10162
10163   // Get rid of the unused bits on the right.
10164   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10165   // Get rid of the unused bits on the left.
10166   if (NarrowedUsedBits.countLeadingZeros())
10167     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10168   // Check that the chunk of bits is completely used.
10169   return NarrowedUsedBits.isAllOnesValue();
10170 }
10171
10172 /// \brief Check whether or not \p First and \p Second are next to each other
10173 /// in memory. This means that there is no hole between the bits loaded
10174 /// by \p First and the bits loaded by \p Second.
10175 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10176                                      const LoadedSlice &Second) {
10177   assert(First.Origin == Second.Origin && First.Origin &&
10178          "Unable to match different memory origins.");
10179   APInt UsedBits = First.getUsedBits();
10180   assert((UsedBits & Second.getUsedBits()) == 0 &&
10181          "Slices are not supposed to overlap.");
10182   UsedBits |= Second.getUsedBits();
10183   return areUsedBitsDense(UsedBits);
10184 }
10185
10186 /// \brief Adjust the \p GlobalLSCost according to the target
10187 /// paring capabilities and the layout of the slices.
10188 /// \pre \p GlobalLSCost should account for at least as many loads as
10189 /// there is in the slices in \p LoadedSlices.
10190 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10191                                  LoadedSlice::Cost &GlobalLSCost) {
10192   unsigned NumberOfSlices = LoadedSlices.size();
10193   // If there is less than 2 elements, no pairing is possible.
10194   if (NumberOfSlices < 2)
10195     return;
10196
10197   // Sort the slices so that elements that are likely to be next to each
10198   // other in memory are next to each other in the list.
10199   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10200             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10201     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10202     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10203   });
10204   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10205   // First (resp. Second) is the first (resp. Second) potentially candidate
10206   // to be placed in a paired load.
10207   const LoadedSlice *First = nullptr;
10208   const LoadedSlice *Second = nullptr;
10209   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10210                 // Set the beginning of the pair.
10211                                                            First = Second) {
10212
10213     Second = &LoadedSlices[CurrSlice];
10214
10215     // If First is NULL, it means we start a new pair.
10216     // Get to the next slice.
10217     if (!First)
10218       continue;
10219
10220     EVT LoadedType = First->getLoadedType();
10221
10222     // If the types of the slices are different, we cannot pair them.
10223     if (LoadedType != Second->getLoadedType())
10224       continue;
10225
10226     // Check if the target supplies paired loads for this type.
10227     unsigned RequiredAlignment = 0;
10228     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10229       // move to the next pair, this type is hopeless.
10230       Second = nullptr;
10231       continue;
10232     }
10233     // Check if we meet the alignment requirement.
10234     if (RequiredAlignment > First->getAlignment())
10235       continue;
10236
10237     // Check that both loads are next to each other in memory.
10238     if (!areSlicesNextToEachOther(*First, *Second))
10239       continue;
10240
10241     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10242     --GlobalLSCost.Loads;
10243     // Move to the next pair.
10244     Second = nullptr;
10245   }
10246 }
10247
10248 /// \brief Check the profitability of all involved LoadedSlice.
10249 /// Currently, it is considered profitable if there is exactly two
10250 /// involved slices (1) which are (2) next to each other in memory, and
10251 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10252 ///
10253 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10254 /// the elements themselves.
10255 ///
10256 /// FIXME: When the cost model will be mature enough, we can relax
10257 /// constraints (1) and (2).
10258 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10259                                 const APInt &UsedBits, bool ForCodeSize) {
10260   unsigned NumberOfSlices = LoadedSlices.size();
10261   if (StressLoadSlicing)
10262     return NumberOfSlices > 1;
10263
10264   // Check (1).
10265   if (NumberOfSlices != 2)
10266     return false;
10267
10268   // Check (2).
10269   if (!areUsedBitsDense(UsedBits))
10270     return false;
10271
10272   // Check (3).
10273   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10274   // The original code has one big load.
10275   OrigCost.Loads = 1;
10276   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10277     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10278     // Accumulate the cost of all the slices.
10279     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10280     GlobalSlicingCost += SliceCost;
10281
10282     // Account as cost in the original configuration the gain obtained
10283     // with the current slices.
10284     OrigCost.addSliceGain(LS);
10285   }
10286
10287   // If the target supports paired load, adjust the cost accordingly.
10288   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10289   return OrigCost > GlobalSlicingCost;
10290 }
10291
10292 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10293 /// operations, split it in the various pieces being extracted.
10294 ///
10295 /// This sort of thing is introduced by SROA.
10296 /// This slicing takes care not to insert overlapping loads.
10297 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10298 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10299   if (Level < AfterLegalizeDAG)
10300     return false;
10301
10302   LoadSDNode *LD = cast<LoadSDNode>(N);
10303   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10304       !LD->getValueType(0).isInteger())
10305     return false;
10306
10307   // Keep track of already used bits to detect overlapping values.
10308   // In that case, we will just abort the transformation.
10309   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10310
10311   SmallVector<LoadedSlice, 4> LoadedSlices;
10312
10313   // Check if this load is used as several smaller chunks of bits.
10314   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10315   // of computation for each trunc.
10316   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10317        UI != UIEnd; ++UI) {
10318     // Skip the uses of the chain.
10319     if (UI.getUse().getResNo() != 0)
10320       continue;
10321
10322     SDNode *User = *UI;
10323     unsigned Shift = 0;
10324
10325     // Check if this is a trunc(lshr).
10326     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10327         isa<ConstantSDNode>(User->getOperand(1))) {
10328       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10329       User = *User->use_begin();
10330     }
10331
10332     // At this point, User is a Truncate, iff we encountered, trunc or
10333     // trunc(lshr).
10334     if (User->getOpcode() != ISD::TRUNCATE)
10335       return false;
10336
10337     // The width of the type must be a power of 2 and greater than 8-bits.
10338     // Otherwise the load cannot be represented in LLVM IR.
10339     // Moreover, if we shifted with a non-8-bits multiple, the slice
10340     // will be across several bytes. We do not support that.
10341     unsigned Width = User->getValueSizeInBits(0);
10342     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10343       return 0;
10344
10345     // Build the slice for this chain of computations.
10346     LoadedSlice LS(User, LD, Shift, &DAG);
10347     APInt CurrentUsedBits = LS.getUsedBits();
10348
10349     // Check if this slice overlaps with another.
10350     if ((CurrentUsedBits & UsedBits) != 0)
10351       return false;
10352     // Update the bits used globally.
10353     UsedBits |= CurrentUsedBits;
10354
10355     // Check if the new slice would be legal.
10356     if (!LS.isLegal())
10357       return false;
10358
10359     // Record the slice.
10360     LoadedSlices.push_back(LS);
10361   }
10362
10363   // Abort slicing if it does not seem to be profitable.
10364   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10365     return false;
10366
10367   ++SlicedLoads;
10368
10369   // Rewrite each chain to use an independent load.
10370   // By construction, each chain can be represented by a unique load.
10371
10372   // Prepare the argument for the new token factor for all the slices.
10373   SmallVector<SDValue, 8> ArgChains;
10374   for (SmallVectorImpl<LoadedSlice>::const_iterator
10375            LSIt = LoadedSlices.begin(),
10376            LSItEnd = LoadedSlices.end();
10377        LSIt != LSItEnd; ++LSIt) {
10378     SDValue SliceInst = LSIt->loadSlice();
10379     CombineTo(LSIt->Inst, SliceInst, true);
10380     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10381       SliceInst = SliceInst.getOperand(0);
10382     assert(SliceInst->getOpcode() == ISD::LOAD &&
10383            "It takes more than a zext to get to the loaded slice!!");
10384     ArgChains.push_back(SliceInst.getValue(1));
10385   }
10386
10387   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10388                               ArgChains);
10389   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10390   return true;
10391 }
10392
10393 /// Check to see if V is (and load (ptr), imm), where the load is having
10394 /// specific bytes cleared out.  If so, return the byte size being masked out
10395 /// and the shift amount.
10396 static std::pair<unsigned, unsigned>
10397 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10398   std::pair<unsigned, unsigned> Result(0, 0);
10399
10400   // Check for the structure we're looking for.
10401   if (V->getOpcode() != ISD::AND ||
10402       !isa<ConstantSDNode>(V->getOperand(1)) ||
10403       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10404     return Result;
10405
10406   // Check the chain and pointer.
10407   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10408   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10409
10410   // The store should be chained directly to the load or be an operand of a
10411   // tokenfactor.
10412   if (LD == Chain.getNode())
10413     ; // ok.
10414   else if (Chain->getOpcode() != ISD::TokenFactor)
10415     return Result; // Fail.
10416   else {
10417     bool isOk = false;
10418     for (const SDValue &ChainOp : Chain->op_values())
10419       if (ChainOp.getNode() == LD) {
10420         isOk = true;
10421         break;
10422       }
10423     if (!isOk) return Result;
10424   }
10425
10426   // This only handles simple types.
10427   if (V.getValueType() != MVT::i16 &&
10428       V.getValueType() != MVT::i32 &&
10429       V.getValueType() != MVT::i64)
10430     return Result;
10431
10432   // Check the constant mask.  Invert it so that the bits being masked out are
10433   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10434   // follow the sign bit for uniformity.
10435   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10436   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10437   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10438   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10439   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10440   if (NotMaskLZ == 64) return Result;  // All zero mask.
10441
10442   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10443   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10444     return Result;
10445
10446   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10447   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10448     NotMaskLZ -= 64-V.getValueSizeInBits();
10449
10450   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10451   switch (MaskedBytes) {
10452   case 1:
10453   case 2:
10454   case 4: break;
10455   default: return Result; // All one mask, or 5-byte mask.
10456   }
10457
10458   // Verify that the first bit starts at a multiple of mask so that the access
10459   // is aligned the same as the access width.
10460   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10461
10462   Result.first = MaskedBytes;
10463   Result.second = NotMaskTZ/8;
10464   return Result;
10465 }
10466
10467
10468 /// Check to see if IVal is something that provides a value as specified by
10469 /// MaskInfo. If so, replace the specified store with a narrower store of
10470 /// truncated IVal.
10471 static SDNode *
10472 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10473                                 SDValue IVal, StoreSDNode *St,
10474                                 DAGCombiner *DC) {
10475   unsigned NumBytes = MaskInfo.first;
10476   unsigned ByteShift = MaskInfo.second;
10477   SelectionDAG &DAG = DC->getDAG();
10478
10479   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10480   // that uses this.  If not, this is not a replacement.
10481   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10482                                   ByteShift*8, (ByteShift+NumBytes)*8);
10483   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10484
10485   // Check that it is legal on the target to do this.  It is legal if the new
10486   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10487   // legalization.
10488   MVT VT = MVT::getIntegerVT(NumBytes*8);
10489   if (!DC->isTypeLegal(VT))
10490     return nullptr;
10491
10492   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10493   // shifted by ByteShift and truncated down to NumBytes.
10494   if (ByteShift) {
10495     SDLoc DL(IVal);
10496     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10497                        DAG.getConstant(ByteShift*8, DL,
10498                                     DC->getShiftAmountTy(IVal.getValueType())));
10499   }
10500
10501   // Figure out the offset for the store and the alignment of the access.
10502   unsigned StOffset;
10503   unsigned NewAlign = St->getAlignment();
10504
10505   if (DAG.getDataLayout().isLittleEndian())
10506     StOffset = ByteShift;
10507   else
10508     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10509
10510   SDValue Ptr = St->getBasePtr();
10511   if (StOffset) {
10512     SDLoc DL(IVal);
10513     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10514                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10515     NewAlign = MinAlign(NewAlign, StOffset);
10516   }
10517
10518   // Truncate down to the new size.
10519   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10520
10521   ++OpsNarrowed;
10522   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10523                       St->getPointerInfo().getWithOffset(StOffset),
10524                       false, false, NewAlign).getNode();
10525 }
10526
10527
10528 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10529 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10530 /// narrowing the load and store if it would end up being a win for performance
10531 /// or code size.
10532 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10533   StoreSDNode *ST  = cast<StoreSDNode>(N);
10534   if (ST->isVolatile())
10535     return SDValue();
10536
10537   SDValue Chain = ST->getChain();
10538   SDValue Value = ST->getValue();
10539   SDValue Ptr   = ST->getBasePtr();
10540   EVT VT = Value.getValueType();
10541
10542   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10543     return SDValue();
10544
10545   unsigned Opc = Value.getOpcode();
10546
10547   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10548   // is a byte mask indicating a consecutive number of bytes, check to see if
10549   // Y is known to provide just those bytes.  If so, we try to replace the
10550   // load + replace + store sequence with a single (narrower) store, which makes
10551   // the load dead.
10552   if (Opc == ISD::OR) {
10553     std::pair<unsigned, unsigned> MaskedLoad;
10554     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10555     if (MaskedLoad.first)
10556       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10557                                                   Value.getOperand(1), ST,this))
10558         return SDValue(NewST, 0);
10559
10560     // Or is commutative, so try swapping X and Y.
10561     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10562     if (MaskedLoad.first)
10563       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10564                                                   Value.getOperand(0), ST,this))
10565         return SDValue(NewST, 0);
10566   }
10567
10568   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10569       Value.getOperand(1).getOpcode() != ISD::Constant)
10570     return SDValue();
10571
10572   SDValue N0 = Value.getOperand(0);
10573   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10574       Chain == SDValue(N0.getNode(), 1)) {
10575     LoadSDNode *LD = cast<LoadSDNode>(N0);
10576     if (LD->getBasePtr() != Ptr ||
10577         LD->getPointerInfo().getAddrSpace() !=
10578         ST->getPointerInfo().getAddrSpace())
10579       return SDValue();
10580
10581     // Find the type to narrow it the load / op / store to.
10582     SDValue N1 = Value.getOperand(1);
10583     unsigned BitWidth = N1.getValueSizeInBits();
10584     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10585     if (Opc == ISD::AND)
10586       Imm ^= APInt::getAllOnesValue(BitWidth);
10587     if (Imm == 0 || Imm.isAllOnesValue())
10588       return SDValue();
10589     unsigned ShAmt = Imm.countTrailingZeros();
10590     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10591     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10592     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10593     // The narrowing should be profitable, the load/store operation should be
10594     // legal (or custom) and the store size should be equal to the NewVT width.
10595     while (NewBW < BitWidth &&
10596            (NewVT.getStoreSizeInBits() != NewBW ||
10597             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10598             !TLI.isNarrowingProfitable(VT, NewVT))) {
10599       NewBW = NextPowerOf2(NewBW);
10600       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10601     }
10602     if (NewBW >= BitWidth)
10603       return SDValue();
10604
10605     // If the lsb changed does not start at the type bitwidth boundary,
10606     // start at the previous one.
10607     if (ShAmt % NewBW)
10608       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10609     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10610                                    std::min(BitWidth, ShAmt + NewBW));
10611     if ((Imm & Mask) == Imm) {
10612       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10613       if (Opc == ISD::AND)
10614         NewImm ^= APInt::getAllOnesValue(NewBW);
10615       uint64_t PtrOff = ShAmt / 8;
10616       // For big endian targets, we need to adjust the offset to the pointer to
10617       // load the correct bytes.
10618       if (DAG.getDataLayout().isBigEndian())
10619         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10620
10621       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10622       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10623       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10624         return SDValue();
10625
10626       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10627                                    Ptr.getValueType(), Ptr,
10628                                    DAG.getConstant(PtrOff, SDLoc(LD),
10629                                                    Ptr.getValueType()));
10630       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10631                                   LD->getChain(), NewPtr,
10632                                   LD->getPointerInfo().getWithOffset(PtrOff),
10633                                   LD->isVolatile(), LD->isNonTemporal(),
10634                                   LD->isInvariant(), NewAlign,
10635                                   LD->getAAInfo());
10636       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10637                                    DAG.getConstant(NewImm, SDLoc(Value),
10638                                                    NewVT));
10639       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10640                                    NewVal, NewPtr,
10641                                    ST->getPointerInfo().getWithOffset(PtrOff),
10642                                    false, false, NewAlign);
10643
10644       AddToWorklist(NewPtr.getNode());
10645       AddToWorklist(NewLD.getNode());
10646       AddToWorklist(NewVal.getNode());
10647       WorklistRemover DeadNodes(*this);
10648       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10649       ++OpsNarrowed;
10650       return NewST;
10651     }
10652   }
10653
10654   return SDValue();
10655 }
10656
10657 /// For a given floating point load / store pair, if the load value isn't used
10658 /// by any other operations, then consider transforming the pair to integer
10659 /// load / store operations if the target deems the transformation profitable.
10660 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10661   StoreSDNode *ST  = cast<StoreSDNode>(N);
10662   SDValue Chain = ST->getChain();
10663   SDValue Value = ST->getValue();
10664   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10665       Value.hasOneUse() &&
10666       Chain == SDValue(Value.getNode(), 1)) {
10667     LoadSDNode *LD = cast<LoadSDNode>(Value);
10668     EVT VT = LD->getMemoryVT();
10669     if (!VT.isFloatingPoint() ||
10670         VT != ST->getMemoryVT() ||
10671         LD->isNonTemporal() ||
10672         ST->isNonTemporal() ||
10673         LD->getPointerInfo().getAddrSpace() != 0 ||
10674         ST->getPointerInfo().getAddrSpace() != 0)
10675       return SDValue();
10676
10677     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10678     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10679         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10680         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10681         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10682       return SDValue();
10683
10684     unsigned LDAlign = LD->getAlignment();
10685     unsigned STAlign = ST->getAlignment();
10686     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10687     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10688     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10689       return SDValue();
10690
10691     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10692                                 LD->getChain(), LD->getBasePtr(),
10693                                 LD->getPointerInfo(),
10694                                 false, false, false, LDAlign);
10695
10696     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10697                                  NewLD, ST->getBasePtr(),
10698                                  ST->getPointerInfo(),
10699                                  false, false, STAlign);
10700
10701     AddToWorklist(NewLD.getNode());
10702     AddToWorklist(NewST.getNode());
10703     WorklistRemover DeadNodes(*this);
10704     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10705     ++LdStFP2Int;
10706     return NewST;
10707   }
10708
10709   return SDValue();
10710 }
10711
10712 namespace {
10713 /// Helper struct to parse and store a memory address as base + index + offset.
10714 /// We ignore sign extensions when it is safe to do so.
10715 /// The following two expressions are not equivalent. To differentiate we need
10716 /// to store whether there was a sign extension involved in the index
10717 /// computation.
10718 ///  (load (i64 add (i64 copyfromreg %c)
10719 ///                 (i64 signextend (add (i8 load %index)
10720 ///                                      (i8 1))))
10721 /// vs
10722 ///
10723 /// (load (i64 add (i64 copyfromreg %c)
10724 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10725 ///                                         (i32 1)))))
10726 struct BaseIndexOffset {
10727   SDValue Base;
10728   SDValue Index;
10729   int64_t Offset;
10730   bool IsIndexSignExt;
10731
10732   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10733
10734   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10735                   bool IsIndexSignExt) :
10736     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10737
10738   bool equalBaseIndex(const BaseIndexOffset &Other) {
10739     return Other.Base == Base && Other.Index == Index &&
10740       Other.IsIndexSignExt == IsIndexSignExt;
10741   }
10742
10743   /// Parses tree in Ptr for base, index, offset addresses.
10744   static BaseIndexOffset match(SDValue Ptr) {
10745     bool IsIndexSignExt = false;
10746
10747     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10748     // instruction, then it could be just the BASE or everything else we don't
10749     // know how to handle. Just use Ptr as BASE and give up.
10750     if (Ptr->getOpcode() != ISD::ADD)
10751       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10752
10753     // We know that we have at least an ADD instruction. Try to pattern match
10754     // the simple case of BASE + OFFSET.
10755     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10756       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10757       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10758                               IsIndexSignExt);
10759     }
10760
10761     // Inside a loop the current BASE pointer is calculated using an ADD and a
10762     // MUL instruction. In this case Ptr is the actual BASE pointer.
10763     // (i64 add (i64 %array_ptr)
10764     //          (i64 mul (i64 %induction_var)
10765     //                   (i64 %element_size)))
10766     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10767       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10768
10769     // Look at Base + Index + Offset cases.
10770     SDValue Base = Ptr->getOperand(0);
10771     SDValue IndexOffset = Ptr->getOperand(1);
10772
10773     // Skip signextends.
10774     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10775       IndexOffset = IndexOffset->getOperand(0);
10776       IsIndexSignExt = true;
10777     }
10778
10779     // Either the case of Base + Index (no offset) or something else.
10780     if (IndexOffset->getOpcode() != ISD::ADD)
10781       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10782
10783     // Now we have the case of Base + Index + offset.
10784     SDValue Index = IndexOffset->getOperand(0);
10785     SDValue Offset = IndexOffset->getOperand(1);
10786
10787     if (!isa<ConstantSDNode>(Offset))
10788       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10789
10790     // Ignore signextends.
10791     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10792       Index = Index->getOperand(0);
10793       IsIndexSignExt = true;
10794     } else IsIndexSignExt = false;
10795
10796     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10797     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10798   }
10799 };
10800 } // namespace
10801
10802 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10803                                                   SDLoc SL,
10804                                                   ArrayRef<MemOpLink> Stores,
10805                                                   SmallVectorImpl<SDValue> &Chains,
10806                                                   EVT Ty) const {
10807   SmallVector<SDValue, 8> BuildVector;
10808
10809   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10810     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10811     Chains.push_back(St->getChain());
10812     BuildVector.push_back(St->getValue());
10813   }
10814
10815   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10816 }
10817
10818 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10819                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10820                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10821   // Make sure we have something to merge.
10822   if (NumStores < 2)
10823     return false;
10824
10825   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10826   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10827   unsigned LatestNodeUsed = 0;
10828
10829   for (unsigned i=0; i < NumStores; ++i) {
10830     // Find a chain for the new wide-store operand. Notice that some
10831     // of the store nodes that we found may not be selected for inclusion
10832     // in the wide store. The chain we use needs to be the chain of the
10833     // latest store node which is *used* and replaced by the wide store.
10834     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10835       LatestNodeUsed = i;
10836   }
10837
10838   SmallVector<SDValue, 8> Chains;
10839
10840   // The latest Node in the DAG.
10841   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10842   SDLoc DL(StoreNodes[0].MemNode);
10843
10844   SDValue StoredVal;
10845   if (UseVector) {
10846     bool IsVec = MemVT.isVector();
10847     unsigned Elts = NumStores;
10848     if (IsVec) {
10849       // When merging vector stores, get the total number of elements.
10850       Elts *= MemVT.getVectorNumElements();
10851     }
10852     // Get the type for the merged vector store.
10853     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10854     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10855
10856     if (IsConstantSrc) {
10857       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
10858     } else {
10859       SmallVector<SDValue, 8> Ops;
10860       for (unsigned i = 0; i < NumStores; ++i) {
10861         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10862         SDValue Val = St->getValue();
10863         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10864         if (Val.getValueType() != MemVT)
10865           return false;
10866         Ops.push_back(Val);
10867         Chains.push_back(St->getChain());
10868       }
10869
10870       // Build the extracted vector elements back into a vector.
10871       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10872                               DL, Ty, Ops);    }
10873   } else {
10874     // We should always use a vector store when merging extracted vector
10875     // elements, so this path implies a store of constants.
10876     assert(IsConstantSrc && "Merged vector elements should use vector store");
10877
10878     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10879     APInt StoreInt(SizeInBits, 0);
10880
10881     // Construct a single integer constant which is made of the smaller
10882     // constant inputs.
10883     bool IsLE = DAG.getDataLayout().isLittleEndian();
10884     for (unsigned i = 0; i < NumStores; ++i) {
10885       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10886       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10887       Chains.push_back(St->getChain());
10888
10889       SDValue Val = St->getValue();
10890       StoreInt <<= ElementSizeBytes * 8;
10891       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10892         StoreInt |= C->getAPIntValue().zext(SizeInBits);
10893       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10894         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10895       } else {
10896         llvm_unreachable("Invalid constant element type");
10897       }
10898     }
10899
10900     // Create the new Load and Store operations.
10901     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10902     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10903   }
10904
10905   assert(!Chains.empty());
10906
10907   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10908   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
10909                                   FirstInChain->getBasePtr(),
10910                                   FirstInChain->getPointerInfo(),
10911                                   false, false,
10912                                   FirstInChain->getAlignment());
10913
10914   // Replace the last store with the new store
10915   CombineTo(LatestOp, NewStore);
10916   // Erase all other stores.
10917   for (unsigned i = 0; i < NumStores; ++i) {
10918     if (StoreNodes[i].MemNode == LatestOp)
10919       continue;
10920     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10921     // ReplaceAllUsesWith will replace all uses that existed when it was
10922     // called, but graph optimizations may cause new ones to appear. For
10923     // example, the case in pr14333 looks like
10924     //
10925     //  St's chain -> St -> another store -> X
10926     //
10927     // And the only difference from St to the other store is the chain.
10928     // When we change it's chain to be St's chain they become identical,
10929     // get CSEed and the net result is that X is now a use of St.
10930     // Since we know that St is redundant, just iterate.
10931     while (!St->use_empty())
10932       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10933     deleteAndRecombine(St);
10934   }
10935
10936   return true;
10937 }
10938
10939 void DAGCombiner::getStoreMergeAndAliasCandidates(
10940     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10941     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10942   // This holds the base pointer, index, and the offset in bytes from the base
10943   // pointer.
10944   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10945
10946   // We must have a base and an offset.
10947   if (!BasePtr.Base.getNode())
10948     return;
10949
10950   // Do not handle stores to undef base pointers.
10951   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10952     return;
10953
10954   // Walk up the chain and look for nodes with offsets from the same
10955   // base pointer. Stop when reaching an instruction with a different kind
10956   // or instruction which has a different base pointer.
10957   EVT MemVT = St->getMemoryVT();
10958   unsigned Seq = 0;
10959   StoreSDNode *Index = St;
10960
10961
10962   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10963                                                   : DAG.getSubtarget().useAA();
10964
10965   if (UseAA) {
10966     // Look at other users of the same chain. Stores on the same chain do not
10967     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
10968     // to be on the same chain, so don't bother looking at adjacent chains.
10969
10970     SDValue Chain = St->getChain();
10971     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
10972       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
10973         if (I.getOperandNo() != 0)
10974           continue;
10975
10976         if (OtherST->isVolatile() || OtherST->isIndexed())
10977           continue;
10978
10979         if (OtherST->getMemoryVT() != MemVT)
10980           continue;
10981
10982         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
10983
10984         if (Ptr.equalBaseIndex(BasePtr))
10985           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
10986       }
10987     }
10988
10989     return;
10990   }
10991
10992   while (Index) {
10993     // If the chain has more than one use, then we can't reorder the mem ops.
10994     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10995       break;
10996
10997     // Find the base pointer and offset for this memory node.
10998     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10999
11000     // Check that the base pointer is the same as the original one.
11001     if (!Ptr.equalBaseIndex(BasePtr))
11002       break;
11003
11004     // The memory operands must not be volatile.
11005     if (Index->isVolatile() || Index->isIndexed())
11006       break;
11007
11008     // No truncation.
11009     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11010       if (St->isTruncatingStore())
11011         break;
11012
11013     // The stored memory type must be the same.
11014     if (Index->getMemoryVT() != MemVT)
11015       break;
11016
11017     // We found a potential memory operand to merge.
11018     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11019
11020     // Find the next memory operand in the chain. If the next operand in the
11021     // chain is a store then move up and continue the scan with the next
11022     // memory operand. If the next operand is a load save it and use alias
11023     // information to check if it interferes with anything.
11024     SDNode *NextInChain = Index->getChain().getNode();
11025     while (1) {
11026       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11027         // We found a store node. Use it for the next iteration.
11028         Index = STn;
11029         break;
11030       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11031         if (Ldn->isVolatile()) {
11032           Index = nullptr;
11033           break;
11034         }
11035
11036         // Save the load node for later. Continue the scan.
11037         AliasLoadNodes.push_back(Ldn);
11038         NextInChain = Ldn->getChain().getNode();
11039         continue;
11040       } else {
11041         Index = nullptr;
11042         break;
11043       }
11044     }
11045   }
11046 }
11047
11048 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11049   if (OptLevel == CodeGenOpt::None)
11050     return false;
11051
11052   EVT MemVT = St->getMemoryVT();
11053   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11054   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11055       Attribute::NoImplicitFloat);
11056
11057   // This function cannot currently deal with non-byte-sized memory sizes.
11058   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11059     return false;
11060
11061   if (!MemVT.isSimple())
11062     return false;
11063
11064   // Perform an early exit check. Do not bother looking at stored values that
11065   // are not constants, loads, or extracted vector elements.
11066   SDValue StoredVal = St->getValue();
11067   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11068   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11069                        isa<ConstantFPSDNode>(StoredVal);
11070   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11071                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11072
11073   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11074     return false;
11075
11076   // Don't merge vectors into wider vectors if the source data comes from loads.
11077   // TODO: This restriction can be lifted by using logic similar to the
11078   // ExtractVecSrc case.
11079   if (MemVT.isVector() && IsLoadSrc)
11080     return false;
11081
11082   // Only look at ends of store sequences.
11083   SDValue Chain = SDValue(St, 0);
11084   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11085     return false;
11086
11087   // Save the LoadSDNodes that we find in the chain.
11088   // We need to make sure that these nodes do not interfere with
11089   // any of the store nodes.
11090   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11091
11092   // Save the StoreSDNodes that we find in the chain.
11093   SmallVector<MemOpLink, 8> StoreNodes;
11094
11095   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11096
11097   // Check if there is anything to merge.
11098   if (StoreNodes.size() < 2)
11099     return false;
11100
11101   // Sort the memory operands according to their distance from the base pointer.
11102   std::sort(StoreNodes.begin(), StoreNodes.end(),
11103             [](MemOpLink LHS, MemOpLink RHS) {
11104     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11105            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11106             LHS.SequenceNum > RHS.SequenceNum);
11107   });
11108
11109   // Scan the memory operations on the chain and find the first non-consecutive
11110   // store memory address.
11111   unsigned LastConsecutiveStore = 0;
11112   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11113   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11114
11115     // Check that the addresses are consecutive starting from the second
11116     // element in the list of stores.
11117     if (i > 0) {
11118       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11119       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11120         break;
11121     }
11122
11123     bool Alias = false;
11124     // Check if this store interferes with any of the loads that we found.
11125     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11126       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11127         Alias = true;
11128         break;
11129       }
11130     // We found a load that alias with this store. Stop the sequence.
11131     if (Alias)
11132       break;
11133
11134     // Mark this node as useful.
11135     LastConsecutiveStore = i;
11136   }
11137
11138   // The node with the lowest store address.
11139   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11140   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11141   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11142   LLVMContext &Context = *DAG.getContext();
11143   const DataLayout &DL = DAG.getDataLayout();
11144
11145   // Store the constants into memory as one consecutive store.
11146   if (IsConstantSrc) {
11147     unsigned LastLegalType = 0;
11148     unsigned LastLegalVectorType = 0;
11149     bool NonZero = false;
11150     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11151       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11152       SDValue StoredVal = St->getValue();
11153
11154       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11155         NonZero |= !C->isNullValue();
11156       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11157         NonZero |= !C->getConstantFPValue()->isNullValue();
11158       } else {
11159         // Non-constant.
11160         break;
11161       }
11162
11163       // Find a legal type for the constant store.
11164       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11165       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11166       bool IsFast;
11167       if (TLI.isTypeLegal(StoreTy) &&
11168           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11169                                  FirstStoreAlign, &IsFast) && IsFast) {
11170         LastLegalType = i+1;
11171       // Or check whether a truncstore is legal.
11172       } else if (TLI.getTypeAction(Context, StoreTy) ==
11173                  TargetLowering::TypePromoteInteger) {
11174         EVT LegalizedStoredValueTy =
11175           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11176         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11177             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11178                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11179             IsFast) {
11180           LastLegalType = i + 1;
11181         }
11182       }
11183
11184       // We only use vectors if the constant is known to be zero or the target
11185       // allows it and the function is not marked with the noimplicitfloat
11186       // attribute.
11187       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11188                                                         FirstStoreAS)) &&
11189           !NoVectors) {
11190         // Find a legal type for the vector store.
11191         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11192         if (TLI.isTypeLegal(Ty) &&
11193             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11194                                    FirstStoreAlign, &IsFast) && IsFast)
11195           LastLegalVectorType = i + 1;
11196       }
11197     }
11198
11199     // Check if we found a legal integer type to store.
11200     if (LastLegalType == 0 && LastLegalVectorType == 0)
11201       return false;
11202
11203     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11204     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11205
11206     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11207                                            true, UseVector);
11208   }
11209
11210   // When extracting multiple vector elements, try to store them
11211   // in one vector store rather than a sequence of scalar stores.
11212   if (IsExtractVecSrc) {
11213     unsigned NumStoresToMerge = 0;
11214     bool IsVec = MemVT.isVector();
11215     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11216       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11217       unsigned StoreValOpcode = St->getValue().getOpcode();
11218       // This restriction could be loosened.
11219       // Bail out if any stored values are not elements extracted from a vector.
11220       // It should be possible to handle mixed sources, but load sources need
11221       // more careful handling (see the block of code below that handles
11222       // consecutive loads).
11223       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11224           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11225         return false;
11226
11227       // Find a legal type for the vector store.
11228       unsigned Elts = i + 1;
11229       if (IsVec) {
11230         // When merging vector stores, get the total number of elements.
11231         Elts *= MemVT.getVectorNumElements();
11232       }
11233       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11234       bool IsFast;
11235       if (TLI.isTypeLegal(Ty) &&
11236           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11237                                  FirstStoreAlign, &IsFast) && IsFast)
11238         NumStoresToMerge = i + 1;
11239     }
11240
11241     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11242                                            false, true);
11243   }
11244
11245   // Below we handle the case of multiple consecutive stores that
11246   // come from multiple consecutive loads. We merge them into a single
11247   // wide load and a single wide store.
11248
11249   // Look for load nodes which are used by the stored values.
11250   SmallVector<MemOpLink, 8> LoadNodes;
11251
11252   // Find acceptable loads. Loads need to have the same chain (token factor),
11253   // must not be zext, volatile, indexed, and they must be consecutive.
11254   BaseIndexOffset LdBasePtr;
11255   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11256     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11257     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11258     if (!Ld) break;
11259
11260     // Loads must only have one use.
11261     if (!Ld->hasNUsesOfValue(1, 0))
11262       break;
11263
11264     // The memory operands must not be volatile.
11265     if (Ld->isVolatile() || Ld->isIndexed())
11266       break;
11267
11268     // We do not accept ext loads.
11269     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11270       break;
11271
11272     // The stored memory type must be the same.
11273     if (Ld->getMemoryVT() != MemVT)
11274       break;
11275
11276     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11277     // If this is not the first ptr that we check.
11278     if (LdBasePtr.Base.getNode()) {
11279       // The base ptr must be the same.
11280       if (!LdPtr.equalBaseIndex(LdBasePtr))
11281         break;
11282     } else {
11283       // Check that all other base pointers are the same as this one.
11284       LdBasePtr = LdPtr;
11285     }
11286
11287     // We found a potential memory operand to merge.
11288     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11289   }
11290
11291   if (LoadNodes.size() < 2)
11292     return false;
11293
11294   // If we have load/store pair instructions and we only have two values,
11295   // don't bother.
11296   unsigned RequiredAlignment;
11297   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11298       St->getAlignment() >= RequiredAlignment)
11299     return false;
11300
11301   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11302   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11303   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11304
11305   // Scan the memory operations on the chain and find the first non-consecutive
11306   // load memory address. These variables hold the index in the store node
11307   // array.
11308   unsigned LastConsecutiveLoad = 0;
11309   // This variable refers to the size and not index in the array.
11310   unsigned LastLegalVectorType = 0;
11311   unsigned LastLegalIntegerType = 0;
11312   StartAddress = LoadNodes[0].OffsetFromBase;
11313   SDValue FirstChain = FirstLoad->getChain();
11314   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11315     // All loads much share the same chain.
11316     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11317       break;
11318
11319     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11320     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11321       break;
11322     LastConsecutiveLoad = i;
11323     // Find a legal type for the vector store.
11324     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11325     bool IsFastSt, IsFastLd;
11326     if (TLI.isTypeLegal(StoreTy) &&
11327         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11328                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11329         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11330                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11331       LastLegalVectorType = i + 1;
11332     }
11333
11334     // Find a legal type for the integer store.
11335     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11336     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11337     if (TLI.isTypeLegal(StoreTy) &&
11338         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11339                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11340         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11341                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11342       LastLegalIntegerType = i + 1;
11343     // Or check whether a truncstore and extload is legal.
11344     else if (TLI.getTypeAction(Context, StoreTy) ==
11345              TargetLowering::TypePromoteInteger) {
11346       EVT LegalizedStoredValueTy =
11347         TLI.getTypeToTransformTo(Context, StoreTy);
11348       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11349           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11350           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11351           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11352           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11353                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11354           IsFastSt &&
11355           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11356                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11357           IsFastLd)
11358         LastLegalIntegerType = i+1;
11359     }
11360   }
11361
11362   // Only use vector types if the vector type is larger than the integer type.
11363   // If they are the same, use integers.
11364   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11365   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11366
11367   // We add +1 here because the LastXXX variables refer to location while
11368   // the NumElem refers to array/index size.
11369   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11370   NumElem = std::min(LastLegalType, NumElem);
11371
11372   if (NumElem < 2)
11373     return false;
11374
11375   // Collect the chains from all merged stores.
11376   SmallVector<SDValue, 8> MergeStoreChains;
11377   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11378
11379   // The latest Node in the DAG.
11380   unsigned LatestNodeUsed = 0;
11381   for (unsigned i=1; i<NumElem; ++i) {
11382     // Find a chain for the new wide-store operand. Notice that some
11383     // of the store nodes that we found may not be selected for inclusion
11384     // in the wide store. The chain we use needs to be the chain of the
11385     // latest store node which is *used* and replaced by the wide store.
11386     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11387       LatestNodeUsed = i;
11388
11389     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11390   }
11391
11392   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11393
11394   // Find if it is better to use vectors or integers to load and store
11395   // to memory.
11396   EVT JointMemOpVT;
11397   if (UseVectorTy) {
11398     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11399   } else {
11400     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11401     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11402   }
11403
11404   SDLoc LoadDL(LoadNodes[0].MemNode);
11405   SDLoc StoreDL(StoreNodes[0].MemNode);
11406
11407   // The merged loads are required to have the same chain, so using the first's
11408   // chain is acceptable.
11409   SDValue NewLoad = DAG.getLoad(
11410       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11411       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11412
11413   SDValue NewStoreChain =
11414     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11415
11416   SDValue NewStore = DAG.getStore(
11417     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11418       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11419
11420   // Replace one of the loads with the new load.
11421   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11422   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11423                                 SDValue(NewLoad.getNode(), 1));
11424
11425   // Remove the rest of the load chains.
11426   for (unsigned i = 1; i < NumElem ; ++i) {
11427     // Replace all chain users of the old load nodes with the chain of the new
11428     // load node.
11429     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11430     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11431   }
11432
11433   // Replace the last store with the new store.
11434   CombineTo(LatestOp, NewStore);
11435   // Erase all other stores.
11436   for (unsigned i = 0; i < NumElem ; ++i) {
11437     // Remove all Store nodes.
11438     if (StoreNodes[i].MemNode == LatestOp)
11439       continue;
11440     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11441     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11442     deleteAndRecombine(St);
11443   }
11444
11445   return true;
11446 }
11447
11448 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11449   SDLoc SL(ST);
11450   SDValue ReplStore;
11451
11452   // Replace the chain to avoid dependency.
11453   if (ST->isTruncatingStore()) {
11454     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11455                                   ST->getBasePtr(), ST->getMemoryVT(),
11456                                   ST->getMemOperand());
11457   } else {
11458     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11459                              ST->getMemOperand());
11460   }
11461
11462   // Create token to keep both nodes around.
11463   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11464                               MVT::Other, ST->getChain(), ReplStore);
11465
11466   // Make sure the new and old chains are cleaned up.
11467   AddToWorklist(Token.getNode());
11468
11469   // Don't add users to work list.
11470   return CombineTo(ST, Token, false);
11471 }
11472
11473 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11474   SDValue Value = ST->getValue();
11475   if (Value.getOpcode() == ISD::TargetConstantFP)
11476     return SDValue();
11477
11478   SDLoc DL(ST);
11479
11480   SDValue Chain = ST->getChain();
11481   SDValue Ptr = ST->getBasePtr();
11482
11483   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11484
11485   // NOTE: If the original store is volatile, this transform must not increase
11486   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11487   // processor operation but an i64 (which is not legal) requires two.  So the
11488   // transform should not be done in this case.
11489
11490   SDValue Tmp;
11491   switch (CFP->getSimpleValueType(0).SimpleTy) {
11492   default:
11493     llvm_unreachable("Unknown FP type");
11494   case MVT::f16:    // We don't do this for these yet.
11495   case MVT::f80:
11496   case MVT::f128:
11497   case MVT::ppcf128:
11498     return SDValue();
11499   case MVT::f32:
11500     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11501         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11502       ;
11503       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11504                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11505                             MVT::i32);
11506       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11507     }
11508
11509     return SDValue();
11510   case MVT::f64:
11511     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11512          !ST->isVolatile()) ||
11513         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11514       ;
11515       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11516                             getZExtValue(), SDLoc(CFP), MVT::i64);
11517       return DAG.getStore(Chain, DL, Tmp,
11518                           Ptr, ST->getMemOperand());
11519     }
11520
11521     if (!ST->isVolatile() &&
11522         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11523       // Many FP stores are not made apparent until after legalize, e.g. for
11524       // argument passing.  Since this is so common, custom legalize the
11525       // 64-bit integer store into two 32-bit stores.
11526       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11527       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11528       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11529       if (DAG.getDataLayout().isBigEndian())
11530         std::swap(Lo, Hi);
11531
11532       unsigned Alignment = ST->getAlignment();
11533       bool isVolatile = ST->isVolatile();
11534       bool isNonTemporal = ST->isNonTemporal();
11535       AAMDNodes AAInfo = ST->getAAInfo();
11536
11537       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11538                                  Ptr, ST->getPointerInfo(),
11539                                  isVolatile, isNonTemporal,
11540                                  ST->getAlignment(), AAInfo);
11541       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11542                         DAG.getConstant(4, DL, Ptr.getValueType()));
11543       Alignment = MinAlign(Alignment, 4U);
11544       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11545                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11546                                  isVolatile, isNonTemporal,
11547                                  Alignment, AAInfo);
11548       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11549                          St0, St1);
11550     }
11551
11552     return SDValue();
11553   }
11554 }
11555
11556 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11557   StoreSDNode *ST  = cast<StoreSDNode>(N);
11558   SDValue Chain = ST->getChain();
11559   SDValue Value = ST->getValue();
11560   SDValue Ptr   = ST->getBasePtr();
11561
11562   // If this is a store of a bit convert, store the input value if the
11563   // resultant store does not need a higher alignment than the original.
11564   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11565       ST->isUnindexed()) {
11566     unsigned OrigAlign = ST->getAlignment();
11567     EVT SVT = Value.getOperand(0).getValueType();
11568     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11569         SVT.getTypeForEVT(*DAG.getContext()));
11570     if (Align <= OrigAlign &&
11571         ((!LegalOperations && !ST->isVolatile()) ||
11572          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11573       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11574                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11575                           ST->isNonTemporal(), OrigAlign,
11576                           ST->getAAInfo());
11577   }
11578
11579   // Turn 'store undef, Ptr' -> nothing.
11580   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11581     return Chain;
11582
11583   // Try to infer better alignment information than the store already has.
11584   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11585     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11586       if (Align > ST->getAlignment()) {
11587         SDValue NewStore =
11588                DAG.getTruncStore(Chain, SDLoc(N), Value,
11589                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11590                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11591                                  ST->getAAInfo());
11592         if (NewStore.getNode() != N)
11593           return CombineTo(ST, NewStore, true);
11594       }
11595     }
11596   }
11597
11598   // Try transforming a pair floating point load / store ops to integer
11599   // load / store ops.
11600   if (SDValue NewST = TransformFPLoadStorePair(N))
11601     return NewST;
11602
11603   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11604                                                   : DAG.getSubtarget().useAA();
11605 #ifndef NDEBUG
11606   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11607       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11608     UseAA = false;
11609 #endif
11610   if (UseAA && ST->isUnindexed()) {
11611     // FIXME: We should do this even without AA enabled. AA will just allow
11612     // FindBetterChain to work in more situations. The problem with this is that
11613     // any combine that expects memory operations to be on consecutive chains
11614     // first needs to be updated to look for users of the same chain.
11615
11616     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11617     // adjacent stores.
11618     if (findBetterNeighborChains(ST)) {
11619       // replaceStoreChain uses CombineTo, which handled all of the worklist
11620       // manipulation. Return the original node to not do anything else.
11621       return SDValue(ST, 0);
11622     }
11623   }
11624
11625   // Try transforming N to an indexed store.
11626   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11627     return SDValue(N, 0);
11628
11629   // FIXME: is there such a thing as a truncating indexed store?
11630   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11631       Value.getValueType().isInteger()) {
11632     // See if we can simplify the input to this truncstore with knowledge that
11633     // only the low bits are being used.  For example:
11634     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11635     SDValue Shorter =
11636       GetDemandedBits(Value,
11637                       APInt::getLowBitsSet(
11638                         Value.getValueType().getScalarType().getSizeInBits(),
11639                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11640     AddToWorklist(Value.getNode());
11641     if (Shorter.getNode())
11642       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11643                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11644
11645     // Otherwise, see if we can simplify the operation with
11646     // SimplifyDemandedBits, which only works if the value has a single use.
11647     if (SimplifyDemandedBits(Value,
11648                         APInt::getLowBitsSet(
11649                           Value.getValueType().getScalarType().getSizeInBits(),
11650                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11651       return SDValue(N, 0);
11652   }
11653
11654   // If this is a load followed by a store to the same location, then the store
11655   // is dead/noop.
11656   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11657     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11658         ST->isUnindexed() && !ST->isVolatile() &&
11659         // There can't be any side effects between the load and store, such as
11660         // a call or store.
11661         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11662       // The store is dead, remove it.
11663       return Chain;
11664     }
11665   }
11666
11667   // If this is a store followed by a store with the same value to the same
11668   // location, then the store is dead/noop.
11669   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11670     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11671         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11672         ST1->isUnindexed() && !ST1->isVolatile()) {
11673       // The store is dead, remove it.
11674       return Chain;
11675     }
11676   }
11677
11678   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11679   // truncating store.  We can do this even if this is already a truncstore.
11680   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11681       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11682       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11683                             ST->getMemoryVT())) {
11684     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11685                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11686   }
11687
11688   // Only perform this optimization before the types are legal, because we
11689   // don't want to perform this optimization on every DAGCombine invocation.
11690   if (!LegalTypes) {
11691     bool EverChanged = false;
11692
11693     do {
11694       // There can be multiple store sequences on the same chain.
11695       // Keep trying to merge store sequences until we are unable to do so
11696       // or until we merge the last store on the chain.
11697       bool Changed = MergeConsecutiveStores(ST);
11698       EverChanged |= Changed;
11699       if (!Changed) break;
11700     } while (ST->getOpcode() != ISD::DELETED_NODE);
11701
11702     if (EverChanged)
11703       return SDValue(N, 0);
11704   }
11705
11706   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11707   //
11708   // Make sure to do this only after attempting to merge stores in order to
11709   //  avoid changing the types of some subset of stores due to visit order,
11710   //  preventing their merging.
11711   if (isa<ConstantFPSDNode>(Value)) {
11712     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11713       return NewSt;
11714   }
11715
11716   return ReduceLoadOpStoreWidth(N);
11717 }
11718
11719 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11720   SDValue InVec = N->getOperand(0);
11721   SDValue InVal = N->getOperand(1);
11722   SDValue EltNo = N->getOperand(2);
11723   SDLoc dl(N);
11724
11725   // If the inserted element is an UNDEF, just use the input vector.
11726   if (InVal.getOpcode() == ISD::UNDEF)
11727     return InVec;
11728
11729   EVT VT = InVec.getValueType();
11730
11731   // If we can't generate a legal BUILD_VECTOR, exit
11732   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11733     return SDValue();
11734
11735   // Check that we know which element is being inserted
11736   if (!isa<ConstantSDNode>(EltNo))
11737     return SDValue();
11738   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11739
11740   // Canonicalize insert_vector_elt dag nodes.
11741   // Example:
11742   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11743   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11744   //
11745   // Do this only if the child insert_vector node has one use; also
11746   // do this only if indices are both constants and Idx1 < Idx0.
11747   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11748       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11749     unsigned OtherElt =
11750       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11751     if (Elt < OtherElt) {
11752       // Swap nodes.
11753       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11754                                   InVec.getOperand(0), InVal, EltNo);
11755       AddToWorklist(NewOp.getNode());
11756       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11757                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11758     }
11759   }
11760
11761   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11762   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11763   // vector elements.
11764   SmallVector<SDValue, 8> Ops;
11765   // Do not combine these two vectors if the output vector will not replace
11766   // the input vector.
11767   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11768     Ops.append(InVec.getNode()->op_begin(),
11769                InVec.getNode()->op_end());
11770   } else if (InVec.getOpcode() == ISD::UNDEF) {
11771     unsigned NElts = VT.getVectorNumElements();
11772     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11773   } else {
11774     return SDValue();
11775   }
11776
11777   // Insert the element
11778   if (Elt < Ops.size()) {
11779     // All the operands of BUILD_VECTOR must have the same type;
11780     // we enforce that here.
11781     EVT OpVT = Ops[0].getValueType();
11782     if (InVal.getValueType() != OpVT)
11783       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11784                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11785                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11786     Ops[Elt] = InVal;
11787   }
11788
11789   // Return the new vector
11790   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11791 }
11792
11793 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11794     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11795   EVT ResultVT = EVE->getValueType(0);
11796   EVT VecEltVT = InVecVT.getVectorElementType();
11797   unsigned Align = OriginalLoad->getAlignment();
11798   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11799       VecEltVT.getTypeForEVT(*DAG.getContext()));
11800
11801   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11802     return SDValue();
11803
11804   Align = NewAlign;
11805
11806   SDValue NewPtr = OriginalLoad->getBasePtr();
11807   SDValue Offset;
11808   EVT PtrType = NewPtr.getValueType();
11809   MachinePointerInfo MPI;
11810   SDLoc DL(EVE);
11811   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11812     int Elt = ConstEltNo->getZExtValue();
11813     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11814     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11815     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11816   } else {
11817     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11818     Offset = DAG.getNode(
11819         ISD::MUL, DL, PtrType, Offset,
11820         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11821     MPI = OriginalLoad->getPointerInfo();
11822   }
11823   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11824
11825   // The replacement we need to do here is a little tricky: we need to
11826   // replace an extractelement of a load with a load.
11827   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11828   // Note that this replacement assumes that the extractvalue is the only
11829   // use of the load; that's okay because we don't want to perform this
11830   // transformation in other cases anyway.
11831   SDValue Load;
11832   SDValue Chain;
11833   if (ResultVT.bitsGT(VecEltVT)) {
11834     // If the result type of vextract is wider than the load, then issue an
11835     // extending load instead.
11836     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11837                                                   VecEltVT)
11838                                    ? ISD::ZEXTLOAD
11839                                    : ISD::EXTLOAD;
11840     Load = DAG.getExtLoad(
11841         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11842         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11843         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11844     Chain = Load.getValue(1);
11845   } else {
11846     Load = DAG.getLoad(
11847         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11848         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11849         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11850     Chain = Load.getValue(1);
11851     if (ResultVT.bitsLT(VecEltVT))
11852       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11853     else
11854       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11855   }
11856   WorklistRemover DeadNodes(*this);
11857   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11858   SDValue To[] = { Load, Chain };
11859   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11860   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11861   // worklist explicitly as well.
11862   AddToWorklist(Load.getNode());
11863   AddUsersToWorklist(Load.getNode()); // Add users too
11864   // Make sure to revisit this node to clean it up; it will usually be dead.
11865   AddToWorklist(EVE);
11866   ++OpsNarrowed;
11867   return SDValue(EVE, 0);
11868 }
11869
11870 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11871   // (vextract (scalar_to_vector val, 0) -> val
11872   SDValue InVec = N->getOperand(0);
11873   EVT VT = InVec.getValueType();
11874   EVT NVT = N->getValueType(0);
11875
11876   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11877     // Check if the result type doesn't match the inserted element type. A
11878     // SCALAR_TO_VECTOR may truncate the inserted element and the
11879     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11880     SDValue InOp = InVec.getOperand(0);
11881     if (InOp.getValueType() != NVT) {
11882       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11883       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11884     }
11885     return InOp;
11886   }
11887
11888   SDValue EltNo = N->getOperand(1);
11889   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
11890
11891   // extract_vector_elt (build_vector x, y), 1 -> y
11892   if (ConstEltNo &&
11893       InVec.getOpcode() == ISD::BUILD_VECTOR &&
11894       TLI.isTypeLegal(VT) &&
11895       (InVec.hasOneUse() ||
11896        TLI.aggressivelyPreferBuildVectorSources(VT))) {
11897     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
11898     EVT InEltVT = Elt.getValueType();
11899
11900     // Sometimes build_vector's scalar input types do not match result type.
11901     if (NVT == InEltVT)
11902       return Elt;
11903
11904     // TODO: It may be useful to truncate if free if the build_vector implicitly
11905     // converts.
11906   }
11907
11908   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11909   // We only perform this optimization before the op legalization phase because
11910   // we may introduce new vector instructions which are not backed by TD
11911   // patterns. For example on AVX, extracting elements from a wide vector
11912   // without using extract_subvector. However, if we can find an underlying
11913   // scalar value, then we can always use that.
11914   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
11915     int NumElem = VT.getVectorNumElements();
11916     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11917     // Find the new index to extract from.
11918     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
11919
11920     // Extracting an undef index is undef.
11921     if (OrigElt == -1)
11922       return DAG.getUNDEF(NVT);
11923
11924     // Select the right vector half to extract from.
11925     SDValue SVInVec;
11926     if (OrigElt < NumElem) {
11927       SVInVec = InVec->getOperand(0);
11928     } else {
11929       SVInVec = InVec->getOperand(1);
11930       OrigElt -= NumElem;
11931     }
11932
11933     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11934       SDValue InOp = SVInVec.getOperand(OrigElt);
11935       if (InOp.getValueType() != NVT) {
11936         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11937         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11938       }
11939
11940       return InOp;
11941     }
11942
11943     // FIXME: We should handle recursing on other vector shuffles and
11944     // scalar_to_vector here as well.
11945
11946     if (!LegalOperations) {
11947       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11948       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11949                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11950     }
11951   }
11952
11953   bool BCNumEltsChanged = false;
11954   EVT ExtVT = VT.getVectorElementType();
11955   EVT LVT = ExtVT;
11956
11957   // If the result of load has to be truncated, then it's not necessarily
11958   // profitable.
11959   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11960     return SDValue();
11961
11962   if (InVec.getOpcode() == ISD::BITCAST) {
11963     // Don't duplicate a load with other uses.
11964     if (!InVec.hasOneUse())
11965       return SDValue();
11966
11967     EVT BCVT = InVec.getOperand(0).getValueType();
11968     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11969       return SDValue();
11970     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11971       BCNumEltsChanged = true;
11972     InVec = InVec.getOperand(0);
11973     ExtVT = BCVT.getVectorElementType();
11974   }
11975
11976   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11977   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11978       ISD::isNormalLoad(InVec.getNode()) &&
11979       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11980     SDValue Index = N->getOperand(1);
11981     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11982       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11983                                                            OrigLoad);
11984   }
11985
11986   // Perform only after legalization to ensure build_vector / vector_shuffle
11987   // optimizations have already been done.
11988   if (!LegalOperations) return SDValue();
11989
11990   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11991   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11992   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11993
11994   if (ConstEltNo) {
11995     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11996
11997     LoadSDNode *LN0 = nullptr;
11998     const ShuffleVectorSDNode *SVN = nullptr;
11999     if (ISD::isNormalLoad(InVec.getNode())) {
12000       LN0 = cast<LoadSDNode>(InVec);
12001     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12002                InVec.getOperand(0).getValueType() == ExtVT &&
12003                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12004       // Don't duplicate a load with other uses.
12005       if (!InVec.hasOneUse())
12006         return SDValue();
12007
12008       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12009     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12010       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12011       // =>
12012       // (load $addr+1*size)
12013
12014       // Don't duplicate a load with other uses.
12015       if (!InVec.hasOneUse())
12016         return SDValue();
12017
12018       // If the bit convert changed the number of elements, it is unsafe
12019       // to examine the mask.
12020       if (BCNumEltsChanged)
12021         return SDValue();
12022
12023       // Select the input vector, guarding against out of range extract vector.
12024       unsigned NumElems = VT.getVectorNumElements();
12025       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12026       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12027
12028       if (InVec.getOpcode() == ISD::BITCAST) {
12029         // Don't duplicate a load with other uses.
12030         if (!InVec.hasOneUse())
12031           return SDValue();
12032
12033         InVec = InVec.getOperand(0);
12034       }
12035       if (ISD::isNormalLoad(InVec.getNode())) {
12036         LN0 = cast<LoadSDNode>(InVec);
12037         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12038         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12039       }
12040     }
12041
12042     // Make sure we found a non-volatile load and the extractelement is
12043     // the only use.
12044     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12045       return SDValue();
12046
12047     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12048     if (Elt == -1)
12049       return DAG.getUNDEF(LVT);
12050
12051     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12052   }
12053
12054   return SDValue();
12055 }
12056
12057 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12058 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12059   // We perform this optimization post type-legalization because
12060   // the type-legalizer often scalarizes integer-promoted vectors.
12061   // Performing this optimization before may create bit-casts which
12062   // will be type-legalized to complex code sequences.
12063   // We perform this optimization only before the operation legalizer because we
12064   // may introduce illegal operations.
12065   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12066     return SDValue();
12067
12068   unsigned NumInScalars = N->getNumOperands();
12069   SDLoc dl(N);
12070   EVT VT = N->getValueType(0);
12071
12072   // Check to see if this is a BUILD_VECTOR of a bunch of values
12073   // which come from any_extend or zero_extend nodes. If so, we can create
12074   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12075   // optimizations. We do not handle sign-extend because we can't fill the sign
12076   // using shuffles.
12077   EVT SourceType = MVT::Other;
12078   bool AllAnyExt = true;
12079
12080   for (unsigned i = 0; i != NumInScalars; ++i) {
12081     SDValue In = N->getOperand(i);
12082     // Ignore undef inputs.
12083     if (In.getOpcode() == ISD::UNDEF) continue;
12084
12085     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12086     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12087
12088     // Abort if the element is not an extension.
12089     if (!ZeroExt && !AnyExt) {
12090       SourceType = MVT::Other;
12091       break;
12092     }
12093
12094     // The input is a ZeroExt or AnyExt. Check the original type.
12095     EVT InTy = In.getOperand(0).getValueType();
12096
12097     // Check that all of the widened source types are the same.
12098     if (SourceType == MVT::Other)
12099       // First time.
12100       SourceType = InTy;
12101     else if (InTy != SourceType) {
12102       // Multiple income types. Abort.
12103       SourceType = MVT::Other;
12104       break;
12105     }
12106
12107     // Check if all of the extends are ANY_EXTENDs.
12108     AllAnyExt &= AnyExt;
12109   }
12110
12111   // In order to have valid types, all of the inputs must be extended from the
12112   // same source type and all of the inputs must be any or zero extend.
12113   // Scalar sizes must be a power of two.
12114   EVT OutScalarTy = VT.getScalarType();
12115   bool ValidTypes = SourceType != MVT::Other &&
12116                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12117                  isPowerOf2_32(SourceType.getSizeInBits());
12118
12119   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12120   // turn into a single shuffle instruction.
12121   if (!ValidTypes)
12122     return SDValue();
12123
12124   bool isLE = DAG.getDataLayout().isLittleEndian();
12125   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12126   assert(ElemRatio > 1 && "Invalid element size ratio");
12127   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12128                                DAG.getConstant(0, SDLoc(N), SourceType);
12129
12130   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12131   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12132
12133   // Populate the new build_vector
12134   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12135     SDValue Cast = N->getOperand(i);
12136     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12137             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12138             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12139     SDValue In;
12140     if (Cast.getOpcode() == ISD::UNDEF)
12141       In = DAG.getUNDEF(SourceType);
12142     else
12143       In = Cast->getOperand(0);
12144     unsigned Index = isLE ? (i * ElemRatio) :
12145                             (i * ElemRatio + (ElemRatio - 1));
12146
12147     assert(Index < Ops.size() && "Invalid index");
12148     Ops[Index] = In;
12149   }
12150
12151   // The type of the new BUILD_VECTOR node.
12152   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12153   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12154          "Invalid vector size");
12155   // Check if the new vector type is legal.
12156   if (!isTypeLegal(VecVT)) return SDValue();
12157
12158   // Make the new BUILD_VECTOR.
12159   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12160
12161   // The new BUILD_VECTOR node has the potential to be further optimized.
12162   AddToWorklist(BV.getNode());
12163   // Bitcast to the desired type.
12164   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12165 }
12166
12167 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12168   EVT VT = N->getValueType(0);
12169
12170   unsigned NumInScalars = N->getNumOperands();
12171   SDLoc dl(N);
12172
12173   EVT SrcVT = MVT::Other;
12174   unsigned Opcode = ISD::DELETED_NODE;
12175   unsigned NumDefs = 0;
12176
12177   for (unsigned i = 0; i != NumInScalars; ++i) {
12178     SDValue In = N->getOperand(i);
12179     unsigned Opc = In.getOpcode();
12180
12181     if (Opc == ISD::UNDEF)
12182       continue;
12183
12184     // If all scalar values are floats and converted from integers.
12185     if (Opcode == ISD::DELETED_NODE &&
12186         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12187       Opcode = Opc;
12188     }
12189
12190     if (Opc != Opcode)
12191       return SDValue();
12192
12193     EVT InVT = In.getOperand(0).getValueType();
12194
12195     // If all scalar values are typed differently, bail out. It's chosen to
12196     // simplify BUILD_VECTOR of integer types.
12197     if (SrcVT == MVT::Other)
12198       SrcVT = InVT;
12199     if (SrcVT != InVT)
12200       return SDValue();
12201     NumDefs++;
12202   }
12203
12204   // If the vector has just one element defined, it's not worth to fold it into
12205   // a vectorized one.
12206   if (NumDefs < 2)
12207     return SDValue();
12208
12209   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12210          && "Should only handle conversion from integer to float.");
12211   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12212
12213   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12214
12215   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12216     return SDValue();
12217
12218   // Just because the floating-point vector type is legal does not necessarily
12219   // mean that the corresponding integer vector type is.
12220   if (!isTypeLegal(NVT))
12221     return SDValue();
12222
12223   SmallVector<SDValue, 8> Opnds;
12224   for (unsigned i = 0; i != NumInScalars; ++i) {
12225     SDValue In = N->getOperand(i);
12226
12227     if (In.getOpcode() == ISD::UNDEF)
12228       Opnds.push_back(DAG.getUNDEF(SrcVT));
12229     else
12230       Opnds.push_back(In.getOperand(0));
12231   }
12232   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12233   AddToWorklist(BV.getNode());
12234
12235   return DAG.getNode(Opcode, dl, VT, BV);
12236 }
12237
12238 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12239   unsigned NumInScalars = N->getNumOperands();
12240   SDLoc dl(N);
12241   EVT VT = N->getValueType(0);
12242
12243   // A vector built entirely of undefs is undef.
12244   if (ISD::allOperandsUndef(N))
12245     return DAG.getUNDEF(VT);
12246
12247   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12248     return V;
12249
12250   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12251     return V;
12252
12253   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12254   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12255   // at most two distinct vectors, turn this into a shuffle node.
12256
12257   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12258   if (!isTypeLegal(VT))
12259     return SDValue();
12260
12261   // May only combine to shuffle after legalize if shuffle is legal.
12262   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12263     return SDValue();
12264
12265   SDValue VecIn1, VecIn2;
12266   bool UsesZeroVector = false;
12267   for (unsigned i = 0; i != NumInScalars; ++i) {
12268     SDValue Op = N->getOperand(i);
12269     // Ignore undef inputs.
12270     if (Op.getOpcode() == ISD::UNDEF) continue;
12271
12272     // See if we can combine this build_vector into a blend with a zero vector.
12273     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12274       UsesZeroVector = true;
12275       continue;
12276     }
12277
12278     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12279     // constant index, bail out.
12280     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12281         !isa<ConstantSDNode>(Op.getOperand(1))) {
12282       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12283       break;
12284     }
12285
12286     // We allow up to two distinct input vectors.
12287     SDValue ExtractedFromVec = Op.getOperand(0);
12288     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12289       continue;
12290
12291     if (!VecIn1.getNode()) {
12292       VecIn1 = ExtractedFromVec;
12293     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12294       VecIn2 = ExtractedFromVec;
12295     } else {
12296       // Too many inputs.
12297       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12298       break;
12299     }
12300   }
12301
12302   // If everything is good, we can make a shuffle operation.
12303   if (VecIn1.getNode()) {
12304     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12305     SmallVector<int, 8> Mask;
12306     for (unsigned i = 0; i != NumInScalars; ++i) {
12307       unsigned Opcode = N->getOperand(i).getOpcode();
12308       if (Opcode == ISD::UNDEF) {
12309         Mask.push_back(-1);
12310         continue;
12311       }
12312
12313       // Operands can also be zero.
12314       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12315         assert(UsesZeroVector &&
12316                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12317                "Unexpected node found!");
12318         Mask.push_back(NumInScalars+i);
12319         continue;
12320       }
12321
12322       // If extracting from the first vector, just use the index directly.
12323       SDValue Extract = N->getOperand(i);
12324       SDValue ExtVal = Extract.getOperand(1);
12325       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12326       if (Extract.getOperand(0) == VecIn1) {
12327         Mask.push_back(ExtIndex);
12328         continue;
12329       }
12330
12331       // Otherwise, use InIdx + InputVecSize
12332       Mask.push_back(InNumElements + ExtIndex);
12333     }
12334
12335     // Avoid introducing illegal shuffles with zero.
12336     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12337       return SDValue();
12338
12339     // We can't generate a shuffle node with mismatched input and output types.
12340     // Attempt to transform a single input vector to the correct type.
12341     if ((VT != VecIn1.getValueType())) {
12342       // If the input vector type has a different base type to the output
12343       // vector type, bail out.
12344       EVT VTElemType = VT.getVectorElementType();
12345       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12346           (VecIn2.getNode() &&
12347            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12348         return SDValue();
12349
12350       // If the input vector is too small, widen it.
12351       // We only support widening of vectors which are half the size of the
12352       // output registers. For example XMM->YMM widening on X86 with AVX.
12353       EVT VecInT = VecIn1.getValueType();
12354       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12355         // If we only have one small input, widen it by adding undef values.
12356         if (!VecIn2.getNode())
12357           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12358                                DAG.getUNDEF(VecIn1.getValueType()));
12359         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12360           // If we have two small inputs of the same type, try to concat them.
12361           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12362           VecIn2 = SDValue(nullptr, 0);
12363         } else
12364           return SDValue();
12365       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12366         // If the input vector is too large, try to split it.
12367         // We don't support having two input vectors that are too large.
12368         // If the zero vector was used, we can not split the vector,
12369         // since we'd need 3 inputs.
12370         if (UsesZeroVector || VecIn2.getNode())
12371           return SDValue();
12372
12373         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12374           return SDValue();
12375
12376         // Try to replace VecIn1 with two extract_subvectors
12377         // No need to update the masks, they should still be correct.
12378         VecIn2 = DAG.getNode(
12379             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12380             DAG.getConstant(VT.getVectorNumElements(), dl,
12381                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12382         VecIn1 = DAG.getNode(
12383             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12384             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12385       } else
12386         return SDValue();
12387     }
12388
12389     if (UsesZeroVector)
12390       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12391                                 DAG.getConstantFP(0.0, dl, VT);
12392     else
12393       // If VecIn2 is unused then change it to undef.
12394       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12395
12396     // Check that we were able to transform all incoming values to the same
12397     // type.
12398     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12399         VecIn1.getValueType() != VT)
12400           return SDValue();
12401
12402     // Return the new VECTOR_SHUFFLE node.
12403     SDValue Ops[2];
12404     Ops[0] = VecIn1;
12405     Ops[1] = VecIn2;
12406     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12407   }
12408
12409   return SDValue();
12410 }
12411
12412 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12414   EVT OpVT = N->getOperand(0).getValueType();
12415
12416   // If the operands are legal vectors, leave them alone.
12417   if (TLI.isTypeLegal(OpVT))
12418     return SDValue();
12419
12420   SDLoc DL(N);
12421   EVT VT = N->getValueType(0);
12422   SmallVector<SDValue, 8> Ops;
12423
12424   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12425   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12426
12427   // Keep track of what we encounter.
12428   bool AnyInteger = false;
12429   bool AnyFP = false;
12430   for (const SDValue &Op : N->ops()) {
12431     if (ISD::BITCAST == Op.getOpcode() &&
12432         !Op.getOperand(0).getValueType().isVector())
12433       Ops.push_back(Op.getOperand(0));
12434     else if (ISD::UNDEF == Op.getOpcode())
12435       Ops.push_back(ScalarUndef);
12436     else
12437       return SDValue();
12438
12439     // Note whether we encounter an integer or floating point scalar.
12440     // If it's neither, bail out, it could be something weird like x86mmx.
12441     EVT LastOpVT = Ops.back().getValueType();
12442     if (LastOpVT.isFloatingPoint())
12443       AnyFP = true;
12444     else if (LastOpVT.isInteger())
12445       AnyInteger = true;
12446     else
12447       return SDValue();
12448   }
12449
12450   // If any of the operands is a floating point scalar bitcast to a vector,
12451   // use floating point types throughout, and bitcast everything.
12452   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12453   if (AnyFP) {
12454     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12455     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12456     if (AnyInteger) {
12457       for (SDValue &Op : Ops) {
12458         if (Op.getValueType() == SVT)
12459           continue;
12460         if (Op.getOpcode() == ISD::UNDEF)
12461           Op = ScalarUndef;
12462         else
12463           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12464       }
12465     }
12466   }
12467
12468   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12469                                VT.getSizeInBits() / SVT.getSizeInBits());
12470   return DAG.getNode(ISD::BITCAST, DL, VT,
12471                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12472 }
12473
12474 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12475 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12476 // most two distinct vectors the same size as the result, attempt to turn this
12477 // into a legal shuffle.
12478 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12479   EVT VT = N->getValueType(0);
12480   EVT OpVT = N->getOperand(0).getValueType();
12481   int NumElts = VT.getVectorNumElements();
12482   int NumOpElts = OpVT.getVectorNumElements();
12483
12484   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12485   SmallVector<int, 8> Mask;
12486
12487   for (SDValue Op : N->ops()) {
12488     // Peek through any bitcast.
12489     while (Op.getOpcode() == ISD::BITCAST)
12490       Op = Op.getOperand(0);
12491
12492     // UNDEF nodes convert to UNDEF shuffle mask values.
12493     if (Op.getOpcode() == ISD::UNDEF) {
12494       Mask.append((unsigned)NumOpElts, -1);
12495       continue;
12496     }
12497
12498     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12499       return SDValue();
12500
12501     // What vector are we extracting the subvector from and at what index?
12502     SDValue ExtVec = Op.getOperand(0);
12503
12504     // We want the EVT of the original extraction to correctly scale the
12505     // extraction index.
12506     EVT ExtVT = ExtVec.getValueType();
12507
12508     // Peek through any bitcast.
12509     while (ExtVec.getOpcode() == ISD::BITCAST)
12510       ExtVec = ExtVec.getOperand(0);
12511
12512     // UNDEF nodes convert to UNDEF shuffle mask values.
12513     if (ExtVec.getOpcode() == ISD::UNDEF) {
12514       Mask.append((unsigned)NumOpElts, -1);
12515       continue;
12516     }
12517
12518     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12519       return SDValue();
12520     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12521
12522     // Ensure that we are extracting a subvector from a vector the same
12523     // size as the result.
12524     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12525       return SDValue();
12526
12527     // Scale the subvector index to account for any bitcast.
12528     int NumExtElts = ExtVT.getVectorNumElements();
12529     if (0 == (NumExtElts % NumElts))
12530       ExtIdx /= (NumExtElts / NumElts);
12531     else if (0 == (NumElts % NumExtElts))
12532       ExtIdx *= (NumElts / NumExtElts);
12533     else
12534       return SDValue();
12535
12536     // At most we can reference 2 inputs in the final shuffle.
12537     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12538       SV0 = ExtVec;
12539       for (int i = 0; i != NumOpElts; ++i)
12540         Mask.push_back(i + ExtIdx);
12541     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12542       SV1 = ExtVec;
12543       for (int i = 0; i != NumOpElts; ++i)
12544         Mask.push_back(i + ExtIdx + NumElts);
12545     } else {
12546       return SDValue();
12547     }
12548   }
12549
12550   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12551     return SDValue();
12552
12553   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12554                               DAG.getBitcast(VT, SV1), Mask);
12555 }
12556
12557 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12558   // If we only have one input vector, we don't need to do any concatenation.
12559   if (N->getNumOperands() == 1)
12560     return N->getOperand(0);
12561
12562   // Check if all of the operands are undefs.
12563   EVT VT = N->getValueType(0);
12564   if (ISD::allOperandsUndef(N))
12565     return DAG.getUNDEF(VT);
12566
12567   // Optimize concat_vectors where all but the first of the vectors are undef.
12568   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12569         return Op.getOpcode() == ISD::UNDEF;
12570       })) {
12571     SDValue In = N->getOperand(0);
12572     assert(In.getValueType().isVector() && "Must concat vectors");
12573
12574     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12575     if (In->getOpcode() == ISD::BITCAST &&
12576         !In->getOperand(0)->getValueType(0).isVector()) {
12577       SDValue Scalar = In->getOperand(0);
12578
12579       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12580       // look through the trunc so we can still do the transform:
12581       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12582       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12583           !TLI.isTypeLegal(Scalar.getValueType()) &&
12584           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12585         Scalar = Scalar->getOperand(0);
12586
12587       EVT SclTy = Scalar->getValueType(0);
12588
12589       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12590         return SDValue();
12591
12592       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12593                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12594       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12595         return SDValue();
12596
12597       SDLoc dl = SDLoc(N);
12598       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12599       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12600     }
12601   }
12602
12603   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12604   // We have already tested above for an UNDEF only concatenation.
12605   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12606   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12607   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12608     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12609   };
12610   bool AllBuildVectorsOrUndefs =
12611       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12612   if (AllBuildVectorsOrUndefs) {
12613     SmallVector<SDValue, 8> Opnds;
12614     EVT SVT = VT.getScalarType();
12615
12616     EVT MinVT = SVT;
12617     if (!SVT.isFloatingPoint()) {
12618       // If BUILD_VECTOR are from built from integer, they may have different
12619       // operand types. Get the smallest type and truncate all operands to it.
12620       bool FoundMinVT = false;
12621       for (const SDValue &Op : N->ops())
12622         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12623           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12624           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12625           FoundMinVT = true;
12626         }
12627       assert(FoundMinVT && "Concat vector type mismatch");
12628     }
12629
12630     for (const SDValue &Op : N->ops()) {
12631       EVT OpVT = Op.getValueType();
12632       unsigned NumElts = OpVT.getVectorNumElements();
12633
12634       if (ISD::UNDEF == Op.getOpcode())
12635         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12636
12637       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12638         if (SVT.isFloatingPoint()) {
12639           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12640           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12641         } else {
12642           for (unsigned i = 0; i != NumElts; ++i)
12643             Opnds.push_back(
12644                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12645         }
12646       }
12647     }
12648
12649     assert(VT.getVectorNumElements() == Opnds.size() &&
12650            "Concat vector type mismatch");
12651     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12652   }
12653
12654   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12655   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12656     return V;
12657
12658   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12659   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12660     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12661       return V;
12662
12663   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12664   // nodes often generate nop CONCAT_VECTOR nodes.
12665   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12666   // place the incoming vectors at the exact same location.
12667   SDValue SingleSource = SDValue();
12668   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12669
12670   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12671     SDValue Op = N->getOperand(i);
12672
12673     if (Op.getOpcode() == ISD::UNDEF)
12674       continue;
12675
12676     // Check if this is the identity extract:
12677     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12678       return SDValue();
12679
12680     // Find the single incoming vector for the extract_subvector.
12681     if (SingleSource.getNode()) {
12682       if (Op.getOperand(0) != SingleSource)
12683         return SDValue();
12684     } else {
12685       SingleSource = Op.getOperand(0);
12686
12687       // Check the source type is the same as the type of the result.
12688       // If not, this concat may extend the vector, so we can not
12689       // optimize it away.
12690       if (SingleSource.getValueType() != N->getValueType(0))
12691         return SDValue();
12692     }
12693
12694     unsigned IdentityIndex = i * PartNumElem;
12695     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12696     // The extract index must be constant.
12697     if (!CS)
12698       return SDValue();
12699
12700     // Check that we are reading from the identity index.
12701     if (CS->getZExtValue() != IdentityIndex)
12702       return SDValue();
12703   }
12704
12705   if (SingleSource.getNode())
12706     return SingleSource;
12707
12708   return SDValue();
12709 }
12710
12711 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12712   EVT NVT = N->getValueType(0);
12713   SDValue V = N->getOperand(0);
12714
12715   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12716     // Combine:
12717     //    (extract_subvec (concat V1, V2, ...), i)
12718     // Into:
12719     //    Vi if possible
12720     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12721     // type.
12722     if (V->getOperand(0).getValueType() != NVT)
12723       return SDValue();
12724     unsigned Idx = N->getConstantOperandVal(1);
12725     unsigned NumElems = NVT.getVectorNumElements();
12726     assert((Idx % NumElems) == 0 &&
12727            "IDX in concat is not a multiple of the result vector length.");
12728     return V->getOperand(Idx / NumElems);
12729   }
12730
12731   // Skip bitcasting
12732   if (V->getOpcode() == ISD::BITCAST)
12733     V = V.getOperand(0);
12734
12735   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12736     SDLoc dl(N);
12737     // Handle only simple case where vector being inserted and vector
12738     // being extracted are of same type, and are half size of larger vectors.
12739     EVT BigVT = V->getOperand(0).getValueType();
12740     EVT SmallVT = V->getOperand(1).getValueType();
12741     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12742       return SDValue();
12743
12744     // Only handle cases where both indexes are constants with the same type.
12745     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12746     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12747
12748     if (InsIdx && ExtIdx &&
12749         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12750         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12751       // Combine:
12752       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12753       // Into:
12754       //    indices are equal or bit offsets are equal => V1
12755       //    otherwise => (extract_subvec V1, ExtIdx)
12756       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12757           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12758         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12759       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12760                          DAG.getNode(ISD::BITCAST, dl,
12761                                      N->getOperand(0).getValueType(),
12762                                      V->getOperand(0)), N->getOperand(1));
12763     }
12764   }
12765
12766   return SDValue();
12767 }
12768
12769 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12770                                                  SDValue V, SelectionDAG &DAG) {
12771   SDLoc DL(V);
12772   EVT VT = V.getValueType();
12773
12774   switch (V.getOpcode()) {
12775   default:
12776     return V;
12777
12778   case ISD::CONCAT_VECTORS: {
12779     EVT OpVT = V->getOperand(0).getValueType();
12780     int OpSize = OpVT.getVectorNumElements();
12781     SmallBitVector OpUsedElements(OpSize, false);
12782     bool FoundSimplification = false;
12783     SmallVector<SDValue, 4> NewOps;
12784     NewOps.reserve(V->getNumOperands());
12785     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12786       SDValue Op = V->getOperand(i);
12787       bool OpUsed = false;
12788       for (int j = 0; j < OpSize; ++j)
12789         if (UsedElements[i * OpSize + j]) {
12790           OpUsedElements[j] = true;
12791           OpUsed = true;
12792         }
12793       NewOps.push_back(
12794           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12795                  : DAG.getUNDEF(OpVT));
12796       FoundSimplification |= Op == NewOps.back();
12797       OpUsedElements.reset();
12798     }
12799     if (FoundSimplification)
12800       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12801     return V;
12802   }
12803
12804   case ISD::INSERT_SUBVECTOR: {
12805     SDValue BaseV = V->getOperand(0);
12806     SDValue SubV = V->getOperand(1);
12807     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12808     if (!IdxN)
12809       return V;
12810
12811     int SubSize = SubV.getValueType().getVectorNumElements();
12812     int Idx = IdxN->getZExtValue();
12813     bool SubVectorUsed = false;
12814     SmallBitVector SubUsedElements(SubSize, false);
12815     for (int i = 0; i < SubSize; ++i)
12816       if (UsedElements[i + Idx]) {
12817         SubVectorUsed = true;
12818         SubUsedElements[i] = true;
12819         UsedElements[i + Idx] = false;
12820       }
12821
12822     // Now recurse on both the base and sub vectors.
12823     SDValue SimplifiedSubV =
12824         SubVectorUsed
12825             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12826             : DAG.getUNDEF(SubV.getValueType());
12827     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12828     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12829       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12830                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12831     return V;
12832   }
12833   }
12834 }
12835
12836 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12837                                        SDValue N1, SelectionDAG &DAG) {
12838   EVT VT = SVN->getValueType(0);
12839   int NumElts = VT.getVectorNumElements();
12840   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12841   for (int M : SVN->getMask())
12842     if (M >= 0 && M < NumElts)
12843       N0UsedElements[M] = true;
12844     else if (M >= NumElts)
12845       N1UsedElements[M - NumElts] = true;
12846
12847   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12848   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12849   if (S0 == N0 && S1 == N1)
12850     return SDValue();
12851
12852   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12853 }
12854
12855 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12856 // or turn a shuffle of a single concat into simpler shuffle then concat.
12857 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12858   EVT VT = N->getValueType(0);
12859   unsigned NumElts = VT.getVectorNumElements();
12860
12861   SDValue N0 = N->getOperand(0);
12862   SDValue N1 = N->getOperand(1);
12863   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12864
12865   SmallVector<SDValue, 4> Ops;
12866   EVT ConcatVT = N0.getOperand(0).getValueType();
12867   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12868   unsigned NumConcats = NumElts / NumElemsPerConcat;
12869
12870   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12871   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12872   // half vector elements.
12873   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12874       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12875                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12876     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12877                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
12878     N1 = DAG.getUNDEF(ConcatVT);
12879     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12880   }
12881
12882   // Look at every vector that's inserted. We're looking for exact
12883   // subvector-sized copies from a concatenated vector
12884   for (unsigned I = 0; I != NumConcats; ++I) {
12885     // Make sure we're dealing with a copy.
12886     unsigned Begin = I * NumElemsPerConcat;
12887     bool AllUndef = true, NoUndef = true;
12888     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12889       if (SVN->getMaskElt(J) >= 0)
12890         AllUndef = false;
12891       else
12892         NoUndef = false;
12893     }
12894
12895     if (NoUndef) {
12896       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12897         return SDValue();
12898
12899       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12900         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12901           return SDValue();
12902
12903       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12904       if (FirstElt < N0.getNumOperands())
12905         Ops.push_back(N0.getOperand(FirstElt));
12906       else
12907         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12908
12909     } else if (AllUndef) {
12910       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12911     } else { // Mixed with general masks and undefs, can't do optimization.
12912       return SDValue();
12913     }
12914   }
12915
12916   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12917 }
12918
12919 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12920   EVT VT = N->getValueType(0);
12921   unsigned NumElts = VT.getVectorNumElements();
12922
12923   SDValue N0 = N->getOperand(0);
12924   SDValue N1 = N->getOperand(1);
12925
12926   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12927
12928   // Canonicalize shuffle undef, undef -> undef
12929   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12930     return DAG.getUNDEF(VT);
12931
12932   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12933
12934   // Canonicalize shuffle v, v -> v, undef
12935   if (N0 == N1) {
12936     SmallVector<int, 8> NewMask;
12937     for (unsigned i = 0; i != NumElts; ++i) {
12938       int Idx = SVN->getMaskElt(i);
12939       if (Idx >= (int)NumElts) Idx -= NumElts;
12940       NewMask.push_back(Idx);
12941     }
12942     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12943                                 &NewMask[0]);
12944   }
12945
12946   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12947   if (N0.getOpcode() == ISD::UNDEF) {
12948     SmallVector<int, 8> NewMask;
12949     for (unsigned i = 0; i != NumElts; ++i) {
12950       int Idx = SVN->getMaskElt(i);
12951       if (Idx >= 0) {
12952         if (Idx >= (int)NumElts)
12953           Idx -= NumElts;
12954         else
12955           Idx = -1; // remove reference to lhs
12956       }
12957       NewMask.push_back(Idx);
12958     }
12959     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12960                                 &NewMask[0]);
12961   }
12962
12963   // Remove references to rhs if it is undef
12964   if (N1.getOpcode() == ISD::UNDEF) {
12965     bool Changed = false;
12966     SmallVector<int, 8> NewMask;
12967     for (unsigned i = 0; i != NumElts; ++i) {
12968       int Idx = SVN->getMaskElt(i);
12969       if (Idx >= (int)NumElts) {
12970         Idx = -1;
12971         Changed = true;
12972       }
12973       NewMask.push_back(Idx);
12974     }
12975     if (Changed)
12976       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12977   }
12978
12979   // If it is a splat, check if the argument vector is another splat or a
12980   // build_vector.
12981   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12982     SDNode *V = N0.getNode();
12983
12984     // If this is a bit convert that changes the element type of the vector but
12985     // not the number of vector elements, look through it.  Be careful not to
12986     // look though conversions that change things like v4f32 to v2f64.
12987     if (V->getOpcode() == ISD::BITCAST) {
12988       SDValue ConvInput = V->getOperand(0);
12989       if (ConvInput.getValueType().isVector() &&
12990           ConvInput.getValueType().getVectorNumElements() == NumElts)
12991         V = ConvInput.getNode();
12992     }
12993
12994     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12995       assert(V->getNumOperands() == NumElts &&
12996              "BUILD_VECTOR has wrong number of operands");
12997       SDValue Base;
12998       bool AllSame = true;
12999       for (unsigned i = 0; i != NumElts; ++i) {
13000         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13001           Base = V->getOperand(i);
13002           break;
13003         }
13004       }
13005       // Splat of <u, u, u, u>, return <u, u, u, u>
13006       if (!Base.getNode())
13007         return N0;
13008       for (unsigned i = 0; i != NumElts; ++i) {
13009         if (V->getOperand(i) != Base) {
13010           AllSame = false;
13011           break;
13012         }
13013       }
13014       // Splat of <x, x, x, x>, return <x, x, x, x>
13015       if (AllSame)
13016         return N0;
13017
13018       // Canonicalize any other splat as a build_vector.
13019       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13020       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13021       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13022                                   V->getValueType(0), Ops);
13023
13024       // We may have jumped through bitcasts, so the type of the
13025       // BUILD_VECTOR may not match the type of the shuffle.
13026       if (V->getValueType(0) != VT)
13027         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13028       return NewBV;
13029     }
13030   }
13031
13032   // There are various patterns used to build up a vector from smaller vectors,
13033   // subvectors, or elements. Scan chains of these and replace unused insertions
13034   // or components with undef.
13035   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13036     return S;
13037
13038   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13039       Level < AfterLegalizeVectorOps &&
13040       (N1.getOpcode() == ISD::UNDEF ||
13041       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13042        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13043     SDValue V = partitionShuffleOfConcats(N, DAG);
13044
13045     if (V.getNode())
13046       return V;
13047   }
13048
13049   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13050   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13051   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13052     SmallVector<SDValue, 8> Ops;
13053     for (int M : SVN->getMask()) {
13054       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13055       if (M >= 0) {
13056         int Idx = M % NumElts;
13057         SDValue &S = (M < (int)NumElts ? N0 : N1);
13058         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13059           Op = S.getOperand(Idx);
13060         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13061           if (Idx == 0)
13062             Op = S.getOperand(0);
13063         } else {
13064           // Operand can't be combined - bail out.
13065           break;
13066         }
13067       }
13068       Ops.push_back(Op);
13069     }
13070     if (Ops.size() == VT.getVectorNumElements()) {
13071       // BUILD_VECTOR requires all inputs to be of the same type, find the
13072       // maximum type and extend them all.
13073       EVT SVT = VT.getScalarType();
13074       if (SVT.isInteger())
13075         for (SDValue &Op : Ops)
13076           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13077       if (SVT != VT.getScalarType())
13078         for (SDValue &Op : Ops)
13079           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13080                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13081                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13082       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13083     }
13084   }
13085
13086   // If this shuffle only has a single input that is a bitcasted shuffle,
13087   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13088   // back to their original types.
13089   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13090       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13091       TLI.isTypeLegal(VT)) {
13092
13093     // Peek through the bitcast only if there is one user.
13094     SDValue BC0 = N0;
13095     while (BC0.getOpcode() == ISD::BITCAST) {
13096       if (!BC0.hasOneUse())
13097         break;
13098       BC0 = BC0.getOperand(0);
13099     }
13100
13101     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13102       if (Scale == 1)
13103         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13104
13105       SmallVector<int, 8> NewMask;
13106       for (int M : Mask)
13107         for (int s = 0; s != Scale; ++s)
13108           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13109       return NewMask;
13110     };
13111
13112     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13113       EVT SVT = VT.getScalarType();
13114       EVT InnerVT = BC0->getValueType(0);
13115       EVT InnerSVT = InnerVT.getScalarType();
13116
13117       // Determine which shuffle works with the smaller scalar type.
13118       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13119       EVT ScaleSVT = ScaleVT.getScalarType();
13120
13121       if (TLI.isTypeLegal(ScaleVT) &&
13122           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13123           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13124
13125         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13126         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13127
13128         // Scale the shuffle masks to the smaller scalar type.
13129         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13130         SmallVector<int, 8> InnerMask =
13131             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13132         SmallVector<int, 8> OuterMask =
13133             ScaleShuffleMask(SVN->getMask(), OuterScale);
13134
13135         // Merge the shuffle masks.
13136         SmallVector<int, 8> NewMask;
13137         for (int M : OuterMask)
13138           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13139
13140         // Test for shuffle mask legality over both commutations.
13141         SDValue SV0 = BC0->getOperand(0);
13142         SDValue SV1 = BC0->getOperand(1);
13143         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13144         if (!LegalMask) {
13145           std::swap(SV0, SV1);
13146           ShuffleVectorSDNode::commuteMask(NewMask);
13147           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13148         }
13149
13150         if (LegalMask) {
13151           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13152           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13153           return DAG.getNode(
13154               ISD::BITCAST, SDLoc(N), VT,
13155               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13156         }
13157       }
13158     }
13159   }
13160
13161   // Canonicalize shuffles according to rules:
13162   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13163   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13164   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13165   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13166       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13167       TLI.isTypeLegal(VT)) {
13168     // The incoming shuffle must be of the same type as the result of the
13169     // current shuffle.
13170     assert(N1->getOperand(0).getValueType() == VT &&
13171            "Shuffle types don't match");
13172
13173     SDValue SV0 = N1->getOperand(0);
13174     SDValue SV1 = N1->getOperand(1);
13175     bool HasSameOp0 = N0 == SV0;
13176     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13177     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13178       // Commute the operands of this shuffle so that next rule
13179       // will trigger.
13180       return DAG.getCommutedVectorShuffle(*SVN);
13181   }
13182
13183   // Try to fold according to rules:
13184   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13185   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13186   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13187   // Don't try to fold shuffles with illegal type.
13188   // Only fold if this shuffle is the only user of the other shuffle.
13189   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13190       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13191     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13192
13193     // The incoming shuffle must be of the same type as the result of the
13194     // current shuffle.
13195     assert(OtherSV->getOperand(0).getValueType() == VT &&
13196            "Shuffle types don't match");
13197
13198     SDValue SV0, SV1;
13199     SmallVector<int, 4> Mask;
13200     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13201     // operand, and SV1 as the second operand.
13202     for (unsigned i = 0; i != NumElts; ++i) {
13203       int Idx = SVN->getMaskElt(i);
13204       if (Idx < 0) {
13205         // Propagate Undef.
13206         Mask.push_back(Idx);
13207         continue;
13208       }
13209
13210       SDValue CurrentVec;
13211       if (Idx < (int)NumElts) {
13212         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13213         // shuffle mask to identify which vector is actually referenced.
13214         Idx = OtherSV->getMaskElt(Idx);
13215         if (Idx < 0) {
13216           // Propagate Undef.
13217           Mask.push_back(Idx);
13218           continue;
13219         }
13220
13221         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13222                                            : OtherSV->getOperand(1);
13223       } else {
13224         // This shuffle index references an element within N1.
13225         CurrentVec = N1;
13226       }
13227
13228       // Simple case where 'CurrentVec' is UNDEF.
13229       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13230         Mask.push_back(-1);
13231         continue;
13232       }
13233
13234       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13235       // will be the first or second operand of the combined shuffle.
13236       Idx = Idx % NumElts;
13237       if (!SV0.getNode() || SV0 == CurrentVec) {
13238         // Ok. CurrentVec is the left hand side.
13239         // Update the mask accordingly.
13240         SV0 = CurrentVec;
13241         Mask.push_back(Idx);
13242         continue;
13243       }
13244
13245       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13246       if (SV1.getNode() && SV1 != CurrentVec)
13247         return SDValue();
13248
13249       // Ok. CurrentVec is the right hand side.
13250       // Update the mask accordingly.
13251       SV1 = CurrentVec;
13252       Mask.push_back(Idx + NumElts);
13253     }
13254
13255     // Check if all indices in Mask are Undef. In case, propagate Undef.
13256     bool isUndefMask = true;
13257     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13258       isUndefMask &= Mask[i] < 0;
13259
13260     if (isUndefMask)
13261       return DAG.getUNDEF(VT);
13262
13263     if (!SV0.getNode())
13264       SV0 = DAG.getUNDEF(VT);
13265     if (!SV1.getNode())
13266       SV1 = DAG.getUNDEF(VT);
13267
13268     // Avoid introducing shuffles with illegal mask.
13269     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13270       ShuffleVectorSDNode::commuteMask(Mask);
13271
13272       if (!TLI.isShuffleMaskLegal(Mask, VT))
13273         return SDValue();
13274
13275       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13276       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13277       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13278       std::swap(SV0, SV1);
13279     }
13280
13281     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13282     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13283     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13284     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13285   }
13286
13287   return SDValue();
13288 }
13289
13290 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13291   SDValue InVal = N->getOperand(0);
13292   EVT VT = N->getValueType(0);
13293
13294   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13295   // with a VECTOR_SHUFFLE.
13296   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13297     SDValue InVec = InVal->getOperand(0);
13298     SDValue EltNo = InVal->getOperand(1);
13299
13300     // FIXME: We could support implicit truncation if the shuffle can be
13301     // scaled to a smaller vector scalar type.
13302     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13303     if (C0 && VT == InVec.getValueType() &&
13304         VT.getScalarType() == InVal.getValueType()) {
13305       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13306       int Elt = C0->getZExtValue();
13307       NewMask[0] = Elt;
13308
13309       if (TLI.isShuffleMaskLegal(NewMask, VT))
13310         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13311                                     NewMask);
13312     }
13313   }
13314
13315   return SDValue();
13316 }
13317
13318 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13319   SDValue N0 = N->getOperand(0);
13320   SDValue N2 = N->getOperand(2);
13321
13322   // If the input vector is a concatenation, and the insert replaces
13323   // one of the halves, we can optimize into a single concat_vectors.
13324   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13325       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13326     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13327     EVT VT = N->getValueType(0);
13328
13329     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13330     // (concat_vectors Z, Y)
13331     if (InsIdx == 0)
13332       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13333                          N->getOperand(1), N0.getOperand(1));
13334
13335     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13336     // (concat_vectors X, Z)
13337     if (InsIdx == VT.getVectorNumElements()/2)
13338       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13339                          N0.getOperand(0), N->getOperand(1));
13340   }
13341
13342   return SDValue();
13343 }
13344
13345 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13346   SDValue N0 = N->getOperand(0);
13347
13348   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13349   if (N0->getOpcode() == ISD::FP16_TO_FP)
13350     return N0->getOperand(0);
13351
13352   return SDValue();
13353 }
13354
13355 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13356   SDValue N0 = N->getOperand(0);
13357
13358   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13359   if (N0->getOpcode() == ISD::AND) {
13360     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13361     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13362       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13363                          N0.getOperand(0));
13364     }
13365   }
13366
13367   return SDValue();
13368 }
13369
13370 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13371 /// with the destination vector and a zero vector.
13372 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13373 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13374 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13375   EVT VT = N->getValueType(0);
13376   SDValue LHS = N->getOperand(0);
13377   SDValue RHS = N->getOperand(1);
13378   SDLoc dl(N);
13379
13380   // Make sure we're not running after operation legalization where it
13381   // may have custom lowered the vector shuffles.
13382   if (LegalOperations)
13383     return SDValue();
13384
13385   if (N->getOpcode() != ISD::AND)
13386     return SDValue();
13387
13388   if (RHS.getOpcode() == ISD::BITCAST)
13389     RHS = RHS.getOperand(0);
13390
13391   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13392     return SDValue();
13393
13394   EVT RVT = RHS.getValueType();
13395   unsigned NumElts = RHS.getNumOperands();
13396
13397   // Attempt to create a valid clear mask, splitting the mask into
13398   // sub elements and checking to see if each is
13399   // all zeros or all ones - suitable for shuffle masking.
13400   auto BuildClearMask = [&](int Split) {
13401     int NumSubElts = NumElts * Split;
13402     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13403
13404     SmallVector<int, 8> Indices;
13405     for (int i = 0; i != NumSubElts; ++i) {
13406       int EltIdx = i / Split;
13407       int SubIdx = i % Split;
13408       SDValue Elt = RHS.getOperand(EltIdx);
13409       if (Elt.getOpcode() == ISD::UNDEF) {
13410         Indices.push_back(-1);
13411         continue;
13412       }
13413
13414       APInt Bits;
13415       if (isa<ConstantSDNode>(Elt))
13416         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13417       else if (isa<ConstantFPSDNode>(Elt))
13418         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13419       else
13420         return SDValue();
13421
13422       // Extract the sub element from the constant bit mask.
13423       if (DAG.getDataLayout().isBigEndian()) {
13424         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13425       } else {
13426         Bits = Bits.lshr(SubIdx * NumSubBits);
13427       }
13428
13429       if (Split > 1)
13430         Bits = Bits.trunc(NumSubBits);
13431
13432       if (Bits.isAllOnesValue())
13433         Indices.push_back(i);
13434       else if (Bits == 0)
13435         Indices.push_back(i + NumSubElts);
13436       else
13437         return SDValue();
13438     }
13439
13440     // Let's see if the target supports this vector_shuffle.
13441     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13442     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13443     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13444       return SDValue();
13445
13446     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13447     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13448                                                    DAG.getBitcast(ClearVT, LHS),
13449                                                    Zero, &Indices[0]));
13450   };
13451
13452   // Determine maximum split level (byte level masking).
13453   int MaxSplit = 1;
13454   if (RVT.getScalarSizeInBits() % 8 == 0)
13455     MaxSplit = RVT.getScalarSizeInBits() / 8;
13456
13457   for (int Split = 1; Split <= MaxSplit; ++Split)
13458     if (RVT.getScalarSizeInBits() % Split == 0)
13459       if (SDValue S = BuildClearMask(Split))
13460         return S;
13461
13462   return SDValue();
13463 }
13464
13465 /// Visit a binary vector operation, like ADD.
13466 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13467   assert(N->getValueType(0).isVector() &&
13468          "SimplifyVBinOp only works on vectors!");
13469
13470   SDValue LHS = N->getOperand(0);
13471   SDValue RHS = N->getOperand(1);
13472   SDValue Ops[] = {LHS, RHS};
13473
13474   // See if we can constant fold the vector operation.
13475   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13476           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13477     return Fold;
13478
13479   // Try to convert a constant mask AND into a shuffle clear mask.
13480   if (SDValue Shuffle = XformToShuffleWithZero(N))
13481     return Shuffle;
13482
13483   // Type legalization might introduce new shuffles in the DAG.
13484   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13485   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13486   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13487       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13488       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13489       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13490     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13491     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13492
13493     if (SVN0->getMask().equals(SVN1->getMask())) {
13494       EVT VT = N->getValueType(0);
13495       SDValue UndefVector = LHS.getOperand(1);
13496       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13497                                      LHS.getOperand(0), RHS.getOperand(0),
13498                                      N->getFlags());
13499       AddUsersToWorklist(N);
13500       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13501                                   &SVN0->getMask()[0]);
13502     }
13503   }
13504
13505   return SDValue();
13506 }
13507
13508 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13509                                     SDValue N1, SDValue N2){
13510   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13511
13512   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13513                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13514
13515   // If we got a simplified select_cc node back from SimplifySelectCC, then
13516   // break it down into a new SETCC node, and a new SELECT node, and then return
13517   // the SELECT node, since we were called with a SELECT node.
13518   if (SCC.getNode()) {
13519     // Check to see if we got a select_cc back (to turn into setcc/select).
13520     // Otherwise, just return whatever node we got back, like fabs.
13521     if (SCC.getOpcode() == ISD::SELECT_CC) {
13522       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13523                                   N0.getValueType(),
13524                                   SCC.getOperand(0), SCC.getOperand(1),
13525                                   SCC.getOperand(4));
13526       AddToWorklist(SETCC.getNode());
13527       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13528                            SCC.getOperand(2), SCC.getOperand(3));
13529     }
13530
13531     return SCC;
13532   }
13533   return SDValue();
13534 }
13535
13536 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13537 /// being selected between, see if we can simplify the select.  Callers of this
13538 /// should assume that TheSelect is deleted if this returns true.  As such, they
13539 /// should return the appropriate thing (e.g. the node) back to the top-level of
13540 /// the DAG combiner loop to avoid it being looked at.
13541 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13542                                     SDValue RHS) {
13543
13544   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13545   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13546   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13547     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13548       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13549       SDValue Sqrt = RHS;
13550       ISD::CondCode CC;
13551       SDValue CmpLHS;
13552       const ConstantFPSDNode *NegZero = nullptr;
13553
13554       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13555         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13556         CmpLHS = TheSelect->getOperand(0);
13557         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13558       } else {
13559         // SELECT or VSELECT
13560         SDValue Cmp = TheSelect->getOperand(0);
13561         if (Cmp.getOpcode() == ISD::SETCC) {
13562           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13563           CmpLHS = Cmp.getOperand(0);
13564           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13565         }
13566       }
13567       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13568           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13569           CC == ISD::SETULT || CC == ISD::SETLT)) {
13570         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13571         CombineTo(TheSelect, Sqrt);
13572         return true;
13573       }
13574     }
13575   }
13576   // Cannot simplify select with vector condition
13577   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13578
13579   // If this is a select from two identical things, try to pull the operation
13580   // through the select.
13581   if (LHS.getOpcode() != RHS.getOpcode() ||
13582       !LHS.hasOneUse() || !RHS.hasOneUse())
13583     return false;
13584
13585   // If this is a load and the token chain is identical, replace the select
13586   // of two loads with a load through a select of the address to load from.
13587   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13588   // constants have been dropped into the constant pool.
13589   if (LHS.getOpcode() == ISD::LOAD) {
13590     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13591     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13592
13593     // Token chains must be identical.
13594     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13595         // Do not let this transformation reduce the number of volatile loads.
13596         LLD->isVolatile() || RLD->isVolatile() ||
13597         // FIXME: If either is a pre/post inc/dec load,
13598         // we'd need to split out the address adjustment.
13599         LLD->isIndexed() || RLD->isIndexed() ||
13600         // If this is an EXTLOAD, the VT's must match.
13601         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13602         // If this is an EXTLOAD, the kind of extension must match.
13603         (LLD->getExtensionType() != RLD->getExtensionType() &&
13604          // The only exception is if one of the extensions is anyext.
13605          LLD->getExtensionType() != ISD::EXTLOAD &&
13606          RLD->getExtensionType() != ISD::EXTLOAD) ||
13607         // FIXME: this discards src value information.  This is
13608         // over-conservative. It would be beneficial to be able to remember
13609         // both potential memory locations.  Since we are discarding
13610         // src value info, don't do the transformation if the memory
13611         // locations are not in the default address space.
13612         LLD->getPointerInfo().getAddrSpace() != 0 ||
13613         RLD->getPointerInfo().getAddrSpace() != 0 ||
13614         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13615                                       LLD->getBasePtr().getValueType()))
13616       return false;
13617
13618     // Check that the select condition doesn't reach either load.  If so,
13619     // folding this will induce a cycle into the DAG.  If not, this is safe to
13620     // xform, so create a select of the addresses.
13621     SDValue Addr;
13622     if (TheSelect->getOpcode() == ISD::SELECT) {
13623       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13624       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13625           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13626         return false;
13627       // The loads must not depend on one another.
13628       if (LLD->isPredecessorOf(RLD) ||
13629           RLD->isPredecessorOf(LLD))
13630         return false;
13631       Addr = DAG.getSelect(SDLoc(TheSelect),
13632                            LLD->getBasePtr().getValueType(),
13633                            TheSelect->getOperand(0), LLD->getBasePtr(),
13634                            RLD->getBasePtr());
13635     } else {  // Otherwise SELECT_CC
13636       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13637       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13638
13639       if ((LLD->hasAnyUseOfValue(1) &&
13640            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13641           (RLD->hasAnyUseOfValue(1) &&
13642            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13643         return false;
13644
13645       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13646                          LLD->getBasePtr().getValueType(),
13647                          TheSelect->getOperand(0),
13648                          TheSelect->getOperand(1),
13649                          LLD->getBasePtr(), RLD->getBasePtr(),
13650                          TheSelect->getOperand(4));
13651     }
13652
13653     SDValue Load;
13654     // It is safe to replace the two loads if they have different alignments,
13655     // but the new load must be the minimum (most restrictive) alignment of the
13656     // inputs.
13657     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13658     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13659     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13660       Load = DAG.getLoad(TheSelect->getValueType(0),
13661                          SDLoc(TheSelect),
13662                          // FIXME: Discards pointer and AA info.
13663                          LLD->getChain(), Addr, MachinePointerInfo(),
13664                          LLD->isVolatile(), LLD->isNonTemporal(),
13665                          isInvariant, Alignment);
13666     } else {
13667       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13668                             RLD->getExtensionType() : LLD->getExtensionType(),
13669                             SDLoc(TheSelect),
13670                             TheSelect->getValueType(0),
13671                             // FIXME: Discards pointer and AA info.
13672                             LLD->getChain(), Addr, MachinePointerInfo(),
13673                             LLD->getMemoryVT(), LLD->isVolatile(),
13674                             LLD->isNonTemporal(), isInvariant, Alignment);
13675     }
13676
13677     // Users of the select now use the result of the load.
13678     CombineTo(TheSelect, Load);
13679
13680     // Users of the old loads now use the new load's chain.  We know the
13681     // old-load value is dead now.
13682     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13683     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13684     return true;
13685   }
13686
13687   return false;
13688 }
13689
13690 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13691 /// where 'cond' is the comparison specified by CC.
13692 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13693                                       SDValue N2, SDValue N3,
13694                                       ISD::CondCode CC, bool NotExtCompare) {
13695   // (x ? y : y) -> y.
13696   if (N2 == N3) return N2;
13697
13698   EVT VT = N2.getValueType();
13699   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13700   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13701
13702   // Determine if the condition we're dealing with is constant
13703   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13704                               N0, N1, CC, DL, false);
13705   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13706
13707   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13708     // fold select_cc true, x, y -> x
13709     // fold select_cc false, x, y -> y
13710     return !SCCC->isNullValue() ? N2 : N3;
13711   }
13712
13713   // Check to see if we can simplify the select into an fabs node
13714   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13715     // Allow either -0.0 or 0.0
13716     if (CFP->isZero()) {
13717       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13718       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13719           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13720           N2 == N3.getOperand(0))
13721         return DAG.getNode(ISD::FABS, DL, VT, N0);
13722
13723       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13724       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13725           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13726           N2.getOperand(0) == N3)
13727         return DAG.getNode(ISD::FABS, DL, VT, N3);
13728     }
13729   }
13730
13731   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13732   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13733   // in it.  This is a win when the constant is not otherwise available because
13734   // it replaces two constant pool loads with one.  We only do this if the FP
13735   // type is known to be legal, because if it isn't, then we are before legalize
13736   // types an we want the other legalization to happen first (e.g. to avoid
13737   // messing with soft float) and if the ConstantFP is not legal, because if
13738   // it is legal, we may not need to store the FP constant in a constant pool.
13739   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13740     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13741       if (TLI.isTypeLegal(N2.getValueType()) &&
13742           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13743                TargetLowering::Legal &&
13744            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13745            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13746           // If both constants have multiple uses, then we won't need to do an
13747           // extra load, they are likely around in registers for other users.
13748           (TV->hasOneUse() || FV->hasOneUse())) {
13749         Constant *Elts[] = {
13750           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13751           const_cast<ConstantFP*>(TV->getConstantFPValue())
13752         };
13753         Type *FPTy = Elts[0]->getType();
13754         const DataLayout &TD = DAG.getDataLayout();
13755
13756         // Create a ConstantArray of the two constants.
13757         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13758         SDValue CPIdx =
13759             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13760                                 TD.getPrefTypeAlignment(FPTy));
13761         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13762
13763         // Get the offsets to the 0 and 1 element of the array so that we can
13764         // select between them.
13765         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13766         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13767         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13768
13769         SDValue Cond = DAG.getSetCC(DL,
13770                                     getSetCCResultType(N0.getValueType()),
13771                                     N0, N1, CC);
13772         AddToWorklist(Cond.getNode());
13773         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13774                                           Cond, One, Zero);
13775         AddToWorklist(CstOffset.getNode());
13776         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13777                             CstOffset);
13778         AddToWorklist(CPIdx.getNode());
13779         return DAG.getLoad(
13780             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13781             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13782             false, false, false, Alignment);
13783       }
13784     }
13785
13786   // Check to see if we can perform the "gzip trick", transforming
13787   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13788   if (isNullConstant(N3) && CC == ISD::SETLT &&
13789       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13790        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13791     EVT XType = N0.getValueType();
13792     EVT AType = N2.getValueType();
13793     if (XType.bitsGE(AType)) {
13794       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13795       // single-bit constant.
13796       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13797         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13798         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13799         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13800                                        getShiftAmountTy(N0.getValueType()));
13801         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13802                                     XType, N0, ShCt);
13803         AddToWorklist(Shift.getNode());
13804
13805         if (XType.bitsGT(AType)) {
13806           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13807           AddToWorklist(Shift.getNode());
13808         }
13809
13810         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13811       }
13812
13813       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13814                                   XType, N0,
13815                                   DAG.getConstant(XType.getSizeInBits() - 1,
13816                                                   SDLoc(N0),
13817                                          getShiftAmountTy(N0.getValueType())));
13818       AddToWorklist(Shift.getNode());
13819
13820       if (XType.bitsGT(AType)) {
13821         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13822         AddToWorklist(Shift.getNode());
13823       }
13824
13825       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13826     }
13827   }
13828
13829   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13830   // where y is has a single bit set.
13831   // A plaintext description would be, we can turn the SELECT_CC into an AND
13832   // when the condition can be materialized as an all-ones register.  Any
13833   // single bit-test can be materialized as an all-ones register with
13834   // shift-left and shift-right-arith.
13835   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13836       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13837     SDValue AndLHS = N0->getOperand(0);
13838     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13839     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13840       // Shift the tested bit over the sign bit.
13841       APInt AndMask = ConstAndRHS->getAPIntValue();
13842       SDValue ShlAmt =
13843         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13844                         getShiftAmountTy(AndLHS.getValueType()));
13845       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13846
13847       // Now arithmetic right shift it all the way over, so the result is either
13848       // all-ones, or zero.
13849       SDValue ShrAmt =
13850         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13851                         getShiftAmountTy(Shl.getValueType()));
13852       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13853
13854       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13855     }
13856   }
13857
13858   // fold select C, 16, 0 -> shl C, 4
13859   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13860       TLI.getBooleanContents(N0.getValueType()) ==
13861           TargetLowering::ZeroOrOneBooleanContent) {
13862
13863     // If the caller doesn't want us to simplify this into a zext of a compare,
13864     // don't do it.
13865     if (NotExtCompare && N2C->isOne())
13866       return SDValue();
13867
13868     // Get a SetCC of the condition
13869     // NOTE: Don't create a SETCC if it's not legal on this target.
13870     if (!LegalOperations ||
13871         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13872       SDValue Temp, SCC;
13873       // cast from setcc result type to select result type
13874       if (LegalTypes) {
13875         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13876                             N0, N1, CC);
13877         if (N2.getValueType().bitsLT(SCC.getValueType()))
13878           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13879                                         N2.getValueType());
13880         else
13881           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13882                              N2.getValueType(), SCC);
13883       } else {
13884         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13885         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13886                            N2.getValueType(), SCC);
13887       }
13888
13889       AddToWorklist(SCC.getNode());
13890       AddToWorklist(Temp.getNode());
13891
13892       if (N2C->isOne())
13893         return Temp;
13894
13895       // shl setcc result by log2 n2c
13896       return DAG.getNode(
13897           ISD::SHL, DL, N2.getValueType(), Temp,
13898           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13899                           getShiftAmountTy(Temp.getValueType())));
13900     }
13901   }
13902
13903   // Check to see if this is an integer abs.
13904   // select_cc setg[te] X,  0,  X, -X ->
13905   // select_cc setgt    X, -1,  X, -X ->
13906   // select_cc setl[te] X,  0, -X,  X ->
13907   // select_cc setlt    X,  1, -X,  X ->
13908   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13909   if (N1C) {
13910     ConstantSDNode *SubC = nullptr;
13911     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13912          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13913         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13914       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13915     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13916               (N1C->isOne() && CC == ISD::SETLT)) &&
13917              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13918       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13919
13920     EVT XType = N0.getValueType();
13921     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13922       SDLoc DL(N0);
13923       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13924                                   N0,
13925                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13926                                          getShiftAmountTy(N0.getValueType())));
13927       SDValue Add = DAG.getNode(ISD::ADD, DL,
13928                                 XType, N0, Shift);
13929       AddToWorklist(Shift.getNode());
13930       AddToWorklist(Add.getNode());
13931       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13932     }
13933   }
13934
13935   return SDValue();
13936 }
13937
13938 /// This is a stub for TargetLowering::SimplifySetCC.
13939 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13940                                    SDValue N1, ISD::CondCode Cond,
13941                                    SDLoc DL, bool foldBooleans) {
13942   TargetLowering::DAGCombinerInfo
13943     DagCombineInfo(DAG, Level, false, this);
13944   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13945 }
13946
13947 /// Given an ISD::SDIV node expressing a divide by constant, return
13948 /// a DAG expression to select that will generate the same value by multiplying
13949 /// by a magic number.
13950 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13951 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13952   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13953   if (!C)
13954     return SDValue();
13955
13956   // Avoid division by zero.
13957   if (C->isNullValue())
13958     return SDValue();
13959
13960   std::vector<SDNode*> Built;
13961   SDValue S =
13962       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13963
13964   for (SDNode *N : Built)
13965     AddToWorklist(N);
13966   return S;
13967 }
13968
13969 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13970 /// DAG expression that will generate the same value by right shifting.
13971 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13972   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13973   if (!C)
13974     return SDValue();
13975
13976   // Avoid division by zero.
13977   if (C->isNullValue())
13978     return SDValue();
13979
13980   std::vector<SDNode *> Built;
13981   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13982
13983   for (SDNode *N : Built)
13984     AddToWorklist(N);
13985   return S;
13986 }
13987
13988 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13989 /// expression that will generate the same value by multiplying by a magic
13990 /// number.
13991 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13992 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13993   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13994   if (!C)
13995     return SDValue();
13996
13997   // Avoid division by zero.
13998   if (C->isNullValue())
13999     return SDValue();
14000
14001   std::vector<SDNode*> Built;
14002   SDValue S =
14003       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14004
14005   for (SDNode *N : Built)
14006     AddToWorklist(N);
14007   return S;
14008 }
14009
14010 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14011   if (Level >= AfterLegalizeDAG)
14012     return SDValue();
14013
14014   // Expose the DAG combiner to the target combiner implementations.
14015   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14016
14017   unsigned Iterations = 0;
14018   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14019     if (Iterations) {
14020       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14021       // For the reciprocal, we need to find the zero of the function:
14022       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14023       //     =>
14024       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14025       //     does not require additional intermediate precision]
14026       EVT VT = Op.getValueType();
14027       SDLoc DL(Op);
14028       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14029
14030       AddToWorklist(Est.getNode());
14031
14032       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14033       for (unsigned i = 0; i < Iterations; ++i) {
14034         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14035         AddToWorklist(NewEst.getNode());
14036
14037         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14038         AddToWorklist(NewEst.getNode());
14039
14040         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14041         AddToWorklist(NewEst.getNode());
14042
14043         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14044         AddToWorklist(Est.getNode());
14045       }
14046     }
14047     return Est;
14048   }
14049
14050   return SDValue();
14051 }
14052
14053 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14054 /// For the reciprocal sqrt, we need to find the zero of the function:
14055 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14056 ///     =>
14057 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14058 /// As a result, we precompute A/2 prior to the iteration loop.
14059 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14060                                           unsigned Iterations,
14061                                           SDNodeFlags *Flags) {
14062   EVT VT = Arg.getValueType();
14063   SDLoc DL(Arg);
14064   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14065
14066   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14067   // this entire sequence requires only one FP constant.
14068   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14069   AddToWorklist(HalfArg.getNode());
14070
14071   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14072   AddToWorklist(HalfArg.getNode());
14073
14074   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14075   for (unsigned i = 0; i < Iterations; ++i) {
14076     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14077     AddToWorklist(NewEst.getNode());
14078
14079     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14080     AddToWorklist(NewEst.getNode());
14081
14082     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14083     AddToWorklist(NewEst.getNode());
14084
14085     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14086     AddToWorklist(Est.getNode());
14087   }
14088   return Est;
14089 }
14090
14091 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14092 /// For the reciprocal sqrt, we need to find the zero of the function:
14093 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14094 ///     =>
14095 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14096 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14097                                           unsigned Iterations,
14098                                           SDNodeFlags *Flags) {
14099   EVT VT = Arg.getValueType();
14100   SDLoc DL(Arg);
14101   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14102   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14103
14104   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14105   for (unsigned i = 0; i < Iterations; ++i) {
14106     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14107     AddToWorklist(HalfEst.getNode());
14108
14109     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14110     AddToWorklist(Est.getNode());
14111
14112     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14113     AddToWorklist(Est.getNode());
14114
14115     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14116     AddToWorklist(Est.getNode());
14117
14118     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14119     AddToWorklist(Est.getNode());
14120   }
14121   return Est;
14122 }
14123
14124 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14125   if (Level >= AfterLegalizeDAG)
14126     return SDValue();
14127
14128   // Expose the DAG combiner to the target combiner implementations.
14129   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14130   unsigned Iterations = 0;
14131   bool UseOneConstNR = false;
14132   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14133     AddToWorklist(Est.getNode());
14134     if (Iterations) {
14135       Est = UseOneConstNR ?
14136         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14137         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14138     }
14139     return Est;
14140   }
14141
14142   return SDValue();
14143 }
14144
14145 /// Return true if base is a frame index, which is known not to alias with
14146 /// anything but itself.  Provides base object and offset as results.
14147 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14148                            const GlobalValue *&GV, const void *&CV) {
14149   // Assume it is a primitive operation.
14150   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14151
14152   // If it's an adding a simple constant then integrate the offset.
14153   if (Base.getOpcode() == ISD::ADD) {
14154     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14155       Base = Base.getOperand(0);
14156       Offset += C->getZExtValue();
14157     }
14158   }
14159
14160   // Return the underlying GlobalValue, and update the Offset.  Return false
14161   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14162   // by multiple nodes with different offsets.
14163   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14164     GV = G->getGlobal();
14165     Offset += G->getOffset();
14166     return false;
14167   }
14168
14169   // Return the underlying Constant value, and update the Offset.  Return false
14170   // for ConstantSDNodes since the same constant pool entry may be represented
14171   // by multiple nodes with different offsets.
14172   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14173     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14174                                          : (const void *)C->getConstVal();
14175     Offset += C->getOffset();
14176     return false;
14177   }
14178   // If it's any of the following then it can't alias with anything but itself.
14179   return isa<FrameIndexSDNode>(Base);
14180 }
14181
14182 /// Return true if there is any possibility that the two addresses overlap.
14183 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14184   // If they are the same then they must be aliases.
14185   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14186
14187   // If they are both volatile then they cannot be reordered.
14188   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14189
14190   // If one operation reads from invariant memory, and the other may store, they
14191   // cannot alias. These should really be checking the equivalent of mayWrite,
14192   // but it only matters for memory nodes other than load /store.
14193   if (Op0->isInvariant() && Op1->writeMem())
14194     return false;
14195
14196   if (Op1->isInvariant() && Op0->writeMem())
14197     return false;
14198
14199   // Gather base node and offset information.
14200   SDValue Base1, Base2;
14201   int64_t Offset1, Offset2;
14202   const GlobalValue *GV1, *GV2;
14203   const void *CV1, *CV2;
14204   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14205                                       Base1, Offset1, GV1, CV1);
14206   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14207                                       Base2, Offset2, GV2, CV2);
14208
14209   // If they have a same base address then check to see if they overlap.
14210   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14211     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14212              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14213
14214   // It is possible for different frame indices to alias each other, mostly
14215   // when tail call optimization reuses return address slots for arguments.
14216   // To catch this case, look up the actual index of frame indices to compute
14217   // the real alias relationship.
14218   if (isFrameIndex1 && isFrameIndex2) {
14219     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14220     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14221     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14222     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14223              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14224   }
14225
14226   // Otherwise, if we know what the bases are, and they aren't identical, then
14227   // we know they cannot alias.
14228   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14229     return false;
14230
14231   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14232   // compared to the size and offset of the access, we may be able to prove they
14233   // do not alias.  This check is conservative for now to catch cases created by
14234   // splitting vector types.
14235   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14236       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14237       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14238        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14239       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14240     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14241     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14242
14243     // There is no overlap between these relatively aligned accesses of similar
14244     // size, return no alias.
14245     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14246         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14247       return false;
14248   }
14249
14250   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14251                    ? CombinerGlobalAA
14252                    : DAG.getSubtarget().useAA();
14253 #ifndef NDEBUG
14254   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14255       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14256     UseAA = false;
14257 #endif
14258   if (UseAA &&
14259       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14260     // Use alias analysis information.
14261     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14262                                  Op1->getSrcValueOffset());
14263     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14264         Op0->getSrcValueOffset() - MinOffset;
14265     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14266         Op1->getSrcValueOffset() - MinOffset;
14267     AliasResult AAResult =
14268         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14269                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14270                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14271                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14272     if (AAResult == NoAlias)
14273       return false;
14274   }
14275
14276   // Otherwise we have to assume they alias.
14277   return true;
14278 }
14279
14280 /// Walk up chain skipping non-aliasing memory nodes,
14281 /// looking for aliasing nodes and adding them to the Aliases vector.
14282 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14283                                    SmallVectorImpl<SDValue> &Aliases) {
14284   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14285   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14286
14287   // Get alias information for node.
14288   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14289
14290   // Starting off.
14291   Chains.push_back(OriginalChain);
14292   unsigned Depth = 0;
14293
14294   // Look at each chain and determine if it is an alias.  If so, add it to the
14295   // aliases list.  If not, then continue up the chain looking for the next
14296   // candidate.
14297   while (!Chains.empty()) {
14298     SDValue Chain = Chains.pop_back_val();
14299
14300     // For TokenFactor nodes, look at each operand and only continue up the
14301     // chain until we find two aliases.  If we've seen two aliases, assume we'll
14302     // find more and revert to original chain since the xform is unlikely to be
14303     // profitable.
14304     //
14305     // FIXME: The depth check could be made to return the last non-aliasing
14306     // chain we found before we hit a tokenfactor rather than the original
14307     // chain.
14308     if (Depth > 6 || Aliases.size() == 2) {
14309       Aliases.clear();
14310       Aliases.push_back(OriginalChain);
14311       return;
14312     }
14313
14314     // Don't bother if we've been before.
14315     if (!Visited.insert(Chain.getNode()).second)
14316       continue;
14317
14318     switch (Chain.getOpcode()) {
14319     case ISD::EntryToken:
14320       // Entry token is ideal chain operand, but handled in FindBetterChain.
14321       break;
14322
14323     case ISD::LOAD:
14324     case ISD::STORE: {
14325       // Get alias information for Chain.
14326       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14327           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14328
14329       // If chain is alias then stop here.
14330       if (!(IsLoad && IsOpLoad) &&
14331           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14332         Aliases.push_back(Chain);
14333       } else {
14334         // Look further up the chain.
14335         Chains.push_back(Chain.getOperand(0));
14336         ++Depth;
14337       }
14338       break;
14339     }
14340
14341     case ISD::TokenFactor:
14342       // We have to check each of the operands of the token factor for "small"
14343       // token factors, so we queue them up.  Adding the operands to the queue
14344       // (stack) in reverse order maintains the original order and increases the
14345       // likelihood that getNode will find a matching token factor (CSE.)
14346       if (Chain.getNumOperands() > 16) {
14347         Aliases.push_back(Chain);
14348         break;
14349       }
14350       for (unsigned n = Chain.getNumOperands(); n;)
14351         Chains.push_back(Chain.getOperand(--n));
14352       ++Depth;
14353       break;
14354
14355     default:
14356       // For all other instructions we will just have to take what we can get.
14357       Aliases.push_back(Chain);
14358       break;
14359     }
14360   }
14361
14362   // We need to be careful here to also search for aliases through the
14363   // value operand of a store, etc. Consider the following situation:
14364   //   Token1 = ...
14365   //   L1 = load Token1, %52
14366   //   S1 = store Token1, L1, %51
14367   //   L2 = load Token1, %52+8
14368   //   S2 = store Token1, L2, %51+8
14369   //   Token2 = Token(S1, S2)
14370   //   L3 = load Token2, %53
14371   //   S3 = store Token2, L3, %52
14372   //   L4 = load Token2, %53+8
14373   //   S4 = store Token2, L4, %52+8
14374   // If we search for aliases of S3 (which loads address %52), and we look
14375   // only through the chain, then we'll miss the trivial dependence on L1
14376   // (which also loads from %52). We then might change all loads and
14377   // stores to use Token1 as their chain operand, which could result in
14378   // copying %53 into %52 before copying %52 into %51 (which should
14379   // happen first).
14380   //
14381   // The problem is, however, that searching for such data dependencies
14382   // can become expensive, and the cost is not directly related to the
14383   // chain depth. Instead, we'll rule out such configurations here by
14384   // insisting that we've visited all chain users (except for users
14385   // of the original chain, which is not necessary). When doing this,
14386   // we need to look through nodes we don't care about (otherwise, things
14387   // like register copies will interfere with trivial cases).
14388
14389   SmallVector<const SDNode *, 16> Worklist;
14390   for (const SDNode *N : Visited)
14391     if (N != OriginalChain.getNode())
14392       Worklist.push_back(N);
14393
14394   while (!Worklist.empty()) {
14395     const SDNode *M = Worklist.pop_back_val();
14396
14397     // We have already visited M, and want to make sure we've visited any uses
14398     // of M that we care about. For uses that we've not visisted, and don't
14399     // care about, queue them to the worklist.
14400
14401     for (SDNode::use_iterator UI = M->use_begin(),
14402          UIE = M->use_end(); UI != UIE; ++UI)
14403       if (UI.getUse().getValueType() == MVT::Other &&
14404           Visited.insert(*UI).second) {
14405         if (isa<MemSDNode>(*UI)) {
14406           // We've not visited this use, and we care about it (it could have an
14407           // ordering dependency with the original node).
14408           Aliases.clear();
14409           Aliases.push_back(OriginalChain);
14410           return;
14411         }
14412
14413         // We've not visited this use, but we don't care about it. Mark it as
14414         // visited and enqueue it to the worklist.
14415         Worklist.push_back(*UI);
14416       }
14417   }
14418 }
14419
14420 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14421 /// (aliasing node.)
14422 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14423   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14424
14425   // Accumulate all the aliases to this node.
14426   GatherAllAliases(N, OldChain, Aliases);
14427
14428   // If no operands then chain to entry token.
14429   if (Aliases.size() == 0)
14430     return DAG.getEntryNode();
14431
14432   // If a single operand then chain to it.  We don't need to revisit it.
14433   if (Aliases.size() == 1)
14434     return Aliases[0];
14435
14436   // Construct a custom tailored token factor.
14437   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14438 }
14439
14440 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14441   // This holds the base pointer, index, and the offset in bytes from the base
14442   // pointer.
14443   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14444
14445   // We must have a base and an offset.
14446   if (!BasePtr.Base.getNode())
14447     return false;
14448
14449   // Do not handle stores to undef base pointers.
14450   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14451     return false;
14452
14453   SmallVector<StoreSDNode *, 8> ChainedStores;
14454   ChainedStores.push_back(St);
14455
14456   // Walk up the chain and look for nodes with offsets from the same
14457   // base pointer. Stop when reaching an instruction with a different kind
14458   // or instruction which has a different base pointer.
14459   StoreSDNode *Index = St;
14460   while (Index) {
14461     // If the chain has more than one use, then we can't reorder the mem ops.
14462     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14463       break;
14464
14465     if (Index->isVolatile() || Index->isIndexed())
14466       break;
14467
14468     // Find the base pointer and offset for this memory node.
14469     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14470
14471     // Check that the base pointer is the same as the original one.
14472     if (!Ptr.equalBaseIndex(BasePtr))
14473       break;
14474
14475     // Find the next memory operand in the chain. If the next operand in the
14476     // chain is a store then move up and continue the scan with the next
14477     // memory operand. If the next operand is a load save it and use alias
14478     // information to check if it interferes with anything.
14479     SDNode *NextInChain = Index->getChain().getNode();
14480     while (true) {
14481       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14482         // We found a store node. Use it for the next iteration.
14483         ChainedStores.push_back(STn);
14484         Index = STn;
14485         break;
14486       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14487         NextInChain = Ldn->getChain().getNode();
14488         continue;
14489       } else {
14490         Index = nullptr;
14491         break;
14492       }
14493     }
14494   }
14495
14496   bool MadeChange = false;
14497   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14498
14499   for (StoreSDNode *ChainedStore : ChainedStores) {
14500     SDValue Chain = ChainedStore->getChain();
14501     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14502
14503     if (Chain != BetterChain) {
14504       MadeChange = true;
14505       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14506     }
14507   }
14508
14509   // Do all replacements after finding the replacements to make to avoid making
14510   // the chains more complicated by introducing new TokenFactors.
14511   for (auto Replacement : BetterChains)
14512     replaceStoreChain(Replacement.first, Replacement.second);
14513
14514   return MadeChange;
14515 }
14516
14517 /// This is the entry point for the file.
14518 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14519                            CodeGenOpt::Level OptLevel) {
14520   /// This is the main entry point to this class.
14521   DAGCombiner(*this, AA, OptLevel).Run(Level);
14522 }