Use makeArrayRef or None to avoid unnecessarily mentioning the ArrayRef type extra...
[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
305     SDValue visitSTORE(SDNode *N);
306     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
307     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
308     SDValue visitBUILD_VECTOR(SDNode *N);
309     SDValue visitCONCAT_VECTORS(SDNode *N);
310     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
311     SDValue visitVECTOR_SHUFFLE(SDNode *N);
312     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
313     SDValue visitINSERT_SUBVECTOR(SDNode *N);
314     SDValue visitMLOAD(SDNode *N);
315     SDValue visitMSTORE(SDNode *N);
316     SDValue visitMGATHER(SDNode *N);
317     SDValue visitMSCATTER(SDNode *N);
318     SDValue visitFP_TO_FP16(SDNode *N);
319     SDValue visitFP16_TO_FP(SDNode *N);
320
321     SDValue visitFADDForFMACombine(SDNode *N);
322     SDValue visitFSUBForFMACombine(SDNode *N);
323
324     SDValue XformToShuffleWithZero(SDNode *N);
325     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
326
327     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
328
329     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
330     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
331     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
332     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
333                              SDValue N3, ISD::CondCode CC,
334                              bool NotExtCompare = false);
335     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
336                           SDLoc DL, bool foldBooleans = true);
337
338     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
339                            SDValue &CC) const;
340     bool isOneUseSetCC(SDValue N) const;
341
342     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
343                                          unsigned HiOp);
344     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
345     SDValue CombineExtLoad(SDNode *N);
346     SDValue combineRepeatedFPDivisors(SDNode *N);
347     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
348     SDValue BuildSDIV(SDNode *N);
349     SDValue BuildSDIVPow2(SDNode *N);
350     SDValue BuildUDIV(SDNode *N);
351     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
352     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
353     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
354                                  SDNodeFlags *Flags);
355     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
356                                  SDNodeFlags *Flags);
357     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
358                                bool DemandHighBits = true);
359     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
360     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
361                               SDValue InnerPos, SDValue InnerNeg,
362                               unsigned PosOpcode, unsigned NegOpcode,
363                               SDLoc DL);
364     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
365     SDValue ReduceLoadWidth(SDNode *N);
366     SDValue ReduceLoadOpStoreWidth(SDNode *N);
367     SDValue TransformFPLoadStorePair(SDNode *N);
368     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
369     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
370
371     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
372
373     /// Walk up chain skipping non-aliasing memory nodes,
374     /// looking for aliasing nodes and adding them to the Aliases vector.
375     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
376                           SmallVectorImpl<SDValue> &Aliases);
377
378     /// Return true if there is any possibility that the two addresses overlap.
379     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
380
381     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
382     /// chain (aliasing node.)
383     SDValue FindBetterChain(SDNode *N, SDValue Chain);
384
385     /// Do FindBetterChain for a store and any possibly adjacent stores on
386     /// consecutive chains.
387     bool findBetterNeighborChains(StoreSDNode *St);
388
389     /// Holds a pointer to an LSBaseSDNode as well as information on where it
390     /// is located in a sequence of memory operations connected by a chain.
391     struct MemOpLink {
392       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
393       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
394       // Ptr to the mem node.
395       LSBaseSDNode *MemNode;
396       // Offset from the base ptr.
397       int64_t OffsetFromBase;
398       // What is the sequence number of this mem node.
399       // Lowest mem operand in the DAG starts at zero.
400       unsigned SequenceNum;
401     };
402
403     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
404     /// constant build_vector of the stored constant values in Stores.
405     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
406                                          SDLoc SL,
407                                          ArrayRef<MemOpLink> Stores,
408                                          EVT Ty) const;
409
410     /// This is a helper function for MergeConsecutiveStores. When the source
411     /// elements of the consecutive stores are all constants or all extracted
412     /// vector elements, try to merge them into one larger store.
413     /// \return True if a merged store was created.
414     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
415                                          EVT MemVT, unsigned NumStores,
416                                          bool IsConstantSrc, bool UseVector);
417
418     /// This is a helper function for MergeConsecutiveStores.
419     /// Stores that may be merged are placed in StoreNodes.
420     /// Loads that may alias with those stores are placed in AliasLoadNodes.
421     void getStoreMergeAndAliasCandidates(
422         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
423         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
424
425     /// Merge consecutive store operations into a wide store.
426     /// This optimization uses wide integers or vectors when possible.
427     /// \return True if some memory operations were changed.
428     bool MergeConsecutiveStores(StoreSDNode *N);
429
430     /// \brief Try to transform a truncation where C is a constant:
431     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
432     ///
433     /// \p N needs to be a truncation and its first operand an AND. Other
434     /// requirements are checked by the function (e.g. that trunc is
435     /// single-use) and if missed an empty SDValue is returned.
436     SDValue distributeTruncateThroughAnd(SDNode *N);
437
438   public:
439     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
440         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
441           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
442       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
443     }
444
445     /// Runs the dag combiner on all nodes in the work list
446     void Run(CombineLevel AtLevel);
447
448     SelectionDAG &getDAG() const { return DAG; }
449
450     /// Returns a type large enough to hold any valid shift amount - before type
451     /// legalization these can be huge.
452     EVT getShiftAmountTy(EVT LHSTy) {
453       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
454       if (LHSTy.isVector())
455         return LHSTy;
456       auto &DL = DAG.getDataLayout();
457       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
458                         : TLI.getPointerTy(DL);
459     }
460
461     /// This method returns true if we are running before type legalization or
462     /// if the specified VT is legal.
463     bool isTypeLegal(const EVT &VT) {
464       if (!LegalTypes) return true;
465       return TLI.isTypeLegal(VT);
466     }
467
468     /// Convenience wrapper around TargetLowering::getSetCCResultType
469     EVT getSetCCResultType(EVT VT) const {
470       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
471     }
472   };
473 }
474
475
476 namespace {
477 /// This class is a DAGUpdateListener that removes any deleted
478 /// nodes from the worklist.
479 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
480   DAGCombiner &DC;
481 public:
482   explicit WorklistRemover(DAGCombiner &dc)
483     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
484
485   void NodeDeleted(SDNode *N, SDNode *E) override {
486     DC.removeFromWorklist(N);
487   }
488 };
489 }
490
491 //===----------------------------------------------------------------------===//
492 //  TargetLowering::DAGCombinerInfo implementation
493 //===----------------------------------------------------------------------===//
494
495 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
496   ((DAGCombiner*)DC)->AddToWorklist(N);
497 }
498
499 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
500   ((DAGCombiner*)DC)->removeFromWorklist(N);
501 }
502
503 SDValue TargetLowering::DAGCombinerInfo::
504 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
505   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
506 }
507
508 SDValue TargetLowering::DAGCombinerInfo::
509 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
510   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
511 }
512
513
514 SDValue TargetLowering::DAGCombinerInfo::
515 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
516   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
517 }
518
519 void TargetLowering::DAGCombinerInfo::
520 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
521   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
522 }
523
524 //===----------------------------------------------------------------------===//
525 // Helper Functions
526 //===----------------------------------------------------------------------===//
527
528 void DAGCombiner::deleteAndRecombine(SDNode *N) {
529   removeFromWorklist(N);
530
531   // If the operands of this node are only used by the node, they will now be
532   // dead. Make sure to re-visit them and recursively delete dead nodes.
533   for (const SDValue &Op : N->ops())
534     // For an operand generating multiple values, one of the values may
535     // become dead allowing further simplification (e.g. split index
536     // arithmetic from an indexed load).
537     if (Op->hasOneUse() || Op->getNumValues() > 1)
538       AddToWorklist(Op.getNode());
539
540   DAG.DeleteNode(N);
541 }
542
543 /// Return 1 if we can compute the negated form of the specified expression for
544 /// the same cost as the expression itself, or 2 if we can compute the negated
545 /// form more cheaply than the expression itself.
546 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
547                                const TargetLowering &TLI,
548                                const TargetOptions *Options,
549                                unsigned Depth = 0) {
550   // fneg is removable even if it has multiple uses.
551   if (Op.getOpcode() == ISD::FNEG) return 2;
552
553   // Don't allow anything with multiple uses.
554   if (!Op.hasOneUse()) return 0;
555
556   // Don't recurse exponentially.
557   if (Depth > 6) return 0;
558
559   switch (Op.getOpcode()) {
560   default: return false;
561   case ISD::ConstantFP:
562     // Don't invert constant FP values after legalize.  The negated constant
563     // isn't necessarily legal.
564     return LegalOperations ? 0 : 1;
565   case ISD::FADD:
566     // FIXME: determine better conditions for this xform.
567     if (!Options->UnsafeFPMath) return 0;
568
569     // After operation legalization, it might not be legal to create new FSUBs.
570     if (LegalOperations &&
571         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
572       return 0;
573
574     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
575     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
576                                     Options, Depth + 1))
577       return V;
578     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
579     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
580                               Depth + 1);
581   case ISD::FSUB:
582     // We can't turn -(A-B) into B-A when we honor signed zeros.
583     if (!Options->UnsafeFPMath) return 0;
584
585     // fold (fneg (fsub A, B)) -> (fsub B, A)
586     return 1;
587
588   case ISD::FMUL:
589   case ISD::FDIV:
590     if (Options->HonorSignDependentRoundingFPMath()) return 0;
591
592     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
593     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
594                                     Options, Depth + 1))
595       return V;
596
597     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
598                               Depth + 1);
599
600   case ISD::FP_EXTEND:
601   case ISD::FP_ROUND:
602   case ISD::FSIN:
603     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
604                               Depth + 1);
605   }
606 }
607
608 /// If isNegatibleForFree returns true, return the newly negated expression.
609 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
610                                     bool LegalOperations, unsigned Depth = 0) {
611   const TargetOptions &Options = DAG.getTarget().Options;
612   // fneg is removable even if it has multiple uses.
613   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
614
615   // Don't allow anything with multiple uses.
616   assert(Op.hasOneUse() && "Unknown reuse!");
617
618   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
619
620   const SDNodeFlags *Flags = Op.getNode()->getFlags();
621   
622   switch (Op.getOpcode()) {
623   default: llvm_unreachable("Unknown code");
624   case ISD::ConstantFP: {
625     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
626     V.changeSign();
627     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
628   }
629   case ISD::FADD:
630     // FIXME: determine better conditions for this xform.
631     assert(Options.UnsafeFPMath);
632
633     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
634     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
635                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
636       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
637                          GetNegatedExpression(Op.getOperand(0), DAG,
638                                               LegalOperations, Depth+1),
639                          Op.getOperand(1), Flags);
640     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
641     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
642                        GetNegatedExpression(Op.getOperand(1), DAG,
643                                             LegalOperations, Depth+1),
644                        Op.getOperand(0), Flags);
645   case ISD::FSUB:
646     // We can't turn -(A-B) into B-A when we honor signed zeros.
647     assert(Options.UnsafeFPMath);
648
649     // fold (fneg (fsub 0, B)) -> B
650     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
651       if (N0CFP->isZero())
652         return Op.getOperand(1);
653
654     // fold (fneg (fsub A, B)) -> (fsub B, A)
655     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
656                        Op.getOperand(1), Op.getOperand(0), Flags);
657
658   case ISD::FMUL:
659   case ISD::FDIV:
660     assert(!Options.HonorSignDependentRoundingFPMath());
661
662     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
663     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
664                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
665       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
666                          GetNegatedExpression(Op.getOperand(0), DAG,
667                                               LegalOperations, Depth+1),
668                          Op.getOperand(1), Flags);
669
670     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
671     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
672                        Op.getOperand(0),
673                        GetNegatedExpression(Op.getOperand(1), DAG,
674                                             LegalOperations, Depth+1), Flags);
675
676   case ISD::FP_EXTEND:
677   case ISD::FSIN:
678     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
679                        GetNegatedExpression(Op.getOperand(0), DAG,
680                                             LegalOperations, Depth+1));
681   case ISD::FP_ROUND:
682       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
683                          GetNegatedExpression(Op.getOperand(0), DAG,
684                                               LegalOperations, Depth+1),
685                          Op.getOperand(1));
686   }
687 }
688
689 // Return true if this node is a setcc, or is a select_cc
690 // that selects between the target values used for true and false, making it
691 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
692 // the appropriate nodes based on the type of node we are checking. This
693 // simplifies life a bit for the callers.
694 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
695                                     SDValue &CC) const {
696   if (N.getOpcode() == ISD::SETCC) {
697     LHS = N.getOperand(0);
698     RHS = N.getOperand(1);
699     CC  = N.getOperand(2);
700     return true;
701   }
702
703   if (N.getOpcode() != ISD::SELECT_CC ||
704       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
705       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
706     return false;
707
708   if (TLI.getBooleanContents(N.getValueType()) ==
709       TargetLowering::UndefinedBooleanContent)
710     return false;
711
712   LHS = N.getOperand(0);
713   RHS = N.getOperand(1);
714   CC  = N.getOperand(4);
715   return true;
716 }
717
718 /// Return true if this is a SetCC-equivalent operation with only one use.
719 /// If this is true, it allows the users to invert the operation for free when
720 /// it is profitable to do so.
721 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
722   SDValue N0, N1, N2;
723   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
724     return true;
725   return false;
726 }
727
728 /// Returns true if N is a BUILD_VECTOR node whose
729 /// elements are all the same constant or undefined.
730 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
731   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
732   if (!C)
733     return false;
734
735   APInt SplatUndef;
736   unsigned SplatBitSize;
737   bool HasAnyUndefs;
738   EVT EltVT = N->getValueType(0).getVectorElementType();
739   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
740                              HasAnyUndefs) &&
741           EltVT.getSizeInBits() >= SplatBitSize);
742 }
743
744 // \brief Returns the SDNode if it is a constant integer BuildVector
745 // or constant integer.
746 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
747   if (isa<ConstantSDNode>(N))
748     return N.getNode();
749   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
750     return N.getNode();
751   return nullptr;
752 }
753
754 // \brief Returns the SDNode if it is a constant float BuildVector
755 // or constant float.
756 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
757   if (isa<ConstantFPSDNode>(N))
758     return N.getNode();
759   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
760     return N.getNode();
761   return nullptr;
762 }
763
764 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
765 // int.
766 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
767   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
768     return CN;
769
770   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
771     BitVector UndefElements;
772     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
773
774     // BuildVectors can truncate their operands. Ignore that case here.
775     // FIXME: We blindly ignore splats which include undef which is overly
776     // pessimistic.
777     if (CN && UndefElements.none() &&
778         CN->getValueType(0) == N.getValueType().getScalarType())
779       return CN;
780   }
781
782   return nullptr;
783 }
784
785 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
786 // float.
787 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
788   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
789     return CN;
790
791   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
792     BitVector UndefElements;
793     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
794
795     if (CN && UndefElements.none())
796       return CN;
797   }
798
799   return nullptr;
800 }
801
802 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
803                                     SDValue N0, SDValue N1) {
804   EVT VT = N0.getValueType();
805   if (N0.getOpcode() == Opc) {
806     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
807       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
808         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
809         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
810           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
811         return SDValue();
812       }
813       if (N0.hasOneUse()) {
814         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
815         // use
816         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
817         if (!OpNode.getNode())
818           return SDValue();
819         AddToWorklist(OpNode.getNode());
820         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
821       }
822     }
823   }
824
825   if (N1.getOpcode() == Opc) {
826     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
827       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
828         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
829         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
830           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
831         return SDValue();
832       }
833       if (N1.hasOneUse()) {
834         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
835         // use
836         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
837         if (!OpNode.getNode())
838           return SDValue();
839         AddToWorklist(OpNode.getNode());
840         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
841       }
842     }
843   }
844
845   return SDValue();
846 }
847
848 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
849                                bool AddTo) {
850   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
851   ++NodesCombined;
852   DEBUG(dbgs() << "\nReplacing.1 ";
853         N->dump(&DAG);
854         dbgs() << "\nWith: ";
855         To[0].getNode()->dump(&DAG);
856         dbgs() << " and " << NumTo-1 << " other values\n");
857   for (unsigned i = 0, e = NumTo; i != e; ++i)
858     assert((!To[i].getNode() ||
859             N->getValueType(i) == To[i].getValueType()) &&
860            "Cannot combine value to value of different type!");
861
862   WorklistRemover DeadNodes(*this);
863   DAG.ReplaceAllUsesWith(N, To);
864   if (AddTo) {
865     // Push the new nodes and any users onto the worklist
866     for (unsigned i = 0, e = NumTo; i != e; ++i) {
867       if (To[i].getNode()) {
868         AddToWorklist(To[i].getNode());
869         AddUsersToWorklist(To[i].getNode());
870       }
871     }
872   }
873
874   // Finally, if the node is now dead, remove it from the graph.  The node
875   // may not be dead if the replacement process recursively simplified to
876   // something else needing this node.
877   if (N->use_empty())
878     deleteAndRecombine(N);
879   return SDValue(N, 0);
880 }
881
882 void DAGCombiner::
883 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
884   // Replace all uses.  If any nodes become isomorphic to other nodes and
885   // are deleted, make sure to remove them from our worklist.
886   WorklistRemover DeadNodes(*this);
887   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
888
889   // Push the new node and any (possibly new) users onto the worklist.
890   AddToWorklist(TLO.New.getNode());
891   AddUsersToWorklist(TLO.New.getNode());
892
893   // Finally, if the node is now dead, remove it from the graph.  The node
894   // may not be dead if the replacement process recursively simplified to
895   // something else needing this node.
896   if (TLO.Old.getNode()->use_empty())
897     deleteAndRecombine(TLO.Old.getNode());
898 }
899
900 /// Check the specified integer node value to see if it can be simplified or if
901 /// things it uses can be simplified by bit propagation. If so, return true.
902 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
903   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
904   APInt KnownZero, KnownOne;
905   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
906     return false;
907
908   // Revisit the node.
909   AddToWorklist(Op.getNode());
910
911   // Replace the old value with the new one.
912   ++NodesCombined;
913   DEBUG(dbgs() << "\nReplacing.2 ";
914         TLO.Old.getNode()->dump(&DAG);
915         dbgs() << "\nWith: ";
916         TLO.New.getNode()->dump(&DAG);
917         dbgs() << '\n');
918
919   CommitTargetLoweringOpt(TLO);
920   return true;
921 }
922
923 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
924   SDLoc dl(Load);
925   EVT VT = Load->getValueType(0);
926   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
927
928   DEBUG(dbgs() << "\nReplacing.9 ";
929         Load->dump(&DAG);
930         dbgs() << "\nWith: ";
931         Trunc.getNode()->dump(&DAG);
932         dbgs() << '\n');
933   WorklistRemover DeadNodes(*this);
934   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
935   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
936   deleteAndRecombine(Load);
937   AddToWorklist(Trunc.getNode());
938 }
939
940 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
941   Replace = false;
942   SDLoc dl(Op);
943   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
944     EVT MemVT = LD->getMemoryVT();
945     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
946       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
947                                                        : ISD::EXTLOAD)
948       : LD->getExtensionType();
949     Replace = true;
950     return DAG.getExtLoad(ExtType, dl, PVT,
951                           LD->getChain(), LD->getBasePtr(),
952                           MemVT, LD->getMemOperand());
953   }
954
955   unsigned Opc = Op.getOpcode();
956   switch (Opc) {
957   default: break;
958   case ISD::AssertSext:
959     return DAG.getNode(ISD::AssertSext, dl, PVT,
960                        SExtPromoteOperand(Op.getOperand(0), PVT),
961                        Op.getOperand(1));
962   case ISD::AssertZext:
963     return DAG.getNode(ISD::AssertZext, dl, PVT,
964                        ZExtPromoteOperand(Op.getOperand(0), PVT),
965                        Op.getOperand(1));
966   case ISD::Constant: {
967     unsigned ExtOpc =
968       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
969     return DAG.getNode(ExtOpc, dl, PVT, Op);
970   }
971   }
972
973   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
974     return SDValue();
975   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
976 }
977
978 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
979   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
980     return SDValue();
981   EVT OldVT = Op.getValueType();
982   SDLoc dl(Op);
983   bool Replace = false;
984   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
985   if (!NewOp.getNode())
986     return SDValue();
987   AddToWorklist(NewOp.getNode());
988
989   if (Replace)
990     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
991   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
992                      DAG.getValueType(OldVT));
993 }
994
995 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
996   EVT OldVT = Op.getValueType();
997   SDLoc dl(Op);
998   bool Replace = false;
999   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1000   if (!NewOp.getNode())
1001     return SDValue();
1002   AddToWorklist(NewOp.getNode());
1003
1004   if (Replace)
1005     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1006   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1007 }
1008
1009 /// Promote the specified integer binary operation if the target indicates it is
1010 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1011 /// i32 since i16 instructions are longer.
1012 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1013   if (!LegalOperations)
1014     return SDValue();
1015
1016   EVT VT = Op.getValueType();
1017   if (VT.isVector() || !VT.isInteger())
1018     return SDValue();
1019
1020   // If operation type is 'undesirable', e.g. i16 on x86, consider
1021   // promoting it.
1022   unsigned Opc = Op.getOpcode();
1023   if (TLI.isTypeDesirableForOp(Opc, VT))
1024     return SDValue();
1025
1026   EVT PVT = VT;
1027   // Consult target whether it is a good idea to promote this operation and
1028   // what's the right type to promote it to.
1029   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1030     assert(PVT != VT && "Don't know what type to promote to!");
1031
1032     bool Replace0 = false;
1033     SDValue N0 = Op.getOperand(0);
1034     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1035     if (!NN0.getNode())
1036       return SDValue();
1037
1038     bool Replace1 = false;
1039     SDValue N1 = Op.getOperand(1);
1040     SDValue NN1;
1041     if (N0 == N1)
1042       NN1 = NN0;
1043     else {
1044       NN1 = PromoteOperand(N1, PVT, Replace1);
1045       if (!NN1.getNode())
1046         return SDValue();
1047     }
1048
1049     AddToWorklist(NN0.getNode());
1050     if (NN1.getNode())
1051       AddToWorklist(NN1.getNode());
1052
1053     if (Replace0)
1054       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1055     if (Replace1)
1056       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1057
1058     DEBUG(dbgs() << "\nPromoting ";
1059           Op.getNode()->dump(&DAG));
1060     SDLoc dl(Op);
1061     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1062                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1063   }
1064   return SDValue();
1065 }
1066
1067 /// Promote the specified integer shift operation if the target indicates it is
1068 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1069 /// i32 since i16 instructions are longer.
1070 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1071   if (!LegalOperations)
1072     return SDValue();
1073
1074   EVT VT = Op.getValueType();
1075   if (VT.isVector() || !VT.isInteger())
1076     return SDValue();
1077
1078   // If operation type is 'undesirable', e.g. i16 on x86, consider
1079   // promoting it.
1080   unsigned Opc = Op.getOpcode();
1081   if (TLI.isTypeDesirableForOp(Opc, VT))
1082     return SDValue();
1083
1084   EVT PVT = VT;
1085   // Consult target whether it is a good idea to promote this operation and
1086   // what's the right type to promote it to.
1087   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1088     assert(PVT != VT && "Don't know what type to promote to!");
1089
1090     bool Replace = false;
1091     SDValue N0 = Op.getOperand(0);
1092     if (Opc == ISD::SRA)
1093       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1094     else if (Opc == ISD::SRL)
1095       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1096     else
1097       N0 = PromoteOperand(N0, PVT, Replace);
1098     if (!N0.getNode())
1099       return SDValue();
1100
1101     AddToWorklist(N0.getNode());
1102     if (Replace)
1103       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1104
1105     DEBUG(dbgs() << "\nPromoting ";
1106           Op.getNode()->dump(&DAG));
1107     SDLoc dl(Op);
1108     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1109                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1110   }
1111   return SDValue();
1112 }
1113
1114 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1115   if (!LegalOperations)
1116     return SDValue();
1117
1118   EVT VT = Op.getValueType();
1119   if (VT.isVector() || !VT.isInteger())
1120     return SDValue();
1121
1122   // If operation type is 'undesirable', e.g. i16 on x86, consider
1123   // promoting it.
1124   unsigned Opc = Op.getOpcode();
1125   if (TLI.isTypeDesirableForOp(Opc, VT))
1126     return SDValue();
1127
1128   EVT PVT = VT;
1129   // Consult target whether it is a good idea to promote this operation and
1130   // what's the right type to promote it to.
1131   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1132     assert(PVT != VT && "Don't know what type to promote to!");
1133     // fold (aext (aext x)) -> (aext x)
1134     // fold (aext (zext x)) -> (zext x)
1135     // fold (aext (sext x)) -> (sext x)
1136     DEBUG(dbgs() << "\nPromoting ";
1137           Op.getNode()->dump(&DAG));
1138     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1139   }
1140   return SDValue();
1141 }
1142
1143 bool DAGCombiner::PromoteLoad(SDValue Op) {
1144   if (!LegalOperations)
1145     return false;
1146
1147   EVT VT = Op.getValueType();
1148   if (VT.isVector() || !VT.isInteger())
1149     return false;
1150
1151   // If operation type is 'undesirable', e.g. i16 on x86, consider
1152   // promoting it.
1153   unsigned Opc = Op.getOpcode();
1154   if (TLI.isTypeDesirableForOp(Opc, VT))
1155     return false;
1156
1157   EVT PVT = VT;
1158   // Consult target whether it is a good idea to promote this operation and
1159   // what's the right type to promote it to.
1160   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1161     assert(PVT != VT && "Don't know what type to promote to!");
1162
1163     SDLoc dl(Op);
1164     SDNode *N = Op.getNode();
1165     LoadSDNode *LD = cast<LoadSDNode>(N);
1166     EVT MemVT = LD->getMemoryVT();
1167     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1168       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1169                                                        : ISD::EXTLOAD)
1170       : LD->getExtensionType();
1171     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1172                                    LD->getChain(), LD->getBasePtr(),
1173                                    MemVT, LD->getMemOperand());
1174     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1175
1176     DEBUG(dbgs() << "\nPromoting ";
1177           N->dump(&DAG);
1178           dbgs() << "\nTo: ";
1179           Result.getNode()->dump(&DAG);
1180           dbgs() << '\n');
1181     WorklistRemover DeadNodes(*this);
1182     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1183     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1184     deleteAndRecombine(N);
1185     AddToWorklist(Result.getNode());
1186     return true;
1187   }
1188   return false;
1189 }
1190
1191 /// \brief Recursively delete a node which has no uses and any operands for
1192 /// which it is the only use.
1193 ///
1194 /// Note that this both deletes the nodes and removes them from the worklist.
1195 /// It also adds any nodes who have had a user deleted to the worklist as they
1196 /// may now have only one use and subject to other combines.
1197 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1198   if (!N->use_empty())
1199     return false;
1200
1201   SmallSetVector<SDNode *, 16> Nodes;
1202   Nodes.insert(N);
1203   do {
1204     N = Nodes.pop_back_val();
1205     if (!N)
1206       continue;
1207
1208     if (N->use_empty()) {
1209       for (const SDValue &ChildN : N->op_values())
1210         Nodes.insert(ChildN.getNode());
1211
1212       removeFromWorklist(N);
1213       DAG.DeleteNode(N);
1214     } else {
1215       AddToWorklist(N);
1216     }
1217   } while (!Nodes.empty());
1218   return true;
1219 }
1220
1221 //===----------------------------------------------------------------------===//
1222 //  Main DAG Combiner implementation
1223 //===----------------------------------------------------------------------===//
1224
1225 void DAGCombiner::Run(CombineLevel AtLevel) {
1226   // set the instance variables, so that the various visit routines may use it.
1227   Level = AtLevel;
1228   LegalOperations = Level >= AfterLegalizeVectorOps;
1229   LegalTypes = Level >= AfterLegalizeTypes;
1230
1231   // Add all the dag nodes to the worklist.
1232   for (SDNode &Node : DAG.allnodes())
1233     AddToWorklist(&Node);
1234
1235   // Create a dummy node (which is not added to allnodes), that adds a reference
1236   // to the root node, preventing it from being deleted, and tracking any
1237   // changes of the root.
1238   HandleSDNode Dummy(DAG.getRoot());
1239
1240   // while the worklist isn't empty, find a node and
1241   // try and combine it.
1242   while (!WorklistMap.empty()) {
1243     SDNode *N;
1244     // The Worklist holds the SDNodes in order, but it may contain null entries.
1245     do {
1246       N = Worklist.pop_back_val();
1247     } while (!N);
1248
1249     bool GoodWorklistEntry = WorklistMap.erase(N);
1250     (void)GoodWorklistEntry;
1251     assert(GoodWorklistEntry &&
1252            "Found a worklist entry without a corresponding map entry!");
1253
1254     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1255     // N is deleted from the DAG, since they too may now be dead or may have a
1256     // reduced number of uses, allowing other xforms.
1257     if (recursivelyDeleteUnusedNodes(N))
1258       continue;
1259
1260     WorklistRemover DeadNodes(*this);
1261
1262     // If this combine is running after legalizing the DAG, re-legalize any
1263     // nodes pulled off the worklist.
1264     if (Level == AfterLegalizeDAG) {
1265       SmallSetVector<SDNode *, 16> UpdatedNodes;
1266       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1267
1268       for (SDNode *LN : UpdatedNodes) {
1269         AddToWorklist(LN);
1270         AddUsersToWorklist(LN);
1271       }
1272       if (!NIsValid)
1273         continue;
1274     }
1275
1276     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1277
1278     // Add any operands of the new node which have not yet been combined to the
1279     // worklist as well. Because the worklist uniques things already, this
1280     // won't repeatedly process the same operand.
1281     CombinedNodes.insert(N);
1282     for (const SDValue &ChildN : N->op_values())
1283       if (!CombinedNodes.count(ChildN.getNode()))
1284         AddToWorklist(ChildN.getNode());
1285
1286     SDValue RV = combine(N);
1287
1288     if (!RV.getNode())
1289       continue;
1290
1291     ++NodesCombined;
1292
1293     // If we get back the same node we passed in, rather than a new node or
1294     // zero, we know that the node must have defined multiple values and
1295     // CombineTo was used.  Since CombineTo takes care of the worklist
1296     // mechanics for us, we have no work to do in this case.
1297     if (RV.getNode() == N)
1298       continue;
1299
1300     assert(N->getOpcode() != ISD::DELETED_NODE &&
1301            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1302            "Node was deleted but visit returned new node!");
1303
1304     DEBUG(dbgs() << " ... into: ";
1305           RV.getNode()->dump(&DAG));
1306
1307     // Transfer debug value.
1308     DAG.TransferDbgValues(SDValue(N, 0), RV);
1309     if (N->getNumValues() == RV.getNode()->getNumValues())
1310       DAG.ReplaceAllUsesWith(N, RV.getNode());
1311     else {
1312       assert(N->getValueType(0) == RV.getValueType() &&
1313              N->getNumValues() == 1 && "Type mismatch");
1314       SDValue OpV = RV;
1315       DAG.ReplaceAllUsesWith(N, &OpV);
1316     }
1317
1318     // Push the new node and any users onto the worklist
1319     AddToWorklist(RV.getNode());
1320     AddUsersToWorklist(RV.getNode());
1321
1322     // Finally, if the node is now dead, remove it from the graph.  The node
1323     // may not be dead if the replacement process recursively simplified to
1324     // something else needing this node. This will also take care of adding any
1325     // operands which have lost a user to the worklist.
1326     recursivelyDeleteUnusedNodes(N);
1327   }
1328
1329   // If the root changed (e.g. it was a dead load, update the root).
1330   DAG.setRoot(Dummy.getValue());
1331   DAG.RemoveDeadNodes();
1332 }
1333
1334 SDValue DAGCombiner::visit(SDNode *N) {
1335   switch (N->getOpcode()) {
1336   default: break;
1337   case ISD::TokenFactor:        return visitTokenFactor(N);
1338   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1339   case ISD::ADD:                return visitADD(N);
1340   case ISD::SUB:                return visitSUB(N);
1341   case ISD::ADDC:               return visitADDC(N);
1342   case ISD::SUBC:               return visitSUBC(N);
1343   case ISD::ADDE:               return visitADDE(N);
1344   case ISD::SUBE:               return visitSUBE(N);
1345   case ISD::MUL:                return visitMUL(N);
1346   case ISD::SDIV:               return visitSDIV(N);
1347   case ISD::UDIV:               return visitUDIV(N);
1348   case ISD::SREM:               return visitSREM(N);
1349   case ISD::UREM:               return visitUREM(N);
1350   case ISD::MULHU:              return visitMULHU(N);
1351   case ISD::MULHS:              return visitMULHS(N);
1352   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1353   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1354   case ISD::SMULO:              return visitSMULO(N);
1355   case ISD::UMULO:              return visitUMULO(N);
1356   case ISD::SDIVREM:            return visitSDIVREM(N);
1357   case ISD::UDIVREM:            return visitUDIVREM(N);
1358   case ISD::SMIN:
1359   case ISD::SMAX:
1360   case ISD::UMIN:
1361   case ISD::UMAX:               return visitIMINMAX(N);
1362   case ISD::AND:                return visitAND(N);
1363   case ISD::OR:                 return visitOR(N);
1364   case ISD::XOR:                return visitXOR(N);
1365   case ISD::SHL:                return visitSHL(N);
1366   case ISD::SRA:                return visitSRA(N);
1367   case ISD::SRL:                return visitSRL(N);
1368   case ISD::ROTR:
1369   case ISD::ROTL:               return visitRotate(N);
1370   case ISD::BSWAP:              return visitBSWAP(N);
1371   case ISD::CTLZ:               return visitCTLZ(N);
1372   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1373   case ISD::CTTZ:               return visitCTTZ(N);
1374   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1375   case ISD::CTPOP:              return visitCTPOP(N);
1376   case ISD::SELECT:             return visitSELECT(N);
1377   case ISD::VSELECT:            return visitVSELECT(N);
1378   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1379   case ISD::SETCC:              return visitSETCC(N);
1380   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1381   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1382   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1383   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1384   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1385   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1386   case ISD::BITCAST:            return visitBITCAST(N);
1387   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1388   case ISD::FADD:               return visitFADD(N);
1389   case ISD::FSUB:               return visitFSUB(N);
1390   case ISD::FMUL:               return visitFMUL(N);
1391   case ISD::FMA:                return visitFMA(N);
1392   case ISD::FDIV:               return visitFDIV(N);
1393   case ISD::FREM:               return visitFREM(N);
1394   case ISD::FSQRT:              return visitFSQRT(N);
1395   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1396   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1397   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1398   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1399   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1400   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1401   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1402   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1403   case ISD::FNEG:               return visitFNEG(N);
1404   case ISD::FABS:               return visitFABS(N);
1405   case ISD::FFLOOR:             return visitFFLOOR(N);
1406   case ISD::FMINNUM:            return visitFMINNUM(N);
1407   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1408   case ISD::FCEIL:              return visitFCEIL(N);
1409   case ISD::FTRUNC:             return visitFTRUNC(N);
1410   case ISD::BRCOND:             return visitBRCOND(N);
1411   case ISD::BR_CC:              return visitBR_CC(N);
1412   case ISD::LOAD:               return visitLOAD(N);
1413   case ISD::STORE:              return visitSTORE(N);
1414   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1415   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1416   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1417   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1418   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1419   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1420   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1421   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1422   case ISD::MGATHER:            return visitMGATHER(N);
1423   case ISD::MLOAD:              return visitMLOAD(N);
1424   case ISD::MSCATTER:           return visitMSCATTER(N);
1425   case ISD::MSTORE:             return visitMSTORE(N);
1426   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1427   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1428   }
1429   return SDValue();
1430 }
1431
1432 SDValue DAGCombiner::combine(SDNode *N) {
1433   SDValue RV = visit(N);
1434
1435   // If nothing happened, try a target-specific DAG combine.
1436   if (!RV.getNode()) {
1437     assert(N->getOpcode() != ISD::DELETED_NODE &&
1438            "Node was deleted but visit returned NULL!");
1439
1440     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1441         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1442
1443       // Expose the DAG combiner to the target combiner impls.
1444       TargetLowering::DAGCombinerInfo
1445         DagCombineInfo(DAG, Level, false, this);
1446
1447       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1448     }
1449   }
1450
1451   // If nothing happened still, try promoting the operation.
1452   if (!RV.getNode()) {
1453     switch (N->getOpcode()) {
1454     default: break;
1455     case ISD::ADD:
1456     case ISD::SUB:
1457     case ISD::MUL:
1458     case ISD::AND:
1459     case ISD::OR:
1460     case ISD::XOR:
1461       RV = PromoteIntBinOp(SDValue(N, 0));
1462       break;
1463     case ISD::SHL:
1464     case ISD::SRA:
1465     case ISD::SRL:
1466       RV = PromoteIntShiftOp(SDValue(N, 0));
1467       break;
1468     case ISD::SIGN_EXTEND:
1469     case ISD::ZERO_EXTEND:
1470     case ISD::ANY_EXTEND:
1471       RV = PromoteExtend(SDValue(N, 0));
1472       break;
1473     case ISD::LOAD:
1474       if (PromoteLoad(SDValue(N, 0)))
1475         RV = SDValue(N, 0);
1476       break;
1477     }
1478   }
1479
1480   // If N is a commutative binary node, try commuting it to enable more
1481   // sdisel CSE.
1482   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1483       N->getNumValues() == 1) {
1484     SDValue N0 = N->getOperand(0);
1485     SDValue N1 = N->getOperand(1);
1486
1487     // Constant operands are canonicalized to RHS.
1488     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1489       SDValue Ops[] = {N1, N0};
1490       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1491                                             N->getFlags());
1492       if (CSENode)
1493         return SDValue(CSENode, 0);
1494     }
1495   }
1496
1497   return RV;
1498 }
1499
1500 /// Given a node, return its input chain if it has one, otherwise return a null
1501 /// sd operand.
1502 static SDValue getInputChainForNode(SDNode *N) {
1503   if (unsigned NumOps = N->getNumOperands()) {
1504     if (N->getOperand(0).getValueType() == MVT::Other)
1505       return N->getOperand(0);
1506     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1507       return N->getOperand(NumOps-1);
1508     for (unsigned i = 1; i < NumOps-1; ++i)
1509       if (N->getOperand(i).getValueType() == MVT::Other)
1510         return N->getOperand(i);
1511   }
1512   return SDValue();
1513 }
1514
1515 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1516   // If N has two operands, where one has an input chain equal to the other,
1517   // the 'other' chain is redundant.
1518   if (N->getNumOperands() == 2) {
1519     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1520       return N->getOperand(0);
1521     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1522       return N->getOperand(1);
1523   }
1524
1525   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1526   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1527   SmallPtrSet<SDNode*, 16> SeenOps;
1528   bool Changed = false;             // If we should replace this token factor.
1529
1530   // Start out with this token factor.
1531   TFs.push_back(N);
1532
1533   // Iterate through token factors.  The TFs grows when new token factors are
1534   // encountered.
1535   for (unsigned i = 0; i < TFs.size(); ++i) {
1536     SDNode *TF = TFs[i];
1537
1538     // Check each of the operands.
1539     for (const SDValue &Op : TF->op_values()) {
1540
1541       switch (Op.getOpcode()) {
1542       case ISD::EntryToken:
1543         // Entry tokens don't need to be added to the list. They are
1544         // redundant.
1545         Changed = true;
1546         break;
1547
1548       case ISD::TokenFactor:
1549         if (Op.hasOneUse() &&
1550             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1551           // Queue up for processing.
1552           TFs.push_back(Op.getNode());
1553           // Clean up in case the token factor is removed.
1554           AddToWorklist(Op.getNode());
1555           Changed = true;
1556           break;
1557         }
1558         // Fall thru
1559
1560       default:
1561         // Only add if it isn't already in the list.
1562         if (SeenOps.insert(Op.getNode()).second)
1563           Ops.push_back(Op);
1564         else
1565           Changed = true;
1566         break;
1567       }
1568     }
1569   }
1570
1571   SDValue Result;
1572
1573   // If we've changed things around then replace token factor.
1574   if (Changed) {
1575     if (Ops.empty()) {
1576       // The entry token is the only possible outcome.
1577       Result = DAG.getEntryNode();
1578     } else {
1579       // New and improved token factor.
1580       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1581     }
1582
1583     // Add users to worklist if AA is enabled, since it may introduce
1584     // a lot of new chained token factors while removing memory deps.
1585     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1586       : DAG.getSubtarget().useAA();
1587     return CombineTo(N, Result, UseAA /*add to worklist*/);
1588   }
1589
1590   return Result;
1591 }
1592
1593 /// MERGE_VALUES can always be eliminated.
1594 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1595   WorklistRemover DeadNodes(*this);
1596   // Replacing results may cause a different MERGE_VALUES to suddenly
1597   // be CSE'd with N, and carry its uses with it. Iterate until no
1598   // uses remain, to ensure that the node can be safely deleted.
1599   // First add the users of this node to the work list so that they
1600   // can be tried again once they have new operands.
1601   AddUsersToWorklist(N);
1602   do {
1603     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1604       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1605   } while (!N->use_empty());
1606   deleteAndRecombine(N);
1607   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1608 }
1609
1610 static bool isNullConstant(SDValue V) {
1611   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1612   return Const != nullptr && Const->isNullValue();
1613 }
1614
1615 static bool isNullFPConstant(SDValue V) {
1616   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1617   return Const != nullptr && Const->isZero() && !Const->isNegative();
1618 }
1619
1620 static bool isAllOnesConstant(SDValue V) {
1621   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1622   return Const != nullptr && Const->isAllOnesValue();
1623 }
1624
1625 static bool isOneConstant(SDValue V) {
1626   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1627   return Const != nullptr && Const->isOne();
1628 }
1629
1630 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1631 /// ContantSDNode pointer else nullptr.
1632 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1633   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1634   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1635 }
1636
1637 SDValue DAGCombiner::visitADD(SDNode *N) {
1638   SDValue N0 = N->getOperand(0);
1639   SDValue N1 = N->getOperand(1);
1640   EVT VT = N0.getValueType();
1641
1642   // fold vector ops
1643   if (VT.isVector()) {
1644     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1645       return FoldedVOp;
1646
1647     // fold (add x, 0) -> x, vector edition
1648     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1649       return N0;
1650     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1651       return N1;
1652   }
1653
1654   // fold (add x, undef) -> undef
1655   if (N0.getOpcode() == ISD::UNDEF)
1656     return N0;
1657   if (N1.getOpcode() == ISD::UNDEF)
1658     return N1;
1659   // fold (add c1, c2) -> c1+c2
1660   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1661   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1662   if (N0C && N1C)
1663     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1664   // canonicalize constant to RHS
1665   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1666      !isConstantIntBuildVectorOrConstantInt(N1))
1667     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1668   // fold (add x, 0) -> x
1669   if (isNullConstant(N1))
1670     return N0;
1671   // fold (add Sym, c) -> Sym+c
1672   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1673     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1674         GA->getOpcode() == ISD::GlobalAddress)
1675       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1676                                   GA->getOffset() +
1677                                     (uint64_t)N1C->getSExtValue());
1678   // fold ((c1-A)+c2) -> (c1+c2)-A
1679   if (N1C && N0.getOpcode() == ISD::SUB)
1680     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1681       SDLoc DL(N);
1682       return DAG.getNode(ISD::SUB, DL, VT,
1683                          DAG.getConstant(N1C->getAPIntValue()+
1684                                          N0C->getAPIntValue(), DL, VT),
1685                          N0.getOperand(1));
1686     }
1687   // reassociate add
1688   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1689     return RADD;
1690   // fold ((0-A) + B) -> B-A
1691   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1692     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1693   // fold (A + (0-B)) -> A-B
1694   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1695     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1696   // fold (A+(B-A)) -> B
1697   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1698     return N1.getOperand(0);
1699   // fold ((B-A)+A) -> B
1700   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1701     return N0.getOperand(0);
1702   // fold (A+(B-(A+C))) to (B-C)
1703   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1704       N0 == N1.getOperand(1).getOperand(0))
1705     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1706                        N1.getOperand(1).getOperand(1));
1707   // fold (A+(B-(C+A))) to (B-C)
1708   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1709       N0 == N1.getOperand(1).getOperand(1))
1710     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1711                        N1.getOperand(1).getOperand(0));
1712   // fold (A+((B-A)+or-C)) to (B+or-C)
1713   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1714       N1.getOperand(0).getOpcode() == ISD::SUB &&
1715       N0 == N1.getOperand(0).getOperand(1))
1716     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1717                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1718
1719   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1720   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1721     SDValue N00 = N0.getOperand(0);
1722     SDValue N01 = N0.getOperand(1);
1723     SDValue N10 = N1.getOperand(0);
1724     SDValue N11 = N1.getOperand(1);
1725
1726     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1727       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1728                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1729                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1730   }
1731
1732   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1733     return SDValue(N, 0);
1734
1735   // fold (a+b) -> (a|b) iff a and b share no bits.
1736   if (VT.isInteger() && !VT.isVector()) {
1737     APInt LHSZero, LHSOne;
1738     APInt RHSZero, RHSOne;
1739     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1740
1741     if (LHSZero.getBoolValue()) {
1742       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1743
1744       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1745       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1746       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1747         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1748           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1749       }
1750     }
1751   }
1752
1753   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1754   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1755       isNullConstant(N1.getOperand(0).getOperand(0)))
1756     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1757                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1758                                    N1.getOperand(0).getOperand(1),
1759                                    N1.getOperand(1)));
1760   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1761       isNullConstant(N0.getOperand(0).getOperand(0)))
1762     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1763                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1764                                    N0.getOperand(0).getOperand(1),
1765                                    N0.getOperand(1)));
1766
1767   if (N1.getOpcode() == ISD::AND) {
1768     SDValue AndOp0 = N1.getOperand(0);
1769     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1770     unsigned DestBits = VT.getScalarType().getSizeInBits();
1771
1772     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1773     // and similar xforms where the inner op is either ~0 or 0.
1774     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1775       SDLoc DL(N);
1776       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1777     }
1778   }
1779
1780   // add (sext i1), X -> sub X, (zext i1)
1781   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1782       N0.getOperand(0).getValueType() == MVT::i1 &&
1783       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1784     SDLoc DL(N);
1785     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1786     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1787   }
1788
1789   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1790   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1791     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1792     if (TN->getVT() == MVT::i1) {
1793       SDLoc DL(N);
1794       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1795                                  DAG.getConstant(1, DL, VT));
1796       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1797     }
1798   }
1799
1800   return SDValue();
1801 }
1802
1803 SDValue DAGCombiner::visitADDC(SDNode *N) {
1804   SDValue N0 = N->getOperand(0);
1805   SDValue N1 = N->getOperand(1);
1806   EVT VT = N0.getValueType();
1807
1808   // If the flag result is dead, turn this into an ADD.
1809   if (!N->hasAnyUseOfValue(1))
1810     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1811                      DAG.getNode(ISD::CARRY_FALSE,
1812                                  SDLoc(N), MVT::Glue));
1813
1814   // canonicalize constant to RHS.
1815   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1816   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1817   if (N0C && !N1C)
1818     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1819
1820   // fold (addc x, 0) -> x + no carry out
1821   if (isNullConstant(N1))
1822     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1823                                         SDLoc(N), MVT::Glue));
1824
1825   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1826   APInt LHSZero, LHSOne;
1827   APInt RHSZero, RHSOne;
1828   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1829
1830   if (LHSZero.getBoolValue()) {
1831     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1832
1833     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1834     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1835     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1836       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1837                        DAG.getNode(ISD::CARRY_FALSE,
1838                                    SDLoc(N), MVT::Glue));
1839   }
1840
1841   return SDValue();
1842 }
1843
1844 SDValue DAGCombiner::visitADDE(SDNode *N) {
1845   SDValue N0 = N->getOperand(0);
1846   SDValue N1 = N->getOperand(1);
1847   SDValue CarryIn = N->getOperand(2);
1848
1849   // canonicalize constant to RHS
1850   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1851   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1852   if (N0C && !N1C)
1853     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1854                        N1, N0, CarryIn);
1855
1856   // fold (adde x, y, false) -> (addc x, y)
1857   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1858     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1859
1860   return SDValue();
1861 }
1862
1863 // Since it may not be valid to emit a fold to zero for vector initializers
1864 // check if we can before folding.
1865 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1866                              SelectionDAG &DAG,
1867                              bool LegalOperations, bool LegalTypes) {
1868   if (!VT.isVector())
1869     return DAG.getConstant(0, DL, VT);
1870   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1871     return DAG.getConstant(0, DL, VT);
1872   return SDValue();
1873 }
1874
1875 SDValue DAGCombiner::visitSUB(SDNode *N) {
1876   SDValue N0 = N->getOperand(0);
1877   SDValue N1 = N->getOperand(1);
1878   EVT VT = N0.getValueType();
1879
1880   // fold vector ops
1881   if (VT.isVector()) {
1882     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1883       return FoldedVOp;
1884
1885     // fold (sub x, 0) -> x, vector edition
1886     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1887       return N0;
1888   }
1889
1890   // fold (sub x, x) -> 0
1891   // FIXME: Refactor this and xor and other similar operations together.
1892   if (N0 == N1)
1893     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1894   // fold (sub c1, c2) -> c1-c2
1895   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1896   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1897   if (N0C && N1C)
1898     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1899   // fold (sub x, c) -> (add x, -c)
1900   if (N1C) {
1901     SDLoc DL(N);
1902     return DAG.getNode(ISD::ADD, DL, VT, N0,
1903                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1904   }
1905   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1906   if (isAllOnesConstant(N0))
1907     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1908   // fold A-(A-B) -> B
1909   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1910     return N1.getOperand(1);
1911   // fold (A+B)-A -> B
1912   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1913     return N0.getOperand(1);
1914   // fold (A+B)-B -> A
1915   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1916     return N0.getOperand(0);
1917   // fold C2-(A+C1) -> (C2-C1)-A
1918   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1919     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1920   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1921     SDLoc DL(N);
1922     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1923                                    DL, VT);
1924     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1925                        N1.getOperand(0));
1926   }
1927   // fold ((A+(B+or-C))-B) -> A+or-C
1928   if (N0.getOpcode() == ISD::ADD &&
1929       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1930        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1931       N0.getOperand(1).getOperand(0) == N1)
1932     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1933                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1934   // fold ((A+(C+B))-B) -> A+C
1935   if (N0.getOpcode() == ISD::ADD &&
1936       N0.getOperand(1).getOpcode() == ISD::ADD &&
1937       N0.getOperand(1).getOperand(1) == N1)
1938     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1939                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1940   // fold ((A-(B-C))-C) -> A-B
1941   if (N0.getOpcode() == ISD::SUB &&
1942       N0.getOperand(1).getOpcode() == ISD::SUB &&
1943       N0.getOperand(1).getOperand(1) == N1)
1944     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1945                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1946
1947   // If either operand of a sub is undef, the result is undef
1948   if (N0.getOpcode() == ISD::UNDEF)
1949     return N0;
1950   if (N1.getOpcode() == ISD::UNDEF)
1951     return N1;
1952
1953   // If the relocation model supports it, consider symbol offsets.
1954   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1955     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1956       // fold (sub Sym, c) -> Sym-c
1957       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1958         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1959                                     GA->getOffset() -
1960                                       (uint64_t)N1C->getSExtValue());
1961       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1962       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1963         if (GA->getGlobal() == GB->getGlobal())
1964           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1965                                  SDLoc(N), VT);
1966     }
1967
1968   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1969   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1970     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1971     if (TN->getVT() == MVT::i1) {
1972       SDLoc DL(N);
1973       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1974                                  DAG.getConstant(1, DL, VT));
1975       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1976     }
1977   }
1978
1979   return SDValue();
1980 }
1981
1982 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1983   SDValue N0 = N->getOperand(0);
1984   SDValue N1 = N->getOperand(1);
1985   EVT VT = N0.getValueType();
1986
1987   // If the flag result is dead, turn this into an SUB.
1988   if (!N->hasAnyUseOfValue(1))
1989     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1990                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1991                                  MVT::Glue));
1992
1993   // fold (subc x, x) -> 0 + no borrow
1994   if (N0 == N1) {
1995     SDLoc DL(N);
1996     return CombineTo(N, DAG.getConstant(0, DL, VT),
1997                      DAG.getNode(ISD::CARRY_FALSE, DL,
1998                                  MVT::Glue));
1999   }
2000
2001   // fold (subc x, 0) -> x + no borrow
2002   if (isNullConstant(N1))
2003     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2004                                         MVT::Glue));
2005
2006   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2007   if (isAllOnesConstant(N0))
2008     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2009                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2010                                  MVT::Glue));
2011
2012   return SDValue();
2013 }
2014
2015 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2016   SDValue N0 = N->getOperand(0);
2017   SDValue N1 = N->getOperand(1);
2018   SDValue CarryIn = N->getOperand(2);
2019
2020   // fold (sube x, y, false) -> (subc x, y)
2021   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2022     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2023
2024   return SDValue();
2025 }
2026
2027 SDValue DAGCombiner::visitMUL(SDNode *N) {
2028   SDValue N0 = N->getOperand(0);
2029   SDValue N1 = N->getOperand(1);
2030   EVT VT = N0.getValueType();
2031
2032   // fold (mul x, undef) -> 0
2033   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2034     return DAG.getConstant(0, SDLoc(N), VT);
2035
2036   bool N0IsConst = false;
2037   bool N1IsConst = false;
2038   bool N1IsOpaqueConst = false;
2039   bool N0IsOpaqueConst = false;
2040   APInt ConstValue0, ConstValue1;
2041   // fold vector ops
2042   if (VT.isVector()) {
2043     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2044       return FoldedVOp;
2045
2046     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2047     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2048   } else {
2049     N0IsConst = isa<ConstantSDNode>(N0);
2050     if (N0IsConst) {
2051       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2052       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2053     }
2054     N1IsConst = isa<ConstantSDNode>(N1);
2055     if (N1IsConst) {
2056       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2057       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2058     }
2059   }
2060
2061   // fold (mul c1, c2) -> c1*c2
2062   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2063     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2064                                       N0.getNode(), N1.getNode());
2065
2066   // canonicalize constant to RHS (vector doesn't have to splat)
2067   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2068      !isConstantIntBuildVectorOrConstantInt(N1))
2069     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2070   // fold (mul x, 0) -> 0
2071   if (N1IsConst && ConstValue1 == 0)
2072     return N1;
2073   // We require a splat of the entire scalar bit width for non-contiguous
2074   // bit patterns.
2075   bool IsFullSplat =
2076     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2077   // fold (mul x, 1) -> x
2078   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2079     return N0;
2080   // fold (mul x, -1) -> 0-x
2081   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2082     SDLoc DL(N);
2083     return DAG.getNode(ISD::SUB, DL, VT,
2084                        DAG.getConstant(0, DL, VT), N0);
2085   }
2086   // fold (mul x, (1 << c)) -> x << c
2087   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2088       IsFullSplat) {
2089     SDLoc DL(N);
2090     return DAG.getNode(ISD::SHL, DL, VT, N0,
2091                        DAG.getConstant(ConstValue1.logBase2(), DL,
2092                                        getShiftAmountTy(N0.getValueType())));
2093   }
2094   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2095   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2096       IsFullSplat) {
2097     unsigned Log2Val = (-ConstValue1).logBase2();
2098     SDLoc DL(N);
2099     // FIXME: If the input is something that is easily negated (e.g. a
2100     // single-use add), we should put the negate there.
2101     return DAG.getNode(ISD::SUB, DL, VT,
2102                        DAG.getConstant(0, DL, VT),
2103                        DAG.getNode(ISD::SHL, DL, VT, N0,
2104                             DAG.getConstant(Log2Val, DL,
2105                                       getShiftAmountTy(N0.getValueType()))));
2106   }
2107
2108   APInt Val;
2109   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2110   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2111       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2112                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2113     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2114                              N1, N0.getOperand(1));
2115     AddToWorklist(C3.getNode());
2116     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2117                        N0.getOperand(0), C3);
2118   }
2119
2120   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2121   // use.
2122   {
2123     SDValue Sh(nullptr,0), Y(nullptr,0);
2124     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2125     if (N0.getOpcode() == ISD::SHL &&
2126         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2127                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2128         N0.getNode()->hasOneUse()) {
2129       Sh = N0; Y = N1;
2130     } else if (N1.getOpcode() == ISD::SHL &&
2131                isa<ConstantSDNode>(N1.getOperand(1)) &&
2132                N1.getNode()->hasOneUse()) {
2133       Sh = N1; Y = N0;
2134     }
2135
2136     if (Sh.getNode()) {
2137       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2138                                 Sh.getOperand(0), Y);
2139       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2140                          Mul, Sh.getOperand(1));
2141     }
2142   }
2143
2144   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2145   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2146       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2147                      isa<ConstantSDNode>(N0.getOperand(1))))
2148     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2149                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2150                                    N0.getOperand(0), N1),
2151                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2152                                    N0.getOperand(1), N1));
2153
2154   // reassociate mul
2155   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2156     return RMUL;
2157
2158   return SDValue();
2159 }
2160
2161 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2162   SDValue N0 = N->getOperand(0);
2163   SDValue N1 = N->getOperand(1);
2164   EVT VT = N->getValueType(0);
2165
2166   // fold vector ops
2167   if (VT.isVector())
2168     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2169       return FoldedVOp;
2170
2171   // fold (sdiv c1, c2) -> c1/c2
2172   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2173   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2174   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2175     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2176   // fold (sdiv X, 1) -> X
2177   if (N1C && N1C->isOne())
2178     return N0;
2179   // fold (sdiv X, -1) -> 0-X
2180   if (N1C && N1C->isAllOnesValue()) {
2181     SDLoc DL(N);
2182     return DAG.getNode(ISD::SUB, DL, VT,
2183                        DAG.getConstant(0, DL, VT), N0);
2184   }
2185   // If we know the sign bits of both operands are zero, strength reduce to a
2186   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2187   if (!VT.isVector()) {
2188     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2189       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2190                          N0, N1);
2191   }
2192
2193   // fold (sdiv X, pow2) -> simple ops after legalize
2194   // FIXME: We check for the exact bit here because the generic lowering gives
2195   // better results in that case. The target-specific lowering should learn how
2196   // to handle exact sdivs efficiently.
2197   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2198       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2199       (N1C->getAPIntValue().isPowerOf2() ||
2200        (-N1C->getAPIntValue()).isPowerOf2())) {
2201     // Target-specific implementation of sdiv x, pow2.
2202     if (SDValue Res = BuildSDIVPow2(N))
2203       return Res;
2204
2205     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2206     SDLoc DL(N);
2207
2208     // Splat the sign bit into the register
2209     SDValue SGN =
2210         DAG.getNode(ISD::SRA, DL, VT, N0,
2211                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2212                                     getShiftAmountTy(N0.getValueType())));
2213     AddToWorklist(SGN.getNode());
2214
2215     // Add (N0 < 0) ? abs2 - 1 : 0;
2216     SDValue SRL =
2217         DAG.getNode(ISD::SRL, DL, VT, SGN,
2218                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2219                                     getShiftAmountTy(SGN.getValueType())));
2220     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2221     AddToWorklist(SRL.getNode());
2222     AddToWorklist(ADD.getNode());    // Divide by pow2
2223     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2224                   DAG.getConstant(lg2, DL,
2225                                   getShiftAmountTy(ADD.getValueType())));
2226
2227     // If we're dividing by a positive value, we're done.  Otherwise, we must
2228     // negate the result.
2229     if (N1C->getAPIntValue().isNonNegative())
2230       return SRA;
2231
2232     AddToWorklist(SRA.getNode());
2233     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2234   }
2235
2236   // If integer divide is expensive and we satisfy the requirements, emit an
2237   // alternate sequence.  Targets may check function attributes for size/speed
2238   // trade-offs.
2239   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2240   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2241     if (SDValue Op = BuildSDIV(N))
2242       return Op;
2243
2244   // undef / X -> 0
2245   if (N0.getOpcode() == ISD::UNDEF)
2246     return DAG.getConstant(0, SDLoc(N), VT);
2247   // X / undef -> undef
2248   if (N1.getOpcode() == ISD::UNDEF)
2249     return N1;
2250
2251   return SDValue();
2252 }
2253
2254 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2255   SDValue N0 = N->getOperand(0);
2256   SDValue N1 = N->getOperand(1);
2257   EVT VT = N->getValueType(0);
2258
2259   // fold vector ops
2260   if (VT.isVector())
2261     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2262       return FoldedVOp;
2263
2264   // fold (udiv c1, c2) -> c1/c2
2265   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2266   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2267   if (N0C && N1C)
2268     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2269                                                     N0C, N1C))
2270       return Folded;
2271   // fold (udiv x, (1 << c)) -> x >>u c
2272   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2273     SDLoc DL(N);
2274     return DAG.getNode(ISD::SRL, DL, VT, N0,
2275                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2276                                        getShiftAmountTy(N0.getValueType())));
2277   }
2278   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2279   if (N1.getOpcode() == ISD::SHL) {
2280     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2281       if (SHC->getAPIntValue().isPowerOf2()) {
2282         EVT ADDVT = N1.getOperand(1).getValueType();
2283         SDLoc DL(N);
2284         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2285                                   N1.getOperand(1),
2286                                   DAG.getConstant(SHC->getAPIntValue()
2287                                                                   .logBase2(),
2288                                                   DL, ADDVT));
2289         AddToWorklist(Add.getNode());
2290         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2291       }
2292     }
2293   }
2294
2295   // fold (udiv x, c) -> alternate
2296   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2297   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2298     if (SDValue Op = BuildUDIV(N))
2299       return Op;
2300
2301   // undef / X -> 0
2302   if (N0.getOpcode() == ISD::UNDEF)
2303     return DAG.getConstant(0, SDLoc(N), VT);
2304   // X / undef -> undef
2305   if (N1.getOpcode() == ISD::UNDEF)
2306     return N1;
2307
2308   return SDValue();
2309 }
2310
2311 SDValue DAGCombiner::visitSREM(SDNode *N) {
2312   SDValue N0 = N->getOperand(0);
2313   SDValue N1 = N->getOperand(1);
2314   EVT VT = N->getValueType(0);
2315
2316   // fold (srem c1, c2) -> c1%c2
2317   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2318   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2319   if (N0C && N1C)
2320     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2321                                                     N0C, N1C))
2322       return Folded;
2323   // If we know the sign bits of both operands are zero, strength reduce to a
2324   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2325   if (!VT.isVector()) {
2326     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2327       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2328   }
2329
2330   // If X/C can be simplified by the division-by-constant logic, lower
2331   // X%C to the equivalent of X-X/C*C.
2332   if (N1C && !N1C->isNullValue()) {
2333     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2334     AddToWorklist(Div.getNode());
2335     SDValue OptimizedDiv = combine(Div.getNode());
2336     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2337       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2338                                 OptimizedDiv, N1);
2339       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2340       AddToWorklist(Mul.getNode());
2341       return Sub;
2342     }
2343   }
2344
2345   // undef % X -> 0
2346   if (N0.getOpcode() == ISD::UNDEF)
2347     return DAG.getConstant(0, SDLoc(N), VT);
2348   // X % undef -> undef
2349   if (N1.getOpcode() == ISD::UNDEF)
2350     return N1;
2351
2352   return SDValue();
2353 }
2354
2355 SDValue DAGCombiner::visitUREM(SDNode *N) {
2356   SDValue N0 = N->getOperand(0);
2357   SDValue N1 = N->getOperand(1);
2358   EVT VT = N->getValueType(0);
2359
2360   // fold (urem c1, c2) -> c1%c2
2361   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2362   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2363   if (N0C && N1C)
2364     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2365                                                     N0C, N1C))
2366       return Folded;
2367   // fold (urem x, pow2) -> (and x, pow2-1)
2368   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2369       N1C->getAPIntValue().isPowerOf2()) {
2370     SDLoc DL(N);
2371     return DAG.getNode(ISD::AND, DL, VT, N0,
2372                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2373   }
2374   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2375   if (N1.getOpcode() == ISD::SHL) {
2376     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2377       if (SHC->getAPIntValue().isPowerOf2()) {
2378         SDLoc DL(N);
2379         SDValue Add =
2380           DAG.getNode(ISD::ADD, DL, VT, N1,
2381                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2382                                  VT));
2383         AddToWorklist(Add.getNode());
2384         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2385       }
2386     }
2387   }
2388
2389   // If X/C can be simplified by the division-by-constant logic, lower
2390   // X%C to the equivalent of X-X/C*C.
2391   if (N1C && !N1C->isNullValue()) {
2392     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2393     AddToWorklist(Div.getNode());
2394     SDValue OptimizedDiv = combine(Div.getNode());
2395     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2396       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2397                                 OptimizedDiv, N1);
2398       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2399       AddToWorklist(Mul.getNode());
2400       return Sub;
2401     }
2402   }
2403
2404   // undef % X -> 0
2405   if (N0.getOpcode() == ISD::UNDEF)
2406     return DAG.getConstant(0, SDLoc(N), VT);
2407   // X % undef -> undef
2408   if (N1.getOpcode() == ISD::UNDEF)
2409     return N1;
2410
2411   return SDValue();
2412 }
2413
2414 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2415   SDValue N0 = N->getOperand(0);
2416   SDValue N1 = N->getOperand(1);
2417   EVT VT = N->getValueType(0);
2418   SDLoc DL(N);
2419
2420   // fold (mulhs x, 0) -> 0
2421   if (isNullConstant(N1))
2422     return N1;
2423   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2424   if (isOneConstant(N1)) {
2425     SDLoc DL(N);
2426     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2427                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2428                                        DL,
2429                                        getShiftAmountTy(N0.getValueType())));
2430   }
2431   // fold (mulhs x, undef) -> 0
2432   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2433     return DAG.getConstant(0, SDLoc(N), VT);
2434
2435   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2436   // plus a shift.
2437   if (VT.isSimple() && !VT.isVector()) {
2438     MVT Simple = VT.getSimpleVT();
2439     unsigned SimpleSize = Simple.getSizeInBits();
2440     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2441     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2442       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2443       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2444       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2445       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2446             DAG.getConstant(SimpleSize, DL,
2447                             getShiftAmountTy(N1.getValueType())));
2448       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2449     }
2450   }
2451
2452   return SDValue();
2453 }
2454
2455 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2456   SDValue N0 = N->getOperand(0);
2457   SDValue N1 = N->getOperand(1);
2458   EVT VT = N->getValueType(0);
2459   SDLoc DL(N);
2460
2461   // fold (mulhu x, 0) -> 0
2462   if (isNullConstant(N1))
2463     return N1;
2464   // fold (mulhu x, 1) -> 0
2465   if (isOneConstant(N1))
2466     return DAG.getConstant(0, DL, N0.getValueType());
2467   // fold (mulhu x, undef) -> 0
2468   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2469     return DAG.getConstant(0, DL, VT);
2470
2471   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2472   // plus a shift.
2473   if (VT.isSimple() && !VT.isVector()) {
2474     MVT Simple = VT.getSimpleVT();
2475     unsigned SimpleSize = Simple.getSizeInBits();
2476     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2477     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2478       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2479       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2480       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2481       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2482             DAG.getConstant(SimpleSize, DL,
2483                             getShiftAmountTy(N1.getValueType())));
2484       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2485     }
2486   }
2487
2488   return SDValue();
2489 }
2490
2491 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2492 /// give the opcodes for the two computations that are being performed. Return
2493 /// true if a simplification was made.
2494 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2495                                                 unsigned HiOp) {
2496   // If the high half is not needed, just compute the low half.
2497   bool HiExists = N->hasAnyUseOfValue(1);
2498   if (!HiExists &&
2499       (!LegalOperations ||
2500        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2501     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2502     return CombineTo(N, Res, Res);
2503   }
2504
2505   // If the low half is not needed, just compute the high half.
2506   bool LoExists = N->hasAnyUseOfValue(0);
2507   if (!LoExists &&
2508       (!LegalOperations ||
2509        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2510     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2511     return CombineTo(N, Res, Res);
2512   }
2513
2514   // If both halves are used, return as it is.
2515   if (LoExists && HiExists)
2516     return SDValue();
2517
2518   // If the two computed results can be simplified separately, separate them.
2519   if (LoExists) {
2520     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2521     AddToWorklist(Lo.getNode());
2522     SDValue LoOpt = combine(Lo.getNode());
2523     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2524         (!LegalOperations ||
2525          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2526       return CombineTo(N, LoOpt, LoOpt);
2527   }
2528
2529   if (HiExists) {
2530     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2531     AddToWorklist(Hi.getNode());
2532     SDValue HiOpt = combine(Hi.getNode());
2533     if (HiOpt.getNode() && HiOpt != Hi &&
2534         (!LegalOperations ||
2535          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2536       return CombineTo(N, HiOpt, HiOpt);
2537   }
2538
2539   return SDValue();
2540 }
2541
2542 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2543   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2544     return Res;
2545
2546   EVT VT = N->getValueType(0);
2547   SDLoc DL(N);
2548
2549   // If the type is twice as wide is legal, transform the mulhu to a wider
2550   // multiply plus a shift.
2551   if (VT.isSimple() && !VT.isVector()) {
2552     MVT Simple = VT.getSimpleVT();
2553     unsigned SimpleSize = Simple.getSizeInBits();
2554     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2555     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2556       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2557       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2558       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2559       // Compute the high part as N1.
2560       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2561             DAG.getConstant(SimpleSize, DL,
2562                             getShiftAmountTy(Lo.getValueType())));
2563       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2564       // Compute the low part as N0.
2565       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2566       return CombineTo(N, Lo, Hi);
2567     }
2568   }
2569
2570   return SDValue();
2571 }
2572
2573 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2574   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2575     return Res;
2576
2577   EVT VT = N->getValueType(0);
2578   SDLoc DL(N);
2579
2580   // If the type is twice as wide is legal, transform the mulhu to a wider
2581   // multiply plus a shift.
2582   if (VT.isSimple() && !VT.isVector()) {
2583     MVT Simple = VT.getSimpleVT();
2584     unsigned SimpleSize = Simple.getSizeInBits();
2585     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2586     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2587       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2588       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2589       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2590       // Compute the high part as N1.
2591       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2592             DAG.getConstant(SimpleSize, DL,
2593                             getShiftAmountTy(Lo.getValueType())));
2594       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2595       // Compute the low part as N0.
2596       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2597       return CombineTo(N, Lo, Hi);
2598     }
2599   }
2600
2601   return SDValue();
2602 }
2603
2604 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2605   // (smulo x, 2) -> (saddo x, x)
2606   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2607     if (C2->getAPIntValue() == 2)
2608       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2609                          N->getOperand(0), N->getOperand(0));
2610
2611   return SDValue();
2612 }
2613
2614 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2615   // (umulo x, 2) -> (uaddo x, x)
2616   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2617     if (C2->getAPIntValue() == 2)
2618       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2619                          N->getOperand(0), N->getOperand(0));
2620
2621   return SDValue();
2622 }
2623
2624 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2625   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2626     return Res;
2627
2628   return SDValue();
2629 }
2630
2631 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2632   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2633     return Res;
2634
2635   return SDValue();
2636 }
2637
2638 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2639   SDValue N0 = N->getOperand(0);
2640   SDValue N1 = N->getOperand(1);
2641   EVT VT = N0.getValueType();
2642
2643   // fold vector ops
2644   if (VT.isVector())
2645     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2646       return FoldedVOp;
2647
2648   // fold (add c1, c2) -> c1+c2
2649   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2650   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2651   if (N0C && N1C)
2652     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2653
2654   // canonicalize constant to RHS
2655   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2656      !isConstantIntBuildVectorOrConstantInt(N1))
2657     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2658
2659   return SDValue();
2660 }
2661
2662 /// If this is a binary operator with two operands of the same opcode, try to
2663 /// simplify it.
2664 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2665   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2666   EVT VT = N0.getValueType();
2667   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2668
2669   // Bail early if none of these transforms apply.
2670   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2671
2672   // For each of OP in AND/OR/XOR:
2673   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2674   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2675   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2676   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2677   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2678   //
2679   // do not sink logical op inside of a vector extend, since it may combine
2680   // into a vsetcc.
2681   EVT Op0VT = N0.getOperand(0).getValueType();
2682   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2683        N0.getOpcode() == ISD::SIGN_EXTEND ||
2684        N0.getOpcode() == ISD::BSWAP ||
2685        // Avoid infinite looping with PromoteIntBinOp.
2686        (N0.getOpcode() == ISD::ANY_EXTEND &&
2687         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2688        (N0.getOpcode() == ISD::TRUNCATE &&
2689         (!TLI.isZExtFree(VT, Op0VT) ||
2690          !TLI.isTruncateFree(Op0VT, VT)) &&
2691         TLI.isTypeLegal(Op0VT))) &&
2692       !VT.isVector() &&
2693       Op0VT == N1.getOperand(0).getValueType() &&
2694       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2695     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2696                                  N0.getOperand(0).getValueType(),
2697                                  N0.getOperand(0), N1.getOperand(0));
2698     AddToWorklist(ORNode.getNode());
2699     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2700   }
2701
2702   // For each of OP in SHL/SRL/SRA/AND...
2703   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2704   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2705   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2706   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2707        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2708       N0.getOperand(1) == N1.getOperand(1)) {
2709     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2710                                  N0.getOperand(0).getValueType(),
2711                                  N0.getOperand(0), N1.getOperand(0));
2712     AddToWorklist(ORNode.getNode());
2713     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2714                        ORNode, N0.getOperand(1));
2715   }
2716
2717   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2718   // Only perform this optimization after type legalization and before
2719   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2720   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2721   // we don't want to undo this promotion.
2722   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2723   // on scalars.
2724   if ((N0.getOpcode() == ISD::BITCAST ||
2725        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2726       Level == AfterLegalizeTypes) {
2727     SDValue In0 = N0.getOperand(0);
2728     SDValue In1 = N1.getOperand(0);
2729     EVT In0Ty = In0.getValueType();
2730     EVT In1Ty = In1.getValueType();
2731     SDLoc DL(N);
2732     // If both incoming values are integers, and the original types are the
2733     // same.
2734     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2735       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2736       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2737       AddToWorklist(Op.getNode());
2738       return BC;
2739     }
2740   }
2741
2742   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2743   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2744   // If both shuffles use the same mask, and both shuffle within a single
2745   // vector, then it is worthwhile to move the swizzle after the operation.
2746   // The type-legalizer generates this pattern when loading illegal
2747   // vector types from memory. In many cases this allows additional shuffle
2748   // optimizations.
2749   // There are other cases where moving the shuffle after the xor/and/or
2750   // is profitable even if shuffles don't perform a swizzle.
2751   // If both shuffles use the same mask, and both shuffles have the same first
2752   // or second operand, then it might still be profitable to move the shuffle
2753   // after the xor/and/or operation.
2754   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2755     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2756     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2757
2758     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2759            "Inputs to shuffles are not the same type");
2760
2761     // Check that both shuffles use the same mask. The masks are known to be of
2762     // the same length because the result vector type is the same.
2763     // Check also that shuffles have only one use to avoid introducing extra
2764     // instructions.
2765     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2766         SVN0->getMask().equals(SVN1->getMask())) {
2767       SDValue ShOp = N0->getOperand(1);
2768
2769       // Don't try to fold this node if it requires introducing a
2770       // build vector of all zeros that might be illegal at this stage.
2771       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2772         if (!LegalTypes)
2773           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2774         else
2775           ShOp = SDValue();
2776       }
2777
2778       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2779       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2780       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2781       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2782         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2783                                       N0->getOperand(0), N1->getOperand(0));
2784         AddToWorklist(NewNode.getNode());
2785         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2786                                     &SVN0->getMask()[0]);
2787       }
2788
2789       // Don't try to fold this node if it requires introducing a
2790       // build vector of all zeros that might be illegal at this stage.
2791       ShOp = N0->getOperand(0);
2792       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2793         if (!LegalTypes)
2794           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2795         else
2796           ShOp = SDValue();
2797       }
2798
2799       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2800       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2801       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2802       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2803         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2804                                       N0->getOperand(1), N1->getOperand(1));
2805         AddToWorklist(NewNode.getNode());
2806         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2807                                     &SVN0->getMask()[0]);
2808       }
2809     }
2810   }
2811
2812   return SDValue();
2813 }
2814
2815 /// This contains all DAGCombine rules which reduce two values combined by
2816 /// an And operation to a single value. This makes them reusable in the context
2817 /// of visitSELECT(). Rules involving constants are not included as
2818 /// visitSELECT() already handles those cases.
2819 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2820                                   SDNode *LocReference) {
2821   EVT VT = N1.getValueType();
2822
2823   // fold (and x, undef) -> 0
2824   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2825     return DAG.getConstant(0, SDLoc(LocReference), VT);
2826   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2827   SDValue LL, LR, RL, RR, CC0, CC1;
2828   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2829     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2830     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2831
2832     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2833         LL.getValueType().isInteger()) {
2834       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2835       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2836         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2837                                      LR.getValueType(), LL, RL);
2838         AddToWorklist(ORNode.getNode());
2839         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2840       }
2841       if (isAllOnesConstant(LR)) {
2842         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2843         if (Op1 == ISD::SETEQ) {
2844           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2845                                         LR.getValueType(), LL, RL);
2846           AddToWorklist(ANDNode.getNode());
2847           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2848         }
2849         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2850         if (Op1 == ISD::SETGT) {
2851           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2852                                        LR.getValueType(), LL, RL);
2853           AddToWorklist(ORNode.getNode());
2854           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2855         }
2856       }
2857     }
2858     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2859     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2860         Op0 == Op1 && LL.getValueType().isInteger() &&
2861       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2862                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2863       SDLoc DL(N0);
2864       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2865                                     LL, DAG.getConstant(1, DL,
2866                                                         LL.getValueType()));
2867       AddToWorklist(ADDNode.getNode());
2868       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2869                           DAG.getConstant(2, DL, LL.getValueType()),
2870                           ISD::SETUGE);
2871     }
2872     // canonicalize equivalent to ll == rl
2873     if (LL == RR && LR == RL) {
2874       Op1 = ISD::getSetCCSwappedOperands(Op1);
2875       std::swap(RL, RR);
2876     }
2877     if (LL == RL && LR == RR) {
2878       bool isInteger = LL.getValueType().isInteger();
2879       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2880       if (Result != ISD::SETCC_INVALID &&
2881           (!LegalOperations ||
2882            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2883             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2884         EVT CCVT = getSetCCResultType(LL.getValueType());
2885         if (N0.getValueType() == CCVT ||
2886             (!LegalOperations && N0.getValueType() == MVT::i1))
2887           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2888                               LL, LR, Result);
2889       }
2890     }
2891   }
2892
2893   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2894       VT.getSizeInBits() <= 64) {
2895     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2896       APInt ADDC = ADDI->getAPIntValue();
2897       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2898         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2899         // immediate for an add, but it is legal if its top c2 bits are set,
2900         // transform the ADD so the immediate doesn't need to be materialized
2901         // in a register.
2902         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2903           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2904                                              SRLI->getZExtValue());
2905           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2906             ADDC |= Mask;
2907             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2908               SDLoc DL(N0);
2909               SDValue NewAdd =
2910                 DAG.getNode(ISD::ADD, DL, VT,
2911                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2912               CombineTo(N0.getNode(), NewAdd);
2913               // Return N so it doesn't get rechecked!
2914               return SDValue(LocReference, 0);
2915             }
2916           }
2917         }
2918       }
2919     }
2920   }
2921
2922   return SDValue();
2923 }
2924
2925 SDValue DAGCombiner::visitAND(SDNode *N) {
2926   SDValue N0 = N->getOperand(0);
2927   SDValue N1 = N->getOperand(1);
2928   EVT VT = N1.getValueType();
2929
2930   // fold vector ops
2931   if (VT.isVector()) {
2932     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2933       return FoldedVOp;
2934
2935     // fold (and x, 0) -> 0, vector edition
2936     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2937       // do not return N0, because undef node may exist in N0
2938       return DAG.getConstant(
2939           APInt::getNullValue(
2940               N0.getValueType().getScalarType().getSizeInBits()),
2941           SDLoc(N), N0.getValueType());
2942     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2943       // do not return N1, because undef node may exist in N1
2944       return DAG.getConstant(
2945           APInt::getNullValue(
2946               N1.getValueType().getScalarType().getSizeInBits()),
2947           SDLoc(N), N1.getValueType());
2948
2949     // fold (and x, -1) -> x, vector edition
2950     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2951       return N1;
2952     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2953       return N0;
2954   }
2955
2956   // fold (and c1, c2) -> c1&c2
2957   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2958   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2959   if (N0C && N1C && !N1C->isOpaque())
2960     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2961   // canonicalize constant to RHS
2962   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2963      !isConstantIntBuildVectorOrConstantInt(N1))
2964     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2965   // fold (and x, -1) -> x
2966   if (isAllOnesConstant(N1))
2967     return N0;
2968   // if (and x, c) is known to be zero, return 0
2969   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2970   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2971                                    APInt::getAllOnesValue(BitWidth)))
2972     return DAG.getConstant(0, SDLoc(N), VT);
2973   // reassociate and
2974   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2975     return RAND;
2976   // fold (and (or x, C), D) -> D if (C & D) == D
2977   if (N1C && N0.getOpcode() == ISD::OR)
2978     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2979       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2980         return N1;
2981   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2982   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2983     SDValue N0Op0 = N0.getOperand(0);
2984     APInt Mask = ~N1C->getAPIntValue();
2985     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2986     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2987       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2988                                  N0.getValueType(), N0Op0);
2989
2990       // Replace uses of the AND with uses of the Zero extend node.
2991       CombineTo(N, Zext);
2992
2993       // We actually want to replace all uses of the any_extend with the
2994       // zero_extend, to avoid duplicating things.  This will later cause this
2995       // AND to be folded.
2996       CombineTo(N0.getNode(), Zext);
2997       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2998     }
2999   }
3000   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3001   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3002   // already be zero by virtue of the width of the base type of the load.
3003   //
3004   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3005   // more cases.
3006   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3007        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3008       N0.getOpcode() == ISD::LOAD) {
3009     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3010                                          N0 : N0.getOperand(0) );
3011
3012     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3013     // This can be a pure constant or a vector splat, in which case we treat the
3014     // vector as a scalar and use the splat value.
3015     APInt Constant = APInt::getNullValue(1);
3016     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3017       Constant = C->getAPIntValue();
3018     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3019       APInt SplatValue, SplatUndef;
3020       unsigned SplatBitSize;
3021       bool HasAnyUndefs;
3022       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3023                                              SplatBitSize, HasAnyUndefs);
3024       if (IsSplat) {
3025         // Undef bits can contribute to a possible optimisation if set, so
3026         // set them.
3027         SplatValue |= SplatUndef;
3028
3029         // The splat value may be something like "0x00FFFFFF", which means 0 for
3030         // the first vector value and FF for the rest, repeating. We need a mask
3031         // that will apply equally to all members of the vector, so AND all the
3032         // lanes of the constant together.
3033         EVT VT = Vector->getValueType(0);
3034         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3035
3036         // If the splat value has been compressed to a bitlength lower
3037         // than the size of the vector lane, we need to re-expand it to
3038         // the lane size.
3039         if (BitWidth > SplatBitSize)
3040           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3041                SplatBitSize < BitWidth;
3042                SplatBitSize = SplatBitSize * 2)
3043             SplatValue |= SplatValue.shl(SplatBitSize);
3044
3045         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3046         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3047         if (SplatBitSize % BitWidth == 0) {
3048           Constant = APInt::getAllOnesValue(BitWidth);
3049           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3050             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3051         }
3052       }
3053     }
3054
3055     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3056     // actually legal and isn't going to get expanded, else this is a false
3057     // optimisation.
3058     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3059                                                     Load->getValueType(0),
3060                                                     Load->getMemoryVT());
3061
3062     // Resize the constant to the same size as the original memory access before
3063     // extension. If it is still the AllOnesValue then this AND is completely
3064     // unneeded.
3065     Constant =
3066       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3067
3068     bool B;
3069     switch (Load->getExtensionType()) {
3070     default: B = false; break;
3071     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3072     case ISD::ZEXTLOAD:
3073     case ISD::NON_EXTLOAD: B = true; break;
3074     }
3075
3076     if (B && Constant.isAllOnesValue()) {
3077       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3078       // preserve semantics once we get rid of the AND.
3079       SDValue NewLoad(Load, 0);
3080       if (Load->getExtensionType() == ISD::EXTLOAD) {
3081         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3082                               Load->getValueType(0), SDLoc(Load),
3083                               Load->getChain(), Load->getBasePtr(),
3084                               Load->getOffset(), Load->getMemoryVT(),
3085                               Load->getMemOperand());
3086         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3087         if (Load->getNumValues() == 3) {
3088           // PRE/POST_INC loads have 3 values.
3089           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3090                            NewLoad.getValue(2) };
3091           CombineTo(Load, To, 3, true);
3092         } else {
3093           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3094         }
3095       }
3096
3097       // Fold the AND away, taking care not to fold to the old load node if we
3098       // replaced it.
3099       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3100
3101       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3102     }
3103   }
3104
3105   // fold (and (load x), 255) -> (zextload x, i8)
3106   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3107   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3108   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3109               (N0.getOpcode() == ISD::ANY_EXTEND &&
3110                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3111     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3112     LoadSDNode *LN0 = HasAnyExt
3113       ? cast<LoadSDNode>(N0.getOperand(0))
3114       : cast<LoadSDNode>(N0);
3115     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3116         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3117       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3118       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3119         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3120         EVT LoadedVT = LN0->getMemoryVT();
3121         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3122
3123         if (ExtVT == LoadedVT &&
3124             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3125                                                     ExtVT))) {
3126
3127           SDValue NewLoad =
3128             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3129                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3130                            LN0->getMemOperand());
3131           AddToWorklist(N);
3132           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3133           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3134         }
3135
3136         // Do not change the width of a volatile load.
3137         // Do not generate loads of non-round integer types since these can
3138         // be expensive (and would be wrong if the type is not byte sized).
3139         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3140             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3141                                                     ExtVT))) {
3142           EVT PtrType = LN0->getOperand(1).getValueType();
3143
3144           unsigned Alignment = LN0->getAlignment();
3145           SDValue NewPtr = LN0->getBasePtr();
3146
3147           // For big endian targets, we need to add an offset to the pointer
3148           // to load the correct bytes.  For little endian systems, we merely
3149           // need to read fewer bytes from the same pointer.
3150           if (DAG.getDataLayout().isBigEndian()) {
3151             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3152             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3153             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3154             SDLoc DL(LN0);
3155             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3156                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3157             Alignment = MinAlign(Alignment, PtrOff);
3158           }
3159
3160           AddToWorklist(NewPtr.getNode());
3161
3162           SDValue Load =
3163             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3164                            LN0->getChain(), NewPtr,
3165                            LN0->getPointerInfo(),
3166                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3167                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3168           AddToWorklist(N);
3169           CombineTo(LN0, Load, Load.getValue(1));
3170           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3171         }
3172       }
3173     }
3174   }
3175
3176   if (SDValue Combined = visitANDLike(N0, N1, N))
3177     return Combined;
3178
3179   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3180   if (N0.getOpcode() == N1.getOpcode())
3181     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3182       return Tmp;
3183
3184   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3185   // fold (and (sra)) -> (and (srl)) when possible.
3186   if (!VT.isVector() &&
3187       SimplifyDemandedBits(SDValue(N, 0)))
3188     return SDValue(N, 0);
3189
3190   // fold (zext_inreg (extload x)) -> (zextload x)
3191   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3192     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3193     EVT MemVT = LN0->getMemoryVT();
3194     // If we zero all the possible extended bits, then we can turn this into
3195     // a zextload if we are running before legalize or the operation is legal.
3196     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3197     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3198                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3199         ((!LegalOperations && !LN0->isVolatile()) ||
3200          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3201       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3202                                        LN0->getChain(), LN0->getBasePtr(),
3203                                        MemVT, LN0->getMemOperand());
3204       AddToWorklist(N);
3205       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3206       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3207     }
3208   }
3209   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3210   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3211       N0.hasOneUse()) {
3212     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3213     EVT MemVT = LN0->getMemoryVT();
3214     // If we zero all the possible extended bits, then we can turn this into
3215     // a zextload if we are running before legalize or the operation is legal.
3216     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3217     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3218                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3219         ((!LegalOperations && !LN0->isVolatile()) ||
3220          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3221       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3222                                        LN0->getChain(), LN0->getBasePtr(),
3223                                        MemVT, LN0->getMemOperand());
3224       AddToWorklist(N);
3225       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3226       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3227     }
3228   }
3229   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3230   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3231     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3232                                        N0.getOperand(1), false);
3233     if (BSwap.getNode())
3234       return BSwap;
3235   }
3236
3237   return SDValue();
3238 }
3239
3240 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3241 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3242                                         bool DemandHighBits) {
3243   if (!LegalOperations)
3244     return SDValue();
3245
3246   EVT VT = N->getValueType(0);
3247   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3248     return SDValue();
3249   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3250     return SDValue();
3251
3252   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3253   bool LookPassAnd0 = false;
3254   bool LookPassAnd1 = false;
3255   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3256       std::swap(N0, N1);
3257   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3258       std::swap(N0, N1);
3259   if (N0.getOpcode() == ISD::AND) {
3260     if (!N0.getNode()->hasOneUse())
3261       return SDValue();
3262     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3263     if (!N01C || N01C->getZExtValue() != 0xFF00)
3264       return SDValue();
3265     N0 = N0.getOperand(0);
3266     LookPassAnd0 = true;
3267   }
3268
3269   if (N1.getOpcode() == ISD::AND) {
3270     if (!N1.getNode()->hasOneUse())
3271       return SDValue();
3272     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3273     if (!N11C || N11C->getZExtValue() != 0xFF)
3274       return SDValue();
3275     N1 = N1.getOperand(0);
3276     LookPassAnd1 = true;
3277   }
3278
3279   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3280     std::swap(N0, N1);
3281   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3282     return SDValue();
3283   if (!N0.getNode()->hasOneUse() ||
3284       !N1.getNode()->hasOneUse())
3285     return SDValue();
3286
3287   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3288   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3289   if (!N01C || !N11C)
3290     return SDValue();
3291   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3292     return SDValue();
3293
3294   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3295   SDValue N00 = N0->getOperand(0);
3296   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3297     if (!N00.getNode()->hasOneUse())
3298       return SDValue();
3299     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3300     if (!N001C || N001C->getZExtValue() != 0xFF)
3301       return SDValue();
3302     N00 = N00.getOperand(0);
3303     LookPassAnd0 = true;
3304   }
3305
3306   SDValue N10 = N1->getOperand(0);
3307   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3308     if (!N10.getNode()->hasOneUse())
3309       return SDValue();
3310     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3311     if (!N101C || N101C->getZExtValue() != 0xFF00)
3312       return SDValue();
3313     N10 = N10.getOperand(0);
3314     LookPassAnd1 = true;
3315   }
3316
3317   if (N00 != N10)
3318     return SDValue();
3319
3320   // Make sure everything beyond the low halfword gets set to zero since the SRL
3321   // 16 will clear the top bits.
3322   unsigned OpSizeInBits = VT.getSizeInBits();
3323   if (DemandHighBits && OpSizeInBits > 16) {
3324     // If the left-shift isn't masked out then the only way this is a bswap is
3325     // if all bits beyond the low 8 are 0. In that case the entire pattern
3326     // reduces to a left shift anyway: leave it for other parts of the combiner.
3327     if (!LookPassAnd0)
3328       return SDValue();
3329
3330     // However, if the right shift isn't masked out then it might be because
3331     // it's not needed. See if we can spot that too.
3332     if (!LookPassAnd1 &&
3333         !DAG.MaskedValueIsZero(
3334             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3335       return SDValue();
3336   }
3337
3338   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3339   if (OpSizeInBits > 16) {
3340     SDLoc DL(N);
3341     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3342                       DAG.getConstant(OpSizeInBits - 16, DL,
3343                                       getShiftAmountTy(VT)));
3344   }
3345   return Res;
3346 }
3347
3348 /// Return true if the specified node is an element that makes up a 32-bit
3349 /// packed halfword byteswap.
3350 /// ((x & 0x000000ff) << 8) |
3351 /// ((x & 0x0000ff00) >> 8) |
3352 /// ((x & 0x00ff0000) << 8) |
3353 /// ((x & 0xff000000) >> 8)
3354 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3355   if (!N.getNode()->hasOneUse())
3356     return false;
3357
3358   unsigned Opc = N.getOpcode();
3359   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3360     return false;
3361
3362   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3363   if (!N1C)
3364     return false;
3365
3366   unsigned Num;
3367   switch (N1C->getZExtValue()) {
3368   default:
3369     return false;
3370   case 0xFF:       Num = 0; break;
3371   case 0xFF00:     Num = 1; break;
3372   case 0xFF0000:   Num = 2; break;
3373   case 0xFF000000: Num = 3; break;
3374   }
3375
3376   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3377   SDValue N0 = N.getOperand(0);
3378   if (Opc == ISD::AND) {
3379     if (Num == 0 || Num == 2) {
3380       // (x >> 8) & 0xff
3381       // (x >> 8) & 0xff0000
3382       if (N0.getOpcode() != ISD::SRL)
3383         return false;
3384       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3385       if (!C || C->getZExtValue() != 8)
3386         return false;
3387     } else {
3388       // (x << 8) & 0xff00
3389       // (x << 8) & 0xff000000
3390       if (N0.getOpcode() != ISD::SHL)
3391         return false;
3392       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3393       if (!C || C->getZExtValue() != 8)
3394         return false;
3395     }
3396   } else if (Opc == ISD::SHL) {
3397     // (x & 0xff) << 8
3398     // (x & 0xff0000) << 8
3399     if (Num != 0 && Num != 2)
3400       return false;
3401     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3402     if (!C || C->getZExtValue() != 8)
3403       return false;
3404   } else { // Opc == ISD::SRL
3405     // (x & 0xff00) >> 8
3406     // (x & 0xff000000) >> 8
3407     if (Num != 1 && Num != 3)
3408       return false;
3409     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3410     if (!C || C->getZExtValue() != 8)
3411       return false;
3412   }
3413
3414   if (Parts[Num])
3415     return false;
3416
3417   Parts[Num] = N0.getOperand(0).getNode();
3418   return true;
3419 }
3420
3421 /// Match a 32-bit packed halfword bswap. That is
3422 /// ((x & 0x000000ff) << 8) |
3423 /// ((x & 0x0000ff00) >> 8) |
3424 /// ((x & 0x00ff0000) << 8) |
3425 /// ((x & 0xff000000) >> 8)
3426 /// => (rotl (bswap x), 16)
3427 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3428   if (!LegalOperations)
3429     return SDValue();
3430
3431   EVT VT = N->getValueType(0);
3432   if (VT != MVT::i32)
3433     return SDValue();
3434   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3435     return SDValue();
3436
3437   // Look for either
3438   // (or (or (and), (and)), (or (and), (and)))
3439   // (or (or (or (and), (and)), (and)), (and))
3440   if (N0.getOpcode() != ISD::OR)
3441     return SDValue();
3442   SDValue N00 = N0.getOperand(0);
3443   SDValue N01 = N0.getOperand(1);
3444   SDNode *Parts[4] = {};
3445
3446   if (N1.getOpcode() == ISD::OR &&
3447       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3448     // (or (or (and), (and)), (or (and), (and)))
3449     SDValue N000 = N00.getOperand(0);
3450     if (!isBSwapHWordElement(N000, Parts))
3451       return SDValue();
3452
3453     SDValue N001 = N00.getOperand(1);
3454     if (!isBSwapHWordElement(N001, Parts))
3455       return SDValue();
3456     SDValue N010 = N01.getOperand(0);
3457     if (!isBSwapHWordElement(N010, Parts))
3458       return SDValue();
3459     SDValue N011 = N01.getOperand(1);
3460     if (!isBSwapHWordElement(N011, Parts))
3461       return SDValue();
3462   } else {
3463     // (or (or (or (and), (and)), (and)), (and))
3464     if (!isBSwapHWordElement(N1, Parts))
3465       return SDValue();
3466     if (!isBSwapHWordElement(N01, Parts))
3467       return SDValue();
3468     if (N00.getOpcode() != ISD::OR)
3469       return SDValue();
3470     SDValue N000 = N00.getOperand(0);
3471     if (!isBSwapHWordElement(N000, Parts))
3472       return SDValue();
3473     SDValue N001 = N00.getOperand(1);
3474     if (!isBSwapHWordElement(N001, Parts))
3475       return SDValue();
3476   }
3477
3478   // Make sure the parts are all coming from the same node.
3479   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3480     return SDValue();
3481
3482   SDLoc DL(N);
3483   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3484                               SDValue(Parts[0], 0));
3485
3486   // Result of the bswap should be rotated by 16. If it's not legal, then
3487   // do  (x << 16) | (x >> 16).
3488   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3489   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3490     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3491   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3492     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3493   return DAG.getNode(ISD::OR, DL, VT,
3494                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3495                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3496 }
3497
3498 /// This contains all DAGCombine rules which reduce two values combined by
3499 /// an Or operation to a single value \see visitANDLike().
3500 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3501   EVT VT = N1.getValueType();
3502   // fold (or x, undef) -> -1
3503   if (!LegalOperations &&
3504       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3505     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3506     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3507                            SDLoc(LocReference), VT);
3508   }
3509   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3510   SDValue LL, LR, RL, RR, CC0, CC1;
3511   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3512     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3513     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3514
3515     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3516       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3517       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3518       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3519         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3520                                      LR.getValueType(), LL, RL);
3521         AddToWorklist(ORNode.getNode());
3522         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3523       }
3524       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3525       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3526       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3527         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3528                                       LR.getValueType(), LL, RL);
3529         AddToWorklist(ANDNode.getNode());
3530         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3531       }
3532     }
3533     // canonicalize equivalent to ll == rl
3534     if (LL == RR && LR == RL) {
3535       Op1 = ISD::getSetCCSwappedOperands(Op1);
3536       std::swap(RL, RR);
3537     }
3538     if (LL == RL && LR == RR) {
3539       bool isInteger = LL.getValueType().isInteger();
3540       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3541       if (Result != ISD::SETCC_INVALID &&
3542           (!LegalOperations ||
3543            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3544             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3545         EVT CCVT = getSetCCResultType(LL.getValueType());
3546         if (N0.getValueType() == CCVT ||
3547             (!LegalOperations && N0.getValueType() == MVT::i1))
3548           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3549                               LL, LR, Result);
3550       }
3551     }
3552   }
3553
3554   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3555   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3556       // Don't increase # computations.
3557       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3558     // We can only do this xform if we know that bits from X that are set in C2
3559     // but not in C1 are already zero.  Likewise for Y.
3560     if (const ConstantSDNode *N0O1C =
3561         getAsNonOpaqueConstant(N0.getOperand(1))) {
3562       if (const ConstantSDNode *N1O1C =
3563           getAsNonOpaqueConstant(N1.getOperand(1))) {
3564         // We can only do this xform if we know that bits from X that are set in
3565         // C2 but not in C1 are already zero.  Likewise for Y.
3566         const APInt &LHSMask = N0O1C->getAPIntValue();
3567         const APInt &RHSMask = N1O1C->getAPIntValue();
3568
3569         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3570             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3571           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3572                                   N0.getOperand(0), N1.getOperand(0));
3573           SDLoc DL(LocReference);
3574           return DAG.getNode(ISD::AND, DL, VT, X,
3575                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3576         }
3577       }
3578     }
3579   }
3580
3581   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3582   if (N0.getOpcode() == ISD::AND &&
3583       N1.getOpcode() == ISD::AND &&
3584       N0.getOperand(0) == N1.getOperand(0) &&
3585       // Don't increase # computations.
3586       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3587     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3588                             N0.getOperand(1), N1.getOperand(1));
3589     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3590   }
3591
3592   return SDValue();
3593 }
3594
3595 SDValue DAGCombiner::visitOR(SDNode *N) {
3596   SDValue N0 = N->getOperand(0);
3597   SDValue N1 = N->getOperand(1);
3598   EVT VT = N1.getValueType();
3599
3600   // fold vector ops
3601   if (VT.isVector()) {
3602     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3603       return FoldedVOp;
3604
3605     // fold (or x, 0) -> x, vector edition
3606     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3607       return N1;
3608     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3609       return N0;
3610
3611     // fold (or x, -1) -> -1, vector edition
3612     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3613       // do not return N0, because undef node may exist in N0
3614       return DAG.getConstant(
3615           APInt::getAllOnesValue(
3616               N0.getValueType().getScalarType().getSizeInBits()),
3617           SDLoc(N), N0.getValueType());
3618     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3619       // do not return N1, because undef node may exist in N1
3620       return DAG.getConstant(
3621           APInt::getAllOnesValue(
3622               N1.getValueType().getScalarType().getSizeInBits()),
3623           SDLoc(N), N1.getValueType());
3624
3625     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3626     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3627     // Do this only if the resulting shuffle is legal.
3628     if (isa<ShuffleVectorSDNode>(N0) &&
3629         isa<ShuffleVectorSDNode>(N1) &&
3630         // Avoid folding a node with illegal type.
3631         TLI.isTypeLegal(VT) &&
3632         N0->getOperand(1) == N1->getOperand(1) &&
3633         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3634       bool CanFold = true;
3635       unsigned NumElts = VT.getVectorNumElements();
3636       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3637       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3638       // We construct two shuffle masks:
3639       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3640       // and N1 as the second operand.
3641       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3642       // and N0 as the second operand.
3643       // We do this because OR is commutable and therefore there might be
3644       // two ways to fold this node into a shuffle.
3645       SmallVector<int,4> Mask1;
3646       SmallVector<int,4> Mask2;
3647
3648       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3649         int M0 = SV0->getMaskElt(i);
3650         int M1 = SV1->getMaskElt(i);
3651
3652         // Both shuffle indexes are undef. Propagate Undef.
3653         if (M0 < 0 && M1 < 0) {
3654           Mask1.push_back(M0);
3655           Mask2.push_back(M0);
3656           continue;
3657         }
3658
3659         if (M0 < 0 || M1 < 0 ||
3660             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3661             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3662           CanFold = false;
3663           break;
3664         }
3665
3666         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3667         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3668       }
3669
3670       if (CanFold) {
3671         // Fold this sequence only if the resulting shuffle is 'legal'.
3672         if (TLI.isShuffleMaskLegal(Mask1, VT))
3673           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3674                                       N1->getOperand(0), &Mask1[0]);
3675         if (TLI.isShuffleMaskLegal(Mask2, VT))
3676           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3677                                       N0->getOperand(0), &Mask2[0]);
3678       }
3679     }
3680   }
3681
3682   // fold (or c1, c2) -> c1|c2
3683   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3684   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3685   if (N0C && N1C && !N1C->isOpaque())
3686     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3687   // canonicalize constant to RHS
3688   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3689      !isConstantIntBuildVectorOrConstantInt(N1))
3690     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3691   // fold (or x, 0) -> x
3692   if (isNullConstant(N1))
3693     return N0;
3694   // fold (or x, -1) -> -1
3695   if (isAllOnesConstant(N1))
3696     return N1;
3697   // fold (or x, c) -> c iff (x & ~c) == 0
3698   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3699     return N1;
3700
3701   if (SDValue Combined = visitORLike(N0, N1, N))
3702     return Combined;
3703
3704   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3705   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3706     return BSwap;
3707   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3708     return BSwap;
3709
3710   // reassociate or
3711   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3712     return ROR;
3713   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3714   // iff (c1 & c2) == 0.
3715   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3716              isa<ConstantSDNode>(N0.getOperand(1))) {
3717     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3718     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3719       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3720                                                    N1C, C1))
3721         return DAG.getNode(
3722             ISD::AND, SDLoc(N), VT,
3723             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3724       return SDValue();
3725     }
3726   }
3727   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3728   if (N0.getOpcode() == N1.getOpcode())
3729     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3730       return Tmp;
3731
3732   // See if this is some rotate idiom.
3733   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3734     return SDValue(Rot, 0);
3735
3736   // Simplify the operands using demanded-bits information.
3737   if (!VT.isVector() &&
3738       SimplifyDemandedBits(SDValue(N, 0)))
3739     return SDValue(N, 0);
3740
3741   return SDValue();
3742 }
3743
3744 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3745 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3746   if (Op.getOpcode() == ISD::AND) {
3747     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3748       Mask = Op.getOperand(1);
3749       Op = Op.getOperand(0);
3750     } else {
3751       return false;
3752     }
3753   }
3754
3755   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3756     Shift = Op;
3757     return true;
3758   }
3759
3760   return false;
3761 }
3762
3763 // Return true if we can prove that, whenever Neg and Pos are both in the
3764 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3765 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3766 //
3767 //     (or (shift1 X, Neg), (shift2 X, Pos))
3768 //
3769 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3770 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3771 // to consider shift amounts with defined behavior.
3772 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3773   // If OpSize is a power of 2 then:
3774   //
3775   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3776   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3777   //
3778   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3779   // for the stronger condition:
3780   //
3781   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3782   //
3783   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3784   // we can just replace Neg with Neg' for the rest of the function.
3785   //
3786   // In other cases we check for the even stronger condition:
3787   //
3788   //     Neg == OpSize - Pos                                    [B]
3789   //
3790   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3791   // behavior if Pos == 0 (and consequently Neg == OpSize).
3792   //
3793   // We could actually use [A] whenever OpSize is a power of 2, but the
3794   // only extra cases that it would match are those uninteresting ones
3795   // where Neg and Pos are never in range at the same time.  E.g. for
3796   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3797   // as well as (sub 32, Pos), but:
3798   //
3799   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3800   //
3801   // always invokes undefined behavior for 32-bit X.
3802   //
3803   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3804   unsigned MaskLoBits = 0;
3805   if (Neg.getOpcode() == ISD::AND &&
3806       isPowerOf2_64(OpSize) &&
3807       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3808       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3809     Neg = Neg.getOperand(0);
3810     MaskLoBits = Log2_64(OpSize);
3811   }
3812
3813   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3814   if (Neg.getOpcode() != ISD::SUB)
3815     return 0;
3816   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3817   if (!NegC)
3818     return 0;
3819   SDValue NegOp1 = Neg.getOperand(1);
3820
3821   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3822   // Pos'.  The truncation is redundant for the purpose of the equality.
3823   if (MaskLoBits &&
3824       Pos.getOpcode() == ISD::AND &&
3825       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3826       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3827     Pos = Pos.getOperand(0);
3828
3829   // The condition we need is now:
3830   //
3831   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3832   //
3833   // If NegOp1 == Pos then we need:
3834   //
3835   //              OpSize & Mask == NegC & Mask
3836   //
3837   // (because "x & Mask" is a truncation and distributes through subtraction).
3838   APInt Width;
3839   if (Pos == NegOp1)
3840     Width = NegC->getAPIntValue();
3841   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3842   // Then the condition we want to prove becomes:
3843   //
3844   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3845   //
3846   // which, again because "x & Mask" is a truncation, becomes:
3847   //
3848   //                NegC & Mask == (OpSize - PosC) & Mask
3849   //              OpSize & Mask == (NegC + PosC) & Mask
3850   else if (Pos.getOpcode() == ISD::ADD &&
3851            Pos.getOperand(0) == NegOp1 &&
3852            Pos.getOperand(1).getOpcode() == ISD::Constant)
3853     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3854              NegC->getAPIntValue());
3855   else
3856     return false;
3857
3858   // Now we just need to check that OpSize & Mask == Width & Mask.
3859   if (MaskLoBits)
3860     // Opsize & Mask is 0 since Mask is Opsize - 1.
3861     return Width.getLoBits(MaskLoBits) == 0;
3862   return Width == OpSize;
3863 }
3864
3865 // A subroutine of MatchRotate used once we have found an OR of two opposite
3866 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3867 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3868 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3869 // Neg with outer conversions stripped away.
3870 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3871                                        SDValue Neg, SDValue InnerPos,
3872                                        SDValue InnerNeg, unsigned PosOpcode,
3873                                        unsigned NegOpcode, SDLoc DL) {
3874   // fold (or (shl x, (*ext y)),
3875   //          (srl x, (*ext (sub 32, y)))) ->
3876   //   (rotl x, y) or (rotr x, (sub 32, y))
3877   //
3878   // fold (or (shl x, (*ext (sub 32, y))),
3879   //          (srl x, (*ext y))) ->
3880   //   (rotr x, y) or (rotl x, (sub 32, y))
3881   EVT VT = Shifted.getValueType();
3882   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3883     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3884     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3885                        HasPos ? Pos : Neg).getNode();
3886   }
3887
3888   return nullptr;
3889 }
3890
3891 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3892 // idioms for rotate, and if the target supports rotation instructions, generate
3893 // a rot[lr].
3894 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3895   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3896   EVT VT = LHS.getValueType();
3897   if (!TLI.isTypeLegal(VT)) return nullptr;
3898
3899   // The target must have at least one rotate flavor.
3900   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3901   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3902   if (!HasROTL && !HasROTR) return nullptr;
3903
3904   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3905   SDValue LHSShift;   // The shift.
3906   SDValue LHSMask;    // AND value if any.
3907   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3908     return nullptr; // Not part of a rotate.
3909
3910   SDValue RHSShift;   // The shift.
3911   SDValue RHSMask;    // AND value if any.
3912   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3913     return nullptr; // Not part of a rotate.
3914
3915   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3916     return nullptr;   // Not shifting the same value.
3917
3918   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3919     return nullptr;   // Shifts must disagree.
3920
3921   // Canonicalize shl to left side in a shl/srl pair.
3922   if (RHSShift.getOpcode() == ISD::SHL) {
3923     std::swap(LHS, RHS);
3924     std::swap(LHSShift, RHSShift);
3925     std::swap(LHSMask , RHSMask );
3926   }
3927
3928   unsigned OpSizeInBits = VT.getSizeInBits();
3929   SDValue LHSShiftArg = LHSShift.getOperand(0);
3930   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3931   SDValue RHSShiftArg = RHSShift.getOperand(0);
3932   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3933
3934   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3935   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3936   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3937       RHSShiftAmt.getOpcode() == ISD::Constant) {
3938     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3939     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3940     if ((LShVal + RShVal) != OpSizeInBits)
3941       return nullptr;
3942
3943     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3944                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3945
3946     // If there is an AND of either shifted operand, apply it to the result.
3947     if (LHSMask.getNode() || RHSMask.getNode()) {
3948       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3949
3950       if (LHSMask.getNode()) {
3951         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3952         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3953       }
3954       if (RHSMask.getNode()) {
3955         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3956         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3957       }
3958
3959       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3960     }
3961
3962     return Rot.getNode();
3963   }
3964
3965   // If there is a mask here, and we have a variable shift, we can't be sure
3966   // that we're masking out the right stuff.
3967   if (LHSMask.getNode() || RHSMask.getNode())
3968     return nullptr;
3969
3970   // If the shift amount is sign/zext/any-extended just peel it off.
3971   SDValue LExtOp0 = LHSShiftAmt;
3972   SDValue RExtOp0 = RHSShiftAmt;
3973   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3974        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3975        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3976        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3977       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3978        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3979        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3980        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3981     LExtOp0 = LHSShiftAmt.getOperand(0);
3982     RExtOp0 = RHSShiftAmt.getOperand(0);
3983   }
3984
3985   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3986                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3987   if (TryL)
3988     return TryL;
3989
3990   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3991                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3992   if (TryR)
3993     return TryR;
3994
3995   return nullptr;
3996 }
3997
3998 SDValue DAGCombiner::visitXOR(SDNode *N) {
3999   SDValue N0 = N->getOperand(0);
4000   SDValue N1 = N->getOperand(1);
4001   EVT VT = N0.getValueType();
4002
4003   // fold vector ops
4004   if (VT.isVector()) {
4005     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4006       return FoldedVOp;
4007
4008     // fold (xor x, 0) -> x, vector edition
4009     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4010       return N1;
4011     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4012       return N0;
4013   }
4014
4015   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4016   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4017     return DAG.getConstant(0, SDLoc(N), VT);
4018   // fold (xor x, undef) -> undef
4019   if (N0.getOpcode() == ISD::UNDEF)
4020     return N0;
4021   if (N1.getOpcode() == ISD::UNDEF)
4022     return N1;
4023   // fold (xor c1, c2) -> c1^c2
4024   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4025   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4026   if (N0C && N1C)
4027     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4028   // canonicalize constant to RHS
4029   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4030      !isConstantIntBuildVectorOrConstantInt(N1))
4031     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4032   // fold (xor x, 0) -> x
4033   if (isNullConstant(N1))
4034     return N0;
4035   // reassociate xor
4036   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4037     return RXOR;
4038
4039   // fold !(x cc y) -> (x !cc y)
4040   SDValue LHS, RHS, CC;
4041   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4042     bool isInt = LHS.getValueType().isInteger();
4043     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4044                                                isInt);
4045
4046     if (!LegalOperations ||
4047         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4048       switch (N0.getOpcode()) {
4049       default:
4050         llvm_unreachable("Unhandled SetCC Equivalent!");
4051       case ISD::SETCC:
4052         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4053       case ISD::SELECT_CC:
4054         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4055                                N0.getOperand(3), NotCC);
4056       }
4057     }
4058   }
4059
4060   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4061   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4062       N0.getNode()->hasOneUse() &&
4063       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4064     SDValue V = N0.getOperand(0);
4065     SDLoc DL(N0);
4066     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4067                     DAG.getConstant(1, DL, V.getValueType()));
4068     AddToWorklist(V.getNode());
4069     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4070   }
4071
4072   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4073   if (isOneConstant(N1) && VT == MVT::i1 &&
4074       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4075     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4076     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4077       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4078       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4079       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4080       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4081       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4082     }
4083   }
4084   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4085   if (isAllOnesConstant(N1) &&
4086       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4087     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4088     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4089       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4090       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4091       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4092       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4093       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4094     }
4095   }
4096   // fold (xor (and x, y), y) -> (and (not x), y)
4097   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4098       N0->getOperand(1) == N1) {
4099     SDValue X = N0->getOperand(0);
4100     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4101     AddToWorklist(NotX.getNode());
4102     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4103   }
4104   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4105   if (N1C && N0.getOpcode() == ISD::XOR) {
4106     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4107       SDLoc DL(N);
4108       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4109                          DAG.getConstant(N1C->getAPIntValue() ^
4110                                          N00C->getAPIntValue(), DL, VT));
4111     }
4112     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4113       SDLoc DL(N);
4114       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4115                          DAG.getConstant(N1C->getAPIntValue() ^
4116                                          N01C->getAPIntValue(), DL, VT));
4117     }
4118   }
4119   // fold (xor x, x) -> 0
4120   if (N0 == N1)
4121     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4122
4123   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4124   // Here is a concrete example of this equivalence:
4125   // i16   x ==  14
4126   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4127   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4128   //
4129   // =>
4130   //
4131   // i16     ~1      == 0b1111111111111110
4132   // i16 rol(~1, 14) == 0b1011111111111111
4133   //
4134   // Some additional tips to help conceptualize this transform:
4135   // - Try to see the operation as placing a single zero in a value of all ones.
4136   // - There exists no value for x which would allow the result to contain zero.
4137   // - Values of x larger than the bitwidth are undefined and do not require a
4138   //   consistent result.
4139   // - Pushing the zero left requires shifting one bits in from the right.
4140   // A rotate left of ~1 is a nice way of achieving the desired result.
4141   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4142       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4143     SDLoc DL(N);
4144     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4145                        N0.getOperand(1));
4146   }
4147
4148   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4149   if (N0.getOpcode() == N1.getOpcode())
4150     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4151       return Tmp;
4152
4153   // Simplify the expression using non-local knowledge.
4154   if (!VT.isVector() &&
4155       SimplifyDemandedBits(SDValue(N, 0)))
4156     return SDValue(N, 0);
4157
4158   return SDValue();
4159 }
4160
4161 /// Handle transforms common to the three shifts, when the shift amount is a
4162 /// constant.
4163 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4164   SDNode *LHS = N->getOperand(0).getNode();
4165   if (!LHS->hasOneUse()) return SDValue();
4166
4167   // We want to pull some binops through shifts, so that we have (and (shift))
4168   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4169   // thing happens with address calculations, so it's important to canonicalize
4170   // it.
4171   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4172
4173   switch (LHS->getOpcode()) {
4174   default: return SDValue();
4175   case ISD::OR:
4176   case ISD::XOR:
4177     HighBitSet = false; // We can only transform sra if the high bit is clear.
4178     break;
4179   case ISD::AND:
4180     HighBitSet = true;  // We can only transform sra if the high bit is set.
4181     break;
4182   case ISD::ADD:
4183     if (N->getOpcode() != ISD::SHL)
4184       return SDValue(); // only shl(add) not sr[al](add).
4185     HighBitSet = false; // We can only transform sra if the high bit is clear.
4186     break;
4187   }
4188
4189   // We require the RHS of the binop to be a constant and not opaque as well.
4190   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4191   if (!BinOpCst) return SDValue();
4192
4193   // FIXME: disable this unless the input to the binop is a shift by a constant.
4194   // If it is not a shift, it pessimizes some common cases like:
4195   //
4196   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4197   //    int bar(int *X, int i) { return X[i & 255]; }
4198   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4199   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4200        BinOpLHSVal->getOpcode() != ISD::SRA &&
4201        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4202       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4203     return SDValue();
4204
4205   EVT VT = N->getValueType(0);
4206
4207   // If this is a signed shift right, and the high bit is modified by the
4208   // logical operation, do not perform the transformation. The highBitSet
4209   // boolean indicates the value of the high bit of the constant which would
4210   // cause it to be modified for this operation.
4211   if (N->getOpcode() == ISD::SRA) {
4212     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4213     if (BinOpRHSSignSet != HighBitSet)
4214       return SDValue();
4215   }
4216
4217   if (!TLI.isDesirableToCommuteWithShift(LHS))
4218     return SDValue();
4219
4220   // Fold the constants, shifting the binop RHS by the shift amount.
4221   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4222                                N->getValueType(0),
4223                                LHS->getOperand(1), N->getOperand(1));
4224   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4225
4226   // Create the new shift.
4227   SDValue NewShift = DAG.getNode(N->getOpcode(),
4228                                  SDLoc(LHS->getOperand(0)),
4229                                  VT, LHS->getOperand(0), N->getOperand(1));
4230
4231   // Create the new binop.
4232   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4233 }
4234
4235 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4236   assert(N->getOpcode() == ISD::TRUNCATE);
4237   assert(N->getOperand(0).getOpcode() == ISD::AND);
4238
4239   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4240   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4241     SDValue N01 = N->getOperand(0).getOperand(1);
4242
4243     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4244       if (!N01C->isOpaque()) {
4245         EVT TruncVT = N->getValueType(0);
4246         SDValue N00 = N->getOperand(0).getOperand(0);
4247         APInt TruncC = N01C->getAPIntValue();
4248         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4249         SDLoc DL(N);
4250
4251         return DAG.getNode(ISD::AND, DL, TruncVT,
4252                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4253                            DAG.getConstant(TruncC, DL, TruncVT));
4254       }
4255     }
4256   }
4257
4258   return SDValue();
4259 }
4260
4261 SDValue DAGCombiner::visitRotate(SDNode *N) {
4262   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4263   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4264       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4265     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4266     if (NewOp1.getNode())
4267       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4268                          N->getOperand(0), NewOp1);
4269   }
4270   return SDValue();
4271 }
4272
4273 SDValue DAGCombiner::visitSHL(SDNode *N) {
4274   SDValue N0 = N->getOperand(0);
4275   SDValue N1 = N->getOperand(1);
4276   EVT VT = N0.getValueType();
4277   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4278
4279   // fold vector ops
4280   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4281   if (VT.isVector()) {
4282     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4283       return FoldedVOp;
4284
4285     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4286     // If setcc produces all-one true value then:
4287     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4288     if (N1CV && N1CV->isConstant()) {
4289       if (N0.getOpcode() == ISD::AND) {
4290         SDValue N00 = N0->getOperand(0);
4291         SDValue N01 = N0->getOperand(1);
4292         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4293
4294         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4295             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4296                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4297           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4298                                                      N01CV, N1CV))
4299             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4300         }
4301       } else {
4302         N1C = isConstOrConstSplat(N1);
4303       }
4304     }
4305   }
4306
4307   // fold (shl c1, c2) -> c1<<c2
4308   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4309   if (N0C && N1C && !N1C->isOpaque())
4310     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4311   // fold (shl 0, x) -> 0
4312   if (isNullConstant(N0))
4313     return N0;
4314   // fold (shl x, c >= size(x)) -> undef
4315   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4316     return DAG.getUNDEF(VT);
4317   // fold (shl x, 0) -> x
4318   if (N1C && N1C->isNullValue())
4319     return N0;
4320   // fold (shl undef, x) -> 0
4321   if (N0.getOpcode() == ISD::UNDEF)
4322     return DAG.getConstant(0, SDLoc(N), VT);
4323   // if (shl x, c) is known to be zero, return 0
4324   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4325                             APInt::getAllOnesValue(OpSizeInBits)))
4326     return DAG.getConstant(0, SDLoc(N), VT);
4327   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4328   if (N1.getOpcode() == ISD::TRUNCATE &&
4329       N1.getOperand(0).getOpcode() == ISD::AND) {
4330     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4331     if (NewOp1.getNode())
4332       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4333   }
4334
4335   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4336     return SDValue(N, 0);
4337
4338   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4339   if (N1C && N0.getOpcode() == ISD::SHL) {
4340     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4341       uint64_t c1 = N0C1->getZExtValue();
4342       uint64_t c2 = N1C->getZExtValue();
4343       SDLoc DL(N);
4344       if (c1 + c2 >= OpSizeInBits)
4345         return DAG.getConstant(0, DL, VT);
4346       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4347                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4348     }
4349   }
4350
4351   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4352   // For this to be valid, the second form must not preserve any of the bits
4353   // that are shifted out by the inner shift in the first form.  This means
4354   // the outer shift size must be >= the number of bits added by the ext.
4355   // As a corollary, we don't care what kind of ext it is.
4356   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4357               N0.getOpcode() == ISD::ANY_EXTEND ||
4358               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4359       N0.getOperand(0).getOpcode() == ISD::SHL) {
4360     SDValue N0Op0 = N0.getOperand(0);
4361     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4362       uint64_t c1 = N0Op0C1->getZExtValue();
4363       uint64_t c2 = N1C->getZExtValue();
4364       EVT InnerShiftVT = N0Op0.getValueType();
4365       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4366       if (c2 >= OpSizeInBits - InnerShiftSize) {
4367         SDLoc DL(N0);
4368         if (c1 + c2 >= OpSizeInBits)
4369           return DAG.getConstant(0, DL, VT);
4370         return DAG.getNode(ISD::SHL, DL, VT,
4371                            DAG.getNode(N0.getOpcode(), DL, VT,
4372                                        N0Op0->getOperand(0)),
4373                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4374       }
4375     }
4376   }
4377
4378   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4379   // Only fold this if the inner zext has no other uses to avoid increasing
4380   // the total number of instructions.
4381   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4382       N0.getOperand(0).getOpcode() == ISD::SRL) {
4383     SDValue N0Op0 = N0.getOperand(0);
4384     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4385       uint64_t c1 = N0Op0C1->getZExtValue();
4386       if (c1 < VT.getScalarSizeInBits()) {
4387         uint64_t c2 = N1C->getZExtValue();
4388         if (c1 == c2) {
4389           SDValue NewOp0 = N0.getOperand(0);
4390           EVT CountVT = NewOp0.getOperand(1).getValueType();
4391           SDLoc DL(N);
4392           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4393                                        NewOp0,
4394                                        DAG.getConstant(c2, DL, CountVT));
4395           AddToWorklist(NewSHL.getNode());
4396           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4397         }
4398       }
4399     }
4400   }
4401
4402   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4403   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4404   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4405       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4406     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4407       uint64_t C1 = N0C1->getZExtValue();
4408       uint64_t C2 = N1C->getZExtValue();
4409       SDLoc DL(N);
4410       if (C1 <= C2)
4411         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4412                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4413       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4414                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4415     }
4416   }
4417
4418   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4419   //                               (and (srl x, (sub c1, c2), MASK)
4420   // Only fold this if the inner shift has no other uses -- if it does, folding
4421   // this will increase the total number of instructions.
4422   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4423     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4424       uint64_t c1 = N0C1->getZExtValue();
4425       if (c1 < OpSizeInBits) {
4426         uint64_t c2 = N1C->getZExtValue();
4427         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4428         SDValue Shift;
4429         if (c2 > c1) {
4430           Mask = Mask.shl(c2 - c1);
4431           SDLoc DL(N);
4432           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4433                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4434         } else {
4435           Mask = Mask.lshr(c1 - c2);
4436           SDLoc DL(N);
4437           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4438                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4439         }
4440         SDLoc DL(N0);
4441         return DAG.getNode(ISD::AND, DL, VT, Shift,
4442                            DAG.getConstant(Mask, DL, VT));
4443       }
4444     }
4445   }
4446   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4447   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4448     unsigned BitSize = VT.getScalarSizeInBits();
4449     SDLoc DL(N);
4450     SDValue HiBitsMask =
4451       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4452                                             BitSize - N1C->getZExtValue()),
4453                       DL, VT);
4454     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4455                        HiBitsMask);
4456   }
4457
4458   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4459   // Variant of version done on multiply, except mul by a power of 2 is turned
4460   // into a shift.
4461   APInt Val;
4462   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4463       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4464        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4465     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4466     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4467     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4468   }
4469
4470   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4471   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4472     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4473       if (SDValue Folded =
4474               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4475         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4476     }
4477   }
4478
4479   if (N1C && !N1C->isOpaque())
4480     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4481       return NewSHL;
4482
4483   return SDValue();
4484 }
4485
4486 SDValue DAGCombiner::visitSRA(SDNode *N) {
4487   SDValue N0 = N->getOperand(0);
4488   SDValue N1 = N->getOperand(1);
4489   EVT VT = N0.getValueType();
4490   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4491
4492   // fold vector ops
4493   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4494   if (VT.isVector()) {
4495     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4496       return FoldedVOp;
4497
4498     N1C = isConstOrConstSplat(N1);
4499   }
4500
4501   // fold (sra c1, c2) -> (sra c1, c2)
4502   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4503   if (N0C && N1C && !N1C->isOpaque())
4504     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4505   // fold (sra 0, x) -> 0
4506   if (isNullConstant(N0))
4507     return N0;
4508   // fold (sra -1, x) -> -1
4509   if (isAllOnesConstant(N0))
4510     return N0;
4511   // fold (sra x, (setge c, size(x))) -> undef
4512   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4513     return DAG.getUNDEF(VT);
4514   // fold (sra x, 0) -> x
4515   if (N1C && N1C->isNullValue())
4516     return N0;
4517   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4518   // sext_inreg.
4519   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4520     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4521     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4522     if (VT.isVector())
4523       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4524                                ExtVT, VT.getVectorNumElements());
4525     if ((!LegalOperations ||
4526          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4527       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4528                          N0.getOperand(0), DAG.getValueType(ExtVT));
4529   }
4530
4531   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4532   if (N1C && N0.getOpcode() == ISD::SRA) {
4533     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4534       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4535       if (Sum >= OpSizeInBits)
4536         Sum = OpSizeInBits - 1;
4537       SDLoc DL(N);
4538       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4539                          DAG.getConstant(Sum, DL, N1.getValueType()));
4540     }
4541   }
4542
4543   // fold (sra (shl X, m), (sub result_size, n))
4544   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4545   // result_size - n != m.
4546   // If truncate is free for the target sext(shl) is likely to result in better
4547   // code.
4548   if (N0.getOpcode() == ISD::SHL && N1C) {
4549     // Get the two constanst of the shifts, CN0 = m, CN = n.
4550     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4551     if (N01C) {
4552       LLVMContext &Ctx = *DAG.getContext();
4553       // Determine what the truncate's result bitsize and type would be.
4554       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4555
4556       if (VT.isVector())
4557         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4558
4559       // Determine the residual right-shift amount.
4560       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4561
4562       // If the shift is not a no-op (in which case this should be just a sign
4563       // extend already), the truncated to type is legal, sign_extend is legal
4564       // on that type, and the truncate to that type is both legal and free,
4565       // perform the transform.
4566       if ((ShiftAmt > 0) &&
4567           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4568           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4569           TLI.isTruncateFree(VT, TruncVT)) {
4570
4571         SDLoc DL(N);
4572         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4573             getShiftAmountTy(N0.getOperand(0).getValueType()));
4574         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4575                                     N0.getOperand(0), Amt);
4576         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4577                                     Shift);
4578         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4579                            N->getValueType(0), Trunc);
4580       }
4581     }
4582   }
4583
4584   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4585   if (N1.getOpcode() == ISD::TRUNCATE &&
4586       N1.getOperand(0).getOpcode() == ISD::AND) {
4587     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4588     if (NewOp1.getNode())
4589       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4590   }
4591
4592   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4593   //      if c1 is equal to the number of bits the trunc removes
4594   if (N0.getOpcode() == ISD::TRUNCATE &&
4595       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4596        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4597       N0.getOperand(0).hasOneUse() &&
4598       N0.getOperand(0).getOperand(1).hasOneUse() &&
4599       N1C) {
4600     SDValue N0Op0 = N0.getOperand(0);
4601     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4602       unsigned LargeShiftVal = LargeShift->getZExtValue();
4603       EVT LargeVT = N0Op0.getValueType();
4604
4605       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4606         SDLoc DL(N);
4607         SDValue Amt =
4608           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4609                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4610         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4611                                   N0Op0.getOperand(0), Amt);
4612         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4613       }
4614     }
4615   }
4616
4617   // Simplify, based on bits shifted out of the LHS.
4618   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4619     return SDValue(N, 0);
4620
4621
4622   // If the sign bit is known to be zero, switch this to a SRL.
4623   if (DAG.SignBitIsZero(N0))
4624     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4625
4626   if (N1C && !N1C->isOpaque())
4627     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4628       return NewSRA;
4629
4630   return SDValue();
4631 }
4632
4633 SDValue DAGCombiner::visitSRL(SDNode *N) {
4634   SDValue N0 = N->getOperand(0);
4635   SDValue N1 = N->getOperand(1);
4636   EVT VT = N0.getValueType();
4637   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4638
4639   // fold vector ops
4640   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4641   if (VT.isVector()) {
4642     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4643       return FoldedVOp;
4644
4645     N1C = isConstOrConstSplat(N1);
4646   }
4647
4648   // fold (srl c1, c2) -> c1 >>u c2
4649   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4650   if (N0C && N1C && !N1C->isOpaque())
4651     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4652   // fold (srl 0, x) -> 0
4653   if (isNullConstant(N0))
4654     return N0;
4655   // fold (srl x, c >= size(x)) -> undef
4656   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4657     return DAG.getUNDEF(VT);
4658   // fold (srl x, 0) -> x
4659   if (N1C && N1C->isNullValue())
4660     return N0;
4661   // if (srl x, c) is known to be zero, return 0
4662   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4663                                    APInt::getAllOnesValue(OpSizeInBits)))
4664     return DAG.getConstant(0, SDLoc(N), VT);
4665
4666   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4667   if (N1C && N0.getOpcode() == ISD::SRL) {
4668     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4669       uint64_t c1 = N01C->getZExtValue();
4670       uint64_t c2 = N1C->getZExtValue();
4671       SDLoc DL(N);
4672       if (c1 + c2 >= OpSizeInBits)
4673         return DAG.getConstant(0, DL, VT);
4674       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4675                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4676     }
4677   }
4678
4679   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4680   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4681       N0.getOperand(0).getOpcode() == ISD::SRL &&
4682       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4683     uint64_t c1 =
4684       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4685     uint64_t c2 = N1C->getZExtValue();
4686     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4687     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4688     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4689     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4690     if (c1 + OpSizeInBits == InnerShiftSize) {
4691       SDLoc DL(N0);
4692       if (c1 + c2 >= InnerShiftSize)
4693         return DAG.getConstant(0, DL, VT);
4694       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4695                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4696                                      N0.getOperand(0)->getOperand(0),
4697                                      DAG.getConstant(c1 + c2, DL,
4698                                                      ShiftCountVT)));
4699     }
4700   }
4701
4702   // fold (srl (shl x, c), c) -> (and x, cst2)
4703   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4704     unsigned BitSize = N0.getScalarValueSizeInBits();
4705     if (BitSize <= 64) {
4706       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4707       SDLoc DL(N);
4708       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4709                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4710     }
4711   }
4712
4713   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4714   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4715     // Shifting in all undef bits?
4716     EVT SmallVT = N0.getOperand(0).getValueType();
4717     unsigned BitSize = SmallVT.getScalarSizeInBits();
4718     if (N1C->getZExtValue() >= BitSize)
4719       return DAG.getUNDEF(VT);
4720
4721     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4722       uint64_t ShiftAmt = N1C->getZExtValue();
4723       SDLoc DL0(N0);
4724       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4725                                        N0.getOperand(0),
4726                           DAG.getConstant(ShiftAmt, DL0,
4727                                           getShiftAmountTy(SmallVT)));
4728       AddToWorklist(SmallShift.getNode());
4729       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4730       SDLoc DL(N);
4731       return DAG.getNode(ISD::AND, DL, VT,
4732                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4733                          DAG.getConstant(Mask, DL, VT));
4734     }
4735   }
4736
4737   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4738   // bit, which is unmodified by sra.
4739   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4740     if (N0.getOpcode() == ISD::SRA)
4741       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4742   }
4743
4744   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4745   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4746       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4747     APInt KnownZero, KnownOne;
4748     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4749
4750     // If any of the input bits are KnownOne, then the input couldn't be all
4751     // zeros, thus the result of the srl will always be zero.
4752     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4753
4754     // If all of the bits input the to ctlz node are known to be zero, then
4755     // the result of the ctlz is "32" and the result of the shift is one.
4756     APInt UnknownBits = ~KnownZero;
4757     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4758
4759     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4760     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4761       // Okay, we know that only that the single bit specified by UnknownBits
4762       // could be set on input to the CTLZ node. If this bit is set, the SRL
4763       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4764       // to an SRL/XOR pair, which is likely to simplify more.
4765       unsigned ShAmt = UnknownBits.countTrailingZeros();
4766       SDValue Op = N0.getOperand(0);
4767
4768       if (ShAmt) {
4769         SDLoc DL(N0);
4770         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4771                   DAG.getConstant(ShAmt, DL,
4772                                   getShiftAmountTy(Op.getValueType())));
4773         AddToWorklist(Op.getNode());
4774       }
4775
4776       SDLoc DL(N);
4777       return DAG.getNode(ISD::XOR, DL, VT,
4778                          Op, DAG.getConstant(1, DL, VT));
4779     }
4780   }
4781
4782   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4783   if (N1.getOpcode() == ISD::TRUNCATE &&
4784       N1.getOperand(0).getOpcode() == ISD::AND) {
4785     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4786       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4787   }
4788
4789   // fold operands of srl based on knowledge that the low bits are not
4790   // demanded.
4791   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4792     return SDValue(N, 0);
4793
4794   if (N1C && !N1C->isOpaque())
4795     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4796       return NewSRL;
4797
4798   // Attempt to convert a srl of a load into a narrower zero-extending load.
4799   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4800     return NarrowLoad;
4801
4802   // Here is a common situation. We want to optimize:
4803   //
4804   //   %a = ...
4805   //   %b = and i32 %a, 2
4806   //   %c = srl i32 %b, 1
4807   //   brcond i32 %c ...
4808   //
4809   // into
4810   //
4811   //   %a = ...
4812   //   %b = and %a, 2
4813   //   %c = setcc eq %b, 0
4814   //   brcond %c ...
4815   //
4816   // However when after the source operand of SRL is optimized into AND, the SRL
4817   // itself may not be optimized further. Look for it and add the BRCOND into
4818   // the worklist.
4819   if (N->hasOneUse()) {
4820     SDNode *Use = *N->use_begin();
4821     if (Use->getOpcode() == ISD::BRCOND)
4822       AddToWorklist(Use);
4823     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4824       // Also look pass the truncate.
4825       Use = *Use->use_begin();
4826       if (Use->getOpcode() == ISD::BRCOND)
4827         AddToWorklist(Use);
4828     }
4829   }
4830
4831   return SDValue();
4832 }
4833
4834 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4835   SDValue N0 = N->getOperand(0);
4836   EVT VT = N->getValueType(0);
4837
4838   // fold (bswap c1) -> c2
4839   if (isConstantIntBuildVectorOrConstantInt(N0))
4840     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4841   // fold (bswap (bswap x)) -> x
4842   if (N0.getOpcode() == ISD::BSWAP)
4843     return N0->getOperand(0);
4844   return SDValue();
4845 }
4846
4847 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4848   SDValue N0 = N->getOperand(0);
4849   EVT VT = N->getValueType(0);
4850
4851   // fold (ctlz c1) -> c2
4852   if (isConstantIntBuildVectorOrConstantInt(N0))
4853     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4854   return SDValue();
4855 }
4856
4857 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4858   SDValue N0 = N->getOperand(0);
4859   EVT VT = N->getValueType(0);
4860
4861   // fold (ctlz_zero_undef c1) -> c2
4862   if (isConstantIntBuildVectorOrConstantInt(N0))
4863     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4864   return SDValue();
4865 }
4866
4867 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4868   SDValue N0 = N->getOperand(0);
4869   EVT VT = N->getValueType(0);
4870
4871   // fold (cttz c1) -> c2
4872   if (isConstantIntBuildVectorOrConstantInt(N0))
4873     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4874   return SDValue();
4875 }
4876
4877 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4878   SDValue N0 = N->getOperand(0);
4879   EVT VT = N->getValueType(0);
4880
4881   // fold (cttz_zero_undef c1) -> c2
4882   if (isConstantIntBuildVectorOrConstantInt(N0))
4883     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4884   return SDValue();
4885 }
4886
4887 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4888   SDValue N0 = N->getOperand(0);
4889   EVT VT = N->getValueType(0);
4890
4891   // fold (ctpop c1) -> c2
4892   if (isConstantIntBuildVectorOrConstantInt(N0))
4893     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4894   return SDValue();
4895 }
4896
4897
4898 /// \brief Generate Min/Max node
4899 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4900                                    SDValue True, SDValue False,
4901                                    ISD::CondCode CC, const TargetLowering &TLI,
4902                                    SelectionDAG &DAG) {
4903   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4904     return SDValue();
4905
4906   switch (CC) {
4907   case ISD::SETOLT:
4908   case ISD::SETOLE:
4909   case ISD::SETLT:
4910   case ISD::SETLE:
4911   case ISD::SETULT:
4912   case ISD::SETULE: {
4913     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4914     if (TLI.isOperationLegal(Opcode, VT))
4915       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4916     return SDValue();
4917   }
4918   case ISD::SETOGT:
4919   case ISD::SETOGE:
4920   case ISD::SETGT:
4921   case ISD::SETGE:
4922   case ISD::SETUGT:
4923   case ISD::SETUGE: {
4924     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4925     if (TLI.isOperationLegal(Opcode, VT))
4926       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4927     return SDValue();
4928   }
4929   default:
4930     return SDValue();
4931   }
4932 }
4933
4934 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4935   SDValue N0 = N->getOperand(0);
4936   SDValue N1 = N->getOperand(1);
4937   SDValue N2 = N->getOperand(2);
4938   EVT VT = N->getValueType(0);
4939   EVT VT0 = N0.getValueType();
4940
4941   // fold (select C, X, X) -> X
4942   if (N1 == N2)
4943     return N1;
4944   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4945     // fold (select true, X, Y) -> X
4946     // fold (select false, X, Y) -> Y
4947     return !N0C->isNullValue() ? N1 : N2;
4948   }
4949   // fold (select C, 1, X) -> (or C, X)
4950   if (VT == MVT::i1 && isOneConstant(N1))
4951     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4952   // fold (select C, 0, 1) -> (xor C, 1)
4953   // We can't do this reliably if integer based booleans have different contents
4954   // to floating point based booleans. This is because we can't tell whether we
4955   // have an integer-based boolean or a floating-point-based boolean unless we
4956   // can find the SETCC that produced it and inspect its operands. This is
4957   // fairly easy if C is the SETCC node, but it can potentially be
4958   // undiscoverable (or not reasonably discoverable). For example, it could be
4959   // in another basic block or it could require searching a complicated
4960   // expression.
4961   if (VT.isInteger() &&
4962       (VT0 == MVT::i1 || (VT0.isInteger() &&
4963                           TLI.getBooleanContents(false, false) ==
4964                               TLI.getBooleanContents(false, true) &&
4965                           TLI.getBooleanContents(false, false) ==
4966                               TargetLowering::ZeroOrOneBooleanContent)) &&
4967       isNullConstant(N1) && isOneConstant(N2)) {
4968     SDValue XORNode;
4969     if (VT == VT0) {
4970       SDLoc DL(N);
4971       return DAG.getNode(ISD::XOR, DL, VT0,
4972                          N0, DAG.getConstant(1, DL, VT0));
4973     }
4974     SDLoc DL0(N0);
4975     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4976                           N0, DAG.getConstant(1, DL0, VT0));
4977     AddToWorklist(XORNode.getNode());
4978     if (VT.bitsGT(VT0))
4979       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4980     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4981   }
4982   // fold (select C, 0, X) -> (and (not C), X)
4983   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4984     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4985     AddToWorklist(NOTNode.getNode());
4986     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4987   }
4988   // fold (select C, X, 1) -> (or (not C), X)
4989   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4990     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4991     AddToWorklist(NOTNode.getNode());
4992     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4993   }
4994   // fold (select C, X, 0) -> (and C, X)
4995   if (VT == MVT::i1 && isNullConstant(N2))
4996     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4997   // fold (select X, X, Y) -> (or X, Y)
4998   // fold (select X, 1, Y) -> (or X, Y)
4999   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5000     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5001   // fold (select X, Y, X) -> (and X, Y)
5002   // fold (select X, Y, 0) -> (and X, Y)
5003   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5004     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5005
5006   // If we can fold this based on the true/false value, do so.
5007   if (SimplifySelectOps(N, N1, N2))
5008     return SDValue(N, 0);  // Don't revisit N.
5009
5010   if (VT0 == MVT::i1) {
5011     // The code in this block deals with the following 2 equivalences:
5012     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5013     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5014     // The target can specify its prefered form with the
5015     // shouldNormalizeToSelectSequence() callback. However we always transform
5016     // to the right anyway if we find the inner select exists in the DAG anyway
5017     // and we always transform to the left side if we know that we can further
5018     // optimize the combination of the conditions.
5019     bool normalizeToSequence
5020       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5021     // select (and Cond0, Cond1), X, Y
5022     //   -> select Cond0, (select Cond1, X, Y), Y
5023     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5024       SDValue Cond0 = N0->getOperand(0);
5025       SDValue Cond1 = N0->getOperand(1);
5026       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5027                                         N1.getValueType(), Cond1, N1, N2);
5028       if (normalizeToSequence || !InnerSelect.use_empty())
5029         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5030                            InnerSelect, N2);
5031     }
5032     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5033     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5034       SDValue Cond0 = N0->getOperand(0);
5035       SDValue Cond1 = N0->getOperand(1);
5036       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5037                                         N1.getValueType(), Cond1, N1, N2);
5038       if (normalizeToSequence || !InnerSelect.use_empty())
5039         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5040                            InnerSelect);
5041     }
5042
5043     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5044     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5045       SDValue N1_0 = N1->getOperand(0);
5046       SDValue N1_1 = N1->getOperand(1);
5047       SDValue N1_2 = N1->getOperand(2);
5048       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5049         // Create the actual and node if we can generate good code for it.
5050         if (!normalizeToSequence) {
5051           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5052                                     N0, N1_0);
5053           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5054                              N1_1, N2);
5055         }
5056         // Otherwise see if we can optimize the "and" to a better pattern.
5057         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5058           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5059                              N1_1, N2);
5060       }
5061     }
5062     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5063     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5064       SDValue N2_0 = N2->getOperand(0);
5065       SDValue N2_1 = N2->getOperand(1);
5066       SDValue N2_2 = N2->getOperand(2);
5067       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5068         // Create the actual or node if we can generate good code for it.
5069         if (!normalizeToSequence) {
5070           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5071                                    N0, N2_0);
5072           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5073                              N1, N2_2);
5074         }
5075         // Otherwise see if we can optimize to a better pattern.
5076         if (SDValue Combined = visitORLike(N0, N2_0, N))
5077           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5078                              N1, N2_2);
5079       }
5080     }
5081   }
5082
5083   // fold selects based on a setcc into other things, such as min/max/abs
5084   if (N0.getOpcode() == ISD::SETCC) {
5085     // select x, y (fcmp lt x, y) -> fminnum x, y
5086     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5087     //
5088     // This is OK if we don't care about what happens if either operand is a
5089     // NaN.
5090     //
5091
5092     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5093     // no signed zeros as well as no nans.
5094     const TargetOptions &Options = DAG.getTarget().Options;
5095     if (Options.UnsafeFPMath &&
5096         VT.isFloatingPoint() && N0.hasOneUse() &&
5097         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5098       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5099
5100       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5101                                                 N0.getOperand(1), N1, N2, CC,
5102                                                 TLI, DAG))
5103         return FMinMax;
5104     }
5105
5106     if ((!LegalOperations &&
5107          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5108         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5109       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5110                          N0.getOperand(0), N0.getOperand(1),
5111                          N1, N2, N0.getOperand(2));
5112     return SimplifySelect(SDLoc(N), N0, N1, N2);
5113   }
5114
5115   return SDValue();
5116 }
5117
5118 static
5119 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5120   SDLoc DL(N);
5121   EVT LoVT, HiVT;
5122   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5123
5124   // Split the inputs.
5125   SDValue Lo, Hi, LL, LH, RL, RH;
5126   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5127   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5128
5129   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5130   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5131
5132   return std::make_pair(Lo, Hi);
5133 }
5134
5135 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5136 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5137 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5138   SDLoc dl(N);
5139   SDValue Cond = N->getOperand(0);
5140   SDValue LHS = N->getOperand(1);
5141   SDValue RHS = N->getOperand(2);
5142   EVT VT = N->getValueType(0);
5143   int NumElems = VT.getVectorNumElements();
5144   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5145          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5146          Cond.getOpcode() == ISD::BUILD_VECTOR);
5147
5148   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5149   // binary ones here.
5150   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5151     return SDValue();
5152
5153   // We're sure we have an even number of elements due to the
5154   // concat_vectors we have as arguments to vselect.
5155   // Skip BV elements until we find one that's not an UNDEF
5156   // After we find an UNDEF element, keep looping until we get to half the
5157   // length of the BV and see if all the non-undef nodes are the same.
5158   ConstantSDNode *BottomHalf = nullptr;
5159   for (int i = 0; i < NumElems / 2; ++i) {
5160     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5161       continue;
5162
5163     if (BottomHalf == nullptr)
5164       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5165     else if (Cond->getOperand(i).getNode() != BottomHalf)
5166       return SDValue();
5167   }
5168
5169   // Do the same for the second half of the BuildVector
5170   ConstantSDNode *TopHalf = nullptr;
5171   for (int i = NumElems / 2; i < NumElems; ++i) {
5172     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5173       continue;
5174
5175     if (TopHalf == nullptr)
5176       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5177     else if (Cond->getOperand(i).getNode() != TopHalf)
5178       return SDValue();
5179   }
5180
5181   assert(TopHalf && BottomHalf &&
5182          "One half of the selector was all UNDEFs and the other was all the "
5183          "same value. This should have been addressed before this function.");
5184   return DAG.getNode(
5185       ISD::CONCAT_VECTORS, dl, VT,
5186       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5187       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5188 }
5189
5190 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5191
5192   if (Level >= AfterLegalizeTypes)
5193     return SDValue();
5194
5195   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5196   SDValue Mask = MSC->getMask();
5197   SDValue Data  = MSC->getValue();
5198   SDLoc DL(N);
5199
5200   // If the MSCATTER data type requires splitting and the mask is provided by a
5201   // SETCC, then split both nodes and its operands before legalization. This
5202   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5203   // and enables future optimizations (e.g. min/max pattern matching on X86).
5204   if (Mask.getOpcode() != ISD::SETCC)
5205     return SDValue();
5206
5207   // Check if any splitting is required.
5208   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5209       TargetLowering::TypeSplitVector)
5210     return SDValue();
5211   SDValue MaskLo, MaskHi, Lo, Hi;
5212   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5213
5214   EVT LoVT, HiVT;
5215   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5216
5217   SDValue Chain = MSC->getChain();
5218
5219   EVT MemoryVT = MSC->getMemoryVT();
5220   unsigned Alignment = MSC->getOriginalAlignment();
5221
5222   EVT LoMemVT, HiMemVT;
5223   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5224
5225   SDValue DataLo, DataHi;
5226   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5227
5228   SDValue BasePtr = MSC->getBasePtr();
5229   SDValue IndexLo, IndexHi;
5230   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5231
5232   MachineMemOperand *MMO = DAG.getMachineFunction().
5233     getMachineMemOperand(MSC->getPointerInfo(),
5234                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5235                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5236
5237   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5238   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5239                             DL, OpsLo, MMO);
5240
5241   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5242   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5243                             DL, OpsHi, MMO);
5244
5245   AddToWorklist(Lo.getNode());
5246   AddToWorklist(Hi.getNode());
5247
5248   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5249 }
5250
5251 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5252
5253   if (Level >= AfterLegalizeTypes)
5254     return SDValue();
5255
5256   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5257   SDValue Mask = MST->getMask();
5258   SDValue Data  = MST->getValue();
5259   SDLoc DL(N);
5260
5261   // If the MSTORE data type requires splitting and the mask is provided by a
5262   // SETCC, then split both nodes and its operands before legalization. This
5263   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5264   // and enables future optimizations (e.g. min/max pattern matching on X86).
5265   if (Mask.getOpcode() == ISD::SETCC) {
5266
5267     // Check if any splitting is required.
5268     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5269         TargetLowering::TypeSplitVector)
5270       return SDValue();
5271
5272     SDValue MaskLo, MaskHi, Lo, Hi;
5273     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5274
5275     EVT LoVT, HiVT;
5276     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5277
5278     SDValue Chain = MST->getChain();
5279     SDValue Ptr   = MST->getBasePtr();
5280
5281     EVT MemoryVT = MST->getMemoryVT();
5282     unsigned Alignment = MST->getOriginalAlignment();
5283
5284     // if Alignment is equal to the vector size,
5285     // take the half of it for the second part
5286     unsigned SecondHalfAlignment =
5287       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5288          Alignment/2 : Alignment;
5289
5290     EVT LoMemVT, HiMemVT;
5291     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5292
5293     SDValue DataLo, DataHi;
5294     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5295
5296     MachineMemOperand *MMO = DAG.getMachineFunction().
5297       getMachineMemOperand(MST->getPointerInfo(),
5298                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5299                            Alignment, MST->getAAInfo(), MST->getRanges());
5300
5301     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5302                             MST->isTruncatingStore());
5303
5304     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5305     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5306                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5307
5308     MMO = DAG.getMachineFunction().
5309       getMachineMemOperand(MST->getPointerInfo(),
5310                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5311                            SecondHalfAlignment, MST->getAAInfo(),
5312                            MST->getRanges());
5313
5314     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5315                             MST->isTruncatingStore());
5316
5317     AddToWorklist(Lo.getNode());
5318     AddToWorklist(Hi.getNode());
5319
5320     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5321   }
5322   return SDValue();
5323 }
5324
5325 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5326
5327   if (Level >= AfterLegalizeTypes)
5328     return SDValue();
5329
5330   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5331   SDValue Mask = MGT->getMask();
5332   SDLoc DL(N);
5333
5334   // If the MGATHER result requires splitting and the mask is provided by a
5335   // SETCC, then split both nodes and its operands before legalization. This
5336   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5337   // and enables future optimizations (e.g. min/max pattern matching on X86).
5338
5339   if (Mask.getOpcode() != ISD::SETCC)
5340     return SDValue();
5341
5342   EVT VT = N->getValueType(0);
5343
5344   // Check if any splitting is required.
5345   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5346       TargetLowering::TypeSplitVector)
5347     return SDValue();
5348
5349   SDValue MaskLo, MaskHi, Lo, Hi;
5350   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5351
5352   SDValue Src0 = MGT->getValue();
5353   SDValue Src0Lo, Src0Hi;
5354   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5355
5356   EVT LoVT, HiVT;
5357   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5358
5359   SDValue Chain = MGT->getChain();
5360   EVT MemoryVT = MGT->getMemoryVT();
5361   unsigned Alignment = MGT->getOriginalAlignment();
5362
5363   EVT LoMemVT, HiMemVT;
5364   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5365
5366   SDValue BasePtr = MGT->getBasePtr();
5367   SDValue Index = MGT->getIndex();
5368   SDValue IndexLo, IndexHi;
5369   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5370
5371   MachineMemOperand *MMO = DAG.getMachineFunction().
5372     getMachineMemOperand(MGT->getPointerInfo(),
5373                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5374                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5375
5376   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5377   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5378                             MMO);
5379
5380   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5381   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5382                             MMO);
5383
5384   AddToWorklist(Lo.getNode());
5385   AddToWorklist(Hi.getNode());
5386
5387   // Build a factor node to remember that this load is independent of the
5388   // other one.
5389   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5390                       Hi.getValue(1));
5391
5392   // Legalized the chain result - switch anything that used the old chain to
5393   // use the new one.
5394   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5395
5396   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5397
5398   SDValue RetOps[] = { GatherRes, Chain };
5399   return DAG.getMergeValues(RetOps, DL);
5400 }
5401
5402 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5403
5404   if (Level >= AfterLegalizeTypes)
5405     return SDValue();
5406
5407   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5408   SDValue Mask = MLD->getMask();
5409   SDLoc DL(N);
5410
5411   // If the MLOAD result requires splitting and the mask is provided by a
5412   // SETCC, then split both nodes and its operands before legalization. This
5413   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5414   // and enables future optimizations (e.g. min/max pattern matching on X86).
5415
5416   if (Mask.getOpcode() == ISD::SETCC) {
5417     EVT VT = N->getValueType(0);
5418
5419     // Check if any splitting is required.
5420     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5421         TargetLowering::TypeSplitVector)
5422       return SDValue();
5423
5424     SDValue MaskLo, MaskHi, Lo, Hi;
5425     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5426
5427     SDValue Src0 = MLD->getSrc0();
5428     SDValue Src0Lo, Src0Hi;
5429     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5430
5431     EVT LoVT, HiVT;
5432     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5433
5434     SDValue Chain = MLD->getChain();
5435     SDValue Ptr   = MLD->getBasePtr();
5436     EVT MemoryVT = MLD->getMemoryVT();
5437     unsigned Alignment = MLD->getOriginalAlignment();
5438
5439     // if Alignment is equal to the vector size,
5440     // take the half of it for the second part
5441     unsigned SecondHalfAlignment =
5442       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5443          Alignment/2 : Alignment;
5444
5445     EVT LoMemVT, HiMemVT;
5446     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5447
5448     MachineMemOperand *MMO = DAG.getMachineFunction().
5449     getMachineMemOperand(MLD->getPointerInfo(),
5450                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5451                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5452
5453     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5454                            ISD::NON_EXTLOAD);
5455
5456     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5457     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5458                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5459
5460     MMO = DAG.getMachineFunction().
5461     getMachineMemOperand(MLD->getPointerInfo(),
5462                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5463                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5464
5465     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5466                            ISD::NON_EXTLOAD);
5467
5468     AddToWorklist(Lo.getNode());
5469     AddToWorklist(Hi.getNode());
5470
5471     // Build a factor node to remember that this load is independent of the
5472     // other one.
5473     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5474                         Hi.getValue(1));
5475
5476     // Legalized the chain result - switch anything that used the old chain to
5477     // use the new one.
5478     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5479
5480     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5481
5482     SDValue RetOps[] = { LoadRes, Chain };
5483     return DAG.getMergeValues(RetOps, DL);
5484   }
5485   return SDValue();
5486 }
5487
5488 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5489   SDValue N0 = N->getOperand(0);
5490   SDValue N1 = N->getOperand(1);
5491   SDValue N2 = N->getOperand(2);
5492   SDLoc DL(N);
5493
5494   // Canonicalize integer abs.
5495   // vselect (setg[te] X,  0),  X, -X ->
5496   // vselect (setgt    X, -1),  X, -X ->
5497   // vselect (setl[te] X,  0), -X,  X ->
5498   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5499   if (N0.getOpcode() == ISD::SETCC) {
5500     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5501     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5502     bool isAbs = false;
5503     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5504
5505     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5506          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5507         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5508       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5509     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5510              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5511       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5512
5513     if (isAbs) {
5514       EVT VT = LHS.getValueType();
5515       SDValue Shift = DAG.getNode(
5516           ISD::SRA, DL, VT, LHS,
5517           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5518       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5519       AddToWorklist(Shift.getNode());
5520       AddToWorklist(Add.getNode());
5521       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5522     }
5523   }
5524
5525   if (SimplifySelectOps(N, N1, N2))
5526     return SDValue(N, 0);  // Don't revisit N.
5527
5528   // If the VSELECT result requires splitting and the mask is provided by a
5529   // SETCC, then split both nodes and its operands before legalization. This
5530   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5531   // and enables future optimizations (e.g. min/max pattern matching on X86).
5532   if (N0.getOpcode() == ISD::SETCC) {
5533     EVT VT = N->getValueType(0);
5534
5535     // Check if any splitting is required.
5536     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5537         TargetLowering::TypeSplitVector)
5538       return SDValue();
5539
5540     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5541     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5542     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5543     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5544
5545     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5546     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5547
5548     // Add the new VSELECT nodes to the work list in case they need to be split
5549     // again.
5550     AddToWorklist(Lo.getNode());
5551     AddToWorklist(Hi.getNode());
5552
5553     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5554   }
5555
5556   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5557   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5558     return N1;
5559   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5560   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5561     return N2;
5562
5563   // The ConvertSelectToConcatVector function is assuming both the above
5564   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5565   // and addressed.
5566   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5567       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5568       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5569     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5570       return CV;
5571   }
5572
5573   return SDValue();
5574 }
5575
5576 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5577   SDValue N0 = N->getOperand(0);
5578   SDValue N1 = N->getOperand(1);
5579   SDValue N2 = N->getOperand(2);
5580   SDValue N3 = N->getOperand(3);
5581   SDValue N4 = N->getOperand(4);
5582   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5583
5584   // fold select_cc lhs, rhs, x, x, cc -> x
5585   if (N2 == N3)
5586     return N2;
5587
5588   // Determine if the condition we're dealing with is constant
5589   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5590                               N0, N1, CC, SDLoc(N), false);
5591   if (SCC.getNode()) {
5592     AddToWorklist(SCC.getNode());
5593
5594     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5595       if (!SCCC->isNullValue())
5596         return N2;    // cond always true -> true val
5597       else
5598         return N3;    // cond always false -> false val
5599     } else if (SCC->getOpcode() == ISD::UNDEF) {
5600       // When the condition is UNDEF, just return the first operand. This is
5601       // coherent the DAG creation, no setcc node is created in this case
5602       return N2;
5603     } else if (SCC.getOpcode() == ISD::SETCC) {
5604       // Fold to a simpler select_cc
5605       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5606                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5607                          SCC.getOperand(2));
5608     }
5609   }
5610
5611   // If we can fold this based on the true/false value, do so.
5612   if (SimplifySelectOps(N, N2, N3))
5613     return SDValue(N, 0);  // Don't revisit N.
5614
5615   // fold select_cc into other things, such as min/max/abs
5616   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5617 }
5618
5619 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5620   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5621                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5622                        SDLoc(N));
5623 }
5624
5625 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5626 /// a build_vector of constants.
5627 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5628 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5629 /// Vector extends are not folded if operations are legal; this is to
5630 /// avoid introducing illegal build_vector dag nodes.
5631 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5632                                          SelectionDAG &DAG, bool LegalTypes,
5633                                          bool LegalOperations) {
5634   unsigned Opcode = N->getOpcode();
5635   SDValue N0 = N->getOperand(0);
5636   EVT VT = N->getValueType(0);
5637
5638   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5639          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5640          && "Expected EXTEND dag node in input!");
5641
5642   // fold (sext c1) -> c1
5643   // fold (zext c1) -> c1
5644   // fold (aext c1) -> c1
5645   if (isa<ConstantSDNode>(N0))
5646     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5647
5648   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5649   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5650   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5651   EVT SVT = VT.getScalarType();
5652   if (!(VT.isVector() &&
5653       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5654       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5655     return nullptr;
5656
5657   // We can fold this node into a build_vector.
5658   unsigned VTBits = SVT.getSizeInBits();
5659   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5660   SmallVector<SDValue, 8> Elts;
5661   unsigned NumElts = VT.getVectorNumElements();
5662   SDLoc DL(N);
5663
5664   for (unsigned i=0; i != NumElts; ++i) {
5665     SDValue Op = N0->getOperand(i);
5666     if (Op->getOpcode() == ISD::UNDEF) {
5667       Elts.push_back(DAG.getUNDEF(SVT));
5668       continue;
5669     }
5670
5671     SDLoc DL(Op);
5672     // Get the constant value and if needed trunc it to the size of the type.
5673     // Nodes like build_vector might have constants wider than the scalar type.
5674     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5675     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5676       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5677     else
5678       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5679   }
5680
5681   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5682 }
5683
5684 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5685 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5686 // transformation. Returns true if extension are possible and the above
5687 // mentioned transformation is profitable.
5688 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5689                                     unsigned ExtOpc,
5690                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5691                                     const TargetLowering &TLI) {
5692   bool HasCopyToRegUses = false;
5693   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5694   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5695                             UE = N0.getNode()->use_end();
5696        UI != UE; ++UI) {
5697     SDNode *User = *UI;
5698     if (User == N)
5699       continue;
5700     if (UI.getUse().getResNo() != N0.getResNo())
5701       continue;
5702     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5703     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5704       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5705       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5706         // Sign bits will be lost after a zext.
5707         return false;
5708       bool Add = false;
5709       for (unsigned i = 0; i != 2; ++i) {
5710         SDValue UseOp = User->getOperand(i);
5711         if (UseOp == N0)
5712           continue;
5713         if (!isa<ConstantSDNode>(UseOp))
5714           return false;
5715         Add = true;
5716       }
5717       if (Add)
5718         ExtendNodes.push_back(User);
5719       continue;
5720     }
5721     // If truncates aren't free and there are users we can't
5722     // extend, it isn't worthwhile.
5723     if (!isTruncFree)
5724       return false;
5725     // Remember if this value is live-out.
5726     if (User->getOpcode() == ISD::CopyToReg)
5727       HasCopyToRegUses = true;
5728   }
5729
5730   if (HasCopyToRegUses) {
5731     bool BothLiveOut = false;
5732     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5733          UI != UE; ++UI) {
5734       SDUse &Use = UI.getUse();
5735       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5736         BothLiveOut = true;
5737         break;
5738       }
5739     }
5740     if (BothLiveOut)
5741       // Both unextended and extended values are live out. There had better be
5742       // a good reason for the transformation.
5743       return ExtendNodes.size();
5744   }
5745   return true;
5746 }
5747
5748 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5749                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5750                                   ISD::NodeType ExtType) {
5751   // Extend SetCC uses if necessary.
5752   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5753     SDNode *SetCC = SetCCs[i];
5754     SmallVector<SDValue, 4> Ops;
5755
5756     for (unsigned j = 0; j != 2; ++j) {
5757       SDValue SOp = SetCC->getOperand(j);
5758       if (SOp == Trunc)
5759         Ops.push_back(ExtLoad);
5760       else
5761         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5762     }
5763
5764     Ops.push_back(SetCC->getOperand(2));
5765     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5766   }
5767 }
5768
5769 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5770 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5771   SDValue N0 = N->getOperand(0);
5772   EVT DstVT = N->getValueType(0);
5773   EVT SrcVT = N0.getValueType();
5774
5775   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5776           N->getOpcode() == ISD::ZERO_EXTEND) &&
5777          "Unexpected node type (not an extend)!");
5778
5779   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5780   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5781   //   (v8i32 (sext (v8i16 (load x))))
5782   // into:
5783   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5784   //                          (v4i32 (sextload (x + 16)))))
5785   // Where uses of the original load, i.e.:
5786   //   (v8i16 (load x))
5787   // are replaced with:
5788   //   (v8i16 (truncate
5789   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5790   //                            (v4i32 (sextload (x + 16)))))))
5791   //
5792   // This combine is only applicable to illegal, but splittable, vectors.
5793   // All legal types, and illegal non-vector types, are handled elsewhere.
5794   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5795   //
5796   if (N0->getOpcode() != ISD::LOAD)
5797     return SDValue();
5798
5799   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5800
5801   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5802       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5803       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5804     return SDValue();
5805
5806   SmallVector<SDNode *, 4> SetCCs;
5807   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5808     return SDValue();
5809
5810   ISD::LoadExtType ExtType =
5811       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5812
5813   // Try to split the vector types to get down to legal types.
5814   EVT SplitSrcVT = SrcVT;
5815   EVT SplitDstVT = DstVT;
5816   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5817          SplitSrcVT.getVectorNumElements() > 1) {
5818     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5819     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5820   }
5821
5822   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5823     return SDValue();
5824
5825   SDLoc DL(N);
5826   const unsigned NumSplits =
5827       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5828   const unsigned Stride = SplitSrcVT.getStoreSize();
5829   SmallVector<SDValue, 4> Loads;
5830   SmallVector<SDValue, 4> Chains;
5831
5832   SDValue BasePtr = LN0->getBasePtr();
5833   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5834     const unsigned Offset = Idx * Stride;
5835     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5836
5837     SDValue SplitLoad = DAG.getExtLoad(
5838         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5839         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5840         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5841         Align, LN0->getAAInfo());
5842
5843     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5844                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5845
5846     Loads.push_back(SplitLoad.getValue(0));
5847     Chains.push_back(SplitLoad.getValue(1));
5848   }
5849
5850   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5851   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5852
5853   CombineTo(N, NewValue);
5854
5855   // Replace uses of the original load (before extension)
5856   // with a truncate of the concatenated sextloaded vectors.
5857   SDValue Trunc =
5858       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5859   CombineTo(N0.getNode(), Trunc, NewChain);
5860   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5861                   (ISD::NodeType)N->getOpcode());
5862   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5863 }
5864
5865 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5866   SDValue N0 = N->getOperand(0);
5867   EVT VT = N->getValueType(0);
5868
5869   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5870                                               LegalOperations))
5871     return SDValue(Res, 0);
5872
5873   // fold (sext (sext x)) -> (sext x)
5874   // fold (sext (aext x)) -> (sext x)
5875   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5876     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5877                        N0.getOperand(0));
5878
5879   if (N0.getOpcode() == ISD::TRUNCATE) {
5880     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5881     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5882     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5883       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5884       if (NarrowLoad.getNode() != N0.getNode()) {
5885         CombineTo(N0.getNode(), NarrowLoad);
5886         // CombineTo deleted the truncate, if needed, but not what's under it.
5887         AddToWorklist(oye);
5888       }
5889       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5890     }
5891
5892     // See if the value being truncated is already sign extended.  If so, just
5893     // eliminate the trunc/sext pair.
5894     SDValue Op = N0.getOperand(0);
5895     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5896     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5897     unsigned DestBits = VT.getScalarType().getSizeInBits();
5898     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5899
5900     if (OpBits == DestBits) {
5901       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5902       // bits, it is already ready.
5903       if (NumSignBits > DestBits-MidBits)
5904         return Op;
5905     } else if (OpBits < DestBits) {
5906       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5907       // bits, just sext from i32.
5908       if (NumSignBits > OpBits-MidBits)
5909         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5910     } else {
5911       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5912       // bits, just truncate to i32.
5913       if (NumSignBits > OpBits-MidBits)
5914         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5915     }
5916
5917     // fold (sext (truncate x)) -> (sextinreg x).
5918     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5919                                                  N0.getValueType())) {
5920       if (OpBits < DestBits)
5921         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5922       else if (OpBits > DestBits)
5923         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5924       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5925                          DAG.getValueType(N0.getValueType()));
5926     }
5927   }
5928
5929   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5930   // Only generate vector extloads when 1) they're legal, and 2) they are
5931   // deemed desirable by the target.
5932   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5933       ((!LegalOperations && !VT.isVector() &&
5934         !cast<LoadSDNode>(N0)->isVolatile()) ||
5935        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5936     bool DoXform = true;
5937     SmallVector<SDNode*, 4> SetCCs;
5938     if (!N0.hasOneUse())
5939       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5940     if (VT.isVector())
5941       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5942     if (DoXform) {
5943       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5944       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5945                                        LN0->getChain(),
5946                                        LN0->getBasePtr(), N0.getValueType(),
5947                                        LN0->getMemOperand());
5948       CombineTo(N, ExtLoad);
5949       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5950                                   N0.getValueType(), ExtLoad);
5951       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5952       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5953                       ISD::SIGN_EXTEND);
5954       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5955     }
5956   }
5957
5958   // fold (sext (load x)) to multiple smaller sextloads.
5959   // Only on illegal but splittable vectors.
5960   if (SDValue ExtLoad = CombineExtLoad(N))
5961     return ExtLoad;
5962
5963   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5964   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5965   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5966       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5967     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5968     EVT MemVT = LN0->getMemoryVT();
5969     if ((!LegalOperations && !LN0->isVolatile()) ||
5970         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5971       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5972                                        LN0->getChain(),
5973                                        LN0->getBasePtr(), MemVT,
5974                                        LN0->getMemOperand());
5975       CombineTo(N, ExtLoad);
5976       CombineTo(N0.getNode(),
5977                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5978                             N0.getValueType(), ExtLoad),
5979                 ExtLoad.getValue(1));
5980       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5981     }
5982   }
5983
5984   // fold (sext (and/or/xor (load x), cst)) ->
5985   //      (and/or/xor (sextload x), (sext cst))
5986   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5987        N0.getOpcode() == ISD::XOR) &&
5988       isa<LoadSDNode>(N0.getOperand(0)) &&
5989       N0.getOperand(1).getOpcode() == ISD::Constant &&
5990       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5991       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5992     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5993     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5994       bool DoXform = true;
5995       SmallVector<SDNode*, 4> SetCCs;
5996       if (!N0.hasOneUse())
5997         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5998                                           SetCCs, TLI);
5999       if (DoXform) {
6000         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6001                                          LN0->getChain(), LN0->getBasePtr(),
6002                                          LN0->getMemoryVT(),
6003                                          LN0->getMemOperand());
6004         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6005         Mask = Mask.sext(VT.getSizeInBits());
6006         SDLoc DL(N);
6007         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6008                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6009         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6010                                     SDLoc(N0.getOperand(0)),
6011                                     N0.getOperand(0).getValueType(), ExtLoad);
6012         CombineTo(N, And);
6013         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6014         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6015                         ISD::SIGN_EXTEND);
6016         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6017       }
6018     }
6019   }
6020
6021   if (N0.getOpcode() == ISD::SETCC) {
6022     EVT N0VT = N0.getOperand(0).getValueType();
6023     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6024     // Only do this before legalize for now.
6025     if (VT.isVector() && !LegalOperations &&
6026         TLI.getBooleanContents(N0VT) ==
6027             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6028       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6029       // of the same size as the compared operands. Only optimize sext(setcc())
6030       // if this is the case.
6031       EVT SVT = getSetCCResultType(N0VT);
6032
6033       // We know that the # elements of the results is the same as the
6034       // # elements of the compare (and the # elements of the compare result
6035       // for that matter).  Check to see that they are the same size.  If so,
6036       // we know that the element size of the sext'd result matches the
6037       // element size of the compare operands.
6038       if (VT.getSizeInBits() == SVT.getSizeInBits())
6039         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6040                              N0.getOperand(1),
6041                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6042
6043       // If the desired elements are smaller or larger than the source
6044       // elements we can use a matching integer vector type and then
6045       // truncate/sign extend
6046       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6047       if (SVT == MatchingVectorType) {
6048         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6049                                N0.getOperand(0), N0.getOperand(1),
6050                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6051         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6052       }
6053     }
6054
6055     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6056     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6057     SDLoc DL(N);
6058     SDValue NegOne =
6059       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6060     SDValue SCC =
6061       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6062                        NegOne, DAG.getConstant(0, DL, VT),
6063                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6064     if (SCC.getNode()) return SCC;
6065
6066     if (!VT.isVector()) {
6067       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6068       if (!LegalOperations ||
6069           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6070         SDLoc DL(N);
6071         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6072         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6073                                      N0.getOperand(0), N0.getOperand(1), CC);
6074         return DAG.getSelect(DL, VT, SetCC,
6075                              NegOne, DAG.getConstant(0, DL, VT));
6076       }
6077     }
6078   }
6079
6080   // fold (sext x) -> (zext x) if the sign bit is known zero.
6081   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6082       DAG.SignBitIsZero(N0))
6083     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6084
6085   return SDValue();
6086 }
6087
6088 // isTruncateOf - If N is a truncate of some other value, return true, record
6089 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6090 // This function computes KnownZero to avoid a duplicated call to
6091 // computeKnownBits in the caller.
6092 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6093                          APInt &KnownZero) {
6094   APInt KnownOne;
6095   if (N->getOpcode() == ISD::TRUNCATE) {
6096     Op = N->getOperand(0);
6097     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6098     return true;
6099   }
6100
6101   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6102       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6103     return false;
6104
6105   SDValue Op0 = N->getOperand(0);
6106   SDValue Op1 = N->getOperand(1);
6107   assert(Op0.getValueType() == Op1.getValueType());
6108
6109   if (isNullConstant(Op0))
6110     Op = Op1;
6111   else if (isNullConstant(Op1))
6112     Op = Op0;
6113   else
6114     return false;
6115
6116   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6117
6118   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6119     return false;
6120
6121   return true;
6122 }
6123
6124 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6125   SDValue N0 = N->getOperand(0);
6126   EVT VT = N->getValueType(0);
6127
6128   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6129                                               LegalOperations))
6130     return SDValue(Res, 0);
6131
6132   // fold (zext (zext x)) -> (zext x)
6133   // fold (zext (aext x)) -> (zext x)
6134   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6135     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6136                        N0.getOperand(0));
6137
6138   // fold (zext (truncate x)) -> (zext x) or
6139   //      (zext (truncate x)) -> (truncate x)
6140   // This is valid when the truncated bits of x are already zero.
6141   // FIXME: We should extend this to work for vectors too.
6142   SDValue Op;
6143   APInt KnownZero;
6144   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6145     APInt TruncatedBits =
6146       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6147       APInt(Op.getValueSizeInBits(), 0) :
6148       APInt::getBitsSet(Op.getValueSizeInBits(),
6149                         N0.getValueSizeInBits(),
6150                         std::min(Op.getValueSizeInBits(),
6151                                  VT.getSizeInBits()));
6152     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6153       if (VT.bitsGT(Op.getValueType()))
6154         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6155       if (VT.bitsLT(Op.getValueType()))
6156         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6157
6158       return Op;
6159     }
6160   }
6161
6162   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6163   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6164   if (N0.getOpcode() == ISD::TRUNCATE) {
6165     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6166       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6167       if (NarrowLoad.getNode() != N0.getNode()) {
6168         CombineTo(N0.getNode(), NarrowLoad);
6169         // CombineTo deleted the truncate, if needed, but not what's under it.
6170         AddToWorklist(oye);
6171       }
6172       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6173     }
6174   }
6175
6176   // fold (zext (truncate x)) -> (and x, mask)
6177   if (N0.getOpcode() == ISD::TRUNCATE) {
6178     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6179     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6180     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6181       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6182       if (NarrowLoad.getNode() != N0.getNode()) {
6183         CombineTo(N0.getNode(), NarrowLoad);
6184         // CombineTo deleted the truncate, if needed, but not what's under it.
6185         AddToWorklist(oye);
6186       }
6187       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6188     }
6189
6190     EVT SrcVT = N0.getOperand(0).getValueType();
6191     EVT MinVT = N0.getValueType();
6192
6193     // Try to mask before the extension to avoid having to generate a larger mask,
6194     // possibly over several sub-vectors.
6195     if (SrcVT.bitsLT(VT)) {
6196       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6197                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6198         SDValue Op = N0.getOperand(0);
6199         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6200         AddToWorklist(Op.getNode());
6201         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6202       }
6203     }
6204
6205     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6206       SDValue Op = N0.getOperand(0);
6207       if (SrcVT.bitsLT(VT)) {
6208         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6209         AddToWorklist(Op.getNode());
6210       } else if (SrcVT.bitsGT(VT)) {
6211         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6212         AddToWorklist(Op.getNode());
6213       }
6214       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6215     }
6216   }
6217
6218   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6219   // if either of the casts is not free.
6220   if (N0.getOpcode() == ISD::AND &&
6221       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6222       N0.getOperand(1).getOpcode() == ISD::Constant &&
6223       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6224                            N0.getValueType()) ||
6225        !TLI.isZExtFree(N0.getValueType(), VT))) {
6226     SDValue X = N0.getOperand(0).getOperand(0);
6227     if (X.getValueType().bitsLT(VT)) {
6228       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6229     } else if (X.getValueType().bitsGT(VT)) {
6230       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6231     }
6232     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6233     Mask = Mask.zext(VT.getSizeInBits());
6234     SDLoc DL(N);
6235     return DAG.getNode(ISD::AND, DL, VT,
6236                        X, DAG.getConstant(Mask, DL, VT));
6237   }
6238
6239   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6240   // Only generate vector extloads when 1) they're legal, and 2) they are
6241   // deemed desirable by the target.
6242   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6243       ((!LegalOperations && !VT.isVector() &&
6244         !cast<LoadSDNode>(N0)->isVolatile()) ||
6245        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6246     bool DoXform = true;
6247     SmallVector<SDNode*, 4> SetCCs;
6248     if (!N0.hasOneUse())
6249       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6250     if (VT.isVector())
6251       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6252     if (DoXform) {
6253       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6254       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6255                                        LN0->getChain(),
6256                                        LN0->getBasePtr(), N0.getValueType(),
6257                                        LN0->getMemOperand());
6258       CombineTo(N, ExtLoad);
6259       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6260                                   N0.getValueType(), ExtLoad);
6261       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6262
6263       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6264                       ISD::ZERO_EXTEND);
6265       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6266     }
6267   }
6268
6269   // fold (zext (load x)) to multiple smaller zextloads.
6270   // Only on illegal but splittable vectors.
6271   if (SDValue ExtLoad = CombineExtLoad(N))
6272     return ExtLoad;
6273
6274   // fold (zext (and/or/xor (load x), cst)) ->
6275   //      (and/or/xor (zextload x), (zext cst))
6276   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6277        N0.getOpcode() == ISD::XOR) &&
6278       isa<LoadSDNode>(N0.getOperand(0)) &&
6279       N0.getOperand(1).getOpcode() == ISD::Constant &&
6280       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6281       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6282     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6283     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6284       bool DoXform = true;
6285       SmallVector<SDNode*, 4> SetCCs;
6286       if (!N0.hasOneUse())
6287         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6288                                           SetCCs, TLI);
6289       if (DoXform) {
6290         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6291                                          LN0->getChain(), LN0->getBasePtr(),
6292                                          LN0->getMemoryVT(),
6293                                          LN0->getMemOperand());
6294         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6295         Mask = Mask.zext(VT.getSizeInBits());
6296         SDLoc DL(N);
6297         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6298                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6299         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6300                                     SDLoc(N0.getOperand(0)),
6301                                     N0.getOperand(0).getValueType(), ExtLoad);
6302         CombineTo(N, And);
6303         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6304         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6305                         ISD::ZERO_EXTEND);
6306         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6307       }
6308     }
6309   }
6310
6311   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6312   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6313   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6314       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6315     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6316     EVT MemVT = LN0->getMemoryVT();
6317     if ((!LegalOperations && !LN0->isVolatile()) ||
6318         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6319       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6320                                        LN0->getChain(),
6321                                        LN0->getBasePtr(), MemVT,
6322                                        LN0->getMemOperand());
6323       CombineTo(N, ExtLoad);
6324       CombineTo(N0.getNode(),
6325                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6326                             ExtLoad),
6327                 ExtLoad.getValue(1));
6328       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6329     }
6330   }
6331
6332   if (N0.getOpcode() == ISD::SETCC) {
6333     if (!LegalOperations && VT.isVector() &&
6334         N0.getValueType().getVectorElementType() == MVT::i1) {
6335       EVT N0VT = N0.getOperand(0).getValueType();
6336       if (getSetCCResultType(N0VT) == N0.getValueType())
6337         return SDValue();
6338
6339       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6340       // Only do this before legalize for now.
6341       EVT EltVT = VT.getVectorElementType();
6342       SDLoc DL(N);
6343       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6344                                     DAG.getConstant(1, DL, EltVT));
6345       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6346         // We know that the # elements of the results is the same as the
6347         // # elements of the compare (and the # elements of the compare result
6348         // for that matter).  Check to see that they are the same size.  If so,
6349         // we know that the element size of the sext'd result matches the
6350         // element size of the compare operands.
6351         return DAG.getNode(ISD::AND, DL, VT,
6352                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6353                                          N0.getOperand(1),
6354                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6355                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6356                                        OneOps));
6357
6358       // If the desired elements are smaller or larger than the source
6359       // elements we can use a matching integer vector type and then
6360       // truncate/sign extend
6361       EVT MatchingElementType =
6362         EVT::getIntegerVT(*DAG.getContext(),
6363                           N0VT.getScalarType().getSizeInBits());
6364       EVT MatchingVectorType =
6365         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6366                          N0VT.getVectorNumElements());
6367       SDValue VsetCC =
6368         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6369                       N0.getOperand(1),
6370                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6371       return DAG.getNode(ISD::AND, DL, VT,
6372                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6373                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6374     }
6375
6376     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6377     SDLoc DL(N);
6378     SDValue SCC =
6379       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6380                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6381                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6382     if (SCC.getNode()) return SCC;
6383   }
6384
6385   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6386   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6387       isa<ConstantSDNode>(N0.getOperand(1)) &&
6388       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6389       N0.hasOneUse()) {
6390     SDValue ShAmt = N0.getOperand(1);
6391     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6392     if (N0.getOpcode() == ISD::SHL) {
6393       SDValue InnerZExt = N0.getOperand(0);
6394       // If the original shl may be shifting out bits, do not perform this
6395       // transformation.
6396       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6397         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6398       if (ShAmtVal > KnownZeroBits)
6399         return SDValue();
6400     }
6401
6402     SDLoc DL(N);
6403
6404     // Ensure that the shift amount is wide enough for the shifted value.
6405     if (VT.getSizeInBits() >= 256)
6406       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6407
6408     return DAG.getNode(N0.getOpcode(), DL, VT,
6409                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6410                        ShAmt);
6411   }
6412
6413   return SDValue();
6414 }
6415
6416 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6417   SDValue N0 = N->getOperand(0);
6418   EVT VT = N->getValueType(0);
6419
6420   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6421                                               LegalOperations))
6422     return SDValue(Res, 0);
6423
6424   // fold (aext (aext x)) -> (aext x)
6425   // fold (aext (zext x)) -> (zext x)
6426   // fold (aext (sext x)) -> (sext x)
6427   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6428       N0.getOpcode() == ISD::ZERO_EXTEND ||
6429       N0.getOpcode() == ISD::SIGN_EXTEND)
6430     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6431
6432   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6433   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6434   if (N0.getOpcode() == ISD::TRUNCATE) {
6435     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6436       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6437       if (NarrowLoad.getNode() != N0.getNode()) {
6438         CombineTo(N0.getNode(), NarrowLoad);
6439         // CombineTo deleted the truncate, if needed, but not what's under it.
6440         AddToWorklist(oye);
6441       }
6442       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6443     }
6444   }
6445
6446   // fold (aext (truncate x))
6447   if (N0.getOpcode() == ISD::TRUNCATE) {
6448     SDValue TruncOp = N0.getOperand(0);
6449     if (TruncOp.getValueType() == VT)
6450       return TruncOp; // x iff x size == zext size.
6451     if (TruncOp.getValueType().bitsGT(VT))
6452       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6453     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6454   }
6455
6456   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6457   // if the trunc is not free.
6458   if (N0.getOpcode() == ISD::AND &&
6459       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6460       N0.getOperand(1).getOpcode() == ISD::Constant &&
6461       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6462                           N0.getValueType())) {
6463     SDValue X = N0.getOperand(0).getOperand(0);
6464     if (X.getValueType().bitsLT(VT)) {
6465       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6466     } else if (X.getValueType().bitsGT(VT)) {
6467       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6468     }
6469     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6470     Mask = Mask.zext(VT.getSizeInBits());
6471     SDLoc DL(N);
6472     return DAG.getNode(ISD::AND, DL, VT,
6473                        X, DAG.getConstant(Mask, DL, VT));
6474   }
6475
6476   // fold (aext (load x)) -> (aext (truncate (extload x)))
6477   // None of the supported targets knows how to perform load and any_ext
6478   // on vectors in one instruction.  We only perform this transformation on
6479   // scalars.
6480   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6481       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6482       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6483     bool DoXform = true;
6484     SmallVector<SDNode*, 4> SetCCs;
6485     if (!N0.hasOneUse())
6486       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6487     if (DoXform) {
6488       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6489       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6490                                        LN0->getChain(),
6491                                        LN0->getBasePtr(), N0.getValueType(),
6492                                        LN0->getMemOperand());
6493       CombineTo(N, ExtLoad);
6494       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6495                                   N0.getValueType(), ExtLoad);
6496       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6497       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6498                       ISD::ANY_EXTEND);
6499       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6500     }
6501   }
6502
6503   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6504   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6505   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6506   if (N0.getOpcode() == ISD::LOAD &&
6507       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6508       N0.hasOneUse()) {
6509     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6510     ISD::LoadExtType ExtType = LN0->getExtensionType();
6511     EVT MemVT = LN0->getMemoryVT();
6512     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6513       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6514                                        VT, LN0->getChain(), LN0->getBasePtr(),
6515                                        MemVT, LN0->getMemOperand());
6516       CombineTo(N, ExtLoad);
6517       CombineTo(N0.getNode(),
6518                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6519                             N0.getValueType(), ExtLoad),
6520                 ExtLoad.getValue(1));
6521       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6522     }
6523   }
6524
6525   if (N0.getOpcode() == ISD::SETCC) {
6526     // For vectors:
6527     // aext(setcc) -> vsetcc
6528     // aext(setcc) -> truncate(vsetcc)
6529     // aext(setcc) -> aext(vsetcc)
6530     // Only do this before legalize for now.
6531     if (VT.isVector() && !LegalOperations) {
6532       EVT N0VT = N0.getOperand(0).getValueType();
6533         // We know that the # elements of the results is the same as the
6534         // # elements of the compare (and the # elements of the compare result
6535         // for that matter).  Check to see that they are the same size.  If so,
6536         // we know that the element size of the sext'd result matches the
6537         // element size of the compare operands.
6538       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6539         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6540                              N0.getOperand(1),
6541                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6542       // If the desired elements are smaller or larger than the source
6543       // elements we can use a matching integer vector type and then
6544       // truncate/any extend
6545       else {
6546         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6547         SDValue VsetCC =
6548           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6549                         N0.getOperand(1),
6550                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6551         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6552       }
6553     }
6554
6555     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6556     SDLoc DL(N);
6557     SDValue SCC =
6558       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6559                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6560                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6561     if (SCC.getNode())
6562       return SCC;
6563   }
6564
6565   return SDValue();
6566 }
6567
6568 /// See if the specified operand can be simplified with the knowledge that only
6569 /// the bits specified by Mask are used.  If so, return the simpler operand,
6570 /// otherwise return a null SDValue.
6571 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6572   switch (V.getOpcode()) {
6573   default: break;
6574   case ISD::Constant: {
6575     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6576     assert(CV && "Const value should be ConstSDNode.");
6577     const APInt &CVal = CV->getAPIntValue();
6578     APInt NewVal = CVal & Mask;
6579     if (NewVal != CVal)
6580       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6581     break;
6582   }
6583   case ISD::OR:
6584   case ISD::XOR:
6585     // If the LHS or RHS don't contribute bits to the or, drop them.
6586     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6587       return V.getOperand(1);
6588     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6589       return V.getOperand(0);
6590     break;
6591   case ISD::SRL:
6592     // Only look at single-use SRLs.
6593     if (!V.getNode()->hasOneUse())
6594       break;
6595     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6596       // See if we can recursively simplify the LHS.
6597       unsigned Amt = RHSC->getZExtValue();
6598
6599       // Watch out for shift count overflow though.
6600       if (Amt >= Mask.getBitWidth()) break;
6601       APInt NewMask = Mask << Amt;
6602       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6603         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6604                            SimplifyLHS, V.getOperand(1));
6605     }
6606   }
6607   return SDValue();
6608 }
6609
6610 /// If the result of a wider load is shifted to right of N  bits and then
6611 /// truncated to a narrower type and where N is a multiple of number of bits of
6612 /// the narrower type, transform it to a narrower load from address + N / num of
6613 /// bits of new type. If the result is to be extended, also fold the extension
6614 /// to form a extending load.
6615 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6616   unsigned Opc = N->getOpcode();
6617
6618   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6619   SDValue N0 = N->getOperand(0);
6620   EVT VT = N->getValueType(0);
6621   EVT ExtVT = VT;
6622
6623   // This transformation isn't valid for vector loads.
6624   if (VT.isVector())
6625     return SDValue();
6626
6627   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6628   // extended to VT.
6629   if (Opc == ISD::SIGN_EXTEND_INREG) {
6630     ExtType = ISD::SEXTLOAD;
6631     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6632   } else if (Opc == ISD::SRL) {
6633     // Another special-case: SRL is basically zero-extending a narrower value.
6634     ExtType = ISD::ZEXTLOAD;
6635     N0 = SDValue(N, 0);
6636     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6637     if (!N01) return SDValue();
6638     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6639                               VT.getSizeInBits() - N01->getZExtValue());
6640   }
6641   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6642     return SDValue();
6643
6644   unsigned EVTBits = ExtVT.getSizeInBits();
6645
6646   // Do not generate loads of non-round integer types since these can
6647   // be expensive (and would be wrong if the type is not byte sized).
6648   if (!ExtVT.isRound())
6649     return SDValue();
6650
6651   unsigned ShAmt = 0;
6652   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6653     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6654       ShAmt = N01->getZExtValue();
6655       // Is the shift amount a multiple of size of VT?
6656       if ((ShAmt & (EVTBits-1)) == 0) {
6657         N0 = N0.getOperand(0);
6658         // Is the load width a multiple of size of VT?
6659         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6660           return SDValue();
6661       }
6662
6663       // At this point, we must have a load or else we can't do the transform.
6664       if (!isa<LoadSDNode>(N0)) return SDValue();
6665
6666       // Because a SRL must be assumed to *need* to zero-extend the high bits
6667       // (as opposed to anyext the high bits), we can't combine the zextload
6668       // lowering of SRL and an sextload.
6669       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6670         return SDValue();
6671
6672       // If the shift amount is larger than the input type then we're not
6673       // accessing any of the loaded bytes.  If the load was a zextload/extload
6674       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6675       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6676         return SDValue();
6677     }
6678   }
6679
6680   // If the load is shifted left (and the result isn't shifted back right),
6681   // we can fold the truncate through the shift.
6682   unsigned ShLeftAmt = 0;
6683   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6684       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6685     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6686       ShLeftAmt = N01->getZExtValue();
6687       N0 = N0.getOperand(0);
6688     }
6689   }
6690
6691   // If we haven't found a load, we can't narrow it.  Don't transform one with
6692   // multiple uses, this would require adding a new load.
6693   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6694     return SDValue();
6695
6696   // Don't change the width of a volatile load.
6697   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6698   if (LN0->isVolatile())
6699     return SDValue();
6700
6701   // Verify that we are actually reducing a load width here.
6702   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6703     return SDValue();
6704
6705   // For the transform to be legal, the load must produce only two values
6706   // (the value loaded and the chain).  Don't transform a pre-increment
6707   // load, for example, which produces an extra value.  Otherwise the
6708   // transformation is not equivalent, and the downstream logic to replace
6709   // uses gets things wrong.
6710   if (LN0->getNumValues() > 2)
6711     return SDValue();
6712
6713   // If the load that we're shrinking is an extload and we're not just
6714   // discarding the extension we can't simply shrink the load. Bail.
6715   // TODO: It would be possible to merge the extensions in some cases.
6716   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6717       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6718     return SDValue();
6719
6720   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6721     return SDValue();
6722
6723   EVT PtrType = N0.getOperand(1).getValueType();
6724
6725   if (PtrType == MVT::Untyped || PtrType.isExtended())
6726     // It's not possible to generate a constant of extended or untyped type.
6727     return SDValue();
6728
6729   // For big endian targets, we need to adjust the offset to the pointer to
6730   // load the correct bytes.
6731   if (DAG.getDataLayout().isBigEndian()) {
6732     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6733     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6734     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6735   }
6736
6737   uint64_t PtrOff = ShAmt / 8;
6738   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6739   SDLoc DL(LN0);
6740   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6741                                PtrType, LN0->getBasePtr(),
6742                                DAG.getConstant(PtrOff, DL, PtrType));
6743   AddToWorklist(NewPtr.getNode());
6744
6745   SDValue Load;
6746   if (ExtType == ISD::NON_EXTLOAD)
6747     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6748                         LN0->getPointerInfo().getWithOffset(PtrOff),
6749                         LN0->isVolatile(), LN0->isNonTemporal(),
6750                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6751   else
6752     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6753                           LN0->getPointerInfo().getWithOffset(PtrOff),
6754                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6755                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6756
6757   // Replace the old load's chain with the new load's chain.
6758   WorklistRemover DeadNodes(*this);
6759   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6760
6761   // Shift the result left, if we've swallowed a left shift.
6762   SDValue Result = Load;
6763   if (ShLeftAmt != 0) {
6764     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6765     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6766       ShImmTy = VT;
6767     // If the shift amount is as large as the result size (but, presumably,
6768     // no larger than the source) then the useful bits of the result are
6769     // zero; we can't simply return the shortened shift, because the result
6770     // of that operation is undefined.
6771     SDLoc DL(N0);
6772     if (ShLeftAmt >= VT.getSizeInBits())
6773       Result = DAG.getConstant(0, DL, VT);
6774     else
6775       Result = DAG.getNode(ISD::SHL, DL, VT,
6776                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6777   }
6778
6779   // Return the new loaded value.
6780   return Result;
6781 }
6782
6783 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6784   SDValue N0 = N->getOperand(0);
6785   SDValue N1 = N->getOperand(1);
6786   EVT VT = N->getValueType(0);
6787   EVT EVT = cast<VTSDNode>(N1)->getVT();
6788   unsigned VTBits = VT.getScalarType().getSizeInBits();
6789   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6790
6791   // fold (sext_in_reg c1) -> c1
6792   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6793     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6794
6795   // If the input is already sign extended, just drop the extension.
6796   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6797     return N0;
6798
6799   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6800   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6801       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6802     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6803                        N0.getOperand(0), N1);
6804
6805   // fold (sext_in_reg (sext x)) -> (sext x)
6806   // fold (sext_in_reg (aext x)) -> (sext x)
6807   // if x is small enough.
6808   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6809     SDValue N00 = N0.getOperand(0);
6810     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6811         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6812       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6813   }
6814
6815   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6816   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6817     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6818
6819   // fold operands of sext_in_reg based on knowledge that the top bits are not
6820   // demanded.
6821   if (SimplifyDemandedBits(SDValue(N, 0)))
6822     return SDValue(N, 0);
6823
6824   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6825   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6826   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6827     return NarrowLoad;
6828
6829   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6830   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6831   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6832   if (N0.getOpcode() == ISD::SRL) {
6833     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6834       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6835         // We can turn this into an SRA iff the input to the SRL is already sign
6836         // extended enough.
6837         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6838         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6839           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6840                              N0.getOperand(0), N0.getOperand(1));
6841       }
6842   }
6843
6844   // fold (sext_inreg (extload x)) -> (sextload x)
6845   if (ISD::isEXTLoad(N0.getNode()) &&
6846       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6847       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6848       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6849        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6850     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6851     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6852                                      LN0->getChain(),
6853                                      LN0->getBasePtr(), EVT,
6854                                      LN0->getMemOperand());
6855     CombineTo(N, ExtLoad);
6856     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6857     AddToWorklist(ExtLoad.getNode());
6858     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6859   }
6860   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6861   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6862       N0.hasOneUse() &&
6863       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6864       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6865        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6866     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6867     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6868                                      LN0->getChain(),
6869                                      LN0->getBasePtr(), EVT,
6870                                      LN0->getMemOperand());
6871     CombineTo(N, ExtLoad);
6872     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6873     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6874   }
6875
6876   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6877   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6878     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6879                                        N0.getOperand(1), false);
6880     if (BSwap.getNode())
6881       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6882                          BSwap, N1);
6883   }
6884
6885   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6886   // into a build_vector.
6887   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6888     SmallVector<SDValue, 8> Elts;
6889     unsigned NumElts = N0->getNumOperands();
6890     unsigned ShAmt = VTBits - EVTBits;
6891
6892     for (unsigned i = 0; i != NumElts; ++i) {
6893       SDValue Op = N0->getOperand(i);
6894       if (Op->getOpcode() == ISD::UNDEF) {
6895         Elts.push_back(Op);
6896         continue;
6897       }
6898
6899       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6900       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6901       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6902                                      SDLoc(Op), Op.getValueType()));
6903     }
6904
6905     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6906   }
6907
6908   return SDValue();
6909 }
6910
6911 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6912   SDValue N0 = N->getOperand(0);
6913   EVT VT = N->getValueType(0);
6914
6915   if (N0.getOpcode() == ISD::UNDEF)
6916     return DAG.getUNDEF(VT);
6917
6918   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6919                                               LegalOperations))
6920     return SDValue(Res, 0);
6921
6922   return SDValue();
6923 }
6924
6925 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6926   SDValue N0 = N->getOperand(0);
6927   EVT VT = N->getValueType(0);
6928   bool isLE = DAG.getDataLayout().isLittleEndian();
6929
6930   // noop truncate
6931   if (N0.getValueType() == N->getValueType(0))
6932     return N0;
6933   // fold (truncate c1) -> c1
6934   if (isConstantIntBuildVectorOrConstantInt(N0))
6935     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6936   // fold (truncate (truncate x)) -> (truncate x)
6937   if (N0.getOpcode() == ISD::TRUNCATE)
6938     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6939   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6940   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6941       N0.getOpcode() == ISD::SIGN_EXTEND ||
6942       N0.getOpcode() == ISD::ANY_EXTEND) {
6943     if (N0.getOperand(0).getValueType().bitsLT(VT))
6944       // if the source is smaller than the dest, we still need an extend
6945       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6946                          N0.getOperand(0));
6947     if (N0.getOperand(0).getValueType().bitsGT(VT))
6948       // if the source is larger than the dest, than we just need the truncate
6949       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6950     // if the source and dest are the same type, we can drop both the extend
6951     // and the truncate.
6952     return N0.getOperand(0);
6953   }
6954
6955   // Fold extract-and-trunc into a narrow extract. For example:
6956   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6957   //   i32 y = TRUNCATE(i64 x)
6958   //        -- becomes --
6959   //   v16i8 b = BITCAST (v2i64 val)
6960   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6961   //
6962   // Note: We only run this optimization after type legalization (which often
6963   // creates this pattern) and before operation legalization after which
6964   // we need to be more careful about the vector instructions that we generate.
6965   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6966       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6967
6968     EVT VecTy = N0.getOperand(0).getValueType();
6969     EVT ExTy = N0.getValueType();
6970     EVT TrTy = N->getValueType(0);
6971
6972     unsigned NumElem = VecTy.getVectorNumElements();
6973     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6974
6975     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6976     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6977
6978     SDValue EltNo = N0->getOperand(1);
6979     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6980       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6981       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6982       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6983
6984       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6985                               NVT, N0.getOperand(0));
6986
6987       SDLoc DL(N);
6988       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6989                          DL, TrTy, V,
6990                          DAG.getConstant(Index, DL, IndexTy));
6991     }
6992   }
6993
6994   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6995   if (N0.getOpcode() == ISD::SELECT) {
6996     EVT SrcVT = N0.getValueType();
6997     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6998         TLI.isTruncateFree(SrcVT, VT)) {
6999       SDLoc SL(N0);
7000       SDValue Cond = N0.getOperand(0);
7001       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7002       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7003       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7004     }
7005   }
7006
7007   // Fold a series of buildvector, bitcast, and truncate if possible.
7008   // For example fold
7009   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7010   //   (2xi32 (buildvector x, y)).
7011   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7012       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7013       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7014       N0.getOperand(0).hasOneUse()) {
7015
7016     SDValue BuildVect = N0.getOperand(0);
7017     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7018     EVT TruncVecEltTy = VT.getVectorElementType();
7019
7020     // Check that the element types match.
7021     if (BuildVectEltTy == TruncVecEltTy) {
7022       // Now we only need to compute the offset of the truncated elements.
7023       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7024       unsigned TruncVecNumElts = VT.getVectorNumElements();
7025       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7026
7027       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7028              "Invalid number of elements");
7029
7030       SmallVector<SDValue, 8> Opnds;
7031       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7032         Opnds.push_back(BuildVect.getOperand(i));
7033
7034       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7035     }
7036   }
7037
7038   // See if we can simplify the input to this truncate through knowledge that
7039   // only the low bits are being used.
7040   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7041   // Currently we only perform this optimization on scalars because vectors
7042   // may have different active low bits.
7043   if (!VT.isVector()) {
7044     SDValue Shorter =
7045       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7046                                                VT.getSizeInBits()));
7047     if (Shorter.getNode())
7048       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7049   }
7050   // fold (truncate (load x)) -> (smaller load x)
7051   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7052   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7053     if (SDValue Reduced = ReduceLoadWidth(N))
7054       return Reduced;
7055
7056     // Handle the case where the load remains an extending load even
7057     // after truncation.
7058     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7059       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7060       if (!LN0->isVolatile() &&
7061           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7062         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7063                                          VT, LN0->getChain(), LN0->getBasePtr(),
7064                                          LN0->getMemoryVT(),
7065                                          LN0->getMemOperand());
7066         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7067         return NewLoad;
7068       }
7069     }
7070   }
7071   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7072   // where ... are all 'undef'.
7073   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7074     SmallVector<EVT, 8> VTs;
7075     SDValue V;
7076     unsigned Idx = 0;
7077     unsigned NumDefs = 0;
7078
7079     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7080       SDValue X = N0.getOperand(i);
7081       if (X.getOpcode() != ISD::UNDEF) {
7082         V = X;
7083         Idx = i;
7084         NumDefs++;
7085       }
7086       // Stop if more than one members are non-undef.
7087       if (NumDefs > 1)
7088         break;
7089       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7090                                      VT.getVectorElementType(),
7091                                      X.getValueType().getVectorNumElements()));
7092     }
7093
7094     if (NumDefs == 0)
7095       return DAG.getUNDEF(VT);
7096
7097     if (NumDefs == 1) {
7098       assert(V.getNode() && "The single defined operand is empty!");
7099       SmallVector<SDValue, 8> Opnds;
7100       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7101         if (i != Idx) {
7102           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7103           continue;
7104         }
7105         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7106         AddToWorklist(NV.getNode());
7107         Opnds.push_back(NV);
7108       }
7109       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7110     }
7111   }
7112
7113   // Simplify the operands using demanded-bits information.
7114   if (!VT.isVector() &&
7115       SimplifyDemandedBits(SDValue(N, 0)))
7116     return SDValue(N, 0);
7117
7118   return SDValue();
7119 }
7120
7121 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7122   SDValue Elt = N->getOperand(i);
7123   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7124     return Elt.getNode();
7125   return Elt.getOperand(Elt.getResNo()).getNode();
7126 }
7127
7128 /// build_pair (load, load) -> load
7129 /// if load locations are consecutive.
7130 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7131   assert(N->getOpcode() == ISD::BUILD_PAIR);
7132
7133   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7134   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7135   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7136       LD1->getAddressSpace() != LD2->getAddressSpace())
7137     return SDValue();
7138   EVT LD1VT = LD1->getValueType(0);
7139
7140   if (ISD::isNON_EXTLoad(LD2) &&
7141       LD2->hasOneUse() &&
7142       // If both are volatile this would reduce the number of volatile loads.
7143       // If one is volatile it might be ok, but play conservative and bail out.
7144       !LD1->isVolatile() &&
7145       !LD2->isVolatile() &&
7146       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7147     unsigned Align = LD1->getAlignment();
7148     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7149         VT.getTypeForEVT(*DAG.getContext()));
7150
7151     if (NewAlign <= Align &&
7152         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7153       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7154                          LD1->getBasePtr(), LD1->getPointerInfo(),
7155                          false, false, false, Align);
7156   }
7157
7158   return SDValue();
7159 }
7160
7161 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7162   SDValue N0 = N->getOperand(0);
7163   EVT VT = N->getValueType(0);
7164
7165   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7166   // Only do this before legalize, since afterward the target may be depending
7167   // on the bitconvert.
7168   // First check to see if this is all constant.
7169   if (!LegalTypes &&
7170       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7171       VT.isVector()) {
7172     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7173
7174     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7175     assert(!DestEltVT.isVector() &&
7176            "Element type of vector ValueType must not be vector!");
7177     if (isSimple)
7178       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7179   }
7180
7181   // If the input is a constant, let getNode fold it.
7182   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7183     // If we can't allow illegal operations, we need to check that this is just
7184     // a fp -> int or int -> conversion and that the resulting operation will
7185     // be legal.
7186     if (!LegalOperations ||
7187         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7188          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7189         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7190          TLI.isOperationLegal(ISD::Constant, VT)))
7191       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7192   }
7193
7194   // (conv (conv x, t1), t2) -> (conv x, t2)
7195   if (N0.getOpcode() == ISD::BITCAST)
7196     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7197                        N0.getOperand(0));
7198
7199   // fold (conv (load x)) -> (load (conv*)x)
7200   // If the resultant load doesn't need a higher alignment than the original!
7201   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7202       // Do not change the width of a volatile load.
7203       !cast<LoadSDNode>(N0)->isVolatile() &&
7204       // Do not remove the cast if the types differ in endian layout.
7205       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7206           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7207       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7208       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7209     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7210     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7211         VT.getTypeForEVT(*DAG.getContext()));
7212     unsigned OrigAlign = LN0->getAlignment();
7213
7214     if (Align <= OrigAlign) {
7215       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7216                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7217                                  LN0->isVolatile(), LN0->isNonTemporal(),
7218                                  LN0->isInvariant(), OrigAlign,
7219                                  LN0->getAAInfo());
7220       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7221       return Load;
7222     }
7223   }
7224
7225   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7226   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7227   // This often reduces constant pool loads.
7228   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7229        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7230       N0.getNode()->hasOneUse() && VT.isInteger() &&
7231       !VT.isVector() && !N0.getValueType().isVector()) {
7232     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7233                                   N0.getOperand(0));
7234     AddToWorklist(NewConv.getNode());
7235
7236     SDLoc DL(N);
7237     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7238     if (N0.getOpcode() == ISD::FNEG)
7239       return DAG.getNode(ISD::XOR, DL, VT,
7240                          NewConv, DAG.getConstant(SignBit, DL, VT));
7241     assert(N0.getOpcode() == ISD::FABS);
7242     return DAG.getNode(ISD::AND, DL, VT,
7243                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7244   }
7245
7246   // fold (bitconvert (fcopysign cst, x)) ->
7247   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7248   // Note that we don't handle (copysign x, cst) because this can always be
7249   // folded to an fneg or fabs.
7250   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7251       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7252       VT.isInteger() && !VT.isVector()) {
7253     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7254     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7255     if (isTypeLegal(IntXVT)) {
7256       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7257                               IntXVT, N0.getOperand(1));
7258       AddToWorklist(X.getNode());
7259
7260       // If X has a different width than the result/lhs, sext it or truncate it.
7261       unsigned VTWidth = VT.getSizeInBits();
7262       if (OrigXWidth < VTWidth) {
7263         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7264         AddToWorklist(X.getNode());
7265       } else if (OrigXWidth > VTWidth) {
7266         // To get the sign bit in the right place, we have to shift it right
7267         // before truncating.
7268         SDLoc DL(X);
7269         X = DAG.getNode(ISD::SRL, DL,
7270                         X.getValueType(), X,
7271                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7272                                         X.getValueType()));
7273         AddToWorklist(X.getNode());
7274         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7275         AddToWorklist(X.getNode());
7276       }
7277
7278       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7279       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7280                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7281       AddToWorklist(X.getNode());
7282
7283       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7284                                 VT, N0.getOperand(0));
7285       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7286                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7287       AddToWorklist(Cst.getNode());
7288
7289       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7290     }
7291   }
7292
7293   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7294   if (N0.getOpcode() == ISD::BUILD_PAIR)
7295     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7296       return CombineLD;
7297
7298   // Remove double bitcasts from shuffles - this is often a legacy of
7299   // XformToShuffleWithZero being used to combine bitmaskings (of
7300   // float vectors bitcast to integer vectors) into shuffles.
7301   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7302   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7303       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7304       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7305       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7306     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7307
7308     // If operands are a bitcast, peek through if it casts the original VT.
7309     // If operands are a constant, just bitcast back to original VT.
7310     auto PeekThroughBitcast = [&](SDValue Op) {
7311       if (Op.getOpcode() == ISD::BITCAST &&
7312           Op.getOperand(0).getValueType() == VT)
7313         return SDValue(Op.getOperand(0));
7314       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7315           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7316         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7317       return SDValue();
7318     };
7319
7320     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7321     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7322     if (!(SV0 && SV1))
7323       return SDValue();
7324
7325     int MaskScale =
7326         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7327     SmallVector<int, 8> NewMask;
7328     for (int M : SVN->getMask())
7329       for (int i = 0; i != MaskScale; ++i)
7330         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7331
7332     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7333     if (!LegalMask) {
7334       std::swap(SV0, SV1);
7335       ShuffleVectorSDNode::commuteMask(NewMask);
7336       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7337     }
7338
7339     if (LegalMask)
7340       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7341   }
7342
7343   return SDValue();
7344 }
7345
7346 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7347   EVT VT = N->getValueType(0);
7348   return CombineConsecutiveLoads(N, VT);
7349 }
7350
7351 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7352 /// operands. DstEltVT indicates the destination element value type.
7353 SDValue DAGCombiner::
7354 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7355   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7356
7357   // If this is already the right type, we're done.
7358   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7359
7360   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7361   unsigned DstBitSize = DstEltVT.getSizeInBits();
7362
7363   // If this is a conversion of N elements of one type to N elements of another
7364   // type, convert each element.  This handles FP<->INT cases.
7365   if (SrcBitSize == DstBitSize) {
7366     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7367                               BV->getValueType(0).getVectorNumElements());
7368
7369     // Due to the FP element handling below calling this routine recursively,
7370     // we can end up with a scalar-to-vector node here.
7371     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7372       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7373                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7374                                      DstEltVT, BV->getOperand(0)));
7375
7376     SmallVector<SDValue, 8> Ops;
7377     for (SDValue Op : BV->op_values()) {
7378       // If the vector element type is not legal, the BUILD_VECTOR operands
7379       // are promoted and implicitly truncated.  Make that explicit here.
7380       if (Op.getValueType() != SrcEltVT)
7381         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7382       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7383                                 DstEltVT, Op));
7384       AddToWorklist(Ops.back().getNode());
7385     }
7386     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7387   }
7388
7389   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7390   // handle annoying details of growing/shrinking FP values, we convert them to
7391   // int first.
7392   if (SrcEltVT.isFloatingPoint()) {
7393     // Convert the input float vector to a int vector where the elements are the
7394     // same sizes.
7395     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7396     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7397     SrcEltVT = IntVT;
7398   }
7399
7400   // Now we know the input is an integer vector.  If the output is a FP type,
7401   // convert to integer first, then to FP of the right size.
7402   if (DstEltVT.isFloatingPoint()) {
7403     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7404     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7405
7406     // Next, convert to FP elements of the same size.
7407     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7408   }
7409
7410   SDLoc DL(BV);
7411
7412   // Okay, we know the src/dst types are both integers of differing types.
7413   // Handling growing first.
7414   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7415   if (SrcBitSize < DstBitSize) {
7416     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7417
7418     SmallVector<SDValue, 8> Ops;
7419     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7420          i += NumInputsPerOutput) {
7421       bool isLE = DAG.getDataLayout().isLittleEndian();
7422       APInt NewBits = APInt(DstBitSize, 0);
7423       bool EltIsUndef = true;
7424       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7425         // Shift the previously computed bits over.
7426         NewBits <<= SrcBitSize;
7427         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7428         if (Op.getOpcode() == ISD::UNDEF) continue;
7429         EltIsUndef = false;
7430
7431         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7432                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7433       }
7434
7435       if (EltIsUndef)
7436         Ops.push_back(DAG.getUNDEF(DstEltVT));
7437       else
7438         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7439     }
7440
7441     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7442     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7443   }
7444
7445   // Finally, this must be the case where we are shrinking elements: each input
7446   // turns into multiple outputs.
7447   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7448   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7449                             NumOutputsPerInput*BV->getNumOperands());
7450   SmallVector<SDValue, 8> Ops;
7451
7452   for (const SDValue &Op : BV->op_values()) {
7453     if (Op.getOpcode() == ISD::UNDEF) {
7454       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7455       continue;
7456     }
7457
7458     APInt OpVal = cast<ConstantSDNode>(Op)->
7459                   getAPIntValue().zextOrTrunc(SrcBitSize);
7460
7461     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7462       APInt ThisVal = OpVal.trunc(DstBitSize);
7463       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7464       OpVal = OpVal.lshr(DstBitSize);
7465     }
7466
7467     // For big endian targets, swap the order of the pieces of each element.
7468     if (DAG.getDataLayout().isBigEndian())
7469       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7470   }
7471
7472   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7473 }
7474
7475 /// Try to perform FMA combining on a given FADD node.
7476 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7477   SDValue N0 = N->getOperand(0);
7478   SDValue N1 = N->getOperand(1);
7479   EVT VT = N->getValueType(0);
7480   SDLoc SL(N);
7481
7482   const TargetOptions &Options = DAG.getTarget().Options;
7483   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7484                        Options.UnsafeFPMath);
7485
7486   // Floating-point multiply-add with intermediate rounding.
7487   bool HasFMAD = (LegalOperations &&
7488                   TLI.isOperationLegal(ISD::FMAD, VT));
7489
7490   // Floating-point multiply-add without intermediate rounding.
7491   bool HasFMA = ((!LegalOperations ||
7492                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7493                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7494                  UnsafeFPMath);
7495
7496   // No valid opcode, do not combine.
7497   if (!HasFMAD && !HasFMA)
7498     return SDValue();
7499
7500   // Always prefer FMAD to FMA for precision.
7501   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7502   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7503   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7504
7505   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7506   // prefer to fold the multiply with fewer uses.
7507   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7508       N1.getOpcode() == ISD::FMUL) {
7509     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7510       std::swap(N0, N1);
7511   }
7512
7513   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7514   if (N0.getOpcode() == ISD::FMUL &&
7515       (Aggressive || N0->hasOneUse())) {
7516     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7517                        N0.getOperand(0), N0.getOperand(1), N1);
7518   }
7519
7520   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7521   // Note: Commutes FADD operands.
7522   if (N1.getOpcode() == ISD::FMUL &&
7523       (Aggressive || N1->hasOneUse())) {
7524     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7525                        N1.getOperand(0), N1.getOperand(1), N0);
7526   }
7527
7528   // Look through FP_EXTEND nodes to do more combining.
7529   if (UnsafeFPMath && LookThroughFPExt) {
7530     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7531     if (N0.getOpcode() == ISD::FP_EXTEND) {
7532       SDValue N00 = N0.getOperand(0);
7533       if (N00.getOpcode() == ISD::FMUL)
7534         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7535                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7536                                        N00.getOperand(0)),
7537                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7538                                        N00.getOperand(1)), N1);
7539     }
7540
7541     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7542     // Note: Commutes FADD operands.
7543     if (N1.getOpcode() == ISD::FP_EXTEND) {
7544       SDValue N10 = N1.getOperand(0);
7545       if (N10.getOpcode() == ISD::FMUL)
7546         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7547                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7548                                        N10.getOperand(0)),
7549                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7550                                        N10.getOperand(1)), N0);
7551     }
7552   }
7553
7554   // More folding opportunities when target permits.
7555   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7556     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7557     if (N0.getOpcode() == PreferredFusedOpcode &&
7558         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7559       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7560                          N0.getOperand(0), N0.getOperand(1),
7561                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7562                                      N0.getOperand(2).getOperand(0),
7563                                      N0.getOperand(2).getOperand(1),
7564                                      N1));
7565     }
7566
7567     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7568     if (N1->getOpcode() == PreferredFusedOpcode &&
7569         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7570       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7571                          N1.getOperand(0), N1.getOperand(1),
7572                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7573                                      N1.getOperand(2).getOperand(0),
7574                                      N1.getOperand(2).getOperand(1),
7575                                      N0));
7576     }
7577
7578     if (UnsafeFPMath && LookThroughFPExt) {
7579       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7580       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7581       auto FoldFAddFMAFPExtFMul = [&] (
7582           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7583         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7584                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7585                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7586                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7587                                        Z));
7588       };
7589       if (N0.getOpcode() == PreferredFusedOpcode) {
7590         SDValue N02 = N0.getOperand(2);
7591         if (N02.getOpcode() == ISD::FP_EXTEND) {
7592           SDValue N020 = N02.getOperand(0);
7593           if (N020.getOpcode() == ISD::FMUL)
7594             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7595                                         N020.getOperand(0), N020.getOperand(1),
7596                                         N1);
7597         }
7598       }
7599
7600       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7601       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7602       // FIXME: This turns two single-precision and one double-precision
7603       // operation into two double-precision operations, which might not be
7604       // interesting for all targets, especially GPUs.
7605       auto FoldFAddFPExtFMAFMul = [&] (
7606           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7607         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7608                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7609                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7610                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7611                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7612                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7613                                        Z));
7614       };
7615       if (N0.getOpcode() == ISD::FP_EXTEND) {
7616         SDValue N00 = N0.getOperand(0);
7617         if (N00.getOpcode() == PreferredFusedOpcode) {
7618           SDValue N002 = N00.getOperand(2);
7619           if (N002.getOpcode() == ISD::FMUL)
7620             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7621                                         N002.getOperand(0), N002.getOperand(1),
7622                                         N1);
7623         }
7624       }
7625
7626       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7627       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7628       if (N1.getOpcode() == PreferredFusedOpcode) {
7629         SDValue N12 = N1.getOperand(2);
7630         if (N12.getOpcode() == ISD::FP_EXTEND) {
7631           SDValue N120 = N12.getOperand(0);
7632           if (N120.getOpcode() == ISD::FMUL)
7633             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7634                                         N120.getOperand(0), N120.getOperand(1),
7635                                         N0);
7636         }
7637       }
7638
7639       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7640       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7641       // FIXME: This turns two single-precision and one double-precision
7642       // operation into two double-precision operations, which might not be
7643       // interesting for all targets, especially GPUs.
7644       if (N1.getOpcode() == ISD::FP_EXTEND) {
7645         SDValue N10 = N1.getOperand(0);
7646         if (N10.getOpcode() == PreferredFusedOpcode) {
7647           SDValue N102 = N10.getOperand(2);
7648           if (N102.getOpcode() == ISD::FMUL)
7649             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7650                                         N102.getOperand(0), N102.getOperand(1),
7651                                         N0);
7652         }
7653       }
7654     }
7655   }
7656
7657   return SDValue();
7658 }
7659
7660 /// Try to perform FMA combining on a given FSUB node.
7661 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7662   SDValue N0 = N->getOperand(0);
7663   SDValue N1 = N->getOperand(1);
7664   EVT VT = N->getValueType(0);
7665   SDLoc SL(N);
7666
7667   const TargetOptions &Options = DAG.getTarget().Options;
7668   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7669                        Options.UnsafeFPMath);
7670
7671   // Floating-point multiply-add with intermediate rounding.
7672   bool HasFMAD = (LegalOperations &&
7673                   TLI.isOperationLegal(ISD::FMAD, VT));
7674
7675   // Floating-point multiply-add without intermediate rounding.
7676   bool HasFMA = ((!LegalOperations ||
7677                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7678                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7679                  UnsafeFPMath);
7680
7681   // No valid opcode, do not combine.
7682   if (!HasFMAD && !HasFMA)
7683     return SDValue();
7684
7685   // Always prefer FMAD to FMA for precision.
7686   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7687   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7688   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7689
7690   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7691   if (N0.getOpcode() == ISD::FMUL &&
7692       (Aggressive || N0->hasOneUse())) {
7693     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7694                        N0.getOperand(0), N0.getOperand(1),
7695                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7696   }
7697
7698   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7699   // Note: Commutes FSUB operands.
7700   if (N1.getOpcode() == ISD::FMUL &&
7701       (Aggressive || N1->hasOneUse()))
7702     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7703                        DAG.getNode(ISD::FNEG, SL, VT,
7704                                    N1.getOperand(0)),
7705                        N1.getOperand(1), N0);
7706
7707   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7708   if (N0.getOpcode() == ISD::FNEG &&
7709       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7710       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7711     SDValue N00 = N0.getOperand(0).getOperand(0);
7712     SDValue N01 = N0.getOperand(0).getOperand(1);
7713     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7714                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7715                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7716   }
7717
7718   // Look through FP_EXTEND nodes to do more combining.
7719   if (UnsafeFPMath && LookThroughFPExt) {
7720     // fold (fsub (fpext (fmul x, y)), z)
7721     //   -> (fma (fpext x), (fpext y), (fneg z))
7722     if (N0.getOpcode() == ISD::FP_EXTEND) {
7723       SDValue N00 = N0.getOperand(0);
7724       if (N00.getOpcode() == ISD::FMUL)
7725         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7726                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7727                                        N00.getOperand(0)),
7728                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7729                                        N00.getOperand(1)),
7730                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7731     }
7732
7733     // fold (fsub x, (fpext (fmul y, z)))
7734     //   -> (fma (fneg (fpext y)), (fpext z), x)
7735     // Note: Commutes FSUB operands.
7736     if (N1.getOpcode() == ISD::FP_EXTEND) {
7737       SDValue N10 = N1.getOperand(0);
7738       if (N10.getOpcode() == ISD::FMUL)
7739         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7740                            DAG.getNode(ISD::FNEG, SL, VT,
7741                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7742                                                    N10.getOperand(0))),
7743                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7744                                        N10.getOperand(1)),
7745                            N0);
7746     }
7747
7748     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7749     //   -> (fneg (fma (fpext x), (fpext y), z))
7750     // Note: This could be removed with appropriate canonicalization of the
7751     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7752     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7753     // from implementing the canonicalization in visitFSUB.
7754     if (N0.getOpcode() == ISD::FP_EXTEND) {
7755       SDValue N00 = N0.getOperand(0);
7756       if (N00.getOpcode() == ISD::FNEG) {
7757         SDValue N000 = N00.getOperand(0);
7758         if (N000.getOpcode() == ISD::FMUL) {
7759           return DAG.getNode(ISD::FNEG, SL, VT,
7760                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7761                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7762                                                      N000.getOperand(0)),
7763                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7764                                                      N000.getOperand(1)),
7765                                          N1));
7766         }
7767       }
7768     }
7769
7770     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7771     //   -> (fneg (fma (fpext x)), (fpext y), z)
7772     // Note: This could be removed with appropriate canonicalization of the
7773     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7774     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7775     // from implementing the canonicalization in visitFSUB.
7776     if (N0.getOpcode() == ISD::FNEG) {
7777       SDValue N00 = N0.getOperand(0);
7778       if (N00.getOpcode() == ISD::FP_EXTEND) {
7779         SDValue N000 = N00.getOperand(0);
7780         if (N000.getOpcode() == ISD::FMUL) {
7781           return DAG.getNode(ISD::FNEG, SL, VT,
7782                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7783                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7784                                                      N000.getOperand(0)),
7785                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7786                                                      N000.getOperand(1)),
7787                                          N1));
7788         }
7789       }
7790     }
7791
7792   }
7793
7794   // More folding opportunities when target permits.
7795   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7796     // fold (fsub (fma x, y, (fmul u, v)), z)
7797     //   -> (fma x, y (fma u, v, (fneg z)))
7798     if (N0.getOpcode() == PreferredFusedOpcode &&
7799         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7800       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7801                          N0.getOperand(0), N0.getOperand(1),
7802                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7803                                      N0.getOperand(2).getOperand(0),
7804                                      N0.getOperand(2).getOperand(1),
7805                                      DAG.getNode(ISD::FNEG, SL, VT,
7806                                                  N1)));
7807     }
7808
7809     // fold (fsub x, (fma y, z, (fmul u, v)))
7810     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7811     if (N1.getOpcode() == PreferredFusedOpcode &&
7812         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7813       SDValue N20 = N1.getOperand(2).getOperand(0);
7814       SDValue N21 = N1.getOperand(2).getOperand(1);
7815       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7816                          DAG.getNode(ISD::FNEG, SL, VT,
7817                                      N1.getOperand(0)),
7818                          N1.getOperand(1),
7819                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7820                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7821
7822                                      N21, N0));
7823     }
7824
7825     if (UnsafeFPMath && LookThroughFPExt) {
7826       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7827       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7828       if (N0.getOpcode() == PreferredFusedOpcode) {
7829         SDValue N02 = N0.getOperand(2);
7830         if (N02.getOpcode() == ISD::FP_EXTEND) {
7831           SDValue N020 = N02.getOperand(0);
7832           if (N020.getOpcode() == ISD::FMUL)
7833             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7834                                N0.getOperand(0), N0.getOperand(1),
7835                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7836                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7837                                                        N020.getOperand(0)),
7838                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7839                                                        N020.getOperand(1)),
7840                                            DAG.getNode(ISD::FNEG, SL, VT,
7841                                                        N1)));
7842         }
7843       }
7844
7845       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7846       //   -> (fma (fpext x), (fpext y),
7847       //           (fma (fpext u), (fpext v), (fneg z)))
7848       // FIXME: This turns two single-precision and one double-precision
7849       // operation into two double-precision operations, which might not be
7850       // interesting for all targets, especially GPUs.
7851       if (N0.getOpcode() == ISD::FP_EXTEND) {
7852         SDValue N00 = N0.getOperand(0);
7853         if (N00.getOpcode() == PreferredFusedOpcode) {
7854           SDValue N002 = N00.getOperand(2);
7855           if (N002.getOpcode() == ISD::FMUL)
7856             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7857                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7858                                            N00.getOperand(0)),
7859                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7860                                            N00.getOperand(1)),
7861                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7862                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7863                                                        N002.getOperand(0)),
7864                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7865                                                        N002.getOperand(1)),
7866                                            DAG.getNode(ISD::FNEG, SL, VT,
7867                                                        N1)));
7868         }
7869       }
7870
7871       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7872       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7873       if (N1.getOpcode() == PreferredFusedOpcode &&
7874         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7875         SDValue N120 = N1.getOperand(2).getOperand(0);
7876         if (N120.getOpcode() == ISD::FMUL) {
7877           SDValue N1200 = N120.getOperand(0);
7878           SDValue N1201 = N120.getOperand(1);
7879           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7880                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7881                              N1.getOperand(1),
7882                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7883                                          DAG.getNode(ISD::FNEG, SL, VT,
7884                                              DAG.getNode(ISD::FP_EXTEND, SL,
7885                                                          VT, N1200)),
7886                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7887                                                      N1201),
7888                                          N0));
7889         }
7890       }
7891
7892       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7893       //   -> (fma (fneg (fpext y)), (fpext z),
7894       //           (fma (fneg (fpext u)), (fpext v), x))
7895       // FIXME: This turns two single-precision and one double-precision
7896       // operation into two double-precision operations, which might not be
7897       // interesting for all targets, especially GPUs.
7898       if (N1.getOpcode() == ISD::FP_EXTEND &&
7899         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7900         SDValue N100 = N1.getOperand(0).getOperand(0);
7901         SDValue N101 = N1.getOperand(0).getOperand(1);
7902         SDValue N102 = N1.getOperand(0).getOperand(2);
7903         if (N102.getOpcode() == ISD::FMUL) {
7904           SDValue N1020 = N102.getOperand(0);
7905           SDValue N1021 = N102.getOperand(1);
7906           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7907                              DAG.getNode(ISD::FNEG, SL, VT,
7908                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7909                                                      N100)),
7910                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7911                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7912                                          DAG.getNode(ISD::FNEG, SL, VT,
7913                                              DAG.getNode(ISD::FP_EXTEND, SL,
7914                                                          VT, N1020)),
7915                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7916                                                      N1021),
7917                                          N0));
7918         }
7919       }
7920     }
7921   }
7922
7923   return SDValue();
7924 }
7925
7926 SDValue DAGCombiner::visitFADD(SDNode *N) {
7927   SDValue N0 = N->getOperand(0);
7928   SDValue N1 = N->getOperand(1);
7929   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7930   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7931   EVT VT = N->getValueType(0);
7932   SDLoc DL(N);
7933   const TargetOptions &Options = DAG.getTarget().Options;
7934   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
7935
7936   // fold vector ops
7937   if (VT.isVector())
7938     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7939       return FoldedVOp;
7940
7941   // fold (fadd c1, c2) -> c1 + c2
7942   if (N0CFP && N1CFP)
7943     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
7944
7945   // canonicalize constant to RHS
7946   if (N0CFP && !N1CFP)
7947     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
7948
7949   // fold (fadd A, (fneg B)) -> (fsub A, B)
7950   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7951       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7952     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7953                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
7954
7955   // fold (fadd (fneg A), B) -> (fsub B, A)
7956   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7957       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7958     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7959                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
7960
7961   // If 'unsafe math' is enabled, fold lots of things.
7962   if (Options.UnsafeFPMath) {
7963     // No FP constant should be created after legalization as Instruction
7964     // Selection pass has a hard time dealing with FP constants.
7965     bool AllowNewConst = (Level < AfterLegalizeDAG);
7966
7967     // fold (fadd A, 0) -> A
7968     if (N1CFP && N1CFP->isZero())
7969       return N0;
7970
7971     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7972     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7973         isa<ConstantFPSDNode>(N0.getOperand(1)))
7974       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7975                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
7976                                      Flags),
7977                          Flags);
7978
7979     // If allowed, fold (fadd (fneg x), x) -> 0.0
7980     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7981       return DAG.getConstantFP(0.0, DL, VT);
7982
7983     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7984     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7985       return DAG.getConstantFP(0.0, DL, VT);
7986
7987     // We can fold chains of FADD's of the same value into multiplications.
7988     // This transform is not safe in general because we are reducing the number
7989     // of rounding steps.
7990     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7991       if (N0.getOpcode() == ISD::FMUL) {
7992         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7993         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7994
7995         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7996         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7997           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7998                                        DAG.getConstantFP(1.0, DL, VT), Flags);
7999           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8000         }
8001
8002         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8003         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8004             N1.getOperand(0) == N1.getOperand(1) &&
8005             N0.getOperand(0) == N1.getOperand(0)) {
8006           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
8007                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8008           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8009         }
8010       }
8011
8012       if (N1.getOpcode() == ISD::FMUL) {
8013         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8014         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
8015
8016         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8017         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8018           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8019                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8020           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8021         }
8022
8023         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8024         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8025             N0.getOperand(0) == N0.getOperand(1) &&
8026             N1.getOperand(0) == N0.getOperand(0)) {
8027           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8028                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8029           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8030         }
8031       }
8032
8033       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8034         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
8035         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8036         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
8037             (N0.getOperand(0) == N1)) {
8038           return DAG.getNode(ISD::FMUL, DL, VT,
8039                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8040         }
8041       }
8042
8043       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8044         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8045         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8046         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8047             N1.getOperand(0) == N0) {
8048           return DAG.getNode(ISD::FMUL, DL, VT,
8049                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8050         }
8051       }
8052
8053       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8054       if (AllowNewConst &&
8055           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8056           N0.getOperand(0) == N0.getOperand(1) &&
8057           N1.getOperand(0) == N1.getOperand(1) &&
8058           N0.getOperand(0) == N1.getOperand(0)) {
8059         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8060                            DAG.getConstantFP(4.0, DL, VT), Flags);
8061       }
8062     }
8063   } // enable-unsafe-fp-math
8064
8065   // FADD -> FMA combines:
8066   if (SDValue Fused = visitFADDForFMACombine(N)) {
8067     AddToWorklist(Fused.getNode());
8068     return Fused;
8069   }
8070
8071   return SDValue();
8072 }
8073
8074 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8075   SDValue N0 = N->getOperand(0);
8076   SDValue N1 = N->getOperand(1);
8077   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8078   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8079   EVT VT = N->getValueType(0);
8080   SDLoc dl(N);
8081   const TargetOptions &Options = DAG.getTarget().Options;
8082   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8083
8084   // fold vector ops
8085   if (VT.isVector())
8086     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8087       return FoldedVOp;
8088
8089   // fold (fsub c1, c2) -> c1-c2
8090   if (N0CFP && N1CFP)
8091     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8092
8093   // fold (fsub A, (fneg B)) -> (fadd A, B)
8094   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8095     return DAG.getNode(ISD::FADD, dl, VT, N0,
8096                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8097
8098   // If 'unsafe math' is enabled, fold lots of things.
8099   if (Options.UnsafeFPMath) {
8100     // (fsub A, 0) -> A
8101     if (N1CFP && N1CFP->isZero())
8102       return N0;
8103
8104     // (fsub 0, B) -> -B
8105     if (N0CFP && N0CFP->isZero()) {
8106       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8107         return GetNegatedExpression(N1, DAG, LegalOperations);
8108       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8109         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8110     }
8111
8112     // (fsub x, x) -> 0.0
8113     if (N0 == N1)
8114       return DAG.getConstantFP(0.0f, dl, VT);
8115
8116     // (fsub x, (fadd x, y)) -> (fneg y)
8117     // (fsub x, (fadd y, x)) -> (fneg y)
8118     if (N1.getOpcode() == ISD::FADD) {
8119       SDValue N10 = N1->getOperand(0);
8120       SDValue N11 = N1->getOperand(1);
8121
8122       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8123         return GetNegatedExpression(N11, DAG, LegalOperations);
8124
8125       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8126         return GetNegatedExpression(N10, DAG, LegalOperations);
8127     }
8128   }
8129
8130   // FSUB -> FMA combines:
8131   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8132     AddToWorklist(Fused.getNode());
8133     return Fused;
8134   }
8135
8136   return SDValue();
8137 }
8138
8139 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8140   SDValue N0 = N->getOperand(0);
8141   SDValue N1 = N->getOperand(1);
8142   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8143   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8144   EVT VT = N->getValueType(0);
8145   SDLoc DL(N);
8146   const TargetOptions &Options = DAG.getTarget().Options;
8147   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8148
8149   // fold vector ops
8150   if (VT.isVector()) {
8151     // This just handles C1 * C2 for vectors. Other vector folds are below.
8152     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8153       return FoldedVOp;
8154   }
8155
8156   // fold (fmul c1, c2) -> c1*c2
8157   if (N0CFP && N1CFP)
8158     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8159
8160   // canonicalize constant to RHS
8161   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8162      !isConstantFPBuildVectorOrConstantFP(N1))
8163     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8164
8165   // fold (fmul A, 1.0) -> A
8166   if (N1CFP && N1CFP->isExactlyValue(1.0))
8167     return N0;
8168
8169   if (Options.UnsafeFPMath) {
8170     // fold (fmul A, 0) -> 0
8171     if (N1CFP && N1CFP->isZero())
8172       return N1;
8173
8174     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8175     if (N0.getOpcode() == ISD::FMUL) {
8176       // Fold scalars or any vector constants (not just splats).
8177       // This fold is done in general by InstCombine, but extra fmul insts
8178       // may have been generated during lowering.
8179       SDValue N00 = N0.getOperand(0);
8180       SDValue N01 = N0.getOperand(1);
8181       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8182       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8183       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8184
8185       // Check 1: Make sure that the first operand of the inner multiply is NOT
8186       // a constant. Otherwise, we may induce infinite looping.
8187       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8188         // Check 2: Make sure that the second operand of the inner multiply and
8189         // the second operand of the outer multiply are constants.
8190         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8191             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8192           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8193           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8194         }
8195       }
8196     }
8197
8198     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8199     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8200     // during an early run of DAGCombiner can prevent folding with fmuls
8201     // inserted during lowering.
8202     if (N0.getOpcode() == ISD::FADD &&
8203         (N0.getOperand(0) == N0.getOperand(1)) &&
8204         N0.hasOneUse()) {
8205       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8206       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8207       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8208     }
8209   }
8210
8211   // fold (fmul X, 2.0) -> (fadd X, X)
8212   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8213     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8214
8215   // fold (fmul X, -1.0) -> (fneg X)
8216   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8217     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8218       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8219
8220   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8221   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8222     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8223       // Both can be negated for free, check to see if at least one is cheaper
8224       // negated.
8225       if (LHSNeg == 2 || RHSNeg == 2)
8226         return DAG.getNode(ISD::FMUL, DL, VT,
8227                            GetNegatedExpression(N0, DAG, LegalOperations),
8228                            GetNegatedExpression(N1, DAG, LegalOperations),
8229                            Flags);
8230     }
8231   }
8232
8233   return SDValue();
8234 }
8235
8236 SDValue DAGCombiner::visitFMA(SDNode *N) {
8237   SDValue N0 = N->getOperand(0);
8238   SDValue N1 = N->getOperand(1);
8239   SDValue N2 = N->getOperand(2);
8240   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8241   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8242   EVT VT = N->getValueType(0);
8243   SDLoc dl(N);
8244   const TargetOptions &Options = DAG.getTarget().Options;
8245
8246   // Constant fold FMA.
8247   if (isa<ConstantFPSDNode>(N0) &&
8248       isa<ConstantFPSDNode>(N1) &&
8249       isa<ConstantFPSDNode>(N2)) {
8250     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8251   }
8252
8253   if (Options.UnsafeFPMath) {
8254     if (N0CFP && N0CFP->isZero())
8255       return N2;
8256     if (N1CFP && N1CFP->isZero())
8257       return N2;
8258   }
8259   // TODO: The FMA node should have flags that propagate to these nodes.
8260   if (N0CFP && N0CFP->isExactlyValue(1.0))
8261     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8262   if (N1CFP && N1CFP->isExactlyValue(1.0))
8263     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8264
8265   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8266   if (N0CFP && !N1CFP)
8267     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8268
8269   // TODO: FMA nodes should have flags that propagate to the created nodes.
8270   // For now, create a Flags object for use with all unsafe math transforms.
8271   SDNodeFlags Flags;
8272   Flags.setUnsafeAlgebra(true);
8273
8274   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8275   if (Options.UnsafeFPMath && N1CFP &&
8276       N2.getOpcode() == ISD::FMUL &&
8277       N0 == N2.getOperand(0) &&
8278       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8279     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8280                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8281                                    &Flags), &Flags);
8282   }
8283
8284
8285   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8286   if (Options.UnsafeFPMath &&
8287       N0.getOpcode() == ISD::FMUL && N1CFP &&
8288       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8289     return DAG.getNode(ISD::FMA, dl, VT,
8290                        N0.getOperand(0),
8291                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8292                                    &Flags),
8293                        N2);
8294   }
8295
8296   // (fma x, 1, y) -> (fadd x, y)
8297   // (fma x, -1, y) -> (fadd (fneg x), y)
8298   if (N1CFP) {
8299     if (N1CFP->isExactlyValue(1.0))
8300       // TODO: The FMA node should have flags that propagate to this node.
8301       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8302
8303     if (N1CFP->isExactlyValue(-1.0) &&
8304         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8305       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8306       AddToWorklist(RHSNeg.getNode());
8307       // TODO: The FMA node should have flags that propagate to this node.
8308       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8309     }
8310   }
8311
8312   // (fma x, c, x) -> (fmul x, (c+1))
8313   if (Options.UnsafeFPMath && N1CFP && N0 == N2) {
8314     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8315                        DAG.getNode(ISD::FADD, dl, VT,
8316                                    N1, DAG.getConstantFP(1.0, dl, VT),
8317                                    &Flags), &Flags);
8318   }
8319   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8320   if (Options.UnsafeFPMath && N1CFP &&
8321       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8322     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8323                        DAG.getNode(ISD::FADD, dl, VT,
8324                                    N1, DAG.getConstantFP(-1.0, dl, VT),
8325                                    &Flags), &Flags);
8326   }
8327
8328   return SDValue();
8329 }
8330
8331 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8332 // reciprocal.
8333 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8334 // Notice that this is not always beneficial. One reason is different target
8335 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8336 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8337 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8338 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8339   if (!DAG.getTarget().Options.UnsafeFPMath)
8340     return SDValue();
8341
8342   // Skip if current node is a reciprocal.
8343   SDValue N0 = N->getOperand(0);
8344   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8345   if (N0CFP && N0CFP->isExactlyValue(1.0))
8346     return SDValue();
8347
8348   // Exit early if the target does not want this transform or if there can't
8349   // possibly be enough uses of the divisor to make the transform worthwhile.
8350   SDValue N1 = N->getOperand(1);
8351   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8352   if (!MinUses || N1->use_size() < MinUses)
8353     return SDValue();
8354
8355   // Find all FDIV users of the same divisor.
8356   // Use a set because duplicates may be present in the user list.
8357   SetVector<SDNode *> Users;
8358   for (auto *U : N1->uses())
8359     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8360       Users.insert(U);
8361
8362   // Now that we have the actual number of divisor uses, make sure it meets
8363   // the minimum threshold specified by the target.
8364   if (Users.size() < MinUses)
8365     return SDValue();
8366
8367   EVT VT = N->getValueType(0);
8368   SDLoc DL(N);
8369   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8370   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8371   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8372
8373   // Dividend / Divisor -> Dividend * Reciprocal
8374   for (auto *U : Users) {
8375     SDValue Dividend = U->getOperand(0);
8376     if (Dividend != FPOne) {
8377       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8378                                     Reciprocal, Flags);
8379       CombineTo(U, NewNode);
8380     } else if (U != Reciprocal.getNode()) {
8381       // In the absence of fast-math-flags, this user node is always the
8382       // same node as Reciprocal, but with FMF they may be different nodes.
8383       CombineTo(U, Reciprocal);
8384     }
8385   }
8386   return SDValue(N, 0);  // N was replaced.
8387 }
8388
8389 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8390   SDValue N0 = N->getOperand(0);
8391   SDValue N1 = N->getOperand(1);
8392   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8393   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8394   EVT VT = N->getValueType(0);
8395   SDLoc DL(N);
8396   const TargetOptions &Options = DAG.getTarget().Options;
8397   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8398
8399   // fold vector ops
8400   if (VT.isVector())
8401     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8402       return FoldedVOp;
8403
8404   // fold (fdiv c1, c2) -> c1/c2
8405   if (N0CFP && N1CFP)
8406     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8407
8408   if (Options.UnsafeFPMath) {
8409     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8410     if (N1CFP) {
8411       // Compute the reciprocal 1.0 / c2.
8412       APFloat N1APF = N1CFP->getValueAPF();
8413       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8414       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8415       // Only do the transform if the reciprocal is a legal fp immediate that
8416       // isn't too nasty (eg NaN, denormal, ...).
8417       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8418           (!LegalOperations ||
8419            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8420            // backend)... we should handle this gracefully after Legalize.
8421            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8422            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8423            TLI.isFPImmLegal(Recip, VT)))
8424         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8425                            DAG.getConstantFP(Recip, DL, VT), Flags);
8426     }
8427
8428     // If this FDIV is part of a reciprocal square root, it may be folded
8429     // into a target-specific square root estimate instruction.
8430     if (N1.getOpcode() == ISD::FSQRT) {
8431       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8432         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8433       }
8434     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8435                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8436       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8437                                           Flags)) {
8438         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8439         AddToWorklist(RV.getNode());
8440         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8441       }
8442     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8443                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8444       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8445                                           Flags)) {
8446         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8447         AddToWorklist(RV.getNode());
8448         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8449       }
8450     } else if (N1.getOpcode() == ISD::FMUL) {
8451       // Look through an FMUL. Even though this won't remove the FDIV directly,
8452       // it's still worthwhile to get rid of the FSQRT if possible.
8453       SDValue SqrtOp;
8454       SDValue OtherOp;
8455       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8456         SqrtOp = N1.getOperand(0);
8457         OtherOp = N1.getOperand(1);
8458       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8459         SqrtOp = N1.getOperand(1);
8460         OtherOp = N1.getOperand(0);
8461       }
8462       if (SqrtOp.getNode()) {
8463         // We found a FSQRT, so try to make this fold:
8464         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8465         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8466           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8467           AddToWorklist(RV.getNode());
8468           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8469         }
8470       }
8471     }
8472
8473     // Fold into a reciprocal estimate and multiply instead of a real divide.
8474     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8475       AddToWorklist(RV.getNode());
8476       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8477     }
8478   }
8479
8480   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8481   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8482     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8483       // Both can be negated for free, check to see if at least one is cheaper
8484       // negated.
8485       if (LHSNeg == 2 || RHSNeg == 2)
8486         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8487                            GetNegatedExpression(N0, DAG, LegalOperations),
8488                            GetNegatedExpression(N1, DAG, LegalOperations),
8489                            Flags);
8490     }
8491   }
8492
8493   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8494     return CombineRepeatedDivisors;
8495
8496   return SDValue();
8497 }
8498
8499 SDValue DAGCombiner::visitFREM(SDNode *N) {
8500   SDValue N0 = N->getOperand(0);
8501   SDValue N1 = N->getOperand(1);
8502   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8503   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8504   EVT VT = N->getValueType(0);
8505
8506   // fold (frem c1, c2) -> fmod(c1,c2)
8507   if (N0CFP && N1CFP)
8508     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8509                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8510
8511   return SDValue();
8512 }
8513
8514 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8515   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8516     return SDValue();
8517
8518   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8519   // For now, create a Flags object for use with all unsafe math transforms.
8520   SDNodeFlags Flags;
8521   Flags.setUnsafeAlgebra(true);
8522
8523   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8524   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8525   if (!RV)
8526     return SDValue();
8527
8528   EVT VT = RV.getValueType();
8529   SDLoc DL(N);
8530   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8531   AddToWorklist(RV.getNode());
8532
8533   // Unfortunately, RV is now NaN if the input was exactly 0.
8534   // Select out this case and force the answer to 0.
8535   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8536   EVT CCVT = getSetCCResultType(VT);
8537   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8538   AddToWorklist(ZeroCmp.getNode());
8539   AddToWorklist(RV.getNode());
8540
8541   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8542                      ZeroCmp, Zero, RV);
8543 }
8544
8545 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8546   SDValue N0 = N->getOperand(0);
8547   SDValue N1 = N->getOperand(1);
8548   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8549   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8550   EVT VT = N->getValueType(0);
8551
8552   if (N0CFP && N1CFP)  // Constant fold
8553     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8554
8555   if (N1CFP) {
8556     const APFloat& V = N1CFP->getValueAPF();
8557     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8558     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8559     if (!V.isNegative()) {
8560       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8561         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8562     } else {
8563       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8564         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8565                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8566     }
8567   }
8568
8569   // copysign(fabs(x), y) -> copysign(x, y)
8570   // copysign(fneg(x), y) -> copysign(x, y)
8571   // copysign(copysign(x,z), y) -> copysign(x, y)
8572   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8573       N0.getOpcode() == ISD::FCOPYSIGN)
8574     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8575                        N0.getOperand(0), N1);
8576
8577   // copysign(x, abs(y)) -> abs(x)
8578   if (N1.getOpcode() == ISD::FABS)
8579     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8580
8581   // copysign(x, copysign(y,z)) -> copysign(x, z)
8582   if (N1.getOpcode() == ISD::FCOPYSIGN)
8583     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8584                        N0, N1.getOperand(1));
8585
8586   // copysign(x, fp_extend(y)) -> copysign(x, y)
8587   // copysign(x, fp_round(y)) -> copysign(x, y)
8588   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8589     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8590                        N0, N1.getOperand(0));
8591
8592   return SDValue();
8593 }
8594
8595 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8596   SDValue N0 = N->getOperand(0);
8597   EVT VT = N->getValueType(0);
8598   EVT OpVT = N0.getValueType();
8599
8600   // fold (sint_to_fp c1) -> c1fp
8601   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8602       // ...but only if the target supports immediate floating-point values
8603       (!LegalOperations ||
8604        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8605     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8606
8607   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8608   // but UINT_TO_FP is legal on this target, try to convert.
8609   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8610       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8611     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8612     if (DAG.SignBitIsZero(N0))
8613       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8614   }
8615
8616   // The next optimizations are desirable only if SELECT_CC can be lowered.
8617   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8618     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8619     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8620         !VT.isVector() &&
8621         (!LegalOperations ||
8622          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8623       SDLoc DL(N);
8624       SDValue Ops[] =
8625         { N0.getOperand(0), N0.getOperand(1),
8626           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8627           N0.getOperand(2) };
8628       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8629     }
8630
8631     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8632     //      (select_cc x, y, 1.0, 0.0,, cc)
8633     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8634         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8635         (!LegalOperations ||
8636          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8637       SDLoc DL(N);
8638       SDValue Ops[] =
8639         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8640           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8641           N0.getOperand(0).getOperand(2) };
8642       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8643     }
8644   }
8645
8646   return SDValue();
8647 }
8648
8649 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8650   SDValue N0 = N->getOperand(0);
8651   EVT VT = N->getValueType(0);
8652   EVT OpVT = N0.getValueType();
8653
8654   // fold (uint_to_fp c1) -> c1fp
8655   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8656       // ...but only if the target supports immediate floating-point values
8657       (!LegalOperations ||
8658        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8659     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8660
8661   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8662   // but SINT_TO_FP is legal on this target, try to convert.
8663   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8664       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8665     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8666     if (DAG.SignBitIsZero(N0))
8667       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8668   }
8669
8670   // The next optimizations are desirable only if SELECT_CC can be lowered.
8671   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8672     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8673
8674     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8675         (!LegalOperations ||
8676          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8677       SDLoc DL(N);
8678       SDValue Ops[] =
8679         { N0.getOperand(0), N0.getOperand(1),
8680           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8681           N0.getOperand(2) };
8682       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8683     }
8684   }
8685
8686   return SDValue();
8687 }
8688
8689 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8690 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8691   SDValue N0 = N->getOperand(0);
8692   EVT VT = N->getValueType(0);
8693
8694   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8695     return SDValue();
8696
8697   SDValue Src = N0.getOperand(0);
8698   EVT SrcVT = Src.getValueType();
8699   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8700   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8701
8702   // We can safely assume the conversion won't overflow the output range,
8703   // because (for example) (uint8_t)18293.f is undefined behavior.
8704
8705   // Since we can assume the conversion won't overflow, our decision as to
8706   // whether the input will fit in the float should depend on the minimum
8707   // of the input range and output range.
8708
8709   // This means this is also safe for a signed input and unsigned output, since
8710   // a negative input would lead to undefined behavior.
8711   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8712   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8713   unsigned ActualSize = std::min(InputSize, OutputSize);
8714   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8715
8716   // We can only fold away the float conversion if the input range can be
8717   // represented exactly in the float range.
8718   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8719     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8720       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8721                                                        : ISD::ZERO_EXTEND;
8722       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8723     }
8724     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8725       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8726     if (SrcVT == VT)
8727       return Src;
8728     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8729   }
8730   return SDValue();
8731 }
8732
8733 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8734   SDValue N0 = N->getOperand(0);
8735   EVT VT = N->getValueType(0);
8736
8737   // fold (fp_to_sint c1fp) -> c1
8738   if (isConstantFPBuildVectorOrConstantFP(N0))
8739     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8740
8741   return FoldIntToFPToInt(N, DAG);
8742 }
8743
8744 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8745   SDValue N0 = N->getOperand(0);
8746   EVT VT = N->getValueType(0);
8747
8748   // fold (fp_to_uint c1fp) -> c1
8749   if (isConstantFPBuildVectorOrConstantFP(N0))
8750     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8751
8752   return FoldIntToFPToInt(N, DAG);
8753 }
8754
8755 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8756   SDValue N0 = N->getOperand(0);
8757   SDValue N1 = N->getOperand(1);
8758   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8759   EVT VT = N->getValueType(0);
8760
8761   // fold (fp_round c1fp) -> c1fp
8762   if (N0CFP)
8763     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8764
8765   // fold (fp_round (fp_extend x)) -> x
8766   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8767     return N0.getOperand(0);
8768
8769   // fold (fp_round (fp_round x)) -> (fp_round x)
8770   if (N0.getOpcode() == ISD::FP_ROUND) {
8771     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8772     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8773     // If the first fp_round isn't a value preserving truncation, it might
8774     // introduce a tie in the second fp_round, that wouldn't occur in the
8775     // single-step fp_round we want to fold to.
8776     // In other words, double rounding isn't the same as rounding.
8777     // Also, this is a value preserving truncation iff both fp_round's are.
8778     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8779       SDLoc DL(N);
8780       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8781                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8782     }
8783   }
8784
8785   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8786   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8787     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8788                               N0.getOperand(0), N1);
8789     AddToWorklist(Tmp.getNode());
8790     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8791                        Tmp, N0.getOperand(1));
8792   }
8793
8794   return SDValue();
8795 }
8796
8797 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8798   SDValue N0 = N->getOperand(0);
8799   EVT VT = N->getValueType(0);
8800   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8801   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8802
8803   // fold (fp_round_inreg c1fp) -> c1fp
8804   if (N0CFP && isTypeLegal(EVT)) {
8805     SDLoc DL(N);
8806     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8807     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8808   }
8809
8810   return SDValue();
8811 }
8812
8813 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8814   SDValue N0 = N->getOperand(0);
8815   EVT VT = N->getValueType(0);
8816
8817   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8818   if (N->hasOneUse() &&
8819       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8820     return SDValue();
8821
8822   // fold (fp_extend c1fp) -> c1fp
8823   if (isConstantFPBuildVectorOrConstantFP(N0))
8824     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8825
8826   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8827   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8828       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8829     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8830
8831   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8832   // value of X.
8833   if (N0.getOpcode() == ISD::FP_ROUND
8834       && N0.getNode()->getConstantOperandVal(1) == 1) {
8835     SDValue In = N0.getOperand(0);
8836     if (In.getValueType() == VT) return In;
8837     if (VT.bitsLT(In.getValueType()))
8838       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8839                          In, N0.getOperand(1));
8840     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8841   }
8842
8843   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8844   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8845        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8846     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8847     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8848                                      LN0->getChain(),
8849                                      LN0->getBasePtr(), N0.getValueType(),
8850                                      LN0->getMemOperand());
8851     CombineTo(N, ExtLoad);
8852     CombineTo(N0.getNode(),
8853               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8854                           N0.getValueType(), ExtLoad,
8855                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8856               ExtLoad.getValue(1));
8857     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8858   }
8859
8860   return SDValue();
8861 }
8862
8863 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8864   SDValue N0 = N->getOperand(0);
8865   EVT VT = N->getValueType(0);
8866
8867   // fold (fceil c1) -> fceil(c1)
8868   if (isConstantFPBuildVectorOrConstantFP(N0))
8869     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8870
8871   return SDValue();
8872 }
8873
8874 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8875   SDValue N0 = N->getOperand(0);
8876   EVT VT = N->getValueType(0);
8877
8878   // fold (ftrunc c1) -> ftrunc(c1)
8879   if (isConstantFPBuildVectorOrConstantFP(N0))
8880     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8881
8882   return SDValue();
8883 }
8884
8885 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8886   SDValue N0 = N->getOperand(0);
8887   EVT VT = N->getValueType(0);
8888
8889   // fold (ffloor c1) -> ffloor(c1)
8890   if (isConstantFPBuildVectorOrConstantFP(N0))
8891     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8892
8893   return SDValue();
8894 }
8895
8896 // FIXME: FNEG and FABS have a lot in common; refactor.
8897 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8898   SDValue N0 = N->getOperand(0);
8899   EVT VT = N->getValueType(0);
8900
8901   // Constant fold FNEG.
8902   if (isConstantFPBuildVectorOrConstantFP(N0))
8903     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8904
8905   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8906                          &DAG.getTarget().Options))
8907     return GetNegatedExpression(N0, DAG, LegalOperations);
8908
8909   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8910   // constant pool values.
8911   if (!TLI.isFNegFree(VT) &&
8912       N0.getOpcode() == ISD::BITCAST &&
8913       N0.getNode()->hasOneUse()) {
8914     SDValue Int = N0.getOperand(0);
8915     EVT IntVT = Int.getValueType();
8916     if (IntVT.isInteger() && !IntVT.isVector()) {
8917       APInt SignMask;
8918       if (N0.getValueType().isVector()) {
8919         // For a vector, get a mask such as 0x80... per scalar element
8920         // and splat it.
8921         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8922         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8923       } else {
8924         // For a scalar, just generate 0x80...
8925         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8926       }
8927       SDLoc DL0(N0);
8928       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8929                         DAG.getConstant(SignMask, DL0, IntVT));
8930       AddToWorklist(Int.getNode());
8931       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8932     }
8933   }
8934
8935   // (fneg (fmul c, x)) -> (fmul -c, x)
8936   if (N0.getOpcode() == ISD::FMUL &&
8937       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8938     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8939     if (CFP1) {
8940       APFloat CVal = CFP1->getValueAPF();
8941       CVal.changeSign();
8942       if (Level >= AfterLegalizeDAG &&
8943           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8944            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8945         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8946                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8947                                        N0.getOperand(1)),
8948                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
8949     }
8950   }
8951
8952   return SDValue();
8953 }
8954
8955 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8956   SDValue N0 = N->getOperand(0);
8957   SDValue N1 = N->getOperand(1);
8958   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8959   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8960
8961   if (N0CFP && N1CFP) {
8962     const APFloat &C0 = N0CFP->getValueAPF();
8963     const APFloat &C1 = N1CFP->getValueAPF();
8964     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8965   }
8966
8967   if (N0CFP) {
8968     EVT VT = N->getValueType(0);
8969     // Canonicalize to constant on RHS.
8970     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8971   }
8972
8973   return SDValue();
8974 }
8975
8976 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8977   SDValue N0 = N->getOperand(0);
8978   SDValue N1 = N->getOperand(1);
8979   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8980   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8981
8982   if (N0CFP && N1CFP) {
8983     const APFloat &C0 = N0CFP->getValueAPF();
8984     const APFloat &C1 = N1CFP->getValueAPF();
8985     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8986   }
8987
8988   if (N0CFP) {
8989     EVT VT = N->getValueType(0);
8990     // Canonicalize to constant on RHS.
8991     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8992   }
8993
8994   return SDValue();
8995 }
8996
8997 SDValue DAGCombiner::visitFABS(SDNode *N) {
8998   SDValue N0 = N->getOperand(0);
8999   EVT VT = N->getValueType(0);
9000
9001   // fold (fabs c1) -> fabs(c1)
9002   if (isConstantFPBuildVectorOrConstantFP(N0))
9003     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9004
9005   // fold (fabs (fabs x)) -> (fabs x)
9006   if (N0.getOpcode() == ISD::FABS)
9007     return N->getOperand(0);
9008
9009   // fold (fabs (fneg x)) -> (fabs x)
9010   // fold (fabs (fcopysign x, y)) -> (fabs x)
9011   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9012     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9013
9014   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9015   // constant pool values.
9016   if (!TLI.isFAbsFree(VT) &&
9017       N0.getOpcode() == ISD::BITCAST &&
9018       N0.getNode()->hasOneUse()) {
9019     SDValue Int = N0.getOperand(0);
9020     EVT IntVT = Int.getValueType();
9021     if (IntVT.isInteger() && !IntVT.isVector()) {
9022       APInt SignMask;
9023       if (N0.getValueType().isVector()) {
9024         // For a vector, get a mask such as 0x7f... per scalar element
9025         // and splat it.
9026         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9027         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9028       } else {
9029         // For a scalar, just generate 0x7f...
9030         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9031       }
9032       SDLoc DL(N0);
9033       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9034                         DAG.getConstant(SignMask, DL, IntVT));
9035       AddToWorklist(Int.getNode());
9036       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9037     }
9038   }
9039
9040   return SDValue();
9041 }
9042
9043 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9044   SDValue Chain = N->getOperand(0);
9045   SDValue N1 = N->getOperand(1);
9046   SDValue N2 = N->getOperand(2);
9047
9048   // If N is a constant we could fold this into a fallthrough or unconditional
9049   // branch. However that doesn't happen very often in normal code, because
9050   // Instcombine/SimplifyCFG should have handled the available opportunities.
9051   // If we did this folding here, it would be necessary to update the
9052   // MachineBasicBlock CFG, which is awkward.
9053
9054   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9055   // on the target.
9056   if (N1.getOpcode() == ISD::SETCC &&
9057       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9058                                    N1.getOperand(0).getValueType())) {
9059     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9060                        Chain, N1.getOperand(2),
9061                        N1.getOperand(0), N1.getOperand(1), N2);
9062   }
9063
9064   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9065       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9066        (N1.getOperand(0).hasOneUse() &&
9067         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9068     SDNode *Trunc = nullptr;
9069     if (N1.getOpcode() == ISD::TRUNCATE) {
9070       // Look pass the truncate.
9071       Trunc = N1.getNode();
9072       N1 = N1.getOperand(0);
9073     }
9074
9075     // Match this pattern so that we can generate simpler code:
9076     //
9077     //   %a = ...
9078     //   %b = and i32 %a, 2
9079     //   %c = srl i32 %b, 1
9080     //   brcond i32 %c ...
9081     //
9082     // into
9083     //
9084     //   %a = ...
9085     //   %b = and i32 %a, 2
9086     //   %c = setcc eq %b, 0
9087     //   brcond %c ...
9088     //
9089     // This applies only when the AND constant value has one bit set and the
9090     // SRL constant is equal to the log2 of the AND constant. The back-end is
9091     // smart enough to convert the result into a TEST/JMP sequence.
9092     SDValue Op0 = N1.getOperand(0);
9093     SDValue Op1 = N1.getOperand(1);
9094
9095     if (Op0.getOpcode() == ISD::AND &&
9096         Op1.getOpcode() == ISD::Constant) {
9097       SDValue AndOp1 = Op0.getOperand(1);
9098
9099       if (AndOp1.getOpcode() == ISD::Constant) {
9100         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9101
9102         if (AndConst.isPowerOf2() &&
9103             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9104           SDLoc DL(N);
9105           SDValue SetCC =
9106             DAG.getSetCC(DL,
9107                          getSetCCResultType(Op0.getValueType()),
9108                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9109                          ISD::SETNE);
9110
9111           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9112                                           MVT::Other, Chain, SetCC, N2);
9113           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9114           // will convert it back to (X & C1) >> C2.
9115           CombineTo(N, NewBRCond, false);
9116           // Truncate is dead.
9117           if (Trunc)
9118             deleteAndRecombine(Trunc);
9119           // Replace the uses of SRL with SETCC
9120           WorklistRemover DeadNodes(*this);
9121           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9122           deleteAndRecombine(N1.getNode());
9123           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9124         }
9125       }
9126     }
9127
9128     if (Trunc)
9129       // Restore N1 if the above transformation doesn't match.
9130       N1 = N->getOperand(1);
9131   }
9132
9133   // Transform br(xor(x, y)) -> br(x != y)
9134   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9135   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9136     SDNode *TheXor = N1.getNode();
9137     SDValue Op0 = TheXor->getOperand(0);
9138     SDValue Op1 = TheXor->getOperand(1);
9139     if (Op0.getOpcode() == Op1.getOpcode()) {
9140       // Avoid missing important xor optimizations.
9141       if (SDValue Tmp = visitXOR(TheXor)) {
9142         if (Tmp.getNode() != TheXor) {
9143           DEBUG(dbgs() << "\nReplacing.8 ";
9144                 TheXor->dump(&DAG);
9145                 dbgs() << "\nWith: ";
9146                 Tmp.getNode()->dump(&DAG);
9147                 dbgs() << '\n');
9148           WorklistRemover DeadNodes(*this);
9149           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9150           deleteAndRecombine(TheXor);
9151           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9152                              MVT::Other, Chain, Tmp, N2);
9153         }
9154
9155         // visitXOR has changed XOR's operands or replaced the XOR completely,
9156         // bail out.
9157         return SDValue(N, 0);
9158       }
9159     }
9160
9161     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9162       bool Equal = false;
9163       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9164           Op0.getOpcode() == ISD::XOR) {
9165         TheXor = Op0.getNode();
9166         Equal = true;
9167       }
9168
9169       EVT SetCCVT = N1.getValueType();
9170       if (LegalTypes)
9171         SetCCVT = getSetCCResultType(SetCCVT);
9172       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9173                                    SetCCVT,
9174                                    Op0, Op1,
9175                                    Equal ? ISD::SETEQ : ISD::SETNE);
9176       // Replace the uses of XOR with SETCC
9177       WorklistRemover DeadNodes(*this);
9178       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9179       deleteAndRecombine(N1.getNode());
9180       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9181                          MVT::Other, Chain, SetCC, N2);
9182     }
9183   }
9184
9185   return SDValue();
9186 }
9187
9188 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9189 //
9190 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9191   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9192   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9193
9194   // If N is a constant we could fold this into a fallthrough or unconditional
9195   // branch. However that doesn't happen very often in normal code, because
9196   // Instcombine/SimplifyCFG should have handled the available opportunities.
9197   // If we did this folding here, it would be necessary to update the
9198   // MachineBasicBlock CFG, which is awkward.
9199
9200   // Use SimplifySetCC to simplify SETCC's.
9201   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9202                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9203                                false);
9204   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9205
9206   // fold to a simpler setcc
9207   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9208     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9209                        N->getOperand(0), Simp.getOperand(2),
9210                        Simp.getOperand(0), Simp.getOperand(1),
9211                        N->getOperand(4));
9212
9213   return SDValue();
9214 }
9215
9216 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9217 /// and that N may be folded in the load / store addressing mode.
9218 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9219                                     SelectionDAG &DAG,
9220                                     const TargetLowering &TLI) {
9221   EVT VT;
9222   unsigned AS;
9223
9224   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9225     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9226       return false;
9227     VT = LD->getMemoryVT();
9228     AS = LD->getAddressSpace();
9229   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9230     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9231       return false;
9232     VT = ST->getMemoryVT();
9233     AS = ST->getAddressSpace();
9234   } else
9235     return false;
9236
9237   TargetLowering::AddrMode AM;
9238   if (N->getOpcode() == ISD::ADD) {
9239     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9240     if (Offset)
9241       // [reg +/- imm]
9242       AM.BaseOffs = Offset->getSExtValue();
9243     else
9244       // [reg +/- reg]
9245       AM.Scale = 1;
9246   } else if (N->getOpcode() == ISD::SUB) {
9247     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9248     if (Offset)
9249       // [reg +/- imm]
9250       AM.BaseOffs = -Offset->getSExtValue();
9251     else
9252       // [reg +/- reg]
9253       AM.Scale = 1;
9254   } else
9255     return false;
9256
9257   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9258                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9259 }
9260
9261 /// Try turning a load/store into a pre-indexed load/store when the base
9262 /// pointer is an add or subtract and it has other uses besides the load/store.
9263 /// After the transformation, the new indexed load/store has effectively folded
9264 /// the add/subtract in and all of its other uses are redirected to the
9265 /// new load/store.
9266 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9267   if (Level < AfterLegalizeDAG)
9268     return false;
9269
9270   bool isLoad = true;
9271   SDValue Ptr;
9272   EVT VT;
9273   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9274     if (LD->isIndexed())
9275       return false;
9276     VT = LD->getMemoryVT();
9277     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9278         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9279       return false;
9280     Ptr = LD->getBasePtr();
9281   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9282     if (ST->isIndexed())
9283       return false;
9284     VT = ST->getMemoryVT();
9285     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9286         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9287       return false;
9288     Ptr = ST->getBasePtr();
9289     isLoad = false;
9290   } else {
9291     return false;
9292   }
9293
9294   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9295   // out.  There is no reason to make this a preinc/predec.
9296   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9297       Ptr.getNode()->hasOneUse())
9298     return false;
9299
9300   // Ask the target to do addressing mode selection.
9301   SDValue BasePtr;
9302   SDValue Offset;
9303   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9304   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9305     return false;
9306
9307   // Backends without true r+i pre-indexed forms may need to pass a
9308   // constant base with a variable offset so that constant coercion
9309   // will work with the patterns in canonical form.
9310   bool Swapped = false;
9311   if (isa<ConstantSDNode>(BasePtr)) {
9312     std::swap(BasePtr, Offset);
9313     Swapped = true;
9314   }
9315
9316   // Don't create a indexed load / store with zero offset.
9317   if (isNullConstant(Offset))
9318     return false;
9319
9320   // Try turning it into a pre-indexed load / store except when:
9321   // 1) The new base ptr is a frame index.
9322   // 2) If N is a store and the new base ptr is either the same as or is a
9323   //    predecessor of the value being stored.
9324   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9325   //    that would create a cycle.
9326   // 4) All uses are load / store ops that use it as old base ptr.
9327
9328   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9329   // (plus the implicit offset) to a register to preinc anyway.
9330   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9331     return false;
9332
9333   // Check #2.
9334   if (!isLoad) {
9335     SDValue Val = cast<StoreSDNode>(N)->getValue();
9336     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9337       return false;
9338   }
9339
9340   // If the offset is a constant, there may be other adds of constants that
9341   // can be folded with this one. We should do this to avoid having to keep
9342   // a copy of the original base pointer.
9343   SmallVector<SDNode *, 16> OtherUses;
9344   if (isa<ConstantSDNode>(Offset))
9345     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9346                               UE = BasePtr.getNode()->use_end();
9347          UI != UE; ++UI) {
9348       SDUse &Use = UI.getUse();
9349       // Skip the use that is Ptr and uses of other results from BasePtr's
9350       // node (important for nodes that return multiple results).
9351       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9352         continue;
9353
9354       if (Use.getUser()->isPredecessorOf(N))
9355         continue;
9356
9357       if (Use.getUser()->getOpcode() != ISD::ADD &&
9358           Use.getUser()->getOpcode() != ISD::SUB) {
9359         OtherUses.clear();
9360         break;
9361       }
9362
9363       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9364       if (!isa<ConstantSDNode>(Op1)) {
9365         OtherUses.clear();
9366         break;
9367       }
9368
9369       // FIXME: In some cases, we can be smarter about this.
9370       if (Op1.getValueType() != Offset.getValueType()) {
9371         OtherUses.clear();
9372         break;
9373       }
9374
9375       OtherUses.push_back(Use.getUser());
9376     }
9377
9378   if (Swapped)
9379     std::swap(BasePtr, Offset);
9380
9381   // Now check for #3 and #4.
9382   bool RealUse = false;
9383
9384   // Caches for hasPredecessorHelper
9385   SmallPtrSet<const SDNode *, 32> Visited;
9386   SmallVector<const SDNode *, 16> Worklist;
9387
9388   for (SDNode *Use : Ptr.getNode()->uses()) {
9389     if (Use == N)
9390       continue;
9391     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9392       return false;
9393
9394     // If Ptr may be folded in addressing mode of other use, then it's
9395     // not profitable to do this transformation.
9396     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9397       RealUse = true;
9398   }
9399
9400   if (!RealUse)
9401     return false;
9402
9403   SDValue Result;
9404   if (isLoad)
9405     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9406                                 BasePtr, Offset, AM);
9407   else
9408     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9409                                  BasePtr, Offset, AM);
9410   ++PreIndexedNodes;
9411   ++NodesCombined;
9412   DEBUG(dbgs() << "\nReplacing.4 ";
9413         N->dump(&DAG);
9414         dbgs() << "\nWith: ";
9415         Result.getNode()->dump(&DAG);
9416         dbgs() << '\n');
9417   WorklistRemover DeadNodes(*this);
9418   if (isLoad) {
9419     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9420     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9421   } else {
9422     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9423   }
9424
9425   // Finally, since the node is now dead, remove it from the graph.
9426   deleteAndRecombine(N);
9427
9428   if (Swapped)
9429     std::swap(BasePtr, Offset);
9430
9431   // Replace other uses of BasePtr that can be updated to use Ptr
9432   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9433     unsigned OffsetIdx = 1;
9434     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9435       OffsetIdx = 0;
9436     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9437            BasePtr.getNode() && "Expected BasePtr operand");
9438
9439     // We need to replace ptr0 in the following expression:
9440     //   x0 * offset0 + y0 * ptr0 = t0
9441     // knowing that
9442     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9443     //
9444     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9445     // indexed load/store and the expresion that needs to be re-written.
9446     //
9447     // Therefore, we have:
9448     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9449
9450     ConstantSDNode *CN =
9451       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9452     int X0, X1, Y0, Y1;
9453     APInt Offset0 = CN->getAPIntValue();
9454     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9455
9456     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9457     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9458     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9459     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9460
9461     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9462
9463     APInt CNV = Offset0;
9464     if (X0 < 0) CNV = -CNV;
9465     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9466     else CNV = CNV - Offset1;
9467
9468     SDLoc DL(OtherUses[i]);
9469
9470     // We can now generate the new expression.
9471     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9472     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9473
9474     SDValue NewUse = DAG.getNode(Opcode,
9475                                  DL,
9476                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9477     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9478     deleteAndRecombine(OtherUses[i]);
9479   }
9480
9481   // Replace the uses of Ptr with uses of the updated base value.
9482   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9483   deleteAndRecombine(Ptr.getNode());
9484
9485   return true;
9486 }
9487
9488 /// Try to combine a load/store with a add/sub of the base pointer node into a
9489 /// post-indexed load/store. The transformation folded the add/subtract into the
9490 /// new indexed load/store effectively and all of its uses are redirected to the
9491 /// new load/store.
9492 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9493   if (Level < AfterLegalizeDAG)
9494     return false;
9495
9496   bool isLoad = true;
9497   SDValue Ptr;
9498   EVT VT;
9499   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9500     if (LD->isIndexed())
9501       return false;
9502     VT = LD->getMemoryVT();
9503     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9504         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9505       return false;
9506     Ptr = LD->getBasePtr();
9507   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9508     if (ST->isIndexed())
9509       return false;
9510     VT = ST->getMemoryVT();
9511     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9512         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9513       return false;
9514     Ptr = ST->getBasePtr();
9515     isLoad = false;
9516   } else {
9517     return false;
9518   }
9519
9520   if (Ptr.getNode()->hasOneUse())
9521     return false;
9522
9523   for (SDNode *Op : Ptr.getNode()->uses()) {
9524     if (Op == N ||
9525         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9526       continue;
9527
9528     SDValue BasePtr;
9529     SDValue Offset;
9530     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9531     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9532       // Don't create a indexed load / store with zero offset.
9533       if (isNullConstant(Offset))
9534         continue;
9535
9536       // Try turning it into a post-indexed load / store except when
9537       // 1) All uses are load / store ops that use it as base ptr (and
9538       //    it may be folded as addressing mmode).
9539       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9540       //    nor a successor of N. Otherwise, if Op is folded that would
9541       //    create a cycle.
9542
9543       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9544         continue;
9545
9546       // Check for #1.
9547       bool TryNext = false;
9548       for (SDNode *Use : BasePtr.getNode()->uses()) {
9549         if (Use == Ptr.getNode())
9550           continue;
9551
9552         // If all the uses are load / store addresses, then don't do the
9553         // transformation.
9554         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9555           bool RealUse = false;
9556           for (SDNode *UseUse : Use->uses()) {
9557             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9558               RealUse = true;
9559           }
9560
9561           if (!RealUse) {
9562             TryNext = true;
9563             break;
9564           }
9565         }
9566       }
9567
9568       if (TryNext)
9569         continue;
9570
9571       // Check for #2
9572       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9573         SDValue Result = isLoad
9574           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9575                                BasePtr, Offset, AM)
9576           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9577                                 BasePtr, Offset, AM);
9578         ++PostIndexedNodes;
9579         ++NodesCombined;
9580         DEBUG(dbgs() << "\nReplacing.5 ";
9581               N->dump(&DAG);
9582               dbgs() << "\nWith: ";
9583               Result.getNode()->dump(&DAG);
9584               dbgs() << '\n');
9585         WorklistRemover DeadNodes(*this);
9586         if (isLoad) {
9587           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9588           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9589         } else {
9590           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9591         }
9592
9593         // Finally, since the node is now dead, remove it from the graph.
9594         deleteAndRecombine(N);
9595
9596         // Replace the uses of Use with uses of the updated base value.
9597         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9598                                       Result.getValue(isLoad ? 1 : 0));
9599         deleteAndRecombine(Op);
9600         return true;
9601       }
9602     }
9603   }
9604
9605   return false;
9606 }
9607
9608 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9609 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9610   ISD::MemIndexedMode AM = LD->getAddressingMode();
9611   assert(AM != ISD::UNINDEXED);
9612   SDValue BP = LD->getOperand(1);
9613   SDValue Inc = LD->getOperand(2);
9614
9615   // Some backends use TargetConstants for load offsets, but don't expect
9616   // TargetConstants in general ADD nodes. We can convert these constants into
9617   // regular Constants (if the constant is not opaque).
9618   assert((Inc.getOpcode() != ISD::TargetConstant ||
9619           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9620          "Cannot split out indexing using opaque target constants");
9621   if (Inc.getOpcode() == ISD::TargetConstant) {
9622     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9623     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9624                           ConstInc->getValueType(0));
9625   }
9626
9627   unsigned Opc =
9628       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9629   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9630 }
9631
9632 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9633   LoadSDNode *LD  = cast<LoadSDNode>(N);
9634   SDValue Chain = LD->getChain();
9635   SDValue Ptr   = LD->getBasePtr();
9636
9637   // If load is not volatile and there are no uses of the loaded value (and
9638   // the updated indexed value in case of indexed loads), change uses of the
9639   // chain value into uses of the chain input (i.e. delete the dead load).
9640   if (!LD->isVolatile()) {
9641     if (N->getValueType(1) == MVT::Other) {
9642       // Unindexed loads.
9643       if (!N->hasAnyUseOfValue(0)) {
9644         // It's not safe to use the two value CombineTo variant here. e.g.
9645         // v1, chain2 = load chain1, loc
9646         // v2, chain3 = load chain2, loc
9647         // v3         = add v2, c
9648         // Now we replace use of chain2 with chain1.  This makes the second load
9649         // isomorphic to the one we are deleting, and thus makes this load live.
9650         DEBUG(dbgs() << "\nReplacing.6 ";
9651               N->dump(&DAG);
9652               dbgs() << "\nWith chain: ";
9653               Chain.getNode()->dump(&DAG);
9654               dbgs() << "\n");
9655         WorklistRemover DeadNodes(*this);
9656         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9657
9658         if (N->use_empty())
9659           deleteAndRecombine(N);
9660
9661         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9662       }
9663     } else {
9664       // Indexed loads.
9665       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9666
9667       // If this load has an opaque TargetConstant offset, then we cannot split
9668       // the indexing into an add/sub directly (that TargetConstant may not be
9669       // valid for a different type of node, and we cannot convert an opaque
9670       // target constant into a regular constant).
9671       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9672                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9673
9674       if (!N->hasAnyUseOfValue(0) &&
9675           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9676         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9677         SDValue Index;
9678         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9679           Index = SplitIndexingFromLoad(LD);
9680           // Try to fold the base pointer arithmetic into subsequent loads and
9681           // stores.
9682           AddUsersToWorklist(N);
9683         } else
9684           Index = DAG.getUNDEF(N->getValueType(1));
9685         DEBUG(dbgs() << "\nReplacing.7 ";
9686               N->dump(&DAG);
9687               dbgs() << "\nWith: ";
9688               Undef.getNode()->dump(&DAG);
9689               dbgs() << " and 2 other values\n");
9690         WorklistRemover DeadNodes(*this);
9691         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9692         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9693         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9694         deleteAndRecombine(N);
9695         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9696       }
9697     }
9698   }
9699
9700   // If this load is directly stored, replace the load value with the stored
9701   // value.
9702   // TODO: Handle store large -> read small portion.
9703   // TODO: Handle TRUNCSTORE/LOADEXT
9704   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9705     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9706       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9707       if (PrevST->getBasePtr() == Ptr &&
9708           PrevST->getValue().getValueType() == N->getValueType(0))
9709       return CombineTo(N, Chain.getOperand(1), Chain);
9710     }
9711   }
9712
9713   // Try to infer better alignment information than the load already has.
9714   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9715     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9716       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9717         SDValue NewLoad =
9718                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9719                               LD->getValueType(0),
9720                               Chain, Ptr, LD->getPointerInfo(),
9721                               LD->getMemoryVT(),
9722                               LD->isVolatile(), LD->isNonTemporal(),
9723                               LD->isInvariant(), Align, LD->getAAInfo());
9724         if (NewLoad.getNode() != N)
9725           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9726       }
9727     }
9728   }
9729
9730   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9731                                                   : DAG.getSubtarget().useAA();
9732 #ifndef NDEBUG
9733   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9734       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9735     UseAA = false;
9736 #endif
9737   if (UseAA && LD->isUnindexed()) {
9738     // Walk up chain skipping non-aliasing memory nodes.
9739     SDValue BetterChain = FindBetterChain(N, Chain);
9740
9741     // If there is a better chain.
9742     if (Chain != BetterChain) {
9743       SDValue ReplLoad;
9744
9745       // Replace the chain to void dependency.
9746       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9747         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9748                                BetterChain, Ptr, LD->getMemOperand());
9749       } else {
9750         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9751                                   LD->getValueType(0),
9752                                   BetterChain, Ptr, LD->getMemoryVT(),
9753                                   LD->getMemOperand());
9754       }
9755
9756       // Create token factor to keep old chain connected.
9757       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9758                                   MVT::Other, Chain, ReplLoad.getValue(1));
9759
9760       // Make sure the new and old chains are cleaned up.
9761       AddToWorklist(Token.getNode());
9762
9763       // Replace uses with load result and token factor. Don't add users
9764       // to work list.
9765       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9766     }
9767   }
9768
9769   // Try transforming N to an indexed load.
9770   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9771     return SDValue(N, 0);
9772
9773   // Try to slice up N to more direct loads if the slices are mapped to
9774   // different register banks or pairing can take place.
9775   if (SliceUpLoad(N))
9776     return SDValue(N, 0);
9777
9778   return SDValue();
9779 }
9780
9781 namespace {
9782 /// \brief Helper structure used to slice a load in smaller loads.
9783 /// Basically a slice is obtained from the following sequence:
9784 /// Origin = load Ty1, Base
9785 /// Shift = srl Ty1 Origin, CstTy Amount
9786 /// Inst = trunc Shift to Ty2
9787 ///
9788 /// Then, it will be rewriten into:
9789 /// Slice = load SliceTy, Base + SliceOffset
9790 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9791 ///
9792 /// SliceTy is deduced from the number of bits that are actually used to
9793 /// build Inst.
9794 struct LoadedSlice {
9795   /// \brief Helper structure used to compute the cost of a slice.
9796   struct Cost {
9797     /// Are we optimizing for code size.
9798     bool ForCodeSize;
9799     /// Various cost.
9800     unsigned Loads;
9801     unsigned Truncates;
9802     unsigned CrossRegisterBanksCopies;
9803     unsigned ZExts;
9804     unsigned Shift;
9805
9806     Cost(bool ForCodeSize = false)
9807         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9808           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9809
9810     /// \brief Get the cost of one isolated slice.
9811     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9812         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9813           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9814       EVT TruncType = LS.Inst->getValueType(0);
9815       EVT LoadedType = LS.getLoadedType();
9816       if (TruncType != LoadedType &&
9817           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9818         ZExts = 1;
9819     }
9820
9821     /// \brief Account for slicing gain in the current cost.
9822     /// Slicing provide a few gains like removing a shift or a
9823     /// truncate. This method allows to grow the cost of the original
9824     /// load with the gain from this slice.
9825     void addSliceGain(const LoadedSlice &LS) {
9826       // Each slice saves a truncate.
9827       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9828       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9829                               LS.Inst->getValueType(0)))
9830         ++Truncates;
9831       // If there is a shift amount, this slice gets rid of it.
9832       if (LS.Shift)
9833         ++Shift;
9834       // If this slice can merge a cross register bank copy, account for it.
9835       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9836         ++CrossRegisterBanksCopies;
9837     }
9838
9839     Cost &operator+=(const Cost &RHS) {
9840       Loads += RHS.Loads;
9841       Truncates += RHS.Truncates;
9842       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9843       ZExts += RHS.ZExts;
9844       Shift += RHS.Shift;
9845       return *this;
9846     }
9847
9848     bool operator==(const Cost &RHS) const {
9849       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9850              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9851              ZExts == RHS.ZExts && Shift == RHS.Shift;
9852     }
9853
9854     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9855
9856     bool operator<(const Cost &RHS) const {
9857       // Assume cross register banks copies are as expensive as loads.
9858       // FIXME: Do we want some more target hooks?
9859       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9860       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9861       // Unless we are optimizing for code size, consider the
9862       // expensive operation first.
9863       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9864         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9865       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9866              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9867     }
9868
9869     bool operator>(const Cost &RHS) const { return RHS < *this; }
9870
9871     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9872
9873     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9874   };
9875   // The last instruction that represent the slice. This should be a
9876   // truncate instruction.
9877   SDNode *Inst;
9878   // The original load instruction.
9879   LoadSDNode *Origin;
9880   // The right shift amount in bits from the original load.
9881   unsigned Shift;
9882   // The DAG from which Origin came from.
9883   // This is used to get some contextual information about legal types, etc.
9884   SelectionDAG *DAG;
9885
9886   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9887               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9888       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9889
9890   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9891   /// \return Result is \p BitWidth and has used bits set to 1 and
9892   ///         not used bits set to 0.
9893   APInt getUsedBits() const {
9894     // Reproduce the trunc(lshr) sequence:
9895     // - Start from the truncated value.
9896     // - Zero extend to the desired bit width.
9897     // - Shift left.
9898     assert(Origin && "No original load to compare against.");
9899     unsigned BitWidth = Origin->getValueSizeInBits(0);
9900     assert(Inst && "This slice is not bound to an instruction");
9901     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9902            "Extracted slice is bigger than the whole type!");
9903     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9904     UsedBits.setAllBits();
9905     UsedBits = UsedBits.zext(BitWidth);
9906     UsedBits <<= Shift;
9907     return UsedBits;
9908   }
9909
9910   /// \brief Get the size of the slice to be loaded in bytes.
9911   unsigned getLoadedSize() const {
9912     unsigned SliceSize = getUsedBits().countPopulation();
9913     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9914     return SliceSize / 8;
9915   }
9916
9917   /// \brief Get the type that will be loaded for this slice.
9918   /// Note: This may not be the final type for the slice.
9919   EVT getLoadedType() const {
9920     assert(DAG && "Missing context");
9921     LLVMContext &Ctxt = *DAG->getContext();
9922     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9923   }
9924
9925   /// \brief Get the alignment of the load used for this slice.
9926   unsigned getAlignment() const {
9927     unsigned Alignment = Origin->getAlignment();
9928     unsigned Offset = getOffsetFromBase();
9929     if (Offset != 0)
9930       Alignment = MinAlign(Alignment, Alignment + Offset);
9931     return Alignment;
9932   }
9933
9934   /// \brief Check if this slice can be rewritten with legal operations.
9935   bool isLegal() const {
9936     // An invalid slice is not legal.
9937     if (!Origin || !Inst || !DAG)
9938       return false;
9939
9940     // Offsets are for indexed load only, we do not handle that.
9941     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9942       return false;
9943
9944     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9945
9946     // Check that the type is legal.
9947     EVT SliceType = getLoadedType();
9948     if (!TLI.isTypeLegal(SliceType))
9949       return false;
9950
9951     // Check that the load is legal for this type.
9952     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9953       return false;
9954
9955     // Check that the offset can be computed.
9956     // 1. Check its type.
9957     EVT PtrType = Origin->getBasePtr().getValueType();
9958     if (PtrType == MVT::Untyped || PtrType.isExtended())
9959       return false;
9960
9961     // 2. Check that it fits in the immediate.
9962     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9963       return false;
9964
9965     // 3. Check that the computation is legal.
9966     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9967       return false;
9968
9969     // Check that the zext is legal if it needs one.
9970     EVT TruncateType = Inst->getValueType(0);
9971     if (TruncateType != SliceType &&
9972         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9973       return false;
9974
9975     return true;
9976   }
9977
9978   /// \brief Get the offset in bytes of this slice in the original chunk of
9979   /// bits.
9980   /// \pre DAG != nullptr.
9981   uint64_t getOffsetFromBase() const {
9982     assert(DAG && "Missing context.");
9983     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9984     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9985     uint64_t Offset = Shift / 8;
9986     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9987     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9988            "The size of the original loaded type is not a multiple of a"
9989            " byte.");
9990     // If Offset is bigger than TySizeInBytes, it means we are loading all
9991     // zeros. This should have been optimized before in the process.
9992     assert(TySizeInBytes > Offset &&
9993            "Invalid shift amount for given loaded size");
9994     if (IsBigEndian)
9995       Offset = TySizeInBytes - Offset - getLoadedSize();
9996     return Offset;
9997   }
9998
9999   /// \brief Generate the sequence of instructions to load the slice
10000   /// represented by this object and redirect the uses of this slice to
10001   /// this new sequence of instructions.
10002   /// \pre this->Inst && this->Origin are valid Instructions and this
10003   /// object passed the legal check: LoadedSlice::isLegal returned true.
10004   /// \return The last instruction of the sequence used to load the slice.
10005   SDValue loadSlice() const {
10006     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10007     const SDValue &OldBaseAddr = Origin->getBasePtr();
10008     SDValue BaseAddr = OldBaseAddr;
10009     // Get the offset in that chunk of bytes w.r.t. the endianess.
10010     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10011     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10012     if (Offset) {
10013       // BaseAddr = BaseAddr + Offset.
10014       EVT ArithType = BaseAddr.getValueType();
10015       SDLoc DL(Origin);
10016       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10017                               DAG->getConstant(Offset, DL, ArithType));
10018     }
10019
10020     // Create the type of the loaded slice according to its size.
10021     EVT SliceType = getLoadedType();
10022
10023     // Create the load for the slice.
10024     SDValue LastInst = DAG->getLoad(
10025         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10026         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10027         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10028     // If the final type is not the same as the loaded type, this means that
10029     // we have to pad with zero. Create a zero extend for that.
10030     EVT FinalType = Inst->getValueType(0);
10031     if (SliceType != FinalType)
10032       LastInst =
10033           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10034     return LastInst;
10035   }
10036
10037   /// \brief Check if this slice can be merged with an expensive cross register
10038   /// bank copy. E.g.,
10039   /// i = load i32
10040   /// f = bitcast i32 i to float
10041   bool canMergeExpensiveCrossRegisterBankCopy() const {
10042     if (!Inst || !Inst->hasOneUse())
10043       return false;
10044     SDNode *Use = *Inst->use_begin();
10045     if (Use->getOpcode() != ISD::BITCAST)
10046       return false;
10047     assert(DAG && "Missing context");
10048     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10049     EVT ResVT = Use->getValueType(0);
10050     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10051     const TargetRegisterClass *ArgRC =
10052         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10053     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10054       return false;
10055
10056     // At this point, we know that we perform a cross-register-bank copy.
10057     // Check if it is expensive.
10058     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10059     // Assume bitcasts are cheap, unless both register classes do not
10060     // explicitly share a common sub class.
10061     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10062       return false;
10063
10064     // Check if it will be merged with the load.
10065     // 1. Check the alignment constraint.
10066     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10067         ResVT.getTypeForEVT(*DAG->getContext()));
10068
10069     if (RequiredAlignment > getAlignment())
10070       return false;
10071
10072     // 2. Check that the load is a legal operation for that type.
10073     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10074       return false;
10075
10076     // 3. Check that we do not have a zext in the way.
10077     if (Inst->getValueType(0) != getLoadedType())
10078       return false;
10079
10080     return true;
10081   }
10082 };
10083 }
10084
10085 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10086 /// \p UsedBits looks like 0..0 1..1 0..0.
10087 static bool areUsedBitsDense(const APInt &UsedBits) {
10088   // If all the bits are one, this is dense!
10089   if (UsedBits.isAllOnesValue())
10090     return true;
10091
10092   // Get rid of the unused bits on the right.
10093   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10094   // Get rid of the unused bits on the left.
10095   if (NarrowedUsedBits.countLeadingZeros())
10096     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10097   // Check that the chunk of bits is completely used.
10098   return NarrowedUsedBits.isAllOnesValue();
10099 }
10100
10101 /// \brief Check whether or not \p First and \p Second are next to each other
10102 /// in memory. This means that there is no hole between the bits loaded
10103 /// by \p First and the bits loaded by \p Second.
10104 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10105                                      const LoadedSlice &Second) {
10106   assert(First.Origin == Second.Origin && First.Origin &&
10107          "Unable to match different memory origins.");
10108   APInt UsedBits = First.getUsedBits();
10109   assert((UsedBits & Second.getUsedBits()) == 0 &&
10110          "Slices are not supposed to overlap.");
10111   UsedBits |= Second.getUsedBits();
10112   return areUsedBitsDense(UsedBits);
10113 }
10114
10115 /// \brief Adjust the \p GlobalLSCost according to the target
10116 /// paring capabilities and the layout of the slices.
10117 /// \pre \p GlobalLSCost should account for at least as many loads as
10118 /// there is in the slices in \p LoadedSlices.
10119 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10120                                  LoadedSlice::Cost &GlobalLSCost) {
10121   unsigned NumberOfSlices = LoadedSlices.size();
10122   // If there is less than 2 elements, no pairing is possible.
10123   if (NumberOfSlices < 2)
10124     return;
10125
10126   // Sort the slices so that elements that are likely to be next to each
10127   // other in memory are next to each other in the list.
10128   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10129             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10130     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10131     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10132   });
10133   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10134   // First (resp. Second) is the first (resp. Second) potentially candidate
10135   // to be placed in a paired load.
10136   const LoadedSlice *First = nullptr;
10137   const LoadedSlice *Second = nullptr;
10138   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10139                 // Set the beginning of the pair.
10140                                                            First = Second) {
10141
10142     Second = &LoadedSlices[CurrSlice];
10143
10144     // If First is NULL, it means we start a new pair.
10145     // Get to the next slice.
10146     if (!First)
10147       continue;
10148
10149     EVT LoadedType = First->getLoadedType();
10150
10151     // If the types of the slices are different, we cannot pair them.
10152     if (LoadedType != Second->getLoadedType())
10153       continue;
10154
10155     // Check if the target supplies paired loads for this type.
10156     unsigned RequiredAlignment = 0;
10157     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10158       // move to the next pair, this type is hopeless.
10159       Second = nullptr;
10160       continue;
10161     }
10162     // Check if we meet the alignment requirement.
10163     if (RequiredAlignment > First->getAlignment())
10164       continue;
10165
10166     // Check that both loads are next to each other in memory.
10167     if (!areSlicesNextToEachOther(*First, *Second))
10168       continue;
10169
10170     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10171     --GlobalLSCost.Loads;
10172     // Move to the next pair.
10173     Second = nullptr;
10174   }
10175 }
10176
10177 /// \brief Check the profitability of all involved LoadedSlice.
10178 /// Currently, it is considered profitable if there is exactly two
10179 /// involved slices (1) which are (2) next to each other in memory, and
10180 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10181 ///
10182 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10183 /// the elements themselves.
10184 ///
10185 /// FIXME: When the cost model will be mature enough, we can relax
10186 /// constraints (1) and (2).
10187 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10188                                 const APInt &UsedBits, bool ForCodeSize) {
10189   unsigned NumberOfSlices = LoadedSlices.size();
10190   if (StressLoadSlicing)
10191     return NumberOfSlices > 1;
10192
10193   // Check (1).
10194   if (NumberOfSlices != 2)
10195     return false;
10196
10197   // Check (2).
10198   if (!areUsedBitsDense(UsedBits))
10199     return false;
10200
10201   // Check (3).
10202   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10203   // The original code has one big load.
10204   OrigCost.Loads = 1;
10205   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10206     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10207     // Accumulate the cost of all the slices.
10208     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10209     GlobalSlicingCost += SliceCost;
10210
10211     // Account as cost in the original configuration the gain obtained
10212     // with the current slices.
10213     OrigCost.addSliceGain(LS);
10214   }
10215
10216   // If the target supports paired load, adjust the cost accordingly.
10217   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10218   return OrigCost > GlobalSlicingCost;
10219 }
10220
10221 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10222 /// operations, split it in the various pieces being extracted.
10223 ///
10224 /// This sort of thing is introduced by SROA.
10225 /// This slicing takes care not to insert overlapping loads.
10226 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10227 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10228   if (Level < AfterLegalizeDAG)
10229     return false;
10230
10231   LoadSDNode *LD = cast<LoadSDNode>(N);
10232   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10233       !LD->getValueType(0).isInteger())
10234     return false;
10235
10236   // Keep track of already used bits to detect overlapping values.
10237   // In that case, we will just abort the transformation.
10238   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10239
10240   SmallVector<LoadedSlice, 4> LoadedSlices;
10241
10242   // Check if this load is used as several smaller chunks of bits.
10243   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10244   // of computation for each trunc.
10245   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10246        UI != UIEnd; ++UI) {
10247     // Skip the uses of the chain.
10248     if (UI.getUse().getResNo() != 0)
10249       continue;
10250
10251     SDNode *User = *UI;
10252     unsigned Shift = 0;
10253
10254     // Check if this is a trunc(lshr).
10255     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10256         isa<ConstantSDNode>(User->getOperand(1))) {
10257       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10258       User = *User->use_begin();
10259     }
10260
10261     // At this point, User is a Truncate, iff we encountered, trunc or
10262     // trunc(lshr).
10263     if (User->getOpcode() != ISD::TRUNCATE)
10264       return false;
10265
10266     // The width of the type must be a power of 2 and greater than 8-bits.
10267     // Otherwise the load cannot be represented in LLVM IR.
10268     // Moreover, if we shifted with a non-8-bits multiple, the slice
10269     // will be across several bytes. We do not support that.
10270     unsigned Width = User->getValueSizeInBits(0);
10271     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10272       return 0;
10273
10274     // Build the slice for this chain of computations.
10275     LoadedSlice LS(User, LD, Shift, &DAG);
10276     APInt CurrentUsedBits = LS.getUsedBits();
10277
10278     // Check if this slice overlaps with another.
10279     if ((CurrentUsedBits & UsedBits) != 0)
10280       return false;
10281     // Update the bits used globally.
10282     UsedBits |= CurrentUsedBits;
10283
10284     // Check if the new slice would be legal.
10285     if (!LS.isLegal())
10286       return false;
10287
10288     // Record the slice.
10289     LoadedSlices.push_back(LS);
10290   }
10291
10292   // Abort slicing if it does not seem to be profitable.
10293   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10294     return false;
10295
10296   ++SlicedLoads;
10297
10298   // Rewrite each chain to use an independent load.
10299   // By construction, each chain can be represented by a unique load.
10300
10301   // Prepare the argument for the new token factor for all the slices.
10302   SmallVector<SDValue, 8> ArgChains;
10303   for (SmallVectorImpl<LoadedSlice>::const_iterator
10304            LSIt = LoadedSlices.begin(),
10305            LSItEnd = LoadedSlices.end();
10306        LSIt != LSItEnd; ++LSIt) {
10307     SDValue SliceInst = LSIt->loadSlice();
10308     CombineTo(LSIt->Inst, SliceInst, true);
10309     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10310       SliceInst = SliceInst.getOperand(0);
10311     assert(SliceInst->getOpcode() == ISD::LOAD &&
10312            "It takes more than a zext to get to the loaded slice!!");
10313     ArgChains.push_back(SliceInst.getValue(1));
10314   }
10315
10316   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10317                               ArgChains);
10318   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10319   return true;
10320 }
10321
10322 /// Check to see if V is (and load (ptr), imm), where the load is having
10323 /// specific bytes cleared out.  If so, return the byte size being masked out
10324 /// and the shift amount.
10325 static std::pair<unsigned, unsigned>
10326 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10327   std::pair<unsigned, unsigned> Result(0, 0);
10328
10329   // Check for the structure we're looking for.
10330   if (V->getOpcode() != ISD::AND ||
10331       !isa<ConstantSDNode>(V->getOperand(1)) ||
10332       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10333     return Result;
10334
10335   // Check the chain and pointer.
10336   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10337   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10338
10339   // The store should be chained directly to the load or be an operand of a
10340   // tokenfactor.
10341   if (LD == Chain.getNode())
10342     ; // ok.
10343   else if (Chain->getOpcode() != ISD::TokenFactor)
10344     return Result; // Fail.
10345   else {
10346     bool isOk = false;
10347     for (const SDValue &ChainOp : Chain->op_values())
10348       if (ChainOp.getNode() == LD) {
10349         isOk = true;
10350         break;
10351       }
10352     if (!isOk) return Result;
10353   }
10354
10355   // This only handles simple types.
10356   if (V.getValueType() != MVT::i16 &&
10357       V.getValueType() != MVT::i32 &&
10358       V.getValueType() != MVT::i64)
10359     return Result;
10360
10361   // Check the constant mask.  Invert it so that the bits being masked out are
10362   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10363   // follow the sign bit for uniformity.
10364   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10365   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10366   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10367   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10368   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10369   if (NotMaskLZ == 64) return Result;  // All zero mask.
10370
10371   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10372   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10373     return Result;
10374
10375   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10376   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10377     NotMaskLZ -= 64-V.getValueSizeInBits();
10378
10379   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10380   switch (MaskedBytes) {
10381   case 1:
10382   case 2:
10383   case 4: break;
10384   default: return Result; // All one mask, or 5-byte mask.
10385   }
10386
10387   // Verify that the first bit starts at a multiple of mask so that the access
10388   // is aligned the same as the access width.
10389   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10390
10391   Result.first = MaskedBytes;
10392   Result.second = NotMaskTZ/8;
10393   return Result;
10394 }
10395
10396
10397 /// Check to see if IVal is something that provides a value as specified by
10398 /// MaskInfo. If so, replace the specified store with a narrower store of
10399 /// truncated IVal.
10400 static SDNode *
10401 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10402                                 SDValue IVal, StoreSDNode *St,
10403                                 DAGCombiner *DC) {
10404   unsigned NumBytes = MaskInfo.first;
10405   unsigned ByteShift = MaskInfo.second;
10406   SelectionDAG &DAG = DC->getDAG();
10407
10408   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10409   // that uses this.  If not, this is not a replacement.
10410   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10411                                   ByteShift*8, (ByteShift+NumBytes)*8);
10412   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10413
10414   // Check that it is legal on the target to do this.  It is legal if the new
10415   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10416   // legalization.
10417   MVT VT = MVT::getIntegerVT(NumBytes*8);
10418   if (!DC->isTypeLegal(VT))
10419     return nullptr;
10420
10421   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10422   // shifted by ByteShift and truncated down to NumBytes.
10423   if (ByteShift) {
10424     SDLoc DL(IVal);
10425     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10426                        DAG.getConstant(ByteShift*8, DL,
10427                                     DC->getShiftAmountTy(IVal.getValueType())));
10428   }
10429
10430   // Figure out the offset for the store and the alignment of the access.
10431   unsigned StOffset;
10432   unsigned NewAlign = St->getAlignment();
10433
10434   if (DAG.getDataLayout().isLittleEndian())
10435     StOffset = ByteShift;
10436   else
10437     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10438
10439   SDValue Ptr = St->getBasePtr();
10440   if (StOffset) {
10441     SDLoc DL(IVal);
10442     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10443                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10444     NewAlign = MinAlign(NewAlign, StOffset);
10445   }
10446
10447   // Truncate down to the new size.
10448   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10449
10450   ++OpsNarrowed;
10451   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10452                       St->getPointerInfo().getWithOffset(StOffset),
10453                       false, false, NewAlign).getNode();
10454 }
10455
10456
10457 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10458 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10459 /// narrowing the load and store if it would end up being a win for performance
10460 /// or code size.
10461 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10462   StoreSDNode *ST  = cast<StoreSDNode>(N);
10463   if (ST->isVolatile())
10464     return SDValue();
10465
10466   SDValue Chain = ST->getChain();
10467   SDValue Value = ST->getValue();
10468   SDValue Ptr   = ST->getBasePtr();
10469   EVT VT = Value.getValueType();
10470
10471   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10472     return SDValue();
10473
10474   unsigned Opc = Value.getOpcode();
10475
10476   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10477   // is a byte mask indicating a consecutive number of bytes, check to see if
10478   // Y is known to provide just those bytes.  If so, we try to replace the
10479   // load + replace + store sequence with a single (narrower) store, which makes
10480   // the load dead.
10481   if (Opc == ISD::OR) {
10482     std::pair<unsigned, unsigned> MaskedLoad;
10483     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10484     if (MaskedLoad.first)
10485       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10486                                                   Value.getOperand(1), ST,this))
10487         return SDValue(NewST, 0);
10488
10489     // Or is commutative, so try swapping X and Y.
10490     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10491     if (MaskedLoad.first)
10492       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10493                                                   Value.getOperand(0), ST,this))
10494         return SDValue(NewST, 0);
10495   }
10496
10497   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10498       Value.getOperand(1).getOpcode() != ISD::Constant)
10499     return SDValue();
10500
10501   SDValue N0 = Value.getOperand(0);
10502   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10503       Chain == SDValue(N0.getNode(), 1)) {
10504     LoadSDNode *LD = cast<LoadSDNode>(N0);
10505     if (LD->getBasePtr() != Ptr ||
10506         LD->getPointerInfo().getAddrSpace() !=
10507         ST->getPointerInfo().getAddrSpace())
10508       return SDValue();
10509
10510     // Find the type to narrow it the load / op / store to.
10511     SDValue N1 = Value.getOperand(1);
10512     unsigned BitWidth = N1.getValueSizeInBits();
10513     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10514     if (Opc == ISD::AND)
10515       Imm ^= APInt::getAllOnesValue(BitWidth);
10516     if (Imm == 0 || Imm.isAllOnesValue())
10517       return SDValue();
10518     unsigned ShAmt = Imm.countTrailingZeros();
10519     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10520     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10521     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10522     // The narrowing should be profitable, the load/store operation should be
10523     // legal (or custom) and the store size should be equal to the NewVT width.
10524     while (NewBW < BitWidth &&
10525            (NewVT.getStoreSizeInBits() != NewBW ||
10526             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10527             !TLI.isNarrowingProfitable(VT, NewVT))) {
10528       NewBW = NextPowerOf2(NewBW);
10529       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10530     }
10531     if (NewBW >= BitWidth)
10532       return SDValue();
10533
10534     // If the lsb changed does not start at the type bitwidth boundary,
10535     // start at the previous one.
10536     if (ShAmt % NewBW)
10537       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10538     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10539                                    std::min(BitWidth, ShAmt + NewBW));
10540     if ((Imm & Mask) == Imm) {
10541       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10542       if (Opc == ISD::AND)
10543         NewImm ^= APInt::getAllOnesValue(NewBW);
10544       uint64_t PtrOff = ShAmt / 8;
10545       // For big endian targets, we need to adjust the offset to the pointer to
10546       // load the correct bytes.
10547       if (DAG.getDataLayout().isBigEndian())
10548         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10549
10550       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10551       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10552       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10553         return SDValue();
10554
10555       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10556                                    Ptr.getValueType(), Ptr,
10557                                    DAG.getConstant(PtrOff, SDLoc(LD),
10558                                                    Ptr.getValueType()));
10559       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10560                                   LD->getChain(), NewPtr,
10561                                   LD->getPointerInfo().getWithOffset(PtrOff),
10562                                   LD->isVolatile(), LD->isNonTemporal(),
10563                                   LD->isInvariant(), NewAlign,
10564                                   LD->getAAInfo());
10565       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10566                                    DAG.getConstant(NewImm, SDLoc(Value),
10567                                                    NewVT));
10568       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10569                                    NewVal, NewPtr,
10570                                    ST->getPointerInfo().getWithOffset(PtrOff),
10571                                    false, false, NewAlign);
10572
10573       AddToWorklist(NewPtr.getNode());
10574       AddToWorklist(NewLD.getNode());
10575       AddToWorklist(NewVal.getNode());
10576       WorklistRemover DeadNodes(*this);
10577       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10578       ++OpsNarrowed;
10579       return NewST;
10580     }
10581   }
10582
10583   return SDValue();
10584 }
10585
10586 /// For a given floating point load / store pair, if the load value isn't used
10587 /// by any other operations, then consider transforming the pair to integer
10588 /// load / store operations if the target deems the transformation profitable.
10589 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10590   StoreSDNode *ST  = cast<StoreSDNode>(N);
10591   SDValue Chain = ST->getChain();
10592   SDValue Value = ST->getValue();
10593   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10594       Value.hasOneUse() &&
10595       Chain == SDValue(Value.getNode(), 1)) {
10596     LoadSDNode *LD = cast<LoadSDNode>(Value);
10597     EVT VT = LD->getMemoryVT();
10598     if (!VT.isFloatingPoint() ||
10599         VT != ST->getMemoryVT() ||
10600         LD->isNonTemporal() ||
10601         ST->isNonTemporal() ||
10602         LD->getPointerInfo().getAddrSpace() != 0 ||
10603         ST->getPointerInfo().getAddrSpace() != 0)
10604       return SDValue();
10605
10606     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10607     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10608         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10609         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10610         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10611       return SDValue();
10612
10613     unsigned LDAlign = LD->getAlignment();
10614     unsigned STAlign = ST->getAlignment();
10615     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10616     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10617     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10618       return SDValue();
10619
10620     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10621                                 LD->getChain(), LD->getBasePtr(),
10622                                 LD->getPointerInfo(),
10623                                 false, false, false, LDAlign);
10624
10625     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10626                                  NewLD, ST->getBasePtr(),
10627                                  ST->getPointerInfo(),
10628                                  false, false, STAlign);
10629
10630     AddToWorklist(NewLD.getNode());
10631     AddToWorklist(NewST.getNode());
10632     WorklistRemover DeadNodes(*this);
10633     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10634     ++LdStFP2Int;
10635     return NewST;
10636   }
10637
10638   return SDValue();
10639 }
10640
10641 namespace {
10642 /// Helper struct to parse and store a memory address as base + index + offset.
10643 /// We ignore sign extensions when it is safe to do so.
10644 /// The following two expressions are not equivalent. To differentiate we need
10645 /// to store whether there was a sign extension involved in the index
10646 /// computation.
10647 ///  (load (i64 add (i64 copyfromreg %c)
10648 ///                 (i64 signextend (add (i8 load %index)
10649 ///                                      (i8 1))))
10650 /// vs
10651 ///
10652 /// (load (i64 add (i64 copyfromreg %c)
10653 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10654 ///                                         (i32 1)))))
10655 struct BaseIndexOffset {
10656   SDValue Base;
10657   SDValue Index;
10658   int64_t Offset;
10659   bool IsIndexSignExt;
10660
10661   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10662
10663   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10664                   bool IsIndexSignExt) :
10665     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10666
10667   bool equalBaseIndex(const BaseIndexOffset &Other) {
10668     return Other.Base == Base && Other.Index == Index &&
10669       Other.IsIndexSignExt == IsIndexSignExt;
10670   }
10671
10672   /// Parses tree in Ptr for base, index, offset addresses.
10673   static BaseIndexOffset match(SDValue Ptr) {
10674     bool IsIndexSignExt = false;
10675
10676     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10677     // instruction, then it could be just the BASE or everything else we don't
10678     // know how to handle. Just use Ptr as BASE and give up.
10679     if (Ptr->getOpcode() != ISD::ADD)
10680       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10681
10682     // We know that we have at least an ADD instruction. Try to pattern match
10683     // the simple case of BASE + OFFSET.
10684     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10685       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10686       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10687                               IsIndexSignExt);
10688     }
10689
10690     // Inside a loop the current BASE pointer is calculated using an ADD and a
10691     // MUL instruction. In this case Ptr is the actual BASE pointer.
10692     // (i64 add (i64 %array_ptr)
10693     //          (i64 mul (i64 %induction_var)
10694     //                   (i64 %element_size)))
10695     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10696       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10697
10698     // Look at Base + Index + Offset cases.
10699     SDValue Base = Ptr->getOperand(0);
10700     SDValue IndexOffset = Ptr->getOperand(1);
10701
10702     // Skip signextends.
10703     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10704       IndexOffset = IndexOffset->getOperand(0);
10705       IsIndexSignExt = true;
10706     }
10707
10708     // Either the case of Base + Index (no offset) or something else.
10709     if (IndexOffset->getOpcode() != ISD::ADD)
10710       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10711
10712     // Now we have the case of Base + Index + offset.
10713     SDValue Index = IndexOffset->getOperand(0);
10714     SDValue Offset = IndexOffset->getOperand(1);
10715
10716     if (!isa<ConstantSDNode>(Offset))
10717       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10718
10719     // Ignore signextends.
10720     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10721       Index = Index->getOperand(0);
10722       IsIndexSignExt = true;
10723     } else IsIndexSignExt = false;
10724
10725     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10726     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10727   }
10728 };
10729 } // namespace
10730
10731 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10732                                                   SDLoc SL,
10733                                                   ArrayRef<MemOpLink> Stores,
10734                                                   EVT Ty) const {
10735   SmallVector<SDValue, 8> BuildVector;
10736
10737   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10738     BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10739
10740   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10741 }
10742
10743 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10744                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10745                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10746   // Make sure we have something to merge.
10747   if (NumStores < 2)
10748     return false;
10749
10750   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10751   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10752   unsigned LatestNodeUsed = 0;
10753
10754   for (unsigned i=0; i < NumStores; ++i) {
10755     // Find a chain for the new wide-store operand. Notice that some
10756     // of the store nodes that we found may not be selected for inclusion
10757     // in the wide store. The chain we use needs to be the chain of the
10758     // latest store node which is *used* and replaced by the wide store.
10759     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10760       LatestNodeUsed = i;
10761   }
10762
10763   // The latest Node in the DAG.
10764   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10765   SDLoc DL(StoreNodes[0].MemNode);
10766
10767   SDValue StoredVal;
10768   if (UseVector) {
10769     bool IsVec = MemVT.isVector();
10770     unsigned Elts = NumStores;
10771     if (IsVec) {
10772       // When merging vector stores, get the total number of elements.
10773       Elts *= MemVT.getVectorNumElements();
10774     }
10775     // Get the type for the merged vector store.
10776     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10777     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10778
10779     if (IsConstantSrc) {
10780       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10781     } else {
10782       SmallVector<SDValue, 8> Ops;
10783       for (unsigned i = 0; i < NumStores; ++i) {
10784         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10785         SDValue Val = St->getValue();
10786         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10787         if (Val.getValueType() != MemVT)
10788           return false;
10789         Ops.push_back(Val);
10790       }
10791
10792       // Build the extracted vector elements back into a vector.
10793       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10794                               DL, Ty, Ops);    }
10795   } else {
10796     // We should always use a vector store when merging extracted vector
10797     // elements, so this path implies a store of constants.
10798     assert(IsConstantSrc && "Merged vector elements should use vector store");
10799
10800     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10801     APInt StoreInt(SizeInBits, 0);
10802
10803     // Construct a single integer constant which is made of the smaller
10804     // constant inputs.
10805     bool IsLE = DAG.getDataLayout().isLittleEndian();
10806     for (unsigned i = 0; i < NumStores; ++i) {
10807       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10808       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10809       SDValue Val = St->getValue();
10810       StoreInt <<= ElementSizeBytes * 8;
10811       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10812         StoreInt |= C->getAPIntValue().zext(SizeInBits);
10813       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10814         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10815       } else {
10816         llvm_unreachable("Invalid constant element type");
10817       }
10818     }
10819
10820     // Create the new Load and Store operations.
10821     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10822     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10823   }
10824
10825   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10826                                   FirstInChain->getBasePtr(),
10827                                   FirstInChain->getPointerInfo(),
10828                                   false, false,
10829                                   FirstInChain->getAlignment());
10830
10831   // Replace the last store with the new store
10832   CombineTo(LatestOp, NewStore);
10833   // Erase all other stores.
10834   for (unsigned i = 0; i < NumStores; ++i) {
10835     if (StoreNodes[i].MemNode == LatestOp)
10836       continue;
10837     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10838     // ReplaceAllUsesWith will replace all uses that existed when it was
10839     // called, but graph optimizations may cause new ones to appear. For
10840     // example, the case in pr14333 looks like
10841     //
10842     //  St's chain -> St -> another store -> X
10843     //
10844     // And the only difference from St to the other store is the chain.
10845     // When we change it's chain to be St's chain they become identical,
10846     // get CSEed and the net result is that X is now a use of St.
10847     // Since we know that St is redundant, just iterate.
10848     while (!St->use_empty())
10849       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10850     deleteAndRecombine(St);
10851   }
10852
10853   return true;
10854 }
10855
10856 void DAGCombiner::getStoreMergeAndAliasCandidates(
10857     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10858     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10859   // This holds the base pointer, index, and the offset in bytes from the base
10860   // pointer.
10861   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10862
10863   // We must have a base and an offset.
10864   if (!BasePtr.Base.getNode())
10865     return;
10866
10867   // Do not handle stores to undef base pointers.
10868   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10869     return;
10870
10871   // Walk up the chain and look for nodes with offsets from the same
10872   // base pointer. Stop when reaching an instruction with a different kind
10873   // or instruction which has a different base pointer.
10874   EVT MemVT = St->getMemoryVT();
10875   unsigned Seq = 0;
10876   StoreSDNode *Index = St;
10877
10878
10879   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10880                                                   : DAG.getSubtarget().useAA();
10881
10882   if (UseAA) {
10883     // Look at other users of the same chain. Stores on the same chain do not
10884     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
10885     // to be on the same chain, so don't bother looking at adjacent chains.
10886
10887     SDValue Chain = St->getChain();
10888     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
10889       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
10890
10891         if (OtherST->isVolatile() || OtherST->isIndexed())
10892           continue;
10893
10894         if (OtherST->getMemoryVT() != MemVT)
10895           continue;
10896
10897         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
10898
10899         if (Ptr.equalBaseIndex(BasePtr))
10900           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
10901       }
10902     }
10903
10904     return;
10905   }
10906
10907   while (Index) {
10908     // If the chain has more than one use, then we can't reorder the mem ops.
10909     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10910       break;
10911
10912     // Find the base pointer and offset for this memory node.
10913     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10914
10915     // Check that the base pointer is the same as the original one.
10916     if (!Ptr.equalBaseIndex(BasePtr))
10917       break;
10918
10919     // The memory operands must not be volatile.
10920     if (Index->isVolatile() || Index->isIndexed())
10921       break;
10922
10923     // No truncation.
10924     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10925       if (St->isTruncatingStore())
10926         break;
10927
10928     // The stored memory type must be the same.
10929     if (Index->getMemoryVT() != MemVT)
10930       break;
10931
10932     // We found a potential memory operand to merge.
10933     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10934
10935     // Find the next memory operand in the chain. If the next operand in the
10936     // chain is a store then move up and continue the scan with the next
10937     // memory operand. If the next operand is a load save it and use alias
10938     // information to check if it interferes with anything.
10939     SDNode *NextInChain = Index->getChain().getNode();
10940     while (1) {
10941       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10942         // We found a store node. Use it for the next iteration.
10943         Index = STn;
10944         break;
10945       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10946         if (Ldn->isVolatile()) {
10947           Index = nullptr;
10948           break;
10949         }
10950
10951         // Save the load node for later. Continue the scan.
10952         AliasLoadNodes.push_back(Ldn);
10953         NextInChain = Ldn->getChain().getNode();
10954         continue;
10955       } else {
10956         Index = nullptr;
10957         break;
10958       }
10959     }
10960   }
10961 }
10962
10963 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10964   if (OptLevel == CodeGenOpt::None)
10965     return false;
10966
10967   EVT MemVT = St->getMemoryVT();
10968   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10969   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10970       Attribute::NoImplicitFloat);
10971
10972   // This function cannot currently deal with non-byte-sized memory sizes.
10973   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10974     return false;
10975
10976   // Don't merge vectors into wider inputs.
10977   if (MemVT.isVector() || !MemVT.isSimple())
10978     return false;
10979
10980   // Perform an early exit check. Do not bother looking at stored values that
10981   // are not constants, loads, or extracted vector elements.
10982   SDValue StoredVal = St->getValue();
10983   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10984   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10985                        isa<ConstantFPSDNode>(StoredVal);
10986   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10987
10988   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10989     return false;
10990
10991   // Only look at ends of store sequences.
10992   SDValue Chain = SDValue(St, 0);
10993   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10994     return false;
10995
10996   // Save the LoadSDNodes that we find in the chain.
10997   // We need to make sure that these nodes do not interfere with
10998   // any of the store nodes.
10999   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11000
11001   // Save the StoreSDNodes that we find in the chain.
11002   SmallVector<MemOpLink, 8> StoreNodes;
11003
11004   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11005
11006   // Check if there is anything to merge.
11007   if (StoreNodes.size() < 2)
11008     return false;
11009
11010   // Sort the memory operands according to their distance from the base pointer.
11011   std::sort(StoreNodes.begin(), StoreNodes.end(),
11012             [](MemOpLink LHS, MemOpLink RHS) {
11013     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11014            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11015             LHS.SequenceNum > RHS.SequenceNum);
11016   });
11017
11018   // Scan the memory operations on the chain and find the first non-consecutive
11019   // store memory address.
11020   unsigned LastConsecutiveStore = 0;
11021   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11022   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11023
11024     // Check that the addresses are consecutive starting from the second
11025     // element in the list of stores.
11026     if (i > 0) {
11027       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11028       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11029         break;
11030     }
11031
11032     bool Alias = false;
11033     // Check if this store interferes with any of the loads that we found.
11034     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11035       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11036         Alias = true;
11037         break;
11038       }
11039     // We found a load that alias with this store. Stop the sequence.
11040     if (Alias)
11041       break;
11042
11043     // Mark this node as useful.
11044     LastConsecutiveStore = i;
11045   }
11046
11047   // The node with the lowest store address.
11048   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11049   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11050   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11051   LLVMContext &Context = *DAG.getContext();
11052   const DataLayout &DL = DAG.getDataLayout();
11053
11054   // Store the constants into memory as one consecutive store.
11055   if (IsConstantSrc) {
11056     unsigned LastLegalType = 0;
11057     unsigned LastLegalVectorType = 0;
11058     bool NonZero = false;
11059     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11060       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11061       SDValue StoredVal = St->getValue();
11062
11063       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11064         NonZero |= !C->isNullValue();
11065       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11066         NonZero |= !C->getConstantFPValue()->isNullValue();
11067       } else {
11068         // Non-constant.
11069         break;
11070       }
11071
11072       // Find a legal type for the constant store.
11073       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11074       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11075       bool IsFast;
11076       if (TLI.isTypeLegal(StoreTy) &&
11077           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11078                                  FirstStoreAlign, &IsFast) && IsFast) {
11079         LastLegalType = i+1;
11080       // Or check whether a truncstore is legal.
11081       } else if (TLI.getTypeAction(Context, StoreTy) ==
11082                  TargetLowering::TypePromoteInteger) {
11083         EVT LegalizedStoredValueTy =
11084           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11085         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11086             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11087                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11088             IsFast) {
11089           LastLegalType = i + 1;
11090         }
11091       }
11092
11093       // We only use vectors if the constant is known to be zero or the target
11094       // allows it and the function is not marked with the noimplicitfloat
11095       // attribute.
11096       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11097                                                         FirstStoreAS)) &&
11098           !NoVectors) {
11099         // Find a legal type for the vector store.
11100         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11101         if (TLI.isTypeLegal(Ty) &&
11102             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11103                                    FirstStoreAlign, &IsFast) && IsFast)
11104           LastLegalVectorType = i + 1;
11105       }
11106     }
11107
11108     // Check if we found a legal integer type to store.
11109     if (LastLegalType == 0 && LastLegalVectorType == 0)
11110       return false;
11111
11112     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11113     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11114
11115     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11116                                            true, UseVector);
11117   }
11118
11119   // When extracting multiple vector elements, try to store them
11120   // in one vector store rather than a sequence of scalar stores.
11121   if (IsExtractVecEltSrc) {
11122     unsigned NumElem = 0;
11123     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11124       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11125       SDValue StoredVal = St->getValue();
11126       // This restriction could be loosened.
11127       // Bail out if any stored values are not elements extracted from a vector.
11128       // It should be possible to handle mixed sources, but load sources need
11129       // more careful handling (see the block of code below that handles
11130       // consecutive loads).
11131       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11132         return false;
11133
11134       // Find a legal type for the vector store.
11135       EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11136       bool IsFast;
11137       if (TLI.isTypeLegal(Ty) &&
11138           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11139                                  FirstStoreAlign, &IsFast) && IsFast)
11140         NumElem = i + 1;
11141     }
11142
11143     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11144                                            false, true);
11145   }
11146
11147   // Below we handle the case of multiple consecutive stores that
11148   // come from multiple consecutive loads. We merge them into a single
11149   // wide load and a single wide store.
11150
11151   // Look for load nodes which are used by the stored values.
11152   SmallVector<MemOpLink, 8> LoadNodes;
11153
11154   // Find acceptable loads. Loads need to have the same chain (token factor),
11155   // must not be zext, volatile, indexed, and they must be consecutive.
11156   BaseIndexOffset LdBasePtr;
11157   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11158     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11159     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11160     if (!Ld) break;
11161
11162     // Loads must only have one use.
11163     if (!Ld->hasNUsesOfValue(1, 0))
11164       break;
11165
11166     // The memory operands must not be volatile.
11167     if (Ld->isVolatile() || Ld->isIndexed())
11168       break;
11169
11170     // We do not accept ext loads.
11171     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11172       break;
11173
11174     // The stored memory type must be the same.
11175     if (Ld->getMemoryVT() != MemVT)
11176       break;
11177
11178     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11179     // If this is not the first ptr that we check.
11180     if (LdBasePtr.Base.getNode()) {
11181       // The base ptr must be the same.
11182       if (!LdPtr.equalBaseIndex(LdBasePtr))
11183         break;
11184     } else {
11185       // Check that all other base pointers are the same as this one.
11186       LdBasePtr = LdPtr;
11187     }
11188
11189     // We found a potential memory operand to merge.
11190     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11191   }
11192
11193   if (LoadNodes.size() < 2)
11194     return false;
11195
11196   // If we have load/store pair instructions and we only have two values,
11197   // don't bother.
11198   unsigned RequiredAlignment;
11199   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11200       St->getAlignment() >= RequiredAlignment)
11201     return false;
11202
11203   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11204   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11205   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11206
11207   // Scan the memory operations on the chain and find the first non-consecutive
11208   // load memory address. These variables hold the index in the store node
11209   // array.
11210   unsigned LastConsecutiveLoad = 0;
11211   // This variable refers to the size and not index in the array.
11212   unsigned LastLegalVectorType = 0;
11213   unsigned LastLegalIntegerType = 0;
11214   StartAddress = LoadNodes[0].OffsetFromBase;
11215   SDValue FirstChain = FirstLoad->getChain();
11216   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11217     // All loads much share the same chain.
11218     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11219       break;
11220
11221     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11222     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11223       break;
11224     LastConsecutiveLoad = i;
11225     // Find a legal type for the vector store.
11226     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11227     bool IsFastSt, IsFastLd;
11228     if (TLI.isTypeLegal(StoreTy) &&
11229         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11230                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11231         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11232                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11233       LastLegalVectorType = i + 1;
11234     }
11235
11236     // Find a legal type for the integer store.
11237     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11238     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11239     if (TLI.isTypeLegal(StoreTy) &&
11240         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11241                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11242         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11243                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11244       LastLegalIntegerType = i + 1;
11245     // Or check whether a truncstore and extload is legal.
11246     else if (TLI.getTypeAction(Context, StoreTy) ==
11247              TargetLowering::TypePromoteInteger) {
11248       EVT LegalizedStoredValueTy =
11249         TLI.getTypeToTransformTo(Context, StoreTy);
11250       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11251           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11252           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11253           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11254           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11255                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11256           IsFastSt &&
11257           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11258                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11259           IsFastLd)
11260         LastLegalIntegerType = i+1;
11261     }
11262   }
11263
11264   // Only use vector types if the vector type is larger than the integer type.
11265   // If they are the same, use integers.
11266   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11267   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11268
11269   // We add +1 here because the LastXXX variables refer to location while
11270   // the NumElem refers to array/index size.
11271   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11272   NumElem = std::min(LastLegalType, NumElem);
11273
11274   if (NumElem < 2)
11275     return false;
11276
11277   // The latest Node in the DAG.
11278   unsigned LatestNodeUsed = 0;
11279   for (unsigned i=1; i<NumElem; ++i) {
11280     // Find a chain for the new wide-store operand. Notice that some
11281     // of the store nodes that we found may not be selected for inclusion
11282     // in the wide store. The chain we use needs to be the chain of the
11283     // latest store node which is *used* and replaced by the wide store.
11284     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11285       LatestNodeUsed = i;
11286   }
11287
11288   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11289
11290   // Find if it is better to use vectors or integers to load and store
11291   // to memory.
11292   EVT JointMemOpVT;
11293   if (UseVectorTy) {
11294     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11295   } else {
11296     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11297     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11298   }
11299
11300   SDLoc LoadDL(LoadNodes[0].MemNode);
11301   SDLoc StoreDL(StoreNodes[0].MemNode);
11302
11303   SDValue NewLoad = DAG.getLoad(
11304       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11305       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11306
11307   SDValue NewStore = DAG.getStore(
11308       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11309       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11310
11311   // Replace one of the loads with the new load.
11312   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11313   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11314                                 SDValue(NewLoad.getNode(), 1));
11315
11316   // Remove the rest of the load chains.
11317   for (unsigned i = 1; i < NumElem ; ++i) {
11318     // Replace all chain users of the old load nodes with the chain of the new
11319     // load node.
11320     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11321     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11322   }
11323
11324   // Replace the last store with the new store.
11325   CombineTo(LatestOp, NewStore);
11326   // Erase all other stores.
11327   for (unsigned i = 0; i < NumElem ; ++i) {
11328     // Remove all Store nodes.
11329     if (StoreNodes[i].MemNode == LatestOp)
11330       continue;
11331     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11332     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11333     deleteAndRecombine(St);
11334   }
11335
11336   return true;
11337 }
11338
11339 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11340   SDLoc SL(ST);
11341   SDValue ReplStore;
11342
11343   // Replace the chain to avoid dependency.
11344   if (ST->isTruncatingStore()) {
11345     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11346                                   ST->getBasePtr(), ST->getMemoryVT(),
11347                                   ST->getMemOperand());
11348   } else {
11349     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11350                              ST->getMemOperand());
11351   }
11352
11353   // Create token to keep both nodes around.
11354   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11355                               MVT::Other, ST->getChain(), ReplStore);
11356
11357   // Make sure the new and old chains are cleaned up.
11358   AddToWorklist(Token.getNode());
11359
11360   // Don't add users to work list.
11361   return CombineTo(ST, Token, false);
11362 }
11363
11364 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11365   StoreSDNode *ST  = cast<StoreSDNode>(N);
11366   SDValue Chain = ST->getChain();
11367   SDValue Value = ST->getValue();
11368   SDValue Ptr   = ST->getBasePtr();
11369
11370   // If this is a store of a bit convert, store the input value if the
11371   // resultant store does not need a higher alignment than the original.
11372   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11373       ST->isUnindexed()) {
11374     unsigned OrigAlign = ST->getAlignment();
11375     EVT SVT = Value.getOperand(0).getValueType();
11376     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11377         SVT.getTypeForEVT(*DAG.getContext()));
11378     if (Align <= OrigAlign &&
11379         ((!LegalOperations && !ST->isVolatile()) ||
11380          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11381       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11382                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11383                           ST->isNonTemporal(), OrigAlign,
11384                           ST->getAAInfo());
11385   }
11386
11387   // Turn 'store undef, Ptr' -> nothing.
11388   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11389     return Chain;
11390
11391   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11392   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11393     // NOTE: If the original store is volatile, this transform must not increase
11394     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11395     // processor operation but an i64 (which is not legal) requires two.  So the
11396     // transform should not be done in this case.
11397     if (Value.getOpcode() != ISD::TargetConstantFP) {
11398       SDValue Tmp;
11399       switch (CFP->getSimpleValueType(0).SimpleTy) {
11400       default: llvm_unreachable("Unknown FP type");
11401       case MVT::f16:    // We don't do this for these yet.
11402       case MVT::f80:
11403       case MVT::f128:
11404       case MVT::ppcf128:
11405         break;
11406       case MVT::f32:
11407         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11408             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11409           ;
11410           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11411                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11412                               MVT::i32);
11413           return DAG.getStore(Chain, SDLoc(N), Tmp,
11414                               Ptr, ST->getMemOperand());
11415         }
11416         break;
11417       case MVT::f64:
11418         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11419              !ST->isVolatile()) ||
11420             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11421           ;
11422           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11423                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11424           return DAG.getStore(Chain, SDLoc(N), Tmp,
11425                               Ptr, ST->getMemOperand());
11426         }
11427
11428         if (!ST->isVolatile() &&
11429             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11430           // Many FP stores are not made apparent until after legalize, e.g. for
11431           // argument passing.  Since this is so common, custom legalize the
11432           // 64-bit integer store into two 32-bit stores.
11433           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11434           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11435           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11436           if (DAG.getDataLayout().isBigEndian())
11437             std::swap(Lo, Hi);
11438
11439           unsigned Alignment = ST->getAlignment();
11440           bool isVolatile = ST->isVolatile();
11441           bool isNonTemporal = ST->isNonTemporal();
11442           AAMDNodes AAInfo = ST->getAAInfo();
11443
11444           SDLoc DL(N);
11445
11446           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11447                                      Ptr, ST->getPointerInfo(),
11448                                      isVolatile, isNonTemporal,
11449                                      ST->getAlignment(), AAInfo);
11450           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11451                             DAG.getConstant(4, DL, Ptr.getValueType()));
11452           Alignment = MinAlign(Alignment, 4U);
11453           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11454                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11455                                      isVolatile, isNonTemporal,
11456                                      Alignment, AAInfo);
11457           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11458                              St0, St1);
11459         }
11460
11461         break;
11462       }
11463     }
11464   }
11465
11466   // Try to infer better alignment information than the store already has.
11467   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11468     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11469       if (Align > ST->getAlignment()) {
11470         SDValue NewStore =
11471                DAG.getTruncStore(Chain, SDLoc(N), Value,
11472                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11473                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11474                                  ST->getAAInfo());
11475         if (NewStore.getNode() != N)
11476           return CombineTo(ST, NewStore, true);
11477       }
11478     }
11479   }
11480
11481   // Try transforming a pair floating point load / store ops to integer
11482   // load / store ops.
11483   if (SDValue NewST = TransformFPLoadStorePair(N))
11484     return NewST;
11485
11486   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11487                                                   : DAG.getSubtarget().useAA();
11488 #ifndef NDEBUG
11489   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11490       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11491     UseAA = false;
11492 #endif
11493   if (UseAA && ST->isUnindexed()) {
11494     // FIXME: We should do this even without AA enabled. AA will just allow
11495     // FindBetterChain to work in more situations. The problem with this is that
11496     // any combine that expects memory operations to be on consecutive chains
11497     // first needs to be updated to look for users of the same chain.
11498
11499     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11500     // adjacent stores.
11501     if (findBetterNeighborChains(ST)) {
11502       // replaceStoreChain uses CombineTo, which handled all of the worklist
11503       // manipulation. Return the original node to not do anything else.
11504       return SDValue(ST, 0);
11505     }
11506   }
11507
11508   // Try transforming N to an indexed store.
11509   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11510     return SDValue(N, 0);
11511
11512   // FIXME: is there such a thing as a truncating indexed store?
11513   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11514       Value.getValueType().isInteger()) {
11515     // See if we can simplify the input to this truncstore with knowledge that
11516     // only the low bits are being used.  For example:
11517     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11518     SDValue Shorter =
11519       GetDemandedBits(Value,
11520                       APInt::getLowBitsSet(
11521                         Value.getValueType().getScalarType().getSizeInBits(),
11522                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11523     AddToWorklist(Value.getNode());
11524     if (Shorter.getNode())
11525       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11526                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11527
11528     // Otherwise, see if we can simplify the operation with
11529     // SimplifyDemandedBits, which only works if the value has a single use.
11530     if (SimplifyDemandedBits(Value,
11531                         APInt::getLowBitsSet(
11532                           Value.getValueType().getScalarType().getSizeInBits(),
11533                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11534       return SDValue(N, 0);
11535   }
11536
11537   // If this is a load followed by a store to the same location, then the store
11538   // is dead/noop.
11539   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11540     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11541         ST->isUnindexed() && !ST->isVolatile() &&
11542         // There can't be any side effects between the load and store, such as
11543         // a call or store.
11544         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11545       // The store is dead, remove it.
11546       return Chain;
11547     }
11548   }
11549
11550   // If this is a store followed by a store with the same value to the same
11551   // location, then the store is dead/noop.
11552   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11553     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11554         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11555         ST1->isUnindexed() && !ST1->isVolatile()) {
11556       // The store is dead, remove it.
11557       return Chain;
11558     }
11559   }
11560
11561   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11562   // truncating store.  We can do this even if this is already a truncstore.
11563   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11564       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11565       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11566                             ST->getMemoryVT())) {
11567     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11568                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11569   }
11570
11571   // Only perform this optimization before the types are legal, because we
11572   // don't want to perform this optimization on every DAGCombine invocation.
11573   if (!LegalTypes) {
11574     bool EverChanged = false;
11575
11576     do {
11577       // There can be multiple store sequences on the same chain.
11578       // Keep trying to merge store sequences until we are unable to do so
11579       // or until we merge the last store on the chain.
11580       bool Changed = MergeConsecutiveStores(ST);
11581       EverChanged |= Changed;
11582       if (!Changed) break;
11583     } while (ST->getOpcode() != ISD::DELETED_NODE);
11584
11585     if (EverChanged)
11586       return SDValue(N, 0);
11587   }
11588
11589   return ReduceLoadOpStoreWidth(N);
11590 }
11591
11592 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11593   SDValue InVec = N->getOperand(0);
11594   SDValue InVal = N->getOperand(1);
11595   SDValue EltNo = N->getOperand(2);
11596   SDLoc dl(N);
11597
11598   // If the inserted element is an UNDEF, just use the input vector.
11599   if (InVal.getOpcode() == ISD::UNDEF)
11600     return InVec;
11601
11602   EVT VT = InVec.getValueType();
11603
11604   // If we can't generate a legal BUILD_VECTOR, exit
11605   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11606     return SDValue();
11607
11608   // Check that we know which element is being inserted
11609   if (!isa<ConstantSDNode>(EltNo))
11610     return SDValue();
11611   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11612
11613   // Canonicalize insert_vector_elt dag nodes.
11614   // Example:
11615   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11616   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11617   //
11618   // Do this only if the child insert_vector node has one use; also
11619   // do this only if indices are both constants and Idx1 < Idx0.
11620   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11621       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11622     unsigned OtherElt =
11623       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11624     if (Elt < OtherElt) {
11625       // Swap nodes.
11626       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11627                                   InVec.getOperand(0), InVal, EltNo);
11628       AddToWorklist(NewOp.getNode());
11629       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11630                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11631     }
11632   }
11633
11634   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11635   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11636   // vector elements.
11637   SmallVector<SDValue, 8> Ops;
11638   // Do not combine these two vectors if the output vector will not replace
11639   // the input vector.
11640   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11641     Ops.append(InVec.getNode()->op_begin(),
11642                InVec.getNode()->op_end());
11643   } else if (InVec.getOpcode() == ISD::UNDEF) {
11644     unsigned NElts = VT.getVectorNumElements();
11645     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11646   } else {
11647     return SDValue();
11648   }
11649
11650   // Insert the element
11651   if (Elt < Ops.size()) {
11652     // All the operands of BUILD_VECTOR must have the same type;
11653     // we enforce that here.
11654     EVT OpVT = Ops[0].getValueType();
11655     if (InVal.getValueType() != OpVT)
11656       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11657                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11658                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11659     Ops[Elt] = InVal;
11660   }
11661
11662   // Return the new vector
11663   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11664 }
11665
11666 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11667     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11668   EVT ResultVT = EVE->getValueType(0);
11669   EVT VecEltVT = InVecVT.getVectorElementType();
11670   unsigned Align = OriginalLoad->getAlignment();
11671   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11672       VecEltVT.getTypeForEVT(*DAG.getContext()));
11673
11674   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11675     return SDValue();
11676
11677   Align = NewAlign;
11678
11679   SDValue NewPtr = OriginalLoad->getBasePtr();
11680   SDValue Offset;
11681   EVT PtrType = NewPtr.getValueType();
11682   MachinePointerInfo MPI;
11683   SDLoc DL(EVE);
11684   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11685     int Elt = ConstEltNo->getZExtValue();
11686     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11687     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11688     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11689   } else {
11690     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11691     Offset = DAG.getNode(
11692         ISD::MUL, DL, PtrType, Offset,
11693         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11694     MPI = OriginalLoad->getPointerInfo();
11695   }
11696   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11697
11698   // The replacement we need to do here is a little tricky: we need to
11699   // replace an extractelement of a load with a load.
11700   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11701   // Note that this replacement assumes that the extractvalue is the only
11702   // use of the load; that's okay because we don't want to perform this
11703   // transformation in other cases anyway.
11704   SDValue Load;
11705   SDValue Chain;
11706   if (ResultVT.bitsGT(VecEltVT)) {
11707     // If the result type of vextract is wider than the load, then issue an
11708     // extending load instead.
11709     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11710                                                   VecEltVT)
11711                                    ? ISD::ZEXTLOAD
11712                                    : ISD::EXTLOAD;
11713     Load = DAG.getExtLoad(
11714         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11715         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11716         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11717     Chain = Load.getValue(1);
11718   } else {
11719     Load = DAG.getLoad(
11720         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11721         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11722         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11723     Chain = Load.getValue(1);
11724     if (ResultVT.bitsLT(VecEltVT))
11725       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11726     else
11727       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11728   }
11729   WorklistRemover DeadNodes(*this);
11730   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11731   SDValue To[] = { Load, Chain };
11732   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11733   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11734   // worklist explicitly as well.
11735   AddToWorklist(Load.getNode());
11736   AddUsersToWorklist(Load.getNode()); // Add users too
11737   // Make sure to revisit this node to clean it up; it will usually be dead.
11738   AddToWorklist(EVE);
11739   ++OpsNarrowed;
11740   return SDValue(EVE, 0);
11741 }
11742
11743 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11744   // (vextract (scalar_to_vector val, 0) -> val
11745   SDValue InVec = N->getOperand(0);
11746   EVT VT = InVec.getValueType();
11747   EVT NVT = N->getValueType(0);
11748
11749   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11750     // Check if the result type doesn't match the inserted element type. A
11751     // SCALAR_TO_VECTOR may truncate the inserted element and the
11752     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11753     SDValue InOp = InVec.getOperand(0);
11754     if (InOp.getValueType() != NVT) {
11755       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11756       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11757     }
11758     return InOp;
11759   }
11760
11761   SDValue EltNo = N->getOperand(1);
11762   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11763
11764   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11765   // We only perform this optimization before the op legalization phase because
11766   // we may introduce new vector instructions which are not backed by TD
11767   // patterns. For example on AVX, extracting elements from a wide vector
11768   // without using extract_subvector. However, if we can find an underlying
11769   // scalar value, then we can always use that.
11770   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11771       && ConstEltNo) {
11772     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11773     int NumElem = VT.getVectorNumElements();
11774     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11775     // Find the new index to extract from.
11776     int OrigElt = SVOp->getMaskElt(Elt);
11777
11778     // Extracting an undef index is undef.
11779     if (OrigElt == -1)
11780       return DAG.getUNDEF(NVT);
11781
11782     // Select the right vector half to extract from.
11783     SDValue SVInVec;
11784     if (OrigElt < NumElem) {
11785       SVInVec = InVec->getOperand(0);
11786     } else {
11787       SVInVec = InVec->getOperand(1);
11788       OrigElt -= NumElem;
11789     }
11790
11791     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11792       SDValue InOp = SVInVec.getOperand(OrigElt);
11793       if (InOp.getValueType() != NVT) {
11794         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11795         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11796       }
11797
11798       return InOp;
11799     }
11800
11801     // FIXME: We should handle recursing on other vector shuffles and
11802     // scalar_to_vector here as well.
11803
11804     if (!LegalOperations) {
11805       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11806       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11807                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11808     }
11809   }
11810
11811   bool BCNumEltsChanged = false;
11812   EVT ExtVT = VT.getVectorElementType();
11813   EVT LVT = ExtVT;
11814
11815   // If the result of load has to be truncated, then it's not necessarily
11816   // profitable.
11817   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11818     return SDValue();
11819
11820   if (InVec.getOpcode() == ISD::BITCAST) {
11821     // Don't duplicate a load with other uses.
11822     if (!InVec.hasOneUse())
11823       return SDValue();
11824
11825     EVT BCVT = InVec.getOperand(0).getValueType();
11826     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11827       return SDValue();
11828     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11829       BCNumEltsChanged = true;
11830     InVec = InVec.getOperand(0);
11831     ExtVT = BCVT.getVectorElementType();
11832   }
11833
11834   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11835   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11836       ISD::isNormalLoad(InVec.getNode()) &&
11837       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11838     SDValue Index = N->getOperand(1);
11839     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11840       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11841                                                            OrigLoad);
11842   }
11843
11844   // Perform only after legalization to ensure build_vector / vector_shuffle
11845   // optimizations have already been done.
11846   if (!LegalOperations) return SDValue();
11847
11848   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11849   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11850   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11851
11852   if (ConstEltNo) {
11853     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11854
11855     LoadSDNode *LN0 = nullptr;
11856     const ShuffleVectorSDNode *SVN = nullptr;
11857     if (ISD::isNormalLoad(InVec.getNode())) {
11858       LN0 = cast<LoadSDNode>(InVec);
11859     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11860                InVec.getOperand(0).getValueType() == ExtVT &&
11861                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11862       // Don't duplicate a load with other uses.
11863       if (!InVec.hasOneUse())
11864         return SDValue();
11865
11866       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11867     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11868       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11869       // =>
11870       // (load $addr+1*size)
11871
11872       // Don't duplicate a load with other uses.
11873       if (!InVec.hasOneUse())
11874         return SDValue();
11875
11876       // If the bit convert changed the number of elements, it is unsafe
11877       // to examine the mask.
11878       if (BCNumEltsChanged)
11879         return SDValue();
11880
11881       // Select the input vector, guarding against out of range extract vector.
11882       unsigned NumElems = VT.getVectorNumElements();
11883       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11884       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11885
11886       if (InVec.getOpcode() == ISD::BITCAST) {
11887         // Don't duplicate a load with other uses.
11888         if (!InVec.hasOneUse())
11889           return SDValue();
11890
11891         InVec = InVec.getOperand(0);
11892       }
11893       if (ISD::isNormalLoad(InVec.getNode())) {
11894         LN0 = cast<LoadSDNode>(InVec);
11895         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11896         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11897       }
11898     }
11899
11900     // Make sure we found a non-volatile load and the extractelement is
11901     // the only use.
11902     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11903       return SDValue();
11904
11905     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11906     if (Elt == -1)
11907       return DAG.getUNDEF(LVT);
11908
11909     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11910   }
11911
11912   return SDValue();
11913 }
11914
11915 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11916 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11917   // We perform this optimization post type-legalization because
11918   // the type-legalizer often scalarizes integer-promoted vectors.
11919   // Performing this optimization before may create bit-casts which
11920   // will be type-legalized to complex code sequences.
11921   // We perform this optimization only before the operation legalizer because we
11922   // may introduce illegal operations.
11923   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11924     return SDValue();
11925
11926   unsigned NumInScalars = N->getNumOperands();
11927   SDLoc dl(N);
11928   EVT VT = N->getValueType(0);
11929
11930   // Check to see if this is a BUILD_VECTOR of a bunch of values
11931   // which come from any_extend or zero_extend nodes. If so, we can create
11932   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11933   // optimizations. We do not handle sign-extend because we can't fill the sign
11934   // using shuffles.
11935   EVT SourceType = MVT::Other;
11936   bool AllAnyExt = true;
11937
11938   for (unsigned i = 0; i != NumInScalars; ++i) {
11939     SDValue In = N->getOperand(i);
11940     // Ignore undef inputs.
11941     if (In.getOpcode() == ISD::UNDEF) continue;
11942
11943     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11944     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11945
11946     // Abort if the element is not an extension.
11947     if (!ZeroExt && !AnyExt) {
11948       SourceType = MVT::Other;
11949       break;
11950     }
11951
11952     // The input is a ZeroExt or AnyExt. Check the original type.
11953     EVT InTy = In.getOperand(0).getValueType();
11954
11955     // Check that all of the widened source types are the same.
11956     if (SourceType == MVT::Other)
11957       // First time.
11958       SourceType = InTy;
11959     else if (InTy != SourceType) {
11960       // Multiple income types. Abort.
11961       SourceType = MVT::Other;
11962       break;
11963     }
11964
11965     // Check if all of the extends are ANY_EXTENDs.
11966     AllAnyExt &= AnyExt;
11967   }
11968
11969   // In order to have valid types, all of the inputs must be extended from the
11970   // same source type and all of the inputs must be any or zero extend.
11971   // Scalar sizes must be a power of two.
11972   EVT OutScalarTy = VT.getScalarType();
11973   bool ValidTypes = SourceType != MVT::Other &&
11974                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11975                  isPowerOf2_32(SourceType.getSizeInBits());
11976
11977   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11978   // turn into a single shuffle instruction.
11979   if (!ValidTypes)
11980     return SDValue();
11981
11982   bool isLE = DAG.getDataLayout().isLittleEndian();
11983   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11984   assert(ElemRatio > 1 && "Invalid element size ratio");
11985   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11986                                DAG.getConstant(0, SDLoc(N), SourceType);
11987
11988   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11989   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11990
11991   // Populate the new build_vector
11992   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11993     SDValue Cast = N->getOperand(i);
11994     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11995             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11996             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11997     SDValue In;
11998     if (Cast.getOpcode() == ISD::UNDEF)
11999       In = DAG.getUNDEF(SourceType);
12000     else
12001       In = Cast->getOperand(0);
12002     unsigned Index = isLE ? (i * ElemRatio) :
12003                             (i * ElemRatio + (ElemRatio - 1));
12004
12005     assert(Index < Ops.size() && "Invalid index");
12006     Ops[Index] = In;
12007   }
12008
12009   // The type of the new BUILD_VECTOR node.
12010   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12011   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12012          "Invalid vector size");
12013   // Check if the new vector type is legal.
12014   if (!isTypeLegal(VecVT)) return SDValue();
12015
12016   // Make the new BUILD_VECTOR.
12017   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12018
12019   // The new BUILD_VECTOR node has the potential to be further optimized.
12020   AddToWorklist(BV.getNode());
12021   // Bitcast to the desired type.
12022   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12023 }
12024
12025 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12026   EVT VT = N->getValueType(0);
12027
12028   unsigned NumInScalars = N->getNumOperands();
12029   SDLoc dl(N);
12030
12031   EVT SrcVT = MVT::Other;
12032   unsigned Opcode = ISD::DELETED_NODE;
12033   unsigned NumDefs = 0;
12034
12035   for (unsigned i = 0; i != NumInScalars; ++i) {
12036     SDValue In = N->getOperand(i);
12037     unsigned Opc = In.getOpcode();
12038
12039     if (Opc == ISD::UNDEF)
12040       continue;
12041
12042     // If all scalar values are floats and converted from integers.
12043     if (Opcode == ISD::DELETED_NODE &&
12044         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12045       Opcode = Opc;
12046     }
12047
12048     if (Opc != Opcode)
12049       return SDValue();
12050
12051     EVT InVT = In.getOperand(0).getValueType();
12052
12053     // If all scalar values are typed differently, bail out. It's chosen to
12054     // simplify BUILD_VECTOR of integer types.
12055     if (SrcVT == MVT::Other)
12056       SrcVT = InVT;
12057     if (SrcVT != InVT)
12058       return SDValue();
12059     NumDefs++;
12060   }
12061
12062   // If the vector has just one element defined, it's not worth to fold it into
12063   // a vectorized one.
12064   if (NumDefs < 2)
12065     return SDValue();
12066
12067   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12068          && "Should only handle conversion from integer to float.");
12069   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12070
12071   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12072
12073   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12074     return SDValue();
12075
12076   // Just because the floating-point vector type is legal does not necessarily
12077   // mean that the corresponding integer vector type is.
12078   if (!isTypeLegal(NVT))
12079     return SDValue();
12080
12081   SmallVector<SDValue, 8> Opnds;
12082   for (unsigned i = 0; i != NumInScalars; ++i) {
12083     SDValue In = N->getOperand(i);
12084
12085     if (In.getOpcode() == ISD::UNDEF)
12086       Opnds.push_back(DAG.getUNDEF(SrcVT));
12087     else
12088       Opnds.push_back(In.getOperand(0));
12089   }
12090   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12091   AddToWorklist(BV.getNode());
12092
12093   return DAG.getNode(Opcode, dl, VT, BV);
12094 }
12095
12096 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12097   unsigned NumInScalars = N->getNumOperands();
12098   SDLoc dl(N);
12099   EVT VT = N->getValueType(0);
12100
12101   // A vector built entirely of undefs is undef.
12102   if (ISD::allOperandsUndef(N))
12103     return DAG.getUNDEF(VT);
12104
12105   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12106     return V;
12107
12108   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12109     return V;
12110
12111   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12112   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12113   // at most two distinct vectors, turn this into a shuffle node.
12114
12115   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12116   if (!isTypeLegal(VT))
12117     return SDValue();
12118
12119   // May only combine to shuffle after legalize if shuffle is legal.
12120   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12121     return SDValue();
12122
12123   SDValue VecIn1, VecIn2;
12124   bool UsesZeroVector = false;
12125   for (unsigned i = 0; i != NumInScalars; ++i) {
12126     SDValue Op = N->getOperand(i);
12127     // Ignore undef inputs.
12128     if (Op.getOpcode() == ISD::UNDEF) continue;
12129
12130     // See if we can combine this build_vector into a blend with a zero vector.
12131     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12132       UsesZeroVector = true;
12133       continue;
12134     }
12135
12136     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12137     // constant index, bail out.
12138     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12139         !isa<ConstantSDNode>(Op.getOperand(1))) {
12140       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12141       break;
12142     }
12143
12144     // We allow up to two distinct input vectors.
12145     SDValue ExtractedFromVec = Op.getOperand(0);
12146     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12147       continue;
12148
12149     if (!VecIn1.getNode()) {
12150       VecIn1 = ExtractedFromVec;
12151     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12152       VecIn2 = ExtractedFromVec;
12153     } else {
12154       // Too many inputs.
12155       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12156       break;
12157     }
12158   }
12159
12160   // If everything is good, we can make a shuffle operation.
12161   if (VecIn1.getNode()) {
12162     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12163     SmallVector<int, 8> Mask;
12164     for (unsigned i = 0; i != NumInScalars; ++i) {
12165       unsigned Opcode = N->getOperand(i).getOpcode();
12166       if (Opcode == ISD::UNDEF) {
12167         Mask.push_back(-1);
12168         continue;
12169       }
12170
12171       // Operands can also be zero.
12172       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12173         assert(UsesZeroVector &&
12174                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12175                "Unexpected node found!");
12176         Mask.push_back(NumInScalars+i);
12177         continue;
12178       }
12179
12180       // If extracting from the first vector, just use the index directly.
12181       SDValue Extract = N->getOperand(i);
12182       SDValue ExtVal = Extract.getOperand(1);
12183       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12184       if (Extract.getOperand(0) == VecIn1) {
12185         Mask.push_back(ExtIndex);
12186         continue;
12187       }
12188
12189       // Otherwise, use InIdx + InputVecSize
12190       Mask.push_back(InNumElements + ExtIndex);
12191     }
12192
12193     // Avoid introducing illegal shuffles with zero.
12194     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12195       return SDValue();
12196
12197     // We can't generate a shuffle node with mismatched input and output types.
12198     // Attempt to transform a single input vector to the correct type.
12199     if ((VT != VecIn1.getValueType())) {
12200       // If the input vector type has a different base type to the output
12201       // vector type, bail out.
12202       EVT VTElemType = VT.getVectorElementType();
12203       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12204           (VecIn2.getNode() &&
12205            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12206         return SDValue();
12207
12208       // If the input vector is too small, widen it.
12209       // We only support widening of vectors which are half the size of the
12210       // output registers. For example XMM->YMM widening on X86 with AVX.
12211       EVT VecInT = VecIn1.getValueType();
12212       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12213         // If we only have one small input, widen it by adding undef values.
12214         if (!VecIn2.getNode())
12215           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12216                                DAG.getUNDEF(VecIn1.getValueType()));
12217         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12218           // If we have two small inputs of the same type, try to concat them.
12219           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12220           VecIn2 = SDValue(nullptr, 0);
12221         } else
12222           return SDValue();
12223       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12224         // If the input vector is too large, try to split it.
12225         // We don't support having two input vectors that are too large.
12226         // If the zero vector was used, we can not split the vector,
12227         // since we'd need 3 inputs.
12228         if (UsesZeroVector || VecIn2.getNode())
12229           return SDValue();
12230
12231         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12232           return SDValue();
12233
12234         // Try to replace VecIn1 with two extract_subvectors
12235         // No need to update the masks, they should still be correct.
12236         VecIn2 = DAG.getNode(
12237             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12238             DAG.getConstant(VT.getVectorNumElements(), dl,
12239                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12240         VecIn1 = DAG.getNode(
12241             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12242             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12243       } else
12244         return SDValue();
12245     }
12246
12247     if (UsesZeroVector)
12248       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12249                                 DAG.getConstantFP(0.0, dl, VT);
12250     else
12251       // If VecIn2 is unused then change it to undef.
12252       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12253
12254     // Check that we were able to transform all incoming values to the same
12255     // type.
12256     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12257         VecIn1.getValueType() != VT)
12258           return SDValue();
12259
12260     // Return the new VECTOR_SHUFFLE node.
12261     SDValue Ops[2];
12262     Ops[0] = VecIn1;
12263     Ops[1] = VecIn2;
12264     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12265   }
12266
12267   return SDValue();
12268 }
12269
12270 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12272   EVT OpVT = N->getOperand(0).getValueType();
12273
12274   // If the operands are legal vectors, leave them alone.
12275   if (TLI.isTypeLegal(OpVT))
12276     return SDValue();
12277
12278   SDLoc DL(N);
12279   EVT VT = N->getValueType(0);
12280   SmallVector<SDValue, 8> Ops;
12281
12282   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12283   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12284
12285   // Keep track of what we encounter.
12286   bool AnyInteger = false;
12287   bool AnyFP = false;
12288   for (const SDValue &Op : N->ops()) {
12289     if (ISD::BITCAST == Op.getOpcode() &&
12290         !Op.getOperand(0).getValueType().isVector())
12291       Ops.push_back(Op.getOperand(0));
12292     else if (ISD::UNDEF == Op.getOpcode())
12293       Ops.push_back(ScalarUndef);
12294     else
12295       return SDValue();
12296
12297     // Note whether we encounter an integer or floating point scalar.
12298     // If it's neither, bail out, it could be something weird like x86mmx.
12299     EVT LastOpVT = Ops.back().getValueType();
12300     if (LastOpVT.isFloatingPoint())
12301       AnyFP = true;
12302     else if (LastOpVT.isInteger())
12303       AnyInteger = true;
12304     else
12305       return SDValue();
12306   }
12307
12308   // If any of the operands is a floating point scalar bitcast to a vector,
12309   // use floating point types throughout, and bitcast everything.
12310   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12311   if (AnyFP) {
12312     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12313     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12314     if (AnyInteger) {
12315       for (SDValue &Op : Ops) {
12316         if (Op.getValueType() == SVT)
12317           continue;
12318         if (Op.getOpcode() == ISD::UNDEF)
12319           Op = ScalarUndef;
12320         else
12321           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12322       }
12323     }
12324   }
12325
12326   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12327                                VT.getSizeInBits() / SVT.getSizeInBits());
12328   return DAG.getNode(ISD::BITCAST, DL, VT,
12329                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12330 }
12331
12332 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12333 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12334 // most two distinct vectors the same size as the result, attempt to turn this
12335 // into a legal shuffle.
12336 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12337   EVT VT = N->getValueType(0);
12338   EVT OpVT = N->getOperand(0).getValueType();
12339   int NumElts = VT.getVectorNumElements();
12340   int NumOpElts = OpVT.getVectorNumElements();
12341
12342   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12343   SmallVector<int, 8> Mask;
12344
12345   for (SDValue Op : N->ops()) {
12346     // Peek through any bitcast.
12347     while (Op.getOpcode() == ISD::BITCAST)
12348       Op = Op.getOperand(0);
12349
12350     // UNDEF nodes convert to UNDEF shuffle mask values.
12351     if (Op.getOpcode() == ISD::UNDEF) {
12352       Mask.append((unsigned)NumOpElts, -1);
12353       continue;
12354     }
12355
12356     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12357       return SDValue();
12358
12359     // What vector are we extracting the subvector from and at what index?
12360     SDValue ExtVec = Op.getOperand(0);
12361
12362     // We want the EVT of the original extraction to correctly scale the
12363     // extraction index.
12364     EVT ExtVT = ExtVec.getValueType();
12365
12366     // Peek through any bitcast.
12367     while (ExtVec.getOpcode() == ISD::BITCAST)
12368       ExtVec = ExtVec.getOperand(0);
12369
12370     // UNDEF nodes convert to UNDEF shuffle mask values.
12371     if (ExtVec.getOpcode() == ISD::UNDEF) {
12372       Mask.append((unsigned)NumOpElts, -1);
12373       continue;
12374     }
12375
12376     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12377       return SDValue();
12378     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12379
12380     // Ensure that we are extracting a subvector from a vector the same
12381     // size as the result.
12382     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12383       return SDValue();
12384
12385     // Scale the subvector index to account for any bitcast.
12386     int NumExtElts = ExtVT.getVectorNumElements();
12387     if (0 == (NumExtElts % NumElts))
12388       ExtIdx /= (NumExtElts / NumElts);
12389     else if (0 == (NumElts % NumExtElts))
12390       ExtIdx *= (NumElts / NumExtElts);
12391     else
12392       return SDValue();
12393
12394     // At most we can reference 2 inputs in the final shuffle.
12395     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12396       SV0 = ExtVec;
12397       for (int i = 0; i != NumOpElts; ++i)
12398         Mask.push_back(i + ExtIdx);
12399     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12400       SV1 = ExtVec;
12401       for (int i = 0; i != NumOpElts; ++i)
12402         Mask.push_back(i + ExtIdx + NumElts);
12403     } else {
12404       return SDValue();
12405     }
12406   }
12407
12408   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12409     return SDValue();
12410
12411   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12412                               DAG.getBitcast(VT, SV1), Mask);
12413 }
12414
12415 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12416   // If we only have one input vector, we don't need to do any concatenation.
12417   if (N->getNumOperands() == 1)
12418     return N->getOperand(0);
12419
12420   // Check if all of the operands are undefs.
12421   EVT VT = N->getValueType(0);
12422   if (ISD::allOperandsUndef(N))
12423     return DAG.getUNDEF(VT);
12424
12425   // Optimize concat_vectors where all but the first of the vectors are undef.
12426   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12427         return Op.getOpcode() == ISD::UNDEF;
12428       })) {
12429     SDValue In = N->getOperand(0);
12430     assert(In.getValueType().isVector() && "Must concat vectors");
12431
12432     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12433     if (In->getOpcode() == ISD::BITCAST &&
12434         !In->getOperand(0)->getValueType(0).isVector()) {
12435       SDValue Scalar = In->getOperand(0);
12436
12437       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12438       // look through the trunc so we can still do the transform:
12439       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12440       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12441           !TLI.isTypeLegal(Scalar.getValueType()) &&
12442           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12443         Scalar = Scalar->getOperand(0);
12444
12445       EVT SclTy = Scalar->getValueType(0);
12446
12447       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12448         return SDValue();
12449
12450       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12451                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12452       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12453         return SDValue();
12454
12455       SDLoc dl = SDLoc(N);
12456       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12457       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12458     }
12459   }
12460
12461   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12462   // We have already tested above for an UNDEF only concatenation.
12463   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12464   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12465   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12466     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12467   };
12468   bool AllBuildVectorsOrUndefs =
12469       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12470   if (AllBuildVectorsOrUndefs) {
12471     SmallVector<SDValue, 8> Opnds;
12472     EVT SVT = VT.getScalarType();
12473
12474     EVT MinVT = SVT;
12475     if (!SVT.isFloatingPoint()) {
12476       // If BUILD_VECTOR are from built from integer, they may have different
12477       // operand types. Get the smallest type and truncate all operands to it.
12478       bool FoundMinVT = false;
12479       for (const SDValue &Op : N->ops())
12480         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12481           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12482           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12483           FoundMinVT = true;
12484         }
12485       assert(FoundMinVT && "Concat vector type mismatch");
12486     }
12487
12488     for (const SDValue &Op : N->ops()) {
12489       EVT OpVT = Op.getValueType();
12490       unsigned NumElts = OpVT.getVectorNumElements();
12491
12492       if (ISD::UNDEF == Op.getOpcode())
12493         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12494
12495       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12496         if (SVT.isFloatingPoint()) {
12497           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12498           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12499         } else {
12500           for (unsigned i = 0; i != NumElts; ++i)
12501             Opnds.push_back(
12502                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12503         }
12504       }
12505     }
12506
12507     assert(VT.getVectorNumElements() == Opnds.size() &&
12508            "Concat vector type mismatch");
12509     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12510   }
12511
12512   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12513   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12514     return V;
12515
12516   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12517   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12518     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12519       return V;
12520
12521   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12522   // nodes often generate nop CONCAT_VECTOR nodes.
12523   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12524   // place the incoming vectors at the exact same location.
12525   SDValue SingleSource = SDValue();
12526   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12527
12528   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12529     SDValue Op = N->getOperand(i);
12530
12531     if (Op.getOpcode() == ISD::UNDEF)
12532       continue;
12533
12534     // Check if this is the identity extract:
12535     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12536       return SDValue();
12537
12538     // Find the single incoming vector for the extract_subvector.
12539     if (SingleSource.getNode()) {
12540       if (Op.getOperand(0) != SingleSource)
12541         return SDValue();
12542     } else {
12543       SingleSource = Op.getOperand(0);
12544
12545       // Check the source type is the same as the type of the result.
12546       // If not, this concat may extend the vector, so we can not
12547       // optimize it away.
12548       if (SingleSource.getValueType() != N->getValueType(0))
12549         return SDValue();
12550     }
12551
12552     unsigned IdentityIndex = i * PartNumElem;
12553     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12554     // The extract index must be constant.
12555     if (!CS)
12556       return SDValue();
12557
12558     // Check that we are reading from the identity index.
12559     if (CS->getZExtValue() != IdentityIndex)
12560       return SDValue();
12561   }
12562
12563   if (SingleSource.getNode())
12564     return SingleSource;
12565
12566   return SDValue();
12567 }
12568
12569 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12570   EVT NVT = N->getValueType(0);
12571   SDValue V = N->getOperand(0);
12572
12573   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12574     // Combine:
12575     //    (extract_subvec (concat V1, V2, ...), i)
12576     // Into:
12577     //    Vi if possible
12578     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12579     // type.
12580     if (V->getOperand(0).getValueType() != NVT)
12581       return SDValue();
12582     unsigned Idx = N->getConstantOperandVal(1);
12583     unsigned NumElems = NVT.getVectorNumElements();
12584     assert((Idx % NumElems) == 0 &&
12585            "IDX in concat is not a multiple of the result vector length.");
12586     return V->getOperand(Idx / NumElems);
12587   }
12588
12589   // Skip bitcasting
12590   if (V->getOpcode() == ISD::BITCAST)
12591     V = V.getOperand(0);
12592
12593   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12594     SDLoc dl(N);
12595     // Handle only simple case where vector being inserted and vector
12596     // being extracted are of same type, and are half size of larger vectors.
12597     EVT BigVT = V->getOperand(0).getValueType();
12598     EVT SmallVT = V->getOperand(1).getValueType();
12599     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12600       return SDValue();
12601
12602     // Only handle cases where both indexes are constants with the same type.
12603     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12604     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12605
12606     if (InsIdx && ExtIdx &&
12607         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12608         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12609       // Combine:
12610       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12611       // Into:
12612       //    indices are equal or bit offsets are equal => V1
12613       //    otherwise => (extract_subvec V1, ExtIdx)
12614       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12615           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12616         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12617       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12618                          DAG.getNode(ISD::BITCAST, dl,
12619                                      N->getOperand(0).getValueType(),
12620                                      V->getOperand(0)), N->getOperand(1));
12621     }
12622   }
12623
12624   return SDValue();
12625 }
12626
12627 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12628                                                  SDValue V, SelectionDAG &DAG) {
12629   SDLoc DL(V);
12630   EVT VT = V.getValueType();
12631
12632   switch (V.getOpcode()) {
12633   default:
12634     return V;
12635
12636   case ISD::CONCAT_VECTORS: {
12637     EVT OpVT = V->getOperand(0).getValueType();
12638     int OpSize = OpVT.getVectorNumElements();
12639     SmallBitVector OpUsedElements(OpSize, false);
12640     bool FoundSimplification = false;
12641     SmallVector<SDValue, 4> NewOps;
12642     NewOps.reserve(V->getNumOperands());
12643     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12644       SDValue Op = V->getOperand(i);
12645       bool OpUsed = false;
12646       for (int j = 0; j < OpSize; ++j)
12647         if (UsedElements[i * OpSize + j]) {
12648           OpUsedElements[j] = true;
12649           OpUsed = true;
12650         }
12651       NewOps.push_back(
12652           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12653                  : DAG.getUNDEF(OpVT));
12654       FoundSimplification |= Op == NewOps.back();
12655       OpUsedElements.reset();
12656     }
12657     if (FoundSimplification)
12658       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12659     return V;
12660   }
12661
12662   case ISD::INSERT_SUBVECTOR: {
12663     SDValue BaseV = V->getOperand(0);
12664     SDValue SubV = V->getOperand(1);
12665     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12666     if (!IdxN)
12667       return V;
12668
12669     int SubSize = SubV.getValueType().getVectorNumElements();
12670     int Idx = IdxN->getZExtValue();
12671     bool SubVectorUsed = false;
12672     SmallBitVector SubUsedElements(SubSize, false);
12673     for (int i = 0; i < SubSize; ++i)
12674       if (UsedElements[i + Idx]) {
12675         SubVectorUsed = true;
12676         SubUsedElements[i] = true;
12677         UsedElements[i + Idx] = false;
12678       }
12679
12680     // Now recurse on both the base and sub vectors.
12681     SDValue SimplifiedSubV =
12682         SubVectorUsed
12683             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12684             : DAG.getUNDEF(SubV.getValueType());
12685     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12686     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12687       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12688                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12689     return V;
12690   }
12691   }
12692 }
12693
12694 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12695                                        SDValue N1, SelectionDAG &DAG) {
12696   EVT VT = SVN->getValueType(0);
12697   int NumElts = VT.getVectorNumElements();
12698   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12699   for (int M : SVN->getMask())
12700     if (M >= 0 && M < NumElts)
12701       N0UsedElements[M] = true;
12702     else if (M >= NumElts)
12703       N1UsedElements[M - NumElts] = true;
12704
12705   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12706   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12707   if (S0 == N0 && S1 == N1)
12708     return SDValue();
12709
12710   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12711 }
12712
12713 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12714 // or turn a shuffle of a single concat into simpler shuffle then concat.
12715 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12716   EVT VT = N->getValueType(0);
12717   unsigned NumElts = VT.getVectorNumElements();
12718
12719   SDValue N0 = N->getOperand(0);
12720   SDValue N1 = N->getOperand(1);
12721   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12722
12723   SmallVector<SDValue, 4> Ops;
12724   EVT ConcatVT = N0.getOperand(0).getValueType();
12725   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12726   unsigned NumConcats = NumElts / NumElemsPerConcat;
12727
12728   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12729   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12730   // half vector elements.
12731   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12732       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12733                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12734     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12735                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
12736     N1 = DAG.getUNDEF(ConcatVT);
12737     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12738   }
12739
12740   // Look at every vector that's inserted. We're looking for exact
12741   // subvector-sized copies from a concatenated vector
12742   for (unsigned I = 0; I != NumConcats; ++I) {
12743     // Make sure we're dealing with a copy.
12744     unsigned Begin = I * NumElemsPerConcat;
12745     bool AllUndef = true, NoUndef = true;
12746     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12747       if (SVN->getMaskElt(J) >= 0)
12748         AllUndef = false;
12749       else
12750         NoUndef = false;
12751     }
12752
12753     if (NoUndef) {
12754       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12755         return SDValue();
12756
12757       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12758         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12759           return SDValue();
12760
12761       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12762       if (FirstElt < N0.getNumOperands())
12763         Ops.push_back(N0.getOperand(FirstElt));
12764       else
12765         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12766
12767     } else if (AllUndef) {
12768       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12769     } else { // Mixed with general masks and undefs, can't do optimization.
12770       return SDValue();
12771     }
12772   }
12773
12774   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12775 }
12776
12777 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12778   EVT VT = N->getValueType(0);
12779   unsigned NumElts = VT.getVectorNumElements();
12780
12781   SDValue N0 = N->getOperand(0);
12782   SDValue N1 = N->getOperand(1);
12783
12784   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12785
12786   // Canonicalize shuffle undef, undef -> undef
12787   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12788     return DAG.getUNDEF(VT);
12789
12790   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12791
12792   // Canonicalize shuffle v, v -> v, undef
12793   if (N0 == N1) {
12794     SmallVector<int, 8> NewMask;
12795     for (unsigned i = 0; i != NumElts; ++i) {
12796       int Idx = SVN->getMaskElt(i);
12797       if (Idx >= (int)NumElts) Idx -= NumElts;
12798       NewMask.push_back(Idx);
12799     }
12800     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12801                                 &NewMask[0]);
12802   }
12803
12804   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12805   if (N0.getOpcode() == ISD::UNDEF) {
12806     SmallVector<int, 8> NewMask;
12807     for (unsigned i = 0; i != NumElts; ++i) {
12808       int Idx = SVN->getMaskElt(i);
12809       if (Idx >= 0) {
12810         if (Idx >= (int)NumElts)
12811           Idx -= NumElts;
12812         else
12813           Idx = -1; // remove reference to lhs
12814       }
12815       NewMask.push_back(Idx);
12816     }
12817     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12818                                 &NewMask[0]);
12819   }
12820
12821   // Remove references to rhs if it is undef
12822   if (N1.getOpcode() == ISD::UNDEF) {
12823     bool Changed = false;
12824     SmallVector<int, 8> NewMask;
12825     for (unsigned i = 0; i != NumElts; ++i) {
12826       int Idx = SVN->getMaskElt(i);
12827       if (Idx >= (int)NumElts) {
12828         Idx = -1;
12829         Changed = true;
12830       }
12831       NewMask.push_back(Idx);
12832     }
12833     if (Changed)
12834       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12835   }
12836
12837   // If it is a splat, check if the argument vector is another splat or a
12838   // build_vector.
12839   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12840     SDNode *V = N0.getNode();
12841
12842     // If this is a bit convert that changes the element type of the vector but
12843     // not the number of vector elements, look through it.  Be careful not to
12844     // look though conversions that change things like v4f32 to v2f64.
12845     if (V->getOpcode() == ISD::BITCAST) {
12846       SDValue ConvInput = V->getOperand(0);
12847       if (ConvInput.getValueType().isVector() &&
12848           ConvInput.getValueType().getVectorNumElements() == NumElts)
12849         V = ConvInput.getNode();
12850     }
12851
12852     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12853       assert(V->getNumOperands() == NumElts &&
12854              "BUILD_VECTOR has wrong number of operands");
12855       SDValue Base;
12856       bool AllSame = true;
12857       for (unsigned i = 0; i != NumElts; ++i) {
12858         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12859           Base = V->getOperand(i);
12860           break;
12861         }
12862       }
12863       // Splat of <u, u, u, u>, return <u, u, u, u>
12864       if (!Base.getNode())
12865         return N0;
12866       for (unsigned i = 0; i != NumElts; ++i) {
12867         if (V->getOperand(i) != Base) {
12868           AllSame = false;
12869           break;
12870         }
12871       }
12872       // Splat of <x, x, x, x>, return <x, x, x, x>
12873       if (AllSame)
12874         return N0;
12875
12876       // Canonicalize any other splat as a build_vector.
12877       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12878       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12879       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12880                                   V->getValueType(0), Ops);
12881
12882       // We may have jumped through bitcasts, so the type of the
12883       // BUILD_VECTOR may not match the type of the shuffle.
12884       if (V->getValueType(0) != VT)
12885         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12886       return NewBV;
12887     }
12888   }
12889
12890   // There are various patterns used to build up a vector from smaller vectors,
12891   // subvectors, or elements. Scan chains of these and replace unused insertions
12892   // or components with undef.
12893   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12894     return S;
12895
12896   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12897       Level < AfterLegalizeVectorOps &&
12898       (N1.getOpcode() == ISD::UNDEF ||
12899       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12900        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12901     SDValue V = partitionShuffleOfConcats(N, DAG);
12902
12903     if (V.getNode())
12904       return V;
12905   }
12906
12907   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12908   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12909   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12910     SmallVector<SDValue, 8> Ops;
12911     for (int M : SVN->getMask()) {
12912       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12913       if (M >= 0) {
12914         int Idx = M % NumElts;
12915         SDValue &S = (M < (int)NumElts ? N0 : N1);
12916         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12917           Op = S.getOperand(Idx);
12918         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12919           if (Idx == 0)
12920             Op = S.getOperand(0);
12921         } else {
12922           // Operand can't be combined - bail out.
12923           break;
12924         }
12925       }
12926       Ops.push_back(Op);
12927     }
12928     if (Ops.size() == VT.getVectorNumElements()) {
12929       // BUILD_VECTOR requires all inputs to be of the same type, find the
12930       // maximum type and extend them all.
12931       EVT SVT = VT.getScalarType();
12932       if (SVT.isInteger())
12933         for (SDValue &Op : Ops)
12934           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12935       if (SVT != VT.getScalarType())
12936         for (SDValue &Op : Ops)
12937           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12938                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12939                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12940       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12941     }
12942   }
12943
12944   // If this shuffle only has a single input that is a bitcasted shuffle,
12945   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12946   // back to their original types.
12947   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12948       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12949       TLI.isTypeLegal(VT)) {
12950
12951     // Peek through the bitcast only if there is one user.
12952     SDValue BC0 = N0;
12953     while (BC0.getOpcode() == ISD::BITCAST) {
12954       if (!BC0.hasOneUse())
12955         break;
12956       BC0 = BC0.getOperand(0);
12957     }
12958
12959     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12960       if (Scale == 1)
12961         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12962
12963       SmallVector<int, 8> NewMask;
12964       for (int M : Mask)
12965         for (int s = 0; s != Scale; ++s)
12966           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12967       return NewMask;
12968     };
12969
12970     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12971       EVT SVT = VT.getScalarType();
12972       EVT InnerVT = BC0->getValueType(0);
12973       EVT InnerSVT = InnerVT.getScalarType();
12974
12975       // Determine which shuffle works with the smaller scalar type.
12976       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12977       EVT ScaleSVT = ScaleVT.getScalarType();
12978
12979       if (TLI.isTypeLegal(ScaleVT) &&
12980           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12981           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12982
12983         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12984         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12985
12986         // Scale the shuffle masks to the smaller scalar type.
12987         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12988         SmallVector<int, 8> InnerMask =
12989             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12990         SmallVector<int, 8> OuterMask =
12991             ScaleShuffleMask(SVN->getMask(), OuterScale);
12992
12993         // Merge the shuffle masks.
12994         SmallVector<int, 8> NewMask;
12995         for (int M : OuterMask)
12996           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12997
12998         // Test for shuffle mask legality over both commutations.
12999         SDValue SV0 = BC0->getOperand(0);
13000         SDValue SV1 = BC0->getOperand(1);
13001         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13002         if (!LegalMask) {
13003           std::swap(SV0, SV1);
13004           ShuffleVectorSDNode::commuteMask(NewMask);
13005           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13006         }
13007
13008         if (LegalMask) {
13009           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13010           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13011           return DAG.getNode(
13012               ISD::BITCAST, SDLoc(N), VT,
13013               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13014         }
13015       }
13016     }
13017   }
13018
13019   // Canonicalize shuffles according to rules:
13020   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13021   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13022   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13023   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13024       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13025       TLI.isTypeLegal(VT)) {
13026     // The incoming shuffle must be of the same type as the result of the
13027     // current shuffle.
13028     assert(N1->getOperand(0).getValueType() == VT &&
13029            "Shuffle types don't match");
13030
13031     SDValue SV0 = N1->getOperand(0);
13032     SDValue SV1 = N1->getOperand(1);
13033     bool HasSameOp0 = N0 == SV0;
13034     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13035     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13036       // Commute the operands of this shuffle so that next rule
13037       // will trigger.
13038       return DAG.getCommutedVectorShuffle(*SVN);
13039   }
13040
13041   // Try to fold according to rules:
13042   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13043   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13044   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13045   // Don't try to fold shuffles with illegal type.
13046   // Only fold if this shuffle is the only user of the other shuffle.
13047   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13048       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13049     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13050
13051     // The incoming shuffle must be of the same type as the result of the
13052     // current shuffle.
13053     assert(OtherSV->getOperand(0).getValueType() == VT &&
13054            "Shuffle types don't match");
13055
13056     SDValue SV0, SV1;
13057     SmallVector<int, 4> Mask;
13058     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13059     // operand, and SV1 as the second operand.
13060     for (unsigned i = 0; i != NumElts; ++i) {
13061       int Idx = SVN->getMaskElt(i);
13062       if (Idx < 0) {
13063         // Propagate Undef.
13064         Mask.push_back(Idx);
13065         continue;
13066       }
13067
13068       SDValue CurrentVec;
13069       if (Idx < (int)NumElts) {
13070         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13071         // shuffle mask to identify which vector is actually referenced.
13072         Idx = OtherSV->getMaskElt(Idx);
13073         if (Idx < 0) {
13074           // Propagate Undef.
13075           Mask.push_back(Idx);
13076           continue;
13077         }
13078
13079         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13080                                            : OtherSV->getOperand(1);
13081       } else {
13082         // This shuffle index references an element within N1.
13083         CurrentVec = N1;
13084       }
13085
13086       // Simple case where 'CurrentVec' is UNDEF.
13087       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13088         Mask.push_back(-1);
13089         continue;
13090       }
13091
13092       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13093       // will be the first or second operand of the combined shuffle.
13094       Idx = Idx % NumElts;
13095       if (!SV0.getNode() || SV0 == CurrentVec) {
13096         // Ok. CurrentVec is the left hand side.
13097         // Update the mask accordingly.
13098         SV0 = CurrentVec;
13099         Mask.push_back(Idx);
13100         continue;
13101       }
13102
13103       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13104       if (SV1.getNode() && SV1 != CurrentVec)
13105         return SDValue();
13106
13107       // Ok. CurrentVec is the right hand side.
13108       // Update the mask accordingly.
13109       SV1 = CurrentVec;
13110       Mask.push_back(Idx + NumElts);
13111     }
13112
13113     // Check if all indices in Mask are Undef. In case, propagate Undef.
13114     bool isUndefMask = true;
13115     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13116       isUndefMask &= Mask[i] < 0;
13117
13118     if (isUndefMask)
13119       return DAG.getUNDEF(VT);
13120
13121     if (!SV0.getNode())
13122       SV0 = DAG.getUNDEF(VT);
13123     if (!SV1.getNode())
13124       SV1 = DAG.getUNDEF(VT);
13125
13126     // Avoid introducing shuffles with illegal mask.
13127     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13128       ShuffleVectorSDNode::commuteMask(Mask);
13129
13130       if (!TLI.isShuffleMaskLegal(Mask, VT))
13131         return SDValue();
13132
13133       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13134       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13135       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13136       std::swap(SV0, SV1);
13137     }
13138
13139     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13140     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13141     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13142     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13143   }
13144
13145   return SDValue();
13146 }
13147
13148 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13149   SDValue InVal = N->getOperand(0);
13150   EVT VT = N->getValueType(0);
13151
13152   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13153   // with a VECTOR_SHUFFLE.
13154   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13155     SDValue InVec = InVal->getOperand(0);
13156     SDValue EltNo = InVal->getOperand(1);
13157
13158     // FIXME: We could support implicit truncation if the shuffle can be
13159     // scaled to a smaller vector scalar type.
13160     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13161     if (C0 && VT == InVec.getValueType() &&
13162         VT.getScalarType() == InVal.getValueType()) {
13163       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13164       int Elt = C0->getZExtValue();
13165       NewMask[0] = Elt;
13166
13167       if (TLI.isShuffleMaskLegal(NewMask, VT))
13168         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13169                                     NewMask);
13170     }
13171   }
13172
13173   return SDValue();
13174 }
13175
13176 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13177   SDValue N0 = N->getOperand(0);
13178   SDValue N2 = N->getOperand(2);
13179
13180   // If the input vector is a concatenation, and the insert replaces
13181   // one of the halves, we can optimize into a single concat_vectors.
13182   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13183       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13184     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13185     EVT VT = N->getValueType(0);
13186
13187     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13188     // (concat_vectors Z, Y)
13189     if (InsIdx == 0)
13190       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13191                          N->getOperand(1), N0.getOperand(1));
13192
13193     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13194     // (concat_vectors X, Z)
13195     if (InsIdx == VT.getVectorNumElements()/2)
13196       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13197                          N0.getOperand(0), N->getOperand(1));
13198   }
13199
13200   return SDValue();
13201 }
13202
13203 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13204   SDValue N0 = N->getOperand(0);
13205
13206   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13207   if (N0->getOpcode() == ISD::FP16_TO_FP)
13208     return N0->getOperand(0);
13209
13210   return SDValue();
13211 }
13212
13213 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13214   SDValue N0 = N->getOperand(0);
13215
13216   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13217   if (N0->getOpcode() == ISD::AND) {
13218     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13219     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13220       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13221                          N0.getOperand(0));
13222     }
13223   }
13224
13225   return SDValue();
13226 }
13227
13228 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13229 /// with the destination vector and a zero vector.
13230 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13231 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13232 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13233   EVT VT = N->getValueType(0);
13234   SDValue LHS = N->getOperand(0);
13235   SDValue RHS = N->getOperand(1);
13236   SDLoc dl(N);
13237
13238   // Make sure we're not running after operation legalization where it
13239   // may have custom lowered the vector shuffles.
13240   if (LegalOperations)
13241     return SDValue();
13242
13243   if (N->getOpcode() != ISD::AND)
13244     return SDValue();
13245
13246   if (RHS.getOpcode() == ISD::BITCAST)
13247     RHS = RHS.getOperand(0);
13248
13249   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13250     return SDValue();
13251
13252   EVT RVT = RHS.getValueType();
13253   unsigned NumElts = RHS.getNumOperands();
13254
13255   // Attempt to create a valid clear mask, splitting the mask into
13256   // sub elements and checking to see if each is
13257   // all zeros or all ones - suitable for shuffle masking.
13258   auto BuildClearMask = [&](int Split) {
13259     int NumSubElts = NumElts * Split;
13260     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13261
13262     SmallVector<int, 8> Indices;
13263     for (int i = 0; i != NumSubElts; ++i) {
13264       int EltIdx = i / Split;
13265       int SubIdx = i % Split;
13266       SDValue Elt = RHS.getOperand(EltIdx);
13267       if (Elt.getOpcode() == ISD::UNDEF) {
13268         Indices.push_back(-1);
13269         continue;
13270       }
13271
13272       APInt Bits;
13273       if (isa<ConstantSDNode>(Elt))
13274         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13275       else if (isa<ConstantFPSDNode>(Elt))
13276         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13277       else
13278         return SDValue();
13279
13280       // Extract the sub element from the constant bit mask.
13281       if (DAG.getDataLayout().isBigEndian()) {
13282         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13283       } else {
13284         Bits = Bits.lshr(SubIdx * NumSubBits);
13285       }
13286
13287       if (Split > 1)
13288         Bits = Bits.trunc(NumSubBits);
13289
13290       if (Bits.isAllOnesValue())
13291         Indices.push_back(i);
13292       else if (Bits == 0)
13293         Indices.push_back(i + NumSubElts);
13294       else
13295         return SDValue();
13296     }
13297
13298     // Let's see if the target supports this vector_shuffle.
13299     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13300     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13301     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13302       return SDValue();
13303
13304     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13305     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13306                                                    DAG.getBitcast(ClearVT, LHS),
13307                                                    Zero, &Indices[0]));
13308   };
13309
13310   // Determine maximum split level (byte level masking).
13311   int MaxSplit = 1;
13312   if (RVT.getScalarSizeInBits() % 8 == 0)
13313     MaxSplit = RVT.getScalarSizeInBits() / 8;
13314
13315   for (int Split = 1; Split <= MaxSplit; ++Split)
13316     if (RVT.getScalarSizeInBits() % Split == 0)
13317       if (SDValue S = BuildClearMask(Split))
13318         return S;
13319
13320   return SDValue();
13321 }
13322
13323 /// Visit a binary vector operation, like ADD.
13324 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13325   assert(N->getValueType(0).isVector() &&
13326          "SimplifyVBinOp only works on vectors!");
13327
13328   SDValue LHS = N->getOperand(0);
13329   SDValue RHS = N->getOperand(1);
13330
13331   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13332   // this operation.
13333   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13334       RHS.getOpcode() == ISD::BUILD_VECTOR) {
13335     // Check if both vectors are constants. If not bail out.
13336     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13337           cast<BuildVectorSDNode>(RHS)->isConstant()))
13338       return SDValue();
13339
13340     SmallVector<SDValue, 8> Ops;
13341     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13342       SDValue LHSOp = LHS.getOperand(i);
13343       SDValue RHSOp = RHS.getOperand(i);
13344
13345       // Can't fold divide by zero.
13346       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13347           N->getOpcode() == ISD::FDIV) {
13348         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13349              cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13350           break;
13351       }
13352
13353       EVT VT = LHSOp.getValueType();
13354       EVT RVT = RHSOp.getValueType();
13355       EVT ST = VT;
13356
13357       if (RVT.getSizeInBits() < VT.getSizeInBits())
13358         ST = RVT;
13359
13360       // Integer BUILD_VECTOR operands may have types larger than the element
13361       // size (e.g., when the element type is not legal).  Prior to type
13362       // legalization, the types may not match between the two BUILD_VECTORS.
13363       // Truncate the operands to make them match.
13364       if (VT.getSizeInBits() != LHS.getValueType().getScalarSizeInBits()) {
13365         EVT ScalarT = LHS.getValueType().getScalarType();
13366         LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), ScalarT, LHSOp);
13367         VT = LHSOp.getValueType();
13368       }
13369       if (RVT.getSizeInBits() != RHS.getValueType().getScalarSizeInBits()) {
13370         EVT ScalarT = RHS.getValueType().getScalarType();
13371         RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), ScalarT, RHSOp);
13372         RVT = RHSOp.getValueType();
13373       }
13374
13375       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13376                                    LHSOp, RHSOp, N->getFlags());
13377
13378       // We need the resulting constant to be legal if we are in a phase after
13379       // legalization, so zero extend to the smallest operand type if required.
13380       if (ST != VT && Level != BeforeLegalizeTypes)
13381         FoldOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LHS), ST, FoldOp);
13382
13383       if (FoldOp.getOpcode() != ISD::UNDEF &&
13384           FoldOp.getOpcode() != ISD::Constant &&
13385           FoldOp.getOpcode() != ISD::ConstantFP)
13386         break;
13387       Ops.push_back(FoldOp);
13388       AddToWorklist(FoldOp.getNode());
13389     }
13390
13391     if (Ops.size() == LHS.getNumOperands())
13392       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13393   }
13394
13395   // Try to convert a constant mask AND into a shuffle clear mask.
13396   if (SDValue Shuffle = XformToShuffleWithZero(N))
13397     return Shuffle;
13398
13399   // Type legalization might introduce new shuffles in the DAG.
13400   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13401   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13402   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13403       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13404       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13405       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13406     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13407     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13408
13409     if (SVN0->getMask().equals(SVN1->getMask())) {
13410       EVT VT = N->getValueType(0);
13411       SDValue UndefVector = LHS.getOperand(1);
13412       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13413                                      LHS.getOperand(0), RHS.getOperand(0),
13414                                      N->getFlags());
13415       AddUsersToWorklist(N);
13416       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13417                                   &SVN0->getMask()[0]);
13418     }
13419   }
13420
13421   return SDValue();
13422 }
13423
13424 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13425                                     SDValue N1, SDValue N2){
13426   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13427
13428   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13429                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13430
13431   // If we got a simplified select_cc node back from SimplifySelectCC, then
13432   // break it down into a new SETCC node, and a new SELECT node, and then return
13433   // the SELECT node, since we were called with a SELECT node.
13434   if (SCC.getNode()) {
13435     // Check to see if we got a select_cc back (to turn into setcc/select).
13436     // Otherwise, just return whatever node we got back, like fabs.
13437     if (SCC.getOpcode() == ISD::SELECT_CC) {
13438       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13439                                   N0.getValueType(),
13440                                   SCC.getOperand(0), SCC.getOperand(1),
13441                                   SCC.getOperand(4));
13442       AddToWorklist(SETCC.getNode());
13443       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13444                            SCC.getOperand(2), SCC.getOperand(3));
13445     }
13446
13447     return SCC;
13448   }
13449   return SDValue();
13450 }
13451
13452 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13453 /// being selected between, see if we can simplify the select.  Callers of this
13454 /// should assume that TheSelect is deleted if this returns true.  As such, they
13455 /// should return the appropriate thing (e.g. the node) back to the top-level of
13456 /// the DAG combiner loop to avoid it being looked at.
13457 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13458                                     SDValue RHS) {
13459
13460   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13461   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13462   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13463     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13464       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13465       SDValue Sqrt = RHS;
13466       ISD::CondCode CC;
13467       SDValue CmpLHS;
13468       const ConstantFPSDNode *NegZero = nullptr;
13469
13470       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13471         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13472         CmpLHS = TheSelect->getOperand(0);
13473         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13474       } else {
13475         // SELECT or VSELECT
13476         SDValue Cmp = TheSelect->getOperand(0);
13477         if (Cmp.getOpcode() == ISD::SETCC) {
13478           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13479           CmpLHS = Cmp.getOperand(0);
13480           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13481         }
13482       }
13483       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13484           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13485           CC == ISD::SETULT || CC == ISD::SETLT)) {
13486         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13487         CombineTo(TheSelect, Sqrt);
13488         return true;
13489       }
13490     }
13491   }
13492   // Cannot simplify select with vector condition
13493   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13494
13495   // If this is a select from two identical things, try to pull the operation
13496   // through the select.
13497   if (LHS.getOpcode() != RHS.getOpcode() ||
13498       !LHS.hasOneUse() || !RHS.hasOneUse())
13499     return false;
13500
13501   // If this is a load and the token chain is identical, replace the select
13502   // of two loads with a load through a select of the address to load from.
13503   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13504   // constants have been dropped into the constant pool.
13505   if (LHS.getOpcode() == ISD::LOAD) {
13506     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13507     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13508
13509     // Token chains must be identical.
13510     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13511         // Do not let this transformation reduce the number of volatile loads.
13512         LLD->isVolatile() || RLD->isVolatile() ||
13513         // FIXME: If either is a pre/post inc/dec load,
13514         // we'd need to split out the address adjustment.
13515         LLD->isIndexed() || RLD->isIndexed() ||
13516         // If this is an EXTLOAD, the VT's must match.
13517         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13518         // If this is an EXTLOAD, the kind of extension must match.
13519         (LLD->getExtensionType() != RLD->getExtensionType() &&
13520          // The only exception is if one of the extensions is anyext.
13521          LLD->getExtensionType() != ISD::EXTLOAD &&
13522          RLD->getExtensionType() != ISD::EXTLOAD) ||
13523         // FIXME: this discards src value information.  This is
13524         // over-conservative. It would be beneficial to be able to remember
13525         // both potential memory locations.  Since we are discarding
13526         // src value info, don't do the transformation if the memory
13527         // locations are not in the default address space.
13528         LLD->getPointerInfo().getAddrSpace() != 0 ||
13529         RLD->getPointerInfo().getAddrSpace() != 0 ||
13530         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13531                                       LLD->getBasePtr().getValueType()))
13532       return false;
13533
13534     // Check that the select condition doesn't reach either load.  If so,
13535     // folding this will induce a cycle into the DAG.  If not, this is safe to
13536     // xform, so create a select of the addresses.
13537     SDValue Addr;
13538     if (TheSelect->getOpcode() == ISD::SELECT) {
13539       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13540       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13541           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13542         return false;
13543       // The loads must not depend on one another.
13544       if (LLD->isPredecessorOf(RLD) ||
13545           RLD->isPredecessorOf(LLD))
13546         return false;
13547       Addr = DAG.getSelect(SDLoc(TheSelect),
13548                            LLD->getBasePtr().getValueType(),
13549                            TheSelect->getOperand(0), LLD->getBasePtr(),
13550                            RLD->getBasePtr());
13551     } else {  // Otherwise SELECT_CC
13552       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13553       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13554
13555       if ((LLD->hasAnyUseOfValue(1) &&
13556            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13557           (RLD->hasAnyUseOfValue(1) &&
13558            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13559         return false;
13560
13561       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13562                          LLD->getBasePtr().getValueType(),
13563                          TheSelect->getOperand(0),
13564                          TheSelect->getOperand(1),
13565                          LLD->getBasePtr(), RLD->getBasePtr(),
13566                          TheSelect->getOperand(4));
13567     }
13568
13569     SDValue Load;
13570     // It is safe to replace the two loads if they have different alignments,
13571     // but the new load must be the minimum (most restrictive) alignment of the
13572     // inputs.
13573     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13574     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13575     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13576       Load = DAG.getLoad(TheSelect->getValueType(0),
13577                          SDLoc(TheSelect),
13578                          // FIXME: Discards pointer and AA info.
13579                          LLD->getChain(), Addr, MachinePointerInfo(),
13580                          LLD->isVolatile(), LLD->isNonTemporal(),
13581                          isInvariant, Alignment);
13582     } else {
13583       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13584                             RLD->getExtensionType() : LLD->getExtensionType(),
13585                             SDLoc(TheSelect),
13586                             TheSelect->getValueType(0),
13587                             // FIXME: Discards pointer and AA info.
13588                             LLD->getChain(), Addr, MachinePointerInfo(),
13589                             LLD->getMemoryVT(), LLD->isVolatile(),
13590                             LLD->isNonTemporal(), isInvariant, Alignment);
13591     }
13592
13593     // Users of the select now use the result of the load.
13594     CombineTo(TheSelect, Load);
13595
13596     // Users of the old loads now use the new load's chain.  We know the
13597     // old-load value is dead now.
13598     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13599     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13600     return true;
13601   }
13602
13603   return false;
13604 }
13605
13606 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13607 /// where 'cond' is the comparison specified by CC.
13608 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13609                                       SDValue N2, SDValue N3,
13610                                       ISD::CondCode CC, bool NotExtCompare) {
13611   // (x ? y : y) -> y.
13612   if (N2 == N3) return N2;
13613
13614   EVT VT = N2.getValueType();
13615   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13616   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13617
13618   // Determine if the condition we're dealing with is constant
13619   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13620                               N0, N1, CC, DL, false);
13621   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13622
13623   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13624     // fold select_cc true, x, y -> x
13625     // fold select_cc false, x, y -> y
13626     return !SCCC->isNullValue() ? N2 : N3;
13627   }
13628
13629   // Check to see if we can simplify the select into an fabs node
13630   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13631     // Allow either -0.0 or 0.0
13632     if (CFP->isZero()) {
13633       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13634       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13635           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13636           N2 == N3.getOperand(0))
13637         return DAG.getNode(ISD::FABS, DL, VT, N0);
13638
13639       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13640       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13641           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13642           N2.getOperand(0) == N3)
13643         return DAG.getNode(ISD::FABS, DL, VT, N3);
13644     }
13645   }
13646
13647   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13648   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13649   // in it.  This is a win when the constant is not otherwise available because
13650   // it replaces two constant pool loads with one.  We only do this if the FP
13651   // type is known to be legal, because if it isn't, then we are before legalize
13652   // types an we want the other legalization to happen first (e.g. to avoid
13653   // messing with soft float) and if the ConstantFP is not legal, because if
13654   // it is legal, we may not need to store the FP constant in a constant pool.
13655   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13656     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13657       if (TLI.isTypeLegal(N2.getValueType()) &&
13658           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13659                TargetLowering::Legal &&
13660            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13661            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13662           // If both constants have multiple uses, then we won't need to do an
13663           // extra load, they are likely around in registers for other users.
13664           (TV->hasOneUse() || FV->hasOneUse())) {
13665         Constant *Elts[] = {
13666           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13667           const_cast<ConstantFP*>(TV->getConstantFPValue())
13668         };
13669         Type *FPTy = Elts[0]->getType();
13670         const DataLayout &TD = DAG.getDataLayout();
13671
13672         // Create a ConstantArray of the two constants.
13673         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13674         SDValue CPIdx =
13675             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13676                                 TD.getPrefTypeAlignment(FPTy));
13677         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13678
13679         // Get the offsets to the 0 and 1 element of the array so that we can
13680         // select between them.
13681         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13682         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13683         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13684
13685         SDValue Cond = DAG.getSetCC(DL,
13686                                     getSetCCResultType(N0.getValueType()),
13687                                     N0, N1, CC);
13688         AddToWorklist(Cond.getNode());
13689         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13690                                           Cond, One, Zero);
13691         AddToWorklist(CstOffset.getNode());
13692         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13693                             CstOffset);
13694         AddToWorklist(CPIdx.getNode());
13695         return DAG.getLoad(
13696             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13697             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13698             false, false, false, Alignment);
13699       }
13700     }
13701
13702   // Check to see if we can perform the "gzip trick", transforming
13703   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13704   if (isNullConstant(N3) && CC == ISD::SETLT &&
13705       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13706        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13707     EVT XType = N0.getValueType();
13708     EVT AType = N2.getValueType();
13709     if (XType.bitsGE(AType)) {
13710       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13711       // single-bit constant.
13712       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13713         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13714         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13715         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13716                                        getShiftAmountTy(N0.getValueType()));
13717         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13718                                     XType, N0, ShCt);
13719         AddToWorklist(Shift.getNode());
13720
13721         if (XType.bitsGT(AType)) {
13722           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13723           AddToWorklist(Shift.getNode());
13724         }
13725
13726         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13727       }
13728
13729       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13730                                   XType, N0,
13731                                   DAG.getConstant(XType.getSizeInBits() - 1,
13732                                                   SDLoc(N0),
13733                                          getShiftAmountTy(N0.getValueType())));
13734       AddToWorklist(Shift.getNode());
13735
13736       if (XType.bitsGT(AType)) {
13737         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13738         AddToWorklist(Shift.getNode());
13739       }
13740
13741       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13742     }
13743   }
13744
13745   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13746   // where y is has a single bit set.
13747   // A plaintext description would be, we can turn the SELECT_CC into an AND
13748   // when the condition can be materialized as an all-ones register.  Any
13749   // single bit-test can be materialized as an all-ones register with
13750   // shift-left and shift-right-arith.
13751   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13752       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13753     SDValue AndLHS = N0->getOperand(0);
13754     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13755     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13756       // Shift the tested bit over the sign bit.
13757       APInt AndMask = ConstAndRHS->getAPIntValue();
13758       SDValue ShlAmt =
13759         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13760                         getShiftAmountTy(AndLHS.getValueType()));
13761       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13762
13763       // Now arithmetic right shift it all the way over, so the result is either
13764       // all-ones, or zero.
13765       SDValue ShrAmt =
13766         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13767                         getShiftAmountTy(Shl.getValueType()));
13768       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13769
13770       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13771     }
13772   }
13773
13774   // fold select C, 16, 0 -> shl C, 4
13775   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13776       TLI.getBooleanContents(N0.getValueType()) ==
13777           TargetLowering::ZeroOrOneBooleanContent) {
13778
13779     // If the caller doesn't want us to simplify this into a zext of a compare,
13780     // don't do it.
13781     if (NotExtCompare && N2C->isOne())
13782       return SDValue();
13783
13784     // Get a SetCC of the condition
13785     // NOTE: Don't create a SETCC if it's not legal on this target.
13786     if (!LegalOperations ||
13787         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13788       SDValue Temp, SCC;
13789       // cast from setcc result type to select result type
13790       if (LegalTypes) {
13791         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13792                             N0, N1, CC);
13793         if (N2.getValueType().bitsLT(SCC.getValueType()))
13794           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13795                                         N2.getValueType());
13796         else
13797           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13798                              N2.getValueType(), SCC);
13799       } else {
13800         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13801         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13802                            N2.getValueType(), SCC);
13803       }
13804
13805       AddToWorklist(SCC.getNode());
13806       AddToWorklist(Temp.getNode());
13807
13808       if (N2C->isOne())
13809         return Temp;
13810
13811       // shl setcc result by log2 n2c
13812       return DAG.getNode(
13813           ISD::SHL, DL, N2.getValueType(), Temp,
13814           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13815                           getShiftAmountTy(Temp.getValueType())));
13816     }
13817   }
13818
13819   // Check to see if this is an integer abs.
13820   // select_cc setg[te] X,  0,  X, -X ->
13821   // select_cc setgt    X, -1,  X, -X ->
13822   // select_cc setl[te] X,  0, -X,  X ->
13823   // select_cc setlt    X,  1, -X,  X ->
13824   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13825   if (N1C) {
13826     ConstantSDNode *SubC = nullptr;
13827     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13828          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13829         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13830       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13831     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13832               (N1C->isOne() && CC == ISD::SETLT)) &&
13833              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13834       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13835
13836     EVT XType = N0.getValueType();
13837     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13838       SDLoc DL(N0);
13839       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13840                                   N0,
13841                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13842                                          getShiftAmountTy(N0.getValueType())));
13843       SDValue Add = DAG.getNode(ISD::ADD, DL,
13844                                 XType, N0, Shift);
13845       AddToWorklist(Shift.getNode());
13846       AddToWorklist(Add.getNode());
13847       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13848     }
13849   }
13850
13851   return SDValue();
13852 }
13853
13854 /// This is a stub for TargetLowering::SimplifySetCC.
13855 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13856                                    SDValue N1, ISD::CondCode Cond,
13857                                    SDLoc DL, bool foldBooleans) {
13858   TargetLowering::DAGCombinerInfo
13859     DagCombineInfo(DAG, Level, false, this);
13860   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13861 }
13862
13863 /// Given an ISD::SDIV node expressing a divide by constant, return
13864 /// a DAG expression to select that will generate the same value by multiplying
13865 /// by a magic number.
13866 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13867 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13868   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13869   if (!C)
13870     return SDValue();
13871
13872   // Avoid division by zero.
13873   if (C->isNullValue())
13874     return SDValue();
13875
13876   std::vector<SDNode*> Built;
13877   SDValue S =
13878       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13879
13880   for (SDNode *N : Built)
13881     AddToWorklist(N);
13882   return S;
13883 }
13884
13885 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13886 /// DAG expression that will generate the same value by right shifting.
13887 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13888   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13889   if (!C)
13890     return SDValue();
13891
13892   // Avoid division by zero.
13893   if (C->isNullValue())
13894     return SDValue();
13895
13896   std::vector<SDNode *> Built;
13897   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13898
13899   for (SDNode *N : Built)
13900     AddToWorklist(N);
13901   return S;
13902 }
13903
13904 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13905 /// expression that will generate the same value by multiplying by a magic
13906 /// number.
13907 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13908 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13909   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13910   if (!C)
13911     return SDValue();
13912
13913   // Avoid division by zero.
13914   if (C->isNullValue())
13915     return SDValue();
13916
13917   std::vector<SDNode*> Built;
13918   SDValue S =
13919       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13920
13921   for (SDNode *N : Built)
13922     AddToWorklist(N);
13923   return S;
13924 }
13925
13926 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
13927   if (Level >= AfterLegalizeDAG)
13928     return SDValue();
13929
13930   // Expose the DAG combiner to the target combiner implementations.
13931   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13932
13933   unsigned Iterations = 0;
13934   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13935     if (Iterations) {
13936       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13937       // For the reciprocal, we need to find the zero of the function:
13938       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13939       //     =>
13940       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13941       //     does not require additional intermediate precision]
13942       EVT VT = Op.getValueType();
13943       SDLoc DL(Op);
13944       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13945
13946       AddToWorklist(Est.getNode());
13947
13948       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13949       for (unsigned i = 0; i < Iterations; ++i) {
13950         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
13951         AddToWorklist(NewEst.getNode());
13952
13953         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
13954         AddToWorklist(NewEst.getNode());
13955
13956         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
13957         AddToWorklist(NewEst.getNode());
13958
13959         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
13960         AddToWorklist(Est.getNode());
13961       }
13962     }
13963     return Est;
13964   }
13965
13966   return SDValue();
13967 }
13968
13969 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13970 /// For the reciprocal sqrt, we need to find the zero of the function:
13971 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13972 ///     =>
13973 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13974 /// As a result, we precompute A/2 prior to the iteration loop.
13975 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13976                                           unsigned Iterations,
13977                                           SDNodeFlags *Flags) {
13978   EVT VT = Arg.getValueType();
13979   SDLoc DL(Arg);
13980   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13981
13982   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13983   // this entire sequence requires only one FP constant.
13984   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
13985   AddToWorklist(HalfArg.getNode());
13986
13987   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
13988   AddToWorklist(HalfArg.getNode());
13989
13990   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13991   for (unsigned i = 0; i < Iterations; ++i) {
13992     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
13993     AddToWorklist(NewEst.getNode());
13994
13995     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
13996     AddToWorklist(NewEst.getNode());
13997
13998     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
13999     AddToWorklist(NewEst.getNode());
14000
14001     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14002     AddToWorklist(Est.getNode());
14003   }
14004   return Est;
14005 }
14006
14007 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14008 /// For the reciprocal sqrt, we need to find the zero of the function:
14009 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14010 ///     =>
14011 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14012 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14013                                           unsigned Iterations,
14014                                           SDNodeFlags *Flags) {
14015   EVT VT = Arg.getValueType();
14016   SDLoc DL(Arg);
14017   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14018   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14019
14020   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14021   for (unsigned i = 0; i < Iterations; ++i) {
14022     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14023     AddToWorklist(HalfEst.getNode());
14024
14025     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14026     AddToWorklist(Est.getNode());
14027
14028     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14029     AddToWorklist(Est.getNode());
14030
14031     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14032     AddToWorklist(Est.getNode());
14033
14034     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14035     AddToWorklist(Est.getNode());
14036   }
14037   return Est;
14038 }
14039
14040 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14041   if (Level >= AfterLegalizeDAG)
14042     return SDValue();
14043
14044   // Expose the DAG combiner to the target combiner implementations.
14045   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14046   unsigned Iterations = 0;
14047   bool UseOneConstNR = false;
14048   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14049     AddToWorklist(Est.getNode());
14050     if (Iterations) {
14051       Est = UseOneConstNR ?
14052         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14053         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14054     }
14055     return Est;
14056   }
14057
14058   return SDValue();
14059 }
14060
14061 /// Return true if base is a frame index, which is known not to alias with
14062 /// anything but itself.  Provides base object and offset as results.
14063 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14064                            const GlobalValue *&GV, const void *&CV) {
14065   // Assume it is a primitive operation.
14066   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14067
14068   // If it's an adding a simple constant then integrate the offset.
14069   if (Base.getOpcode() == ISD::ADD) {
14070     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14071       Base = Base.getOperand(0);
14072       Offset += C->getZExtValue();
14073     }
14074   }
14075
14076   // Return the underlying GlobalValue, and update the Offset.  Return false
14077   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14078   // by multiple nodes with different offsets.
14079   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14080     GV = G->getGlobal();
14081     Offset += G->getOffset();
14082     return false;
14083   }
14084
14085   // Return the underlying Constant value, and update the Offset.  Return false
14086   // for ConstantSDNodes since the same constant pool entry may be represented
14087   // by multiple nodes with different offsets.
14088   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14089     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14090                                          : (const void *)C->getConstVal();
14091     Offset += C->getOffset();
14092     return false;
14093   }
14094   // If it's any of the following then it can't alias with anything but itself.
14095   return isa<FrameIndexSDNode>(Base);
14096 }
14097
14098 /// Return true if there is any possibility that the two addresses overlap.
14099 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14100   // If they are the same then they must be aliases.
14101   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14102
14103   // If they are both volatile then they cannot be reordered.
14104   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14105
14106   // If one operation reads from invariant memory, and the other may store, they
14107   // cannot alias. These should really be checking the equivalent of mayWrite,
14108   // but it only matters for memory nodes other than load /store.
14109   if (Op0->isInvariant() && Op1->writeMem())
14110     return false;
14111
14112   if (Op1->isInvariant() && Op0->writeMem())
14113     return false;
14114
14115   // Gather base node and offset information.
14116   SDValue Base1, Base2;
14117   int64_t Offset1, Offset2;
14118   const GlobalValue *GV1, *GV2;
14119   const void *CV1, *CV2;
14120   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14121                                       Base1, Offset1, GV1, CV1);
14122   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14123                                       Base2, Offset2, GV2, CV2);
14124
14125   // If they have a same base address then check to see if they overlap.
14126   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14127     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14128              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14129
14130   // It is possible for different frame indices to alias each other, mostly
14131   // when tail call optimization reuses return address slots for arguments.
14132   // To catch this case, look up the actual index of frame indices to compute
14133   // the real alias relationship.
14134   if (isFrameIndex1 && isFrameIndex2) {
14135     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14136     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14137     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14138     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14139              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14140   }
14141
14142   // Otherwise, if we know what the bases are, and they aren't identical, then
14143   // we know they cannot alias.
14144   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14145     return false;
14146
14147   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14148   // compared to the size and offset of the access, we may be able to prove they
14149   // do not alias.  This check is conservative for now to catch cases created by
14150   // splitting vector types.
14151   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14152       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14153       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14154        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14155       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14156     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14157     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14158
14159     // There is no overlap between these relatively aligned accesses of similar
14160     // size, return no alias.
14161     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14162         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14163       return false;
14164   }
14165
14166   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14167                    ? CombinerGlobalAA
14168                    : DAG.getSubtarget().useAA();
14169 #ifndef NDEBUG
14170   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14171       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14172     UseAA = false;
14173 #endif
14174   if (UseAA &&
14175       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14176     // Use alias analysis information.
14177     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14178                                  Op1->getSrcValueOffset());
14179     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14180         Op0->getSrcValueOffset() - MinOffset;
14181     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14182         Op1->getSrcValueOffset() - MinOffset;
14183     AliasResult AAResult =
14184         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14185                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14186                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14187                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14188     if (AAResult == NoAlias)
14189       return false;
14190   }
14191
14192   // Otherwise we have to assume they alias.
14193   return true;
14194 }
14195
14196 /// Walk up chain skipping non-aliasing memory nodes,
14197 /// looking for aliasing nodes and adding them to the Aliases vector.
14198 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14199                                    SmallVectorImpl<SDValue> &Aliases) {
14200   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14201   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14202
14203   // Get alias information for node.
14204   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14205
14206   // Starting off.
14207   Chains.push_back(OriginalChain);
14208   unsigned Depth = 0;
14209
14210   // Look at each chain and determine if it is an alias.  If so, add it to the
14211   // aliases list.  If not, then continue up the chain looking for the next
14212   // candidate.
14213   while (!Chains.empty()) {
14214     SDValue Chain = Chains.pop_back_val();
14215
14216     // For TokenFactor nodes, look at each operand and only continue up the
14217     // chain until we find two aliases.  If we've seen two aliases, assume we'll
14218     // find more and revert to original chain since the xform is unlikely to be
14219     // profitable.
14220     //
14221     // FIXME: The depth check could be made to return the last non-aliasing
14222     // chain we found before we hit a tokenfactor rather than the original
14223     // chain.
14224     if (Depth > 6 || Aliases.size() == 2) {
14225       Aliases.clear();
14226       Aliases.push_back(OriginalChain);
14227       return;
14228     }
14229
14230     // Don't bother if we've been before.
14231     if (!Visited.insert(Chain.getNode()).second)
14232       continue;
14233
14234     switch (Chain.getOpcode()) {
14235     case ISD::EntryToken:
14236       // Entry token is ideal chain operand, but handled in FindBetterChain.
14237       break;
14238
14239     case ISD::LOAD:
14240     case ISD::STORE: {
14241       // Get alias information for Chain.
14242       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14243           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14244
14245       // If chain is alias then stop here.
14246       if (!(IsLoad && IsOpLoad) &&
14247           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14248         Aliases.push_back(Chain);
14249       } else {
14250         // Look further up the chain.
14251         Chains.push_back(Chain.getOperand(0));
14252         ++Depth;
14253       }
14254       break;
14255     }
14256
14257     case ISD::TokenFactor:
14258       // We have to check each of the operands of the token factor for "small"
14259       // token factors, so we queue them up.  Adding the operands to the queue
14260       // (stack) in reverse order maintains the original order and increases the
14261       // likelihood that getNode will find a matching token factor (CSE.)
14262       if (Chain.getNumOperands() > 16) {
14263         Aliases.push_back(Chain);
14264         break;
14265       }
14266       for (unsigned n = Chain.getNumOperands(); n;)
14267         Chains.push_back(Chain.getOperand(--n));
14268       ++Depth;
14269       break;
14270
14271     default:
14272       // For all other instructions we will just have to take what we can get.
14273       Aliases.push_back(Chain);
14274       break;
14275     }
14276   }
14277
14278   // We need to be careful here to also search for aliases through the
14279   // value operand of a store, etc. Consider the following situation:
14280   //   Token1 = ...
14281   //   L1 = load Token1, %52
14282   //   S1 = store Token1, L1, %51
14283   //   L2 = load Token1, %52+8
14284   //   S2 = store Token1, L2, %51+8
14285   //   Token2 = Token(S1, S2)
14286   //   L3 = load Token2, %53
14287   //   S3 = store Token2, L3, %52
14288   //   L4 = load Token2, %53+8
14289   //   S4 = store Token2, L4, %52+8
14290   // If we search for aliases of S3 (which loads address %52), and we look
14291   // only through the chain, then we'll miss the trivial dependence on L1
14292   // (which also loads from %52). We then might change all loads and
14293   // stores to use Token1 as their chain operand, which could result in
14294   // copying %53 into %52 before copying %52 into %51 (which should
14295   // happen first).
14296   //
14297   // The problem is, however, that searching for such data dependencies
14298   // can become expensive, and the cost is not directly related to the
14299   // chain depth. Instead, we'll rule out such configurations here by
14300   // insisting that we've visited all chain users (except for users
14301   // of the original chain, which is not necessary). When doing this,
14302   // we need to look through nodes we don't care about (otherwise, things
14303   // like register copies will interfere with trivial cases).
14304
14305   SmallVector<const SDNode *, 16> Worklist;
14306   for (const SDNode *N : Visited)
14307     if (N != OriginalChain.getNode())
14308       Worklist.push_back(N);
14309
14310   while (!Worklist.empty()) {
14311     const SDNode *M = Worklist.pop_back_val();
14312
14313     // We have already visited M, and want to make sure we've visited any uses
14314     // of M that we care about. For uses that we've not visisted, and don't
14315     // care about, queue them to the worklist.
14316
14317     for (SDNode::use_iterator UI = M->use_begin(),
14318          UIE = M->use_end(); UI != UIE; ++UI)
14319       if (UI.getUse().getValueType() == MVT::Other &&
14320           Visited.insert(*UI).second) {
14321         if (isa<MemSDNode>(*UI)) {
14322           // We've not visited this use, and we care about it (it could have an
14323           // ordering dependency with the original node).
14324           Aliases.clear();
14325           Aliases.push_back(OriginalChain);
14326           return;
14327         }
14328
14329         // We've not visited this use, but we don't care about it. Mark it as
14330         // visited and enqueue it to the worklist.
14331         Worklist.push_back(*UI);
14332       }
14333   }
14334 }
14335
14336 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14337 /// (aliasing node.)
14338 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14339   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14340
14341   // Accumulate all the aliases to this node.
14342   GatherAllAliases(N, OldChain, Aliases);
14343
14344   // If no operands then chain to entry token.
14345   if (Aliases.size() == 0)
14346     return DAG.getEntryNode();
14347
14348   // If a single operand then chain to it.  We don't need to revisit it.
14349   if (Aliases.size() == 1)
14350     return Aliases[0];
14351
14352   // Construct a custom tailored token factor.
14353   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14354 }
14355
14356 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14357   // This holds the base pointer, index, and the offset in bytes from the base
14358   // pointer.
14359   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14360
14361   // We must have a base and an offset.
14362   if (!BasePtr.Base.getNode())
14363     return false;
14364
14365   // Do not handle stores to undef base pointers.
14366   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14367     return false;
14368
14369   SmallVector<StoreSDNode *, 8> ChainedStores;
14370   ChainedStores.push_back(St);
14371
14372   // Walk up the chain and look for nodes with offsets from the same
14373   // base pointer. Stop when reaching an instruction with a different kind
14374   // or instruction which has a different base pointer.
14375   StoreSDNode *Index = St;
14376   while (Index) {
14377     // If the chain has more than one use, then we can't reorder the mem ops.
14378     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14379       break;
14380
14381     // Find the base pointer and offset for this memory node.
14382     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14383
14384     // Check that the base pointer is the same as the original one.
14385     if (!Ptr.equalBaseIndex(BasePtr))
14386       break;
14387
14388     if (Index->isVolatile() || Index->isIndexed())
14389       break;
14390
14391     // Find the next memory operand in the chain. If the next operand in the
14392     // chain is a store then move up and continue the scan with the next
14393     // memory operand. If the next operand is a load save it and use alias
14394     // information to check if it interferes with anything.
14395     SDNode *NextInChain = Index->getChain().getNode();
14396     while (true) {
14397       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14398         // We found a store node. Use it for the next iteration.
14399         ChainedStores.push_back(STn);
14400         Index = STn;
14401         break;
14402       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14403         NextInChain = Ldn->getChain().getNode();
14404         continue;
14405       } else {
14406         Index = nullptr;
14407         break;
14408       }
14409     }
14410   }
14411
14412   bool MadeChange = false;
14413   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14414
14415   for (StoreSDNode *ChainedStore : ChainedStores) {
14416     SDValue Chain = ChainedStore->getChain();
14417     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14418
14419     if (Chain != BetterChain) {
14420       MadeChange = true;
14421       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14422     }
14423   }
14424
14425   // Do all replacements after finding the replacements to make to avoid making
14426   // the chains more complicated by introducing new TokenFactors.
14427   for (auto Replacement : BetterChains)
14428     replaceStoreChain(Replacement.first, Replacement.second);
14429
14430   return MadeChange;
14431 }
14432
14433 /// This is the entry point for the file.
14434 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14435                            CodeGenOpt::Level OptLevel) {
14436   /// This is the main entry point to this class.
14437   DAGCombiner(*this, AA, OptLevel).Run(Level);
14438 }