]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Upgrade our copies of clang, llvm, lldb and compiler-rt to r312293 from
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/ADT/SetVector.h"
20 #include "llvm/ADT/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.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/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
29 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/KnownBits.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
44 #include <algorithm>
45 using namespace llvm;
46
47 #define DEBUG_TYPE "dagcombine"
48
49 STATISTIC(NodesCombined   , "Number of dag nodes combined");
50 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
51 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
52 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
53 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
54 STATISTIC(SlicedLoads, "Number of load sliced");
55
56 namespace {
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 *, 32> 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       assert(N->getOpcode() != ISD::DELETED_NODE &&
135              "Deleted Node added to Worklist");
136
137       // Skip handle nodes as they can't usefully be combined and confuse the
138       // zero-use deletion strategy.
139       if (N->getOpcode() == ISD::HANDLENODE)
140         return;
141
142       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
143         Worklist.push_back(N);
144     }
145
146     /// Remove all instances of N from the worklist.
147     void removeFromWorklist(SDNode *N) {
148       CombinedNodes.erase(N);
149
150       auto It = WorklistMap.find(N);
151       if (It == WorklistMap.end())
152         return; // Not in the worklist.
153
154       // Null out the entry rather than erasing it to avoid a linear operation.
155       Worklist[It->second] = nullptr;
156       WorklistMap.erase(It);
157     }
158
159     void deleteAndRecombine(SDNode *N);
160     bool recursivelyDeleteUnusedNodes(SDNode *N);
161
162     /// Replaces all uses of the results of one DAG node with new values.
163     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
164                       bool AddTo = true);
165
166     /// Replaces all uses of the results of one DAG node with new values.
167     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
168       return CombineTo(N, &Res, 1, AddTo);
169     }
170
171     /// Replaces all uses of the results of one DAG node with new values.
172     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
173                       bool AddTo = true) {
174       SDValue To[] = { Res0, Res1 };
175       return CombineTo(N, To, 2, AddTo);
176     }
177
178     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
179
180   private:
181     unsigned MaximumLegalStoreInBits;
182
183     /// Check the specified integer node value to see if it can be simplified or
184     /// if things it uses can be simplified by bit propagation.
185     /// If so, return true.
186     bool SimplifyDemandedBits(SDValue Op) {
187       unsigned BitWidth = Op.getScalarValueSizeInBits();
188       APInt Demanded = APInt::getAllOnesValue(BitWidth);
189       return SimplifyDemandedBits(Op, Demanded);
190     }
191
192     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
193
194     bool CombineToPreIndexedLoadStore(SDNode *N);
195     bool CombineToPostIndexedLoadStore(SDNode *N);
196     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
197     bool SliceUpLoad(SDNode *N);
198
199     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
200     ///   load.
201     ///
202     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
203     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
204     /// \param EltNo index of the vector element to load.
205     /// \param OriginalLoad load that EVE came from to be replaced.
206     /// \returns EVE on success SDValue() on failure.
207     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
208         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
209     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
210     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
211     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
212     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
213     SDValue PromoteIntBinOp(SDValue Op);
214     SDValue PromoteIntShiftOp(SDValue Op);
215     SDValue PromoteExtend(SDValue Op);
216     bool PromoteLoad(SDValue Op);
217
218     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
219                          SDValue ExtLoad, const SDLoc &DL,
220                          ISD::NodeType ExtType);
221
222     /// Call the node-specific routine that knows how to fold each
223     /// particular type of node. If that doesn't do anything, try the
224     /// target-specific DAG combines.
225     SDValue combine(SDNode *N);
226
227     // Visitation implementation - Implement dag node combining for different
228     // node types.  The semantics are as follows:
229     // Return Value:
230     //   SDValue.getNode() == 0 - No change was made
231     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
232     //   otherwise              - N should be replaced by the returned Operand.
233     //
234     SDValue visitTokenFactor(SDNode *N);
235     SDValue visitMERGE_VALUES(SDNode *N);
236     SDValue visitADD(SDNode *N);
237     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
238     SDValue visitSUB(SDNode *N);
239     SDValue visitADDC(SDNode *N);
240     SDValue visitUADDO(SDNode *N);
241     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
242     SDValue visitSUBC(SDNode *N);
243     SDValue visitUSUBO(SDNode *N);
244     SDValue visitADDE(SDNode *N);
245     SDValue visitADDCARRY(SDNode *N);
246     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
247     SDValue visitSUBE(SDNode *N);
248     SDValue visitSUBCARRY(SDNode *N);
249     SDValue visitMUL(SDNode *N);
250     SDValue useDivRem(SDNode *N);
251     SDValue visitSDIV(SDNode *N);
252     SDValue visitUDIV(SDNode *N);
253     SDValue visitREM(SDNode *N);
254     SDValue visitMULHU(SDNode *N);
255     SDValue visitMULHS(SDNode *N);
256     SDValue visitSMUL_LOHI(SDNode *N);
257     SDValue visitUMUL_LOHI(SDNode *N);
258     SDValue visitSMULO(SDNode *N);
259     SDValue visitUMULO(SDNode *N);
260     SDValue visitIMINMAX(SDNode *N);
261     SDValue visitAND(SDNode *N);
262     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
263     SDValue visitOR(SDNode *N);
264     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
265     SDValue visitXOR(SDNode *N);
266     SDValue SimplifyVBinOp(SDNode *N);
267     SDValue visitSHL(SDNode *N);
268     SDValue visitSRA(SDNode *N);
269     SDValue visitSRL(SDNode *N);
270     SDValue visitRotate(SDNode *N);
271     SDValue visitABS(SDNode *N);
272     SDValue visitBSWAP(SDNode *N);
273     SDValue visitBITREVERSE(SDNode *N);
274     SDValue visitCTLZ(SDNode *N);
275     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
276     SDValue visitCTTZ(SDNode *N);
277     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
278     SDValue visitCTPOP(SDNode *N);
279     SDValue visitSELECT(SDNode *N);
280     SDValue visitVSELECT(SDNode *N);
281     SDValue visitSELECT_CC(SDNode *N);
282     SDValue visitSETCC(SDNode *N);
283     SDValue visitSETCCE(SDNode *N);
284     SDValue visitSETCCCARRY(SDNode *N);
285     SDValue visitSIGN_EXTEND(SDNode *N);
286     SDValue visitZERO_EXTEND(SDNode *N);
287     SDValue visitANY_EXTEND(SDNode *N);
288     SDValue visitAssertZext(SDNode *N);
289     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
290     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
291     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
292     SDValue visitTRUNCATE(SDNode *N);
293     SDValue visitBITCAST(SDNode *N);
294     SDValue visitBUILD_PAIR(SDNode *N);
295     SDValue visitFADD(SDNode *N);
296     SDValue visitFSUB(SDNode *N);
297     SDValue visitFMUL(SDNode *N);
298     SDValue visitFMA(SDNode *N);
299     SDValue visitFDIV(SDNode *N);
300     SDValue visitFREM(SDNode *N);
301     SDValue visitFSQRT(SDNode *N);
302     SDValue visitFCOPYSIGN(SDNode *N);
303     SDValue visitSINT_TO_FP(SDNode *N);
304     SDValue visitUINT_TO_FP(SDNode *N);
305     SDValue visitFP_TO_SINT(SDNode *N);
306     SDValue visitFP_TO_UINT(SDNode *N);
307     SDValue visitFP_ROUND(SDNode *N);
308     SDValue visitFP_ROUND_INREG(SDNode *N);
309     SDValue visitFP_EXTEND(SDNode *N);
310     SDValue visitFNEG(SDNode *N);
311     SDValue visitFABS(SDNode *N);
312     SDValue visitFCEIL(SDNode *N);
313     SDValue visitFTRUNC(SDNode *N);
314     SDValue visitFFLOOR(SDNode *N);
315     SDValue visitFMINNUM(SDNode *N);
316     SDValue visitFMAXNUM(SDNode *N);
317     SDValue visitBRCOND(SDNode *N);
318     SDValue visitBR_CC(SDNode *N);
319     SDValue visitLOAD(SDNode *N);
320
321     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
322     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
323
324     SDValue visitSTORE(SDNode *N);
325     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
326     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
327     SDValue visitBUILD_VECTOR(SDNode *N);
328     SDValue visitCONCAT_VECTORS(SDNode *N);
329     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
330     SDValue visitVECTOR_SHUFFLE(SDNode *N);
331     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
332     SDValue visitINSERT_SUBVECTOR(SDNode *N);
333     SDValue visitMLOAD(SDNode *N);
334     SDValue visitMSTORE(SDNode *N);
335     SDValue visitMGATHER(SDNode *N);
336     SDValue visitMSCATTER(SDNode *N);
337     SDValue visitFP_TO_FP16(SDNode *N);
338     SDValue visitFP16_TO_FP(SDNode *N);
339
340     SDValue visitFADDForFMACombine(SDNode *N);
341     SDValue visitFSUBForFMACombine(SDNode *N);
342     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
343
344     SDValue XformToShuffleWithZero(SDNode *N);
345     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
346                            SDValue RHS);
347
348     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
349
350     SDValue foldSelectOfConstants(SDNode *N);
351     SDValue foldBinOpIntoSelect(SDNode *BO);
352     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
353     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
354     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
355     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
356                              SDValue N2, SDValue N3, ISD::CondCode CC,
357                              bool NotExtCompare = false);
358     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
359                                    SDValue N2, SDValue N3, ISD::CondCode CC);
360     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
361                               const SDLoc &DL);
362     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
363                           const SDLoc &DL, bool foldBooleans = true);
364
365     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
366                            SDValue &CC) const;
367     bool isOneUseSetCC(SDValue N) const;
368
369     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
370                                          unsigned HiOp);
371     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
372     SDValue CombineExtLoad(SDNode *N);
373     SDValue combineRepeatedFPDivisors(SDNode *N);
374     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
375     SDValue BuildSDIV(SDNode *N);
376     SDValue BuildSDIVPow2(SDNode *N);
377     SDValue BuildUDIV(SDNode *N);
378     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
379     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
380     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
381     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
382     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
383     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
384                                 SDNodeFlags Flags, bool Reciprocal);
385     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
386                                 SDNodeFlags Flags, bool Reciprocal);
387     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
388                                bool DemandHighBits = true);
389     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
390     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
391                               SDValue InnerPos, SDValue InnerNeg,
392                               unsigned PosOpcode, unsigned NegOpcode,
393                               const SDLoc &DL);
394     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
395     SDValue MatchLoadCombine(SDNode *N);
396     SDValue ReduceLoadWidth(SDNode *N);
397     SDValue ReduceLoadOpStoreWidth(SDNode *N);
398     SDValue splitMergedValStore(StoreSDNode *ST);
399     SDValue TransformFPLoadStorePair(SDNode *N);
400     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
401     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
402     SDValue reduceBuildVecToShuffle(SDNode *N);
403     SDValue reduceBuildVecToTrunc(SDNode *N);
404     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
405                                   ArrayRef<int> VectorMask, SDValue VecIn1,
406                                   SDValue VecIn2, unsigned LeftIdx);
407     SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
408
409     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
410
411     /// Walk up chain skipping non-aliasing memory nodes,
412     /// looking for aliasing nodes and adding them to the Aliases vector.
413     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
414                           SmallVectorImpl<SDValue> &Aliases);
415
416     /// Return true if there is any possibility that the two addresses overlap.
417     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
418
419     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
420     /// chain (aliasing node.)
421     SDValue FindBetterChain(SDNode *N, SDValue Chain);
422
423     /// Try to replace a store and any possibly adjacent stores on
424     /// consecutive chains with better chains. Return true only if St is
425     /// replaced.
426     ///
427     /// Notice that other chains may still be replaced even if the function
428     /// returns false.
429     bool findBetterNeighborChains(StoreSDNode *St);
430
431     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
432     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
433
434     /// Holds a pointer to an LSBaseSDNode as well as information on where it
435     /// is located in a sequence of memory operations connected by a chain.
436     struct MemOpLink {
437       MemOpLink(LSBaseSDNode *N, int64_t Offset)
438           : MemNode(N), OffsetFromBase(Offset) {}
439       // Ptr to the mem node.
440       LSBaseSDNode *MemNode;
441       // Offset from the base ptr.
442       int64_t OffsetFromBase;
443     };
444
445     /// This is a helper function for visitMUL to check the profitability
446     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
447     /// MulNode is the original multiply, AddNode is (add x, c1),
448     /// and ConstNode is c2.
449     bool isMulAddWithConstProfitable(SDNode *MulNode,
450                                      SDValue &AddNode,
451                                      SDValue &ConstNode);
452
453
454     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
455     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
456     /// the type of the loaded value to be extended.  LoadedVT returns the type
457     /// of the original loaded value.  NarrowLoad returns whether the load would
458     /// need to be narrowed in order to match.
459     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
460                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
461                           bool &NarrowLoad);
462
463     /// Helper function for MergeConsecutiveStores which merges the
464     /// component store chains.
465     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
466                                 unsigned NumStores);
467
468     /// This is a helper function for MergeConsecutiveStores. When the source
469     /// elements of the consecutive stores are all constants or all extracted
470     /// vector elements, try to merge them into one larger store.
471     /// \return True if a merged store was created.
472     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
473                                          EVT MemVT, unsigned NumStores,
474                                          bool IsConstantSrc, bool UseVector,
475                                          bool UseTrunc);
476
477     /// This is a helper function for MergeConsecutiveStores.
478     /// Stores that may be merged are placed in StoreNodes.
479     void getStoreMergeCandidates(StoreSDNode *St,
480                                  SmallVectorImpl<MemOpLink> &StoreNodes);
481
482     /// Helper function for MergeConsecutiveStores. Checks if
483     /// Candidate stores have indirect dependency through their
484     /// operands. \return True if safe to merge
485     bool checkMergeStoreCandidatesForDependencies(
486         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
487
488     /// Merge consecutive store operations into a wide store.
489     /// This optimization uses wide integers or vectors when possible.
490     /// \return number of stores that were merged into a merged store (the
491     /// affected nodes are stored as a prefix in \p StoreNodes).
492     bool MergeConsecutiveStores(StoreSDNode *N);
493
494     /// \brief Try to transform a truncation where C is a constant:
495     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
496     ///
497     /// \p N needs to be a truncation and its first operand an AND. Other
498     /// requirements are checked by the function (e.g. that trunc is
499     /// single-use) and if missed an empty SDValue is returned.
500     SDValue distributeTruncateThroughAnd(SDNode *N);
501
502   public:
503     DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
504         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
505           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(AA) {
506       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
507
508       MaximumLegalStoreInBits = 0;
509       for (MVT VT : MVT::all_valuetypes())
510         if (EVT(VT).isSimple() && VT != MVT::Other &&
511             TLI.isTypeLegal(EVT(VT)) &&
512             VT.getSizeInBits() >= MaximumLegalStoreInBits)
513           MaximumLegalStoreInBits = VT.getSizeInBits();
514     }
515
516     /// Runs the dag combiner on all nodes in the work list
517     void Run(CombineLevel AtLevel);
518
519     SelectionDAG &getDAG() const { return DAG; }
520
521     /// Returns a type large enough to hold any valid shift amount - before type
522     /// legalization these can be huge.
523     EVT getShiftAmountTy(EVT LHSTy) {
524       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
525       if (LHSTy.isVector())
526         return LHSTy;
527       auto &DL = DAG.getDataLayout();
528       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
529                         : TLI.getPointerTy(DL);
530     }
531
532     /// This method returns true if we are running before type legalization or
533     /// if the specified VT is legal.
534     bool isTypeLegal(const EVT &VT) {
535       if (!LegalTypes) return true;
536       return TLI.isTypeLegal(VT);
537     }
538
539     /// Convenience wrapper around TargetLowering::getSetCCResultType
540     EVT getSetCCResultType(EVT VT) const {
541       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
542     }
543   };
544 }
545
546
547 namespace {
548 /// This class is a DAGUpdateListener that removes any deleted
549 /// nodes from the worklist.
550 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
551   DAGCombiner &DC;
552 public:
553   explicit WorklistRemover(DAGCombiner &dc)
554     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
555
556   void NodeDeleted(SDNode *N, SDNode *E) override {
557     DC.removeFromWorklist(N);
558   }
559 };
560 }
561
562 //===----------------------------------------------------------------------===//
563 //  TargetLowering::DAGCombinerInfo implementation
564 //===----------------------------------------------------------------------===//
565
566 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
567   ((DAGCombiner*)DC)->AddToWorklist(N);
568 }
569
570 SDValue TargetLowering::DAGCombinerInfo::
571 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
572   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
573 }
574
575 SDValue TargetLowering::DAGCombinerInfo::
576 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
577   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
578 }
579
580
581 SDValue TargetLowering::DAGCombinerInfo::
582 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
583   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
584 }
585
586 void TargetLowering::DAGCombinerInfo::
587 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
588   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
589 }
590
591 //===----------------------------------------------------------------------===//
592 // Helper Functions
593 //===----------------------------------------------------------------------===//
594
595 void DAGCombiner::deleteAndRecombine(SDNode *N) {
596   removeFromWorklist(N);
597
598   // If the operands of this node are only used by the node, they will now be
599   // dead. Make sure to re-visit them and recursively delete dead nodes.
600   for (const SDValue &Op : N->ops())
601     // For an operand generating multiple values, one of the values may
602     // become dead allowing further simplification (e.g. split index
603     // arithmetic from an indexed load).
604     if (Op->hasOneUse() || Op->getNumValues() > 1)
605       AddToWorklist(Op.getNode());
606
607   DAG.DeleteNode(N);
608 }
609
610 /// Return 1 if we can compute the negated form of the specified expression for
611 /// the same cost as the expression itself, or 2 if we can compute the negated
612 /// form more cheaply than the expression itself.
613 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
614                                const TargetLowering &TLI,
615                                const TargetOptions *Options,
616                                unsigned Depth = 0) {
617   // fneg is removable even if it has multiple uses.
618   if (Op.getOpcode() == ISD::FNEG) return 2;
619
620   // Don't allow anything with multiple uses.
621   if (!Op.hasOneUse()) return 0;
622
623   // Don't recurse exponentially.
624   if (Depth > 6) return 0;
625
626   switch (Op.getOpcode()) {
627   default: return false;
628   case ISD::ConstantFP: {
629     if (!LegalOperations)
630       return 1;
631
632     // Don't invert constant FP values after legalization unless the target says
633     // the negated constant is legal.
634     EVT VT = Op.getValueType();
635     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
636       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
637   }
638   case ISD::FADD:
639     // FIXME: determine better conditions for this xform.
640     if (!Options->UnsafeFPMath) return 0;
641
642     // After operation legalization, it might not be legal to create new FSUBs.
643     if (LegalOperations &&
644         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
645       return 0;
646
647     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
648     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
649                                     Options, Depth + 1))
650       return V;
651     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
652     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
653                               Depth + 1);
654   case ISD::FSUB:
655     // We can't turn -(A-B) into B-A when we honor signed zeros.
656     if (!Options->NoSignedZerosFPMath &&
657         !Op.getNode()->getFlags().hasNoSignedZeros())
658       return 0;
659
660     // fold (fneg (fsub A, B)) -> (fsub B, A)
661     return 1;
662
663   case ISD::FMUL:
664   case ISD::FDIV:
665     if (Options->HonorSignDependentRoundingFPMath()) return 0;
666
667     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
668     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
669                                     Options, Depth + 1))
670       return V;
671
672     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
673                               Depth + 1);
674
675   case ISD::FP_EXTEND:
676   case ISD::FP_ROUND:
677   case ISD::FSIN:
678     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
679                               Depth + 1);
680   }
681 }
682
683 /// If isNegatibleForFree returns true, return the newly negated expression.
684 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
685                                     bool LegalOperations, unsigned Depth = 0) {
686   const TargetOptions &Options = DAG.getTarget().Options;
687   // fneg is removable even if it has multiple uses.
688   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
689
690   // Don't allow anything with multiple uses.
691   assert(Op.hasOneUse() && "Unknown reuse!");
692
693   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
694
695   const SDNodeFlags Flags = Op.getNode()->getFlags();
696
697   switch (Op.getOpcode()) {
698   default: llvm_unreachable("Unknown code");
699   case ISD::ConstantFP: {
700     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
701     V.changeSign();
702     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
703   }
704   case ISD::FADD:
705     // FIXME: determine better conditions for this xform.
706     assert(Options.UnsafeFPMath);
707
708     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
709     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
710                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
711       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
712                          GetNegatedExpression(Op.getOperand(0), DAG,
713                                               LegalOperations, Depth+1),
714                          Op.getOperand(1), Flags);
715     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
716     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
717                        GetNegatedExpression(Op.getOperand(1), DAG,
718                                             LegalOperations, Depth+1),
719                        Op.getOperand(0), Flags);
720   case ISD::FSUB:
721     // fold (fneg (fsub 0, B)) -> B
722     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
723       if (N0CFP->isZero())
724         return Op.getOperand(1);
725
726     // fold (fneg (fsub A, B)) -> (fsub B, A)
727     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
728                        Op.getOperand(1), Op.getOperand(0), Flags);
729
730   case ISD::FMUL:
731   case ISD::FDIV:
732     assert(!Options.HonorSignDependentRoundingFPMath());
733
734     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
735     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
736                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
737       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
738                          GetNegatedExpression(Op.getOperand(0), DAG,
739                                               LegalOperations, Depth+1),
740                          Op.getOperand(1), Flags);
741
742     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
743     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
744                        Op.getOperand(0),
745                        GetNegatedExpression(Op.getOperand(1), DAG,
746                                             LegalOperations, Depth+1), Flags);
747
748   case ISD::FP_EXTEND:
749   case ISD::FSIN:
750     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
751                        GetNegatedExpression(Op.getOperand(0), DAG,
752                                             LegalOperations, Depth+1));
753   case ISD::FP_ROUND:
754       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
755                          GetNegatedExpression(Op.getOperand(0), DAG,
756                                               LegalOperations, Depth+1),
757                          Op.getOperand(1));
758   }
759 }
760
761 // APInts must be the same size for most operations, this helper
762 // function zero extends the shorter of the pair so that they match.
763 // We provide an Offset so that we can create bitwidths that won't overflow.
764 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
765   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
766   LHS = LHS.zextOrSelf(Bits);
767   RHS = RHS.zextOrSelf(Bits);
768 }
769
770 // Return true if this node is a setcc, or is a select_cc
771 // that selects between the target values used for true and false, making it
772 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
773 // the appropriate nodes based on the type of node we are checking. This
774 // simplifies life a bit for the callers.
775 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
776                                     SDValue &CC) const {
777   if (N.getOpcode() == ISD::SETCC) {
778     LHS = N.getOperand(0);
779     RHS = N.getOperand(1);
780     CC  = N.getOperand(2);
781     return true;
782   }
783
784   if (N.getOpcode() != ISD::SELECT_CC ||
785       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
786       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
787     return false;
788
789   if (TLI.getBooleanContents(N.getValueType()) ==
790       TargetLowering::UndefinedBooleanContent)
791     return false;
792
793   LHS = N.getOperand(0);
794   RHS = N.getOperand(1);
795   CC  = N.getOperand(4);
796   return true;
797 }
798
799 /// Return true if this is a SetCC-equivalent operation with only one use.
800 /// If this is true, it allows the users to invert the operation for free when
801 /// it is profitable to do so.
802 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
803   SDValue N0, N1, N2;
804   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
805     return true;
806   return false;
807 }
808
809 // \brief Returns the SDNode if it is a constant float BuildVector
810 // or constant float.
811 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
812   if (isa<ConstantFPSDNode>(N))
813     return N.getNode();
814   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
815     return N.getNode();
816   return nullptr;
817 }
818
819 // Determines if it is a constant integer or a build vector of constant
820 // integers (and undefs).
821 // Do not permit build vector implicit truncation.
822 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
823   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
824     return !(Const->isOpaque() && NoOpaques);
825   if (N.getOpcode() != ISD::BUILD_VECTOR)
826     return false;
827   unsigned BitWidth = N.getScalarValueSizeInBits();
828   for (const SDValue &Op : N->op_values()) {
829     if (Op.isUndef())
830       continue;
831     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
832     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
833         (Const->isOpaque() && NoOpaques))
834       return false;
835   }
836   return true;
837 }
838
839 // Determines if it is a constant null integer or a splatted vector of a
840 // constant null integer (with no undefs).
841 // Build vector implicit truncation is not an issue for null values.
842 static bool isNullConstantOrNullSplatConstant(SDValue N) {
843   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
844     return Splat->isNullValue();
845   return false;
846 }
847
848 // Determines if it is a constant integer of one or a splatted vector of a
849 // constant integer of one (with no undefs).
850 // Do not permit build vector implicit truncation.
851 static bool isOneConstantOrOneSplatConstant(SDValue N) {
852   unsigned BitWidth = N.getScalarValueSizeInBits();
853   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
854     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
855   return false;
856 }
857
858 // Determines if it is a constant integer of all ones or a splatted vector of a
859 // constant integer of all ones (with no undefs).
860 // Do not permit build vector implicit truncation.
861 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
862   unsigned BitWidth = N.getScalarValueSizeInBits();
863   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
864     return Splat->isAllOnesValue() &&
865            Splat->getAPIntValue().getBitWidth() == BitWidth;
866   return false;
867 }
868
869 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
870 // undef's.
871 static bool isAnyConstantBuildVector(const SDNode *N) {
872   return ISD::isBuildVectorOfConstantSDNodes(N) ||
873          ISD::isBuildVectorOfConstantFPSDNodes(N);
874 }
875
876 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
877                                     SDValue N1) {
878   EVT VT = N0.getValueType();
879   if (N0.getOpcode() == Opc) {
880     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
881       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
882         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
883         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
884           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
885         return SDValue();
886       }
887       if (N0.hasOneUse()) {
888         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
889         // use
890         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
891         if (!OpNode.getNode())
892           return SDValue();
893         AddToWorklist(OpNode.getNode());
894         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
895       }
896     }
897   }
898
899   if (N1.getOpcode() == Opc) {
900     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
901       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
902         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
903         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
904           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
905         return SDValue();
906       }
907       if (N1.hasOneUse()) {
908         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
909         // use
910         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
911         if (!OpNode.getNode())
912           return SDValue();
913         AddToWorklist(OpNode.getNode());
914         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
915       }
916     }
917   }
918
919   return SDValue();
920 }
921
922 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
923                                bool AddTo) {
924   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
925   ++NodesCombined;
926   DEBUG(dbgs() << "\nReplacing.1 ";
927         N->dump(&DAG);
928         dbgs() << "\nWith: ";
929         To[0].getNode()->dump(&DAG);
930         dbgs() << " and " << NumTo-1 << " other values\n");
931   for (unsigned i = 0, e = NumTo; i != e; ++i)
932     assert((!To[i].getNode() ||
933             N->getValueType(i) == To[i].getValueType()) &&
934            "Cannot combine value to value of different type!");
935
936   WorklistRemover DeadNodes(*this);
937   DAG.ReplaceAllUsesWith(N, To);
938   if (AddTo) {
939     // Push the new nodes and any users onto the worklist
940     for (unsigned i = 0, e = NumTo; i != e; ++i) {
941       if (To[i].getNode()) {
942         AddToWorklist(To[i].getNode());
943         AddUsersToWorklist(To[i].getNode());
944       }
945     }
946   }
947
948   // Finally, if the node is now dead, remove it from the graph.  The node
949   // may not be dead if the replacement process recursively simplified to
950   // something else needing this node.
951   if (N->use_empty())
952     deleteAndRecombine(N);
953   return SDValue(N, 0);
954 }
955
956 void DAGCombiner::
957 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
958   // Replace all uses.  If any nodes become isomorphic to other nodes and
959   // are deleted, make sure to remove them from our worklist.
960   WorklistRemover DeadNodes(*this);
961   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
962
963   // Push the new node and any (possibly new) users onto the worklist.
964   AddToWorklist(TLO.New.getNode());
965   AddUsersToWorklist(TLO.New.getNode());
966
967   // Finally, if the node is now dead, remove it from the graph.  The node
968   // may not be dead if the replacement process recursively simplified to
969   // something else needing this node.
970   if (TLO.Old.getNode()->use_empty())
971     deleteAndRecombine(TLO.Old.getNode());
972 }
973
974 /// Check the specified integer node value to see if it can be simplified or if
975 /// things it uses can be simplified by bit propagation. If so, return true.
976 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
977   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
978   KnownBits Known;
979   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
980     return false;
981
982   // Revisit the node.
983   AddToWorklist(Op.getNode());
984
985   // Replace the old value with the new one.
986   ++NodesCombined;
987   DEBUG(dbgs() << "\nReplacing.2 ";
988         TLO.Old.getNode()->dump(&DAG);
989         dbgs() << "\nWith: ";
990         TLO.New.getNode()->dump(&DAG);
991         dbgs() << '\n');
992
993   CommitTargetLoweringOpt(TLO);
994   return true;
995 }
996
997 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
998   SDLoc DL(Load);
999   EVT VT = Load->getValueType(0);
1000   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1001
1002   DEBUG(dbgs() << "\nReplacing.9 ";
1003         Load->dump(&DAG);
1004         dbgs() << "\nWith: ";
1005         Trunc.getNode()->dump(&DAG);
1006         dbgs() << '\n');
1007   WorklistRemover DeadNodes(*this);
1008   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1009   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1010   deleteAndRecombine(Load);
1011   AddToWorklist(Trunc.getNode());
1012 }
1013
1014 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1015   Replace = false;
1016   SDLoc DL(Op);
1017   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1018     LoadSDNode *LD = cast<LoadSDNode>(Op);
1019     EVT MemVT = LD->getMemoryVT();
1020     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1021       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1022                                                        : ISD::EXTLOAD)
1023       : LD->getExtensionType();
1024     Replace = true;
1025     return DAG.getExtLoad(ExtType, DL, PVT,
1026                           LD->getChain(), LD->getBasePtr(),
1027                           MemVT, LD->getMemOperand());
1028   }
1029
1030   unsigned Opc = Op.getOpcode();
1031   switch (Opc) {
1032   default: break;
1033   case ISD::AssertSext:
1034     if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1035       return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1036     break;
1037   case ISD::AssertZext:
1038     if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1039       return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1040     break;
1041   case ISD::Constant: {
1042     unsigned ExtOpc =
1043       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1044     return DAG.getNode(ExtOpc, DL, PVT, Op);
1045   }
1046   }
1047
1048   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1049     return SDValue();
1050   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1051 }
1052
1053 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1054   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1055     return SDValue();
1056   EVT OldVT = Op.getValueType();
1057   SDLoc DL(Op);
1058   bool Replace = false;
1059   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1060   if (!NewOp.getNode())
1061     return SDValue();
1062   AddToWorklist(NewOp.getNode());
1063
1064   if (Replace)
1065     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1066   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1067                      DAG.getValueType(OldVT));
1068 }
1069
1070 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1071   EVT OldVT = Op.getValueType();
1072   SDLoc DL(Op);
1073   bool Replace = false;
1074   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1075   if (!NewOp.getNode())
1076     return SDValue();
1077   AddToWorklist(NewOp.getNode());
1078
1079   if (Replace)
1080     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1081   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1082 }
1083
1084 /// Promote the specified integer binary operation if the target indicates it is
1085 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1086 /// i32 since i16 instructions are longer.
1087 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1088   if (!LegalOperations)
1089     return SDValue();
1090
1091   EVT VT = Op.getValueType();
1092   if (VT.isVector() || !VT.isInteger())
1093     return SDValue();
1094
1095   // If operation type is 'undesirable', e.g. i16 on x86, consider
1096   // promoting it.
1097   unsigned Opc = Op.getOpcode();
1098   if (TLI.isTypeDesirableForOp(Opc, VT))
1099     return SDValue();
1100
1101   EVT PVT = VT;
1102   // Consult target whether it is a good idea to promote this operation and
1103   // what's the right type to promote it to.
1104   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1105     assert(PVT != VT && "Don't know what type to promote to!");
1106
1107     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1108
1109     bool Replace0 = false;
1110     SDValue N0 = Op.getOperand(0);
1111     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1112
1113     bool Replace1 = false;
1114     SDValue N1 = Op.getOperand(1);
1115     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1116     SDLoc DL(Op);
1117
1118     SDValue RV =
1119         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1120
1121     // We are always replacing N0/N1's use in N and only need
1122     // additional replacements if there are additional uses.
1123     Replace0 &= !N0->hasOneUse();
1124     Replace1 &= (N0 != N1) && !N1->hasOneUse();
1125
1126     // Combine Op here so it is presreved past replacements.
1127     CombineTo(Op.getNode(), RV);
1128
1129     // If operands have a use ordering, make sur we deal with
1130     // predecessor first.
1131     if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1132       std::swap(N0, N1);
1133       std::swap(NN0, NN1);
1134     }
1135
1136     if (Replace0) {
1137       AddToWorklist(NN0.getNode());
1138       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1139     }
1140     if (Replace1) {
1141       AddToWorklist(NN1.getNode());
1142       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1143     }
1144     return Op;
1145   }
1146   return SDValue();
1147 }
1148
1149 /// Promote the specified integer shift operation if the target indicates it is
1150 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1151 /// i32 since i16 instructions are longer.
1152 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1153   if (!LegalOperations)
1154     return SDValue();
1155
1156   EVT VT = Op.getValueType();
1157   if (VT.isVector() || !VT.isInteger())
1158     return SDValue();
1159
1160   // If operation type is 'undesirable', e.g. i16 on x86, consider
1161   // promoting it.
1162   unsigned Opc = Op.getOpcode();
1163   if (TLI.isTypeDesirableForOp(Opc, VT))
1164     return SDValue();
1165
1166   EVT PVT = VT;
1167   // Consult target whether it is a good idea to promote this operation and
1168   // what's the right type to promote it to.
1169   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1170     assert(PVT != VT && "Don't know what type to promote to!");
1171
1172     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1173
1174     bool Replace = false;
1175     SDValue N0 = Op.getOperand(0);
1176     SDValue N1 = Op.getOperand(1);
1177     if (Opc == ISD::SRA)
1178       N0 = SExtPromoteOperand(N0, PVT);
1179     else if (Opc == ISD::SRL)
1180       N0 = ZExtPromoteOperand(N0, PVT);
1181     else
1182       N0 = PromoteOperand(N0, PVT, Replace);
1183
1184     if (!N0.getNode())
1185       return SDValue();
1186
1187     SDLoc DL(Op);
1188     SDValue RV =
1189         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1190
1191     AddToWorklist(N0.getNode());
1192     if (Replace)
1193       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1194
1195     // Deal with Op being deleted.
1196     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1197       return RV;
1198   }
1199   return SDValue();
1200 }
1201
1202 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1203   if (!LegalOperations)
1204     return SDValue();
1205
1206   EVT VT = Op.getValueType();
1207   if (VT.isVector() || !VT.isInteger())
1208     return SDValue();
1209
1210   // If operation type is 'undesirable', e.g. i16 on x86, consider
1211   // promoting it.
1212   unsigned Opc = Op.getOpcode();
1213   if (TLI.isTypeDesirableForOp(Opc, VT))
1214     return SDValue();
1215
1216   EVT PVT = VT;
1217   // Consult target whether it is a good idea to promote this operation and
1218   // what's the right type to promote it to.
1219   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1220     assert(PVT != VT && "Don't know what type to promote to!");
1221     // fold (aext (aext x)) -> (aext x)
1222     // fold (aext (zext x)) -> (zext x)
1223     // fold (aext (sext x)) -> (sext x)
1224     DEBUG(dbgs() << "\nPromoting ";
1225           Op.getNode()->dump(&DAG));
1226     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1227   }
1228   return SDValue();
1229 }
1230
1231 bool DAGCombiner::PromoteLoad(SDValue Op) {
1232   if (!LegalOperations)
1233     return false;
1234
1235   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1236     return false;
1237
1238   EVT VT = Op.getValueType();
1239   if (VT.isVector() || !VT.isInteger())
1240     return false;
1241
1242   // If operation type is 'undesirable', e.g. i16 on x86, consider
1243   // promoting it.
1244   unsigned Opc = Op.getOpcode();
1245   if (TLI.isTypeDesirableForOp(Opc, VT))
1246     return false;
1247
1248   EVT PVT = VT;
1249   // Consult target whether it is a good idea to promote this operation and
1250   // what's the right type to promote it to.
1251   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1252     assert(PVT != VT && "Don't know what type to promote to!");
1253
1254     SDLoc DL(Op);
1255     SDNode *N = Op.getNode();
1256     LoadSDNode *LD = cast<LoadSDNode>(N);
1257     EVT MemVT = LD->getMemoryVT();
1258     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1259       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1260                                                        : ISD::EXTLOAD)
1261       : LD->getExtensionType();
1262     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1263                                    LD->getChain(), LD->getBasePtr(),
1264                                    MemVT, LD->getMemOperand());
1265     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1266
1267     DEBUG(dbgs() << "\nPromoting ";
1268           N->dump(&DAG);
1269           dbgs() << "\nTo: ";
1270           Result.getNode()->dump(&DAG);
1271           dbgs() << '\n');
1272     WorklistRemover DeadNodes(*this);
1273     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1274     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1275     deleteAndRecombine(N);
1276     AddToWorklist(Result.getNode());
1277     return true;
1278   }
1279   return false;
1280 }
1281
1282 /// \brief Recursively delete a node which has no uses and any operands for
1283 /// which it is the only use.
1284 ///
1285 /// Note that this both deletes the nodes and removes them from the worklist.
1286 /// It also adds any nodes who have had a user deleted to the worklist as they
1287 /// may now have only one use and subject to other combines.
1288 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1289   if (!N->use_empty())
1290     return false;
1291
1292   SmallSetVector<SDNode *, 16> Nodes;
1293   Nodes.insert(N);
1294   do {
1295     N = Nodes.pop_back_val();
1296     if (!N)
1297       continue;
1298
1299     if (N->use_empty()) {
1300       for (const SDValue &ChildN : N->op_values())
1301         Nodes.insert(ChildN.getNode());
1302
1303       removeFromWorklist(N);
1304       DAG.DeleteNode(N);
1305     } else {
1306       AddToWorklist(N);
1307     }
1308   } while (!Nodes.empty());
1309   return true;
1310 }
1311
1312 //===----------------------------------------------------------------------===//
1313 //  Main DAG Combiner implementation
1314 //===----------------------------------------------------------------------===//
1315
1316 void DAGCombiner::Run(CombineLevel AtLevel) {
1317   // set the instance variables, so that the various visit routines may use it.
1318   Level = AtLevel;
1319   LegalOperations = Level >= AfterLegalizeVectorOps;
1320   LegalTypes = Level >= AfterLegalizeTypes;
1321
1322   // Add all the dag nodes to the worklist.
1323   for (SDNode &Node : DAG.allnodes())
1324     AddToWorklist(&Node);
1325
1326   // Create a dummy node (which is not added to allnodes), that adds a reference
1327   // to the root node, preventing it from being deleted, and tracking any
1328   // changes of the root.
1329   HandleSDNode Dummy(DAG.getRoot());
1330
1331   // While the worklist isn't empty, find a node and try to combine it.
1332   while (!WorklistMap.empty()) {
1333     SDNode *N;
1334     // The Worklist holds the SDNodes in order, but it may contain null entries.
1335     do {
1336       N = Worklist.pop_back_val();
1337     } while (!N);
1338
1339     bool GoodWorklistEntry = WorklistMap.erase(N);
1340     (void)GoodWorklistEntry;
1341     assert(GoodWorklistEntry &&
1342            "Found a worklist entry without a corresponding map entry!");
1343
1344     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1345     // N is deleted from the DAG, since they too may now be dead or may have a
1346     // reduced number of uses, allowing other xforms.
1347     if (recursivelyDeleteUnusedNodes(N))
1348       continue;
1349
1350     WorklistRemover DeadNodes(*this);
1351
1352     // If this combine is running after legalizing the DAG, re-legalize any
1353     // nodes pulled off the worklist.
1354     if (Level == AfterLegalizeDAG) {
1355       SmallSetVector<SDNode *, 16> UpdatedNodes;
1356       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1357
1358       for (SDNode *LN : UpdatedNodes) {
1359         AddToWorklist(LN);
1360         AddUsersToWorklist(LN);
1361       }
1362       if (!NIsValid)
1363         continue;
1364     }
1365
1366     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1367
1368     // Add any operands of the new node which have not yet been combined to the
1369     // worklist as well. Because the worklist uniques things already, this
1370     // won't repeatedly process the same operand.
1371     CombinedNodes.insert(N);
1372     for (const SDValue &ChildN : N->op_values())
1373       if (!CombinedNodes.count(ChildN.getNode()))
1374         AddToWorklist(ChildN.getNode());
1375
1376     SDValue RV = combine(N);
1377
1378     if (!RV.getNode())
1379       continue;
1380
1381     ++NodesCombined;
1382
1383     // If we get back the same node we passed in, rather than a new node or
1384     // zero, we know that the node must have defined multiple values and
1385     // CombineTo was used.  Since CombineTo takes care of the worklist
1386     // mechanics for us, we have no work to do in this case.
1387     if (RV.getNode() == N)
1388       continue;
1389
1390     assert(N->getOpcode() != ISD::DELETED_NODE &&
1391            RV.getOpcode() != ISD::DELETED_NODE &&
1392            "Node was deleted but visit returned new node!");
1393
1394     DEBUG(dbgs() << " ... into: ";
1395           RV.getNode()->dump(&DAG));
1396
1397     if (N->getNumValues() == RV.getNode()->getNumValues())
1398       DAG.ReplaceAllUsesWith(N, RV.getNode());
1399     else {
1400       assert(N->getValueType(0) == RV.getValueType() &&
1401              N->getNumValues() == 1 && "Type mismatch");
1402       DAG.ReplaceAllUsesWith(N, &RV);
1403     }
1404
1405     // Push the new node and any users onto the worklist
1406     AddToWorklist(RV.getNode());
1407     AddUsersToWorklist(RV.getNode());
1408
1409     // Finally, if the node is now dead, remove it from the graph.  The node
1410     // may not be dead if the replacement process recursively simplified to
1411     // something else needing this node. This will also take care of adding any
1412     // operands which have lost a user to the worklist.
1413     recursivelyDeleteUnusedNodes(N);
1414   }
1415
1416   // If the root changed (e.g. it was a dead load, update the root).
1417   DAG.setRoot(Dummy.getValue());
1418   DAG.RemoveDeadNodes();
1419 }
1420
1421 SDValue DAGCombiner::visit(SDNode *N) {
1422   switch (N->getOpcode()) {
1423   default: break;
1424   case ISD::TokenFactor:        return visitTokenFactor(N);
1425   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1426   case ISD::ADD:                return visitADD(N);
1427   case ISD::SUB:                return visitSUB(N);
1428   case ISD::ADDC:               return visitADDC(N);
1429   case ISD::UADDO:              return visitUADDO(N);
1430   case ISD::SUBC:               return visitSUBC(N);
1431   case ISD::USUBO:              return visitUSUBO(N);
1432   case ISD::ADDE:               return visitADDE(N);
1433   case ISD::ADDCARRY:           return visitADDCARRY(N);
1434   case ISD::SUBE:               return visitSUBE(N);
1435   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1436   case ISD::MUL:                return visitMUL(N);
1437   case ISD::SDIV:               return visitSDIV(N);
1438   case ISD::UDIV:               return visitUDIV(N);
1439   case ISD::SREM:
1440   case ISD::UREM:               return visitREM(N);
1441   case ISD::MULHU:              return visitMULHU(N);
1442   case ISD::MULHS:              return visitMULHS(N);
1443   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1444   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1445   case ISD::SMULO:              return visitSMULO(N);
1446   case ISD::UMULO:              return visitUMULO(N);
1447   case ISD::SMIN:
1448   case ISD::SMAX:
1449   case ISD::UMIN:
1450   case ISD::UMAX:               return visitIMINMAX(N);
1451   case ISD::AND:                return visitAND(N);
1452   case ISD::OR:                 return visitOR(N);
1453   case ISD::XOR:                return visitXOR(N);
1454   case ISD::SHL:                return visitSHL(N);
1455   case ISD::SRA:                return visitSRA(N);
1456   case ISD::SRL:                return visitSRL(N);
1457   case ISD::ROTR:
1458   case ISD::ROTL:               return visitRotate(N);
1459   case ISD::ABS:                return visitABS(N);
1460   case ISD::BSWAP:              return visitBSWAP(N);
1461   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1462   case ISD::CTLZ:               return visitCTLZ(N);
1463   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1464   case ISD::CTTZ:               return visitCTTZ(N);
1465   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1466   case ISD::CTPOP:              return visitCTPOP(N);
1467   case ISD::SELECT:             return visitSELECT(N);
1468   case ISD::VSELECT:            return visitVSELECT(N);
1469   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1470   case ISD::SETCC:              return visitSETCC(N);
1471   case ISD::SETCCE:             return visitSETCCE(N);
1472   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1473   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1474   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1475   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1476   case ISD::AssertZext:         return visitAssertZext(N);
1477   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1478   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1479   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1480   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1481   case ISD::BITCAST:            return visitBITCAST(N);
1482   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1483   case ISD::FADD:               return visitFADD(N);
1484   case ISD::FSUB:               return visitFSUB(N);
1485   case ISD::FMUL:               return visitFMUL(N);
1486   case ISD::FMA:                return visitFMA(N);
1487   case ISD::FDIV:               return visitFDIV(N);
1488   case ISD::FREM:               return visitFREM(N);
1489   case ISD::FSQRT:              return visitFSQRT(N);
1490   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1491   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1492   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1493   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1494   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1495   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1496   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1497   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1498   case ISD::FNEG:               return visitFNEG(N);
1499   case ISD::FABS:               return visitFABS(N);
1500   case ISD::FFLOOR:             return visitFFLOOR(N);
1501   case ISD::FMINNUM:            return visitFMINNUM(N);
1502   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1503   case ISD::FCEIL:              return visitFCEIL(N);
1504   case ISD::FTRUNC:             return visitFTRUNC(N);
1505   case ISD::BRCOND:             return visitBRCOND(N);
1506   case ISD::BR_CC:              return visitBR_CC(N);
1507   case ISD::LOAD:               return visitLOAD(N);
1508   case ISD::STORE:              return visitSTORE(N);
1509   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1510   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1511   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1512   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1513   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1514   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1515   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1516   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1517   case ISD::MGATHER:            return visitMGATHER(N);
1518   case ISD::MLOAD:              return visitMLOAD(N);
1519   case ISD::MSCATTER:           return visitMSCATTER(N);
1520   case ISD::MSTORE:             return visitMSTORE(N);
1521   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1522   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1523   }
1524   return SDValue();
1525 }
1526
1527 SDValue DAGCombiner::combine(SDNode *N) {
1528   SDValue RV = visit(N);
1529
1530   // If nothing happened, try a target-specific DAG combine.
1531   if (!RV.getNode()) {
1532     assert(N->getOpcode() != ISD::DELETED_NODE &&
1533            "Node was deleted but visit returned NULL!");
1534
1535     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1536         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1537
1538       // Expose the DAG combiner to the target combiner impls.
1539       TargetLowering::DAGCombinerInfo
1540         DagCombineInfo(DAG, Level, false, this);
1541
1542       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1543     }
1544   }
1545
1546   // If nothing happened still, try promoting the operation.
1547   if (!RV.getNode()) {
1548     switch (N->getOpcode()) {
1549     default: break;
1550     case ISD::ADD:
1551     case ISD::SUB:
1552     case ISD::MUL:
1553     case ISD::AND:
1554     case ISD::OR:
1555     case ISD::XOR:
1556       RV = PromoteIntBinOp(SDValue(N, 0));
1557       break;
1558     case ISD::SHL:
1559     case ISD::SRA:
1560     case ISD::SRL:
1561       RV = PromoteIntShiftOp(SDValue(N, 0));
1562       break;
1563     case ISD::SIGN_EXTEND:
1564     case ISD::ZERO_EXTEND:
1565     case ISD::ANY_EXTEND:
1566       RV = PromoteExtend(SDValue(N, 0));
1567       break;
1568     case ISD::LOAD:
1569       if (PromoteLoad(SDValue(N, 0)))
1570         RV = SDValue(N, 0);
1571       break;
1572     }
1573   }
1574
1575   // If N is a commutative binary node, try commuting it to enable more
1576   // sdisel CSE.
1577   if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1578       N->getNumValues() == 1) {
1579     SDValue N0 = N->getOperand(0);
1580     SDValue N1 = N->getOperand(1);
1581
1582     // Constant operands are canonicalized to RHS.
1583     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1584       SDValue Ops[] = {N1, N0};
1585       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1586                                             N->getFlags());
1587       if (CSENode)
1588         return SDValue(CSENode, 0);
1589     }
1590   }
1591
1592   return RV;
1593 }
1594
1595 /// Given a node, return its input chain if it has one, otherwise return a null
1596 /// sd operand.
1597 static SDValue getInputChainForNode(SDNode *N) {
1598   if (unsigned NumOps = N->getNumOperands()) {
1599     if (N->getOperand(0).getValueType() == MVT::Other)
1600       return N->getOperand(0);
1601     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1602       return N->getOperand(NumOps-1);
1603     for (unsigned i = 1; i < NumOps-1; ++i)
1604       if (N->getOperand(i).getValueType() == MVT::Other)
1605         return N->getOperand(i);
1606   }
1607   return SDValue();
1608 }
1609
1610 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1611   // If N has two operands, where one has an input chain equal to the other,
1612   // the 'other' chain is redundant.
1613   if (N->getNumOperands() == 2) {
1614     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1615       return N->getOperand(0);
1616     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1617       return N->getOperand(1);
1618   }
1619
1620   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1621   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1622   SmallPtrSet<SDNode*, 16> SeenOps;
1623   bool Changed = false;             // If we should replace this token factor.
1624
1625   // Start out with this token factor.
1626   TFs.push_back(N);
1627
1628   // Iterate through token factors.  The TFs grows when new token factors are
1629   // encountered.
1630   for (unsigned i = 0; i < TFs.size(); ++i) {
1631     SDNode *TF = TFs[i];
1632
1633     // Check each of the operands.
1634     for (const SDValue &Op : TF->op_values()) {
1635
1636       switch (Op.getOpcode()) {
1637       case ISD::EntryToken:
1638         // Entry tokens don't need to be added to the list. They are
1639         // redundant.
1640         Changed = true;
1641         break;
1642
1643       case ISD::TokenFactor:
1644         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1645           // Queue up for processing.
1646           TFs.push_back(Op.getNode());
1647           // Clean up in case the token factor is removed.
1648           AddToWorklist(Op.getNode());
1649           Changed = true;
1650           break;
1651         }
1652         LLVM_FALLTHROUGH;
1653
1654       default:
1655         // Only add if it isn't already in the list.
1656         if (SeenOps.insert(Op.getNode()).second)
1657           Ops.push_back(Op);
1658         else
1659           Changed = true;
1660         break;
1661       }
1662     }
1663   }
1664
1665   // Remove Nodes that are chained to another node in the list. Do so
1666   // by walking up chains breath-first stopping when we've seen
1667   // another operand. In general we must climb to the EntryNode, but we can exit
1668   // early if we find all remaining work is associated with just one operand as
1669   // no further pruning is possible.
1670
1671   // List of nodes to search through and original Ops from which they originate.
1672   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1673   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1674   SmallPtrSet<SDNode *, 16> SeenChains;
1675   bool DidPruneOps = false;
1676
1677   unsigned NumLeftToConsider = 0;
1678   for (const SDValue &Op : Ops) {
1679     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1680     OpWorkCount.push_back(1);
1681   }
1682
1683   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1684     // If this is an Op, we can remove the op from the list. Remark any
1685     // search associated with it as from the current OpNumber.
1686     if (SeenOps.count(Op) != 0) {
1687       Changed = true;
1688       DidPruneOps = true;
1689       unsigned OrigOpNumber = 0;
1690       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1691         OrigOpNumber++;
1692       assert((OrigOpNumber != Ops.size()) &&
1693              "expected to find TokenFactor Operand");
1694       // Re-mark worklist from OrigOpNumber to OpNumber
1695       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1696         if (Worklist[i].second == OrigOpNumber) {
1697           Worklist[i].second = OpNumber;
1698         }
1699       }
1700       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1701       OpWorkCount[OrigOpNumber] = 0;
1702       NumLeftToConsider--;
1703     }
1704     // Add if it's a new chain
1705     if (SeenChains.insert(Op).second) {
1706       OpWorkCount[OpNumber]++;
1707       Worklist.push_back(std::make_pair(Op, OpNumber));
1708     }
1709   };
1710
1711   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1712     // We need at least be consider at least 2 Ops to prune.
1713     if (NumLeftToConsider <= 1)
1714       break;
1715     auto CurNode = Worklist[i].first;
1716     auto CurOpNumber = Worklist[i].second;
1717     assert((OpWorkCount[CurOpNumber] > 0) &&
1718            "Node should not appear in worklist");
1719     switch (CurNode->getOpcode()) {
1720     case ISD::EntryToken:
1721       // Hitting EntryToken is the only way for the search to terminate without
1722       // hitting
1723       // another operand's search. Prevent us from marking this operand
1724       // considered.
1725       NumLeftToConsider++;
1726       break;
1727     case ISD::TokenFactor:
1728       for (const SDValue &Op : CurNode->op_values())
1729         AddToWorklist(i, Op.getNode(), CurOpNumber);
1730       break;
1731     case ISD::CopyFromReg:
1732     case ISD::CopyToReg:
1733       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1734       break;
1735     default:
1736       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1737         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1738       break;
1739     }
1740     OpWorkCount[CurOpNumber]--;
1741     if (OpWorkCount[CurOpNumber] == 0)
1742       NumLeftToConsider--;
1743   }
1744
1745   // If we've changed things around then replace token factor.
1746   if (Changed) {
1747     SDValue Result;
1748     if (Ops.empty()) {
1749       // The entry token is the only possible outcome.
1750       Result = DAG.getEntryNode();
1751     } else {
1752       if (DidPruneOps) {
1753         SmallVector<SDValue, 8> PrunedOps;
1754         //
1755         for (const SDValue &Op : Ops) {
1756           if (SeenChains.count(Op.getNode()) == 0)
1757             PrunedOps.push_back(Op);
1758         }
1759         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1760       } else {
1761         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1762       }
1763     }
1764     return Result;
1765   }
1766   return SDValue();
1767 }
1768
1769 /// MERGE_VALUES can always be eliminated.
1770 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1771   WorklistRemover DeadNodes(*this);
1772   // Replacing results may cause a different MERGE_VALUES to suddenly
1773   // be CSE'd with N, and carry its uses with it. Iterate until no
1774   // uses remain, to ensure that the node can be safely deleted.
1775   // First add the users of this node to the work list so that they
1776   // can be tried again once they have new operands.
1777   AddUsersToWorklist(N);
1778   do {
1779     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1780       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1781   } while (!N->use_empty());
1782   deleteAndRecombine(N);
1783   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1784 }
1785
1786 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1787 /// ConstantSDNode pointer else nullptr.
1788 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1789   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1790   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1791 }
1792
1793 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1794   auto BinOpcode = BO->getOpcode();
1795   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1796           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1797           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1798           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1799           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1800           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1801           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1802           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1803           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1804          "Unexpected binary operator");
1805
1806   // Bail out if any constants are opaque because we can't constant fold those.
1807   SDValue C1 = BO->getOperand(1);
1808   if (!isConstantOrConstantVector(C1, true) &&
1809       !isConstantFPBuildVectorOrConstantFP(C1))
1810     return SDValue();
1811
1812   // Don't do this unless the old select is going away. We want to eliminate the
1813   // binary operator, not replace a binop with a select.
1814   // TODO: Handle ISD::SELECT_CC.
1815   SDValue Sel = BO->getOperand(0);
1816   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1817     return SDValue();
1818
1819   SDValue CT = Sel.getOperand(1);
1820   if (!isConstantOrConstantVector(CT, true) &&
1821       !isConstantFPBuildVectorOrConstantFP(CT))
1822     return SDValue();
1823
1824   SDValue CF = Sel.getOperand(2);
1825   if (!isConstantOrConstantVector(CF, true) &&
1826       !isConstantFPBuildVectorOrConstantFP(CF))
1827     return SDValue();
1828
1829   // We have a select-of-constants followed by a binary operator with a
1830   // constant. Eliminate the binop by pulling the constant math into the select.
1831   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1832   EVT VT = Sel.getValueType();
1833   SDLoc DL(Sel);
1834   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1835   assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1836           isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1837          "Failed to constant fold a binop with constant operands");
1838
1839   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1840   assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1841           isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1842          "Failed to constant fold a binop with constant operands");
1843
1844   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1845 }
1846
1847 SDValue DAGCombiner::visitADD(SDNode *N) {
1848   SDValue N0 = N->getOperand(0);
1849   SDValue N1 = N->getOperand(1);
1850   EVT VT = N0.getValueType();
1851   SDLoc DL(N);
1852
1853   // fold vector ops
1854   if (VT.isVector()) {
1855     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1856       return FoldedVOp;
1857
1858     // fold (add x, 0) -> x, vector edition
1859     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1860       return N0;
1861     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1862       return N1;
1863   }
1864
1865   // fold (add x, undef) -> undef
1866   if (N0.isUndef())
1867     return N0;
1868
1869   if (N1.isUndef())
1870     return N1;
1871
1872   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1873     // canonicalize constant to RHS
1874     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1875       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1876     // fold (add c1, c2) -> c1+c2
1877     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1878                                       N1.getNode());
1879   }
1880
1881   // fold (add x, 0) -> x
1882   if (isNullConstant(N1))
1883     return N0;
1884
1885   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1886     // fold ((c1-A)+c2) -> (c1+c2)-A
1887     if (N0.getOpcode() == ISD::SUB &&
1888         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1889       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1890       return DAG.getNode(ISD::SUB, DL, VT,
1891                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1892                          N0.getOperand(1));
1893     }
1894
1895     // add (sext i1 X), 1 -> zext (not i1 X)
1896     // We don't transform this pattern:
1897     //   add (zext i1 X), -1 -> sext (not i1 X)
1898     // because most (?) targets generate better code for the zext form.
1899     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1900         isOneConstantOrOneSplatConstant(N1)) {
1901       SDValue X = N0.getOperand(0);
1902       if ((!LegalOperations ||
1903            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1904             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1905           X.getScalarValueSizeInBits() == 1) {
1906         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1907         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1908       }
1909     }
1910   }
1911
1912   if (SDValue NewSel = foldBinOpIntoSelect(N))
1913     return NewSel;
1914
1915   // reassociate add
1916   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1917     return RADD;
1918
1919   // fold ((0-A) + B) -> B-A
1920   if (N0.getOpcode() == ISD::SUB &&
1921       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1922     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1923
1924   // fold (A + (0-B)) -> A-B
1925   if (N1.getOpcode() == ISD::SUB &&
1926       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1927     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1928
1929   // fold (A+(B-A)) -> B
1930   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1931     return N1.getOperand(0);
1932
1933   // fold ((B-A)+A) -> B
1934   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1935     return N0.getOperand(0);
1936
1937   // fold (A+(B-(A+C))) to (B-C)
1938   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1939       N0 == N1.getOperand(1).getOperand(0))
1940     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1941                        N1.getOperand(1).getOperand(1));
1942
1943   // fold (A+(B-(C+A))) to (B-C)
1944   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1945       N0 == N1.getOperand(1).getOperand(1))
1946     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1947                        N1.getOperand(1).getOperand(0));
1948
1949   // fold (A+((B-A)+or-C)) to (B+or-C)
1950   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1951       N1.getOperand(0).getOpcode() == ISD::SUB &&
1952       N0 == N1.getOperand(0).getOperand(1))
1953     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1954                        N1.getOperand(1));
1955
1956   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1957   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1958     SDValue N00 = N0.getOperand(0);
1959     SDValue N01 = N0.getOperand(1);
1960     SDValue N10 = N1.getOperand(0);
1961     SDValue N11 = N1.getOperand(1);
1962
1963     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1964       return DAG.getNode(ISD::SUB, DL, VT,
1965                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1966                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1967   }
1968
1969   if (SimplifyDemandedBits(SDValue(N, 0)))
1970     return SDValue(N, 0);
1971
1972   // fold (a+b) -> (a|b) iff a and b share no bits.
1973   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1974       DAG.haveNoCommonBitsSet(N0, N1))
1975     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1976
1977   if (SDValue Combined = visitADDLike(N0, N1, N))
1978     return Combined;
1979
1980   if (SDValue Combined = visitADDLike(N1, N0, N))
1981     return Combined;
1982
1983   return SDValue();
1984 }
1985
1986 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
1987   bool Masked = false;
1988
1989   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
1990   while (true) {
1991     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
1992       V = V.getOperand(0);
1993       continue;
1994     }
1995
1996     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
1997       Masked = true;
1998       V = V.getOperand(0);
1999       continue;
2000     }
2001
2002     break;
2003   }
2004
2005   // If this is not a carry, return.
2006   if (V.getResNo() != 1)
2007     return SDValue();
2008
2009   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2010       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2011     return SDValue();
2012
2013   // If the result is masked, then no matter what kind of bool it is we can
2014   // return. If it isn't, then we need to make sure the bool type is either 0 or
2015   // 1 and not other values.
2016   if (Masked ||
2017       TLI.getBooleanContents(V.getValueType()) ==
2018           TargetLoweringBase::ZeroOrOneBooleanContent)
2019     return V;
2020
2021   return SDValue();
2022 }
2023
2024 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2025   EVT VT = N0.getValueType();
2026   SDLoc DL(LocReference);
2027
2028   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2029   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2030       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2031     return DAG.getNode(ISD::SUB, DL, VT, N0,
2032                        DAG.getNode(ISD::SHL, DL, VT,
2033                                    N1.getOperand(0).getOperand(1),
2034                                    N1.getOperand(1)));
2035
2036   if (N1.getOpcode() == ISD::AND) {
2037     SDValue AndOp0 = N1.getOperand(0);
2038     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2039     unsigned DestBits = VT.getScalarSizeInBits();
2040
2041     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2042     // and similar xforms where the inner op is either ~0 or 0.
2043     if (NumSignBits == DestBits &&
2044         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2045       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2046   }
2047
2048   // add (sext i1), X -> sub X, (zext i1)
2049   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2050       N0.getOperand(0).getValueType() == MVT::i1 &&
2051       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2052     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2053     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2054   }
2055
2056   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2057   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2058     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2059     if (TN->getVT() == MVT::i1) {
2060       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2061                                  DAG.getConstant(1, DL, VT));
2062       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2063     }
2064   }
2065
2066   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2067   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)))
2068     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2069                        N0, N1.getOperand(0), N1.getOperand(2));
2070
2071   // (add X, Carry) -> (addcarry X, 0, Carry)
2072   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2073     if (SDValue Carry = getAsCarry(TLI, N1))
2074       return DAG.getNode(ISD::ADDCARRY, DL,
2075                          DAG.getVTList(VT, Carry.getValueType()), N0,
2076                          DAG.getConstant(0, DL, VT), Carry);
2077
2078   return SDValue();
2079 }
2080
2081 SDValue DAGCombiner::visitADDC(SDNode *N) {
2082   SDValue N0 = N->getOperand(0);
2083   SDValue N1 = N->getOperand(1);
2084   EVT VT = N0.getValueType();
2085   SDLoc DL(N);
2086
2087   // If the flag result is dead, turn this into an ADD.
2088   if (!N->hasAnyUseOfValue(1))
2089     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2090                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2091
2092   // canonicalize constant to RHS.
2093   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2094   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2095   if (N0C && !N1C)
2096     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2097
2098   // fold (addc x, 0) -> x + no carry out
2099   if (isNullConstant(N1))
2100     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2101                                         DL, MVT::Glue));
2102
2103   // If it cannot overflow, transform into an add.
2104   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2105     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2106                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2107
2108   return SDValue();
2109 }
2110
2111 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2112   SDValue N0 = N->getOperand(0);
2113   SDValue N1 = N->getOperand(1);
2114   EVT VT = N0.getValueType();
2115   if (VT.isVector())
2116     return SDValue();
2117
2118   EVT CarryVT = N->getValueType(1);
2119   SDLoc DL(N);
2120
2121   // If the flag result is dead, turn this into an ADD.
2122   if (!N->hasAnyUseOfValue(1))
2123     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2124                      DAG.getUNDEF(CarryVT));
2125
2126   // canonicalize constant to RHS.
2127   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2128   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2129   if (N0C && !N1C)
2130     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2131
2132   // fold (uaddo x, 0) -> x + no carry out
2133   if (isNullConstant(N1))
2134     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2135
2136   // If it cannot overflow, transform into an add.
2137   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2138     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2139                      DAG.getConstant(0, DL, CarryVT));
2140
2141   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2142     return Combined;
2143
2144   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2145     return Combined;
2146
2147   return SDValue();
2148 }
2149
2150 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2151   auto VT = N0.getValueType();
2152
2153   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2154   // If Y + 1 cannot overflow.
2155   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2156     SDValue Y = N1.getOperand(0);
2157     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2158     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2159       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2160                          N1.getOperand(2));
2161   }
2162
2163   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2164   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2165     if (SDValue Carry = getAsCarry(TLI, N1))
2166       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2167                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2168
2169   return SDValue();
2170 }
2171
2172 SDValue DAGCombiner::visitADDE(SDNode *N) {
2173   SDValue N0 = N->getOperand(0);
2174   SDValue N1 = N->getOperand(1);
2175   SDValue CarryIn = N->getOperand(2);
2176
2177   // canonicalize constant to RHS
2178   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2179   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2180   if (N0C && !N1C)
2181     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2182                        N1, N0, CarryIn);
2183
2184   // fold (adde x, y, false) -> (addc x, y)
2185   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2186     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2187
2188   return SDValue();
2189 }
2190
2191 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2192   SDValue N0 = N->getOperand(0);
2193   SDValue N1 = N->getOperand(1);
2194   SDValue CarryIn = N->getOperand(2);
2195   SDLoc DL(N);
2196
2197   // canonicalize constant to RHS
2198   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2199   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2200   if (N0C && !N1C)
2201     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2202
2203   // fold (addcarry x, y, false) -> (uaddo x, y)
2204   if (isNullConstant(CarryIn))
2205     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2206
2207   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2208   if (isNullConstant(N0) && isNullConstant(N1)) {
2209     EVT VT = N0.getValueType();
2210     EVT CarryVT = CarryIn.getValueType();
2211     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2212     AddToWorklist(CarryExt.getNode());
2213     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2214                                     DAG.getConstant(1, DL, VT)),
2215                      DAG.getConstant(0, DL, CarryVT));
2216   }
2217
2218   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2219     return Combined;
2220
2221   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2222     return Combined;
2223
2224   return SDValue();
2225 }
2226
2227 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2228                                        SDNode *N) {
2229   // Iff the flag result is dead:
2230   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2231   if ((N0.getOpcode() == ISD::ADD ||
2232        (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2233       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2234     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2235                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2236
2237   /**
2238    * When one of the addcarry argument is itself a carry, we may be facing
2239    * a diamond carry propagation. In which case we try to transform the DAG
2240    * to ensure linear carry propagation if that is possible.
2241    *
2242    * We are trying to get:
2243    *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2244    */
2245   if (auto Y = getAsCarry(TLI, N1)) {
2246     /**
2247      *            (uaddo A, B)
2248      *             /       \
2249      *          Carry      Sum
2250      *            |          \
2251      *            | (addcarry *, 0, Z)
2252      *            |       /
2253      *             \   Carry
2254      *              |   /
2255      * (addcarry X, *, *)
2256      */
2257     if (Y.getOpcode() == ISD::UADDO &&
2258         CarryIn.getResNo() == 1 &&
2259         CarryIn.getOpcode() == ISD::ADDCARRY &&
2260         isNullConstant(CarryIn.getOperand(1)) &&
2261         CarryIn.getOperand(0) == Y.getValue(0)) {
2262       auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2263                               Y.getOperand(0), Y.getOperand(1),
2264                               CarryIn.getOperand(2));
2265       AddToWorklist(NewY.getNode());
2266       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2267                          DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2268                          NewY.getValue(1));
2269     }
2270   }
2271
2272   return SDValue();
2273 }
2274
2275 // Since it may not be valid to emit a fold to zero for vector initializers
2276 // check if we can before folding.
2277 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2278                              SelectionDAG &DAG, bool LegalOperations,
2279                              bool LegalTypes) {
2280   if (!VT.isVector())
2281     return DAG.getConstant(0, DL, VT);
2282   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2283     return DAG.getConstant(0, DL, VT);
2284   return SDValue();
2285 }
2286
2287 SDValue DAGCombiner::visitSUB(SDNode *N) {
2288   SDValue N0 = N->getOperand(0);
2289   SDValue N1 = N->getOperand(1);
2290   EVT VT = N0.getValueType();
2291   SDLoc DL(N);
2292
2293   // fold vector ops
2294   if (VT.isVector()) {
2295     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2296       return FoldedVOp;
2297
2298     // fold (sub x, 0) -> x, vector edition
2299     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2300       return N0;
2301   }
2302
2303   // fold (sub x, x) -> 0
2304   // FIXME: Refactor this and xor and other similar operations together.
2305   if (N0 == N1)
2306     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2307   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2308       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2309     // fold (sub c1, c2) -> c1-c2
2310     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2311                                       N1.getNode());
2312   }
2313
2314   if (SDValue NewSel = foldBinOpIntoSelect(N))
2315     return NewSel;
2316
2317   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2318
2319   // fold (sub x, c) -> (add x, -c)
2320   if (N1C) {
2321     return DAG.getNode(ISD::ADD, DL, VT, N0,
2322                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2323   }
2324
2325   if (isNullConstantOrNullSplatConstant(N0)) {
2326     unsigned BitWidth = VT.getScalarSizeInBits();
2327     // Right-shifting everything out but the sign bit followed by negation is
2328     // the same as flipping arithmetic/logical shift type without the negation:
2329     // -(X >>u 31) -> (X >>s 31)
2330     // -(X >>s 31) -> (X >>u 31)
2331     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2332       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2333       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2334         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2335         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2336           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2337       }
2338     }
2339
2340     // 0 - X --> 0 if the sub is NUW.
2341     if (N->getFlags().hasNoUnsignedWrap())
2342       return N0;
2343
2344     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2345       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2346       // N1 must be 0 because negating the minimum signed value is undefined.
2347       if (N->getFlags().hasNoSignedWrap())
2348         return N0;
2349
2350       // 0 - X --> X if X is 0 or the minimum signed value.
2351       return N1;
2352     }
2353   }
2354
2355   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2356   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2357     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2358
2359   // fold A-(A-B) -> B
2360   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2361     return N1.getOperand(1);
2362
2363   // fold (A+B)-A -> B
2364   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2365     return N0.getOperand(1);
2366
2367   // fold (A+B)-B -> A
2368   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2369     return N0.getOperand(0);
2370
2371   // fold C2-(A+C1) -> (C2-C1)-A
2372   if (N1.getOpcode() == ISD::ADD) {
2373     SDValue N11 = N1.getOperand(1);
2374     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2375         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2376       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2377       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2378     }
2379   }
2380
2381   // fold ((A+(B+or-C))-B) -> A+or-C
2382   if (N0.getOpcode() == ISD::ADD &&
2383       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2384        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2385       N0.getOperand(1).getOperand(0) == N1)
2386     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2387                        N0.getOperand(1).getOperand(1));
2388
2389   // fold ((A+(C+B))-B) -> A+C
2390   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2391       N0.getOperand(1).getOperand(1) == N1)
2392     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2393                        N0.getOperand(1).getOperand(0));
2394
2395   // fold ((A-(B-C))-C) -> A-B
2396   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2397       N0.getOperand(1).getOperand(1) == N1)
2398     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2399                        N0.getOperand(1).getOperand(0));
2400
2401   // If either operand of a sub is undef, the result is undef
2402   if (N0.isUndef())
2403     return N0;
2404   if (N1.isUndef())
2405     return N1;
2406
2407   // If the relocation model supports it, consider symbol offsets.
2408   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2409     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2410       // fold (sub Sym, c) -> Sym-c
2411       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2412         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2413                                     GA->getOffset() -
2414                                         (uint64_t)N1C->getSExtValue());
2415       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2416       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2417         if (GA->getGlobal() == GB->getGlobal())
2418           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2419                                  DL, VT);
2420     }
2421
2422   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2423   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2424     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2425     if (TN->getVT() == MVT::i1) {
2426       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2427                                  DAG.getConstant(1, DL, VT));
2428       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2429     }
2430   }
2431
2432   return SDValue();
2433 }
2434
2435 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2436   SDValue N0 = N->getOperand(0);
2437   SDValue N1 = N->getOperand(1);
2438   EVT VT = N0.getValueType();
2439   SDLoc DL(N);
2440
2441   // If the flag result is dead, turn this into an SUB.
2442   if (!N->hasAnyUseOfValue(1))
2443     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2444                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2445
2446   // fold (subc x, x) -> 0 + no borrow
2447   if (N0 == N1)
2448     return CombineTo(N, DAG.getConstant(0, DL, VT),
2449                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2450
2451   // fold (subc x, 0) -> x + no borrow
2452   if (isNullConstant(N1))
2453     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2454
2455   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2456   if (isAllOnesConstant(N0))
2457     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2458                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2459
2460   return SDValue();
2461 }
2462
2463 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2464   SDValue N0 = N->getOperand(0);
2465   SDValue N1 = N->getOperand(1);
2466   EVT VT = N0.getValueType();
2467   if (VT.isVector())
2468     return SDValue();
2469
2470   EVT CarryVT = N->getValueType(1);
2471   SDLoc DL(N);
2472
2473   // If the flag result is dead, turn this into an SUB.
2474   if (!N->hasAnyUseOfValue(1))
2475     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2476                      DAG.getUNDEF(CarryVT));
2477
2478   // fold (usubo x, x) -> 0 + no borrow
2479   if (N0 == N1)
2480     return CombineTo(N, DAG.getConstant(0, DL, VT),
2481                      DAG.getConstant(0, DL, CarryVT));
2482
2483   // fold (usubo x, 0) -> x + no borrow
2484   if (isNullConstant(N1))
2485     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2486
2487   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2488   if (isAllOnesConstant(N0))
2489     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2490                      DAG.getConstant(0, DL, CarryVT));
2491
2492   return SDValue();
2493 }
2494
2495 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2496   SDValue N0 = N->getOperand(0);
2497   SDValue N1 = N->getOperand(1);
2498   SDValue CarryIn = N->getOperand(2);
2499
2500   // fold (sube x, y, false) -> (subc x, y)
2501   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2502     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2503
2504   return SDValue();
2505 }
2506
2507 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2508   SDValue N0 = N->getOperand(0);
2509   SDValue N1 = N->getOperand(1);
2510   SDValue CarryIn = N->getOperand(2);
2511
2512   // fold (subcarry x, y, false) -> (usubo x, y)
2513   if (isNullConstant(CarryIn))
2514     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2515
2516   return SDValue();
2517 }
2518
2519 SDValue DAGCombiner::visitMUL(SDNode *N) {
2520   SDValue N0 = N->getOperand(0);
2521   SDValue N1 = N->getOperand(1);
2522   EVT VT = N0.getValueType();
2523
2524   // fold (mul x, undef) -> 0
2525   if (N0.isUndef() || N1.isUndef())
2526     return DAG.getConstant(0, SDLoc(N), VT);
2527
2528   bool N0IsConst = false;
2529   bool N1IsConst = false;
2530   bool N1IsOpaqueConst = false;
2531   bool N0IsOpaqueConst = false;
2532   APInt ConstValue0, ConstValue1;
2533   // fold vector ops
2534   if (VT.isVector()) {
2535     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2536       return FoldedVOp;
2537
2538     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2539     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2540   } else {
2541     N0IsConst = isa<ConstantSDNode>(N0);
2542     if (N0IsConst) {
2543       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2544       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2545     }
2546     N1IsConst = isa<ConstantSDNode>(N1);
2547     if (N1IsConst) {
2548       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2549       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2550     }
2551   }
2552
2553   // fold (mul c1, c2) -> c1*c2
2554   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2555     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2556                                       N0.getNode(), N1.getNode());
2557
2558   // canonicalize constant to RHS (vector doesn't have to splat)
2559   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2560      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2561     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2562   // fold (mul x, 0) -> 0
2563   if (N1IsConst && ConstValue1.isNullValue())
2564     return N1;
2565   // We require a splat of the entire scalar bit width for non-contiguous
2566   // bit patterns.
2567   bool IsFullSplat =
2568     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2569   // fold (mul x, 1) -> x
2570   if (N1IsConst && ConstValue1.isOneValue() && IsFullSplat)
2571     return N0;
2572
2573   if (SDValue NewSel = foldBinOpIntoSelect(N))
2574     return NewSel;
2575
2576   // fold (mul x, -1) -> 0-x
2577   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2578     SDLoc DL(N);
2579     return DAG.getNode(ISD::SUB, DL, VT,
2580                        DAG.getConstant(0, DL, VT), N0);
2581   }
2582   // fold (mul x, (1 << c)) -> x << c
2583   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2584       IsFullSplat) {
2585     SDLoc DL(N);
2586     return DAG.getNode(ISD::SHL, DL, VT, N0,
2587                        DAG.getConstant(ConstValue1.logBase2(), DL,
2588                                        getShiftAmountTy(N0.getValueType())));
2589   }
2590   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2591   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2592       IsFullSplat) {
2593     unsigned Log2Val = (-ConstValue1).logBase2();
2594     SDLoc DL(N);
2595     // FIXME: If the input is something that is easily negated (e.g. a
2596     // single-use add), we should put the negate there.
2597     return DAG.getNode(ISD::SUB, DL, VT,
2598                        DAG.getConstant(0, DL, VT),
2599                        DAG.getNode(ISD::SHL, DL, VT, N0,
2600                             DAG.getConstant(Log2Val, DL,
2601                                       getShiftAmountTy(N0.getValueType()))));
2602   }
2603
2604   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2605   if (N0.getOpcode() == ISD::SHL &&
2606       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2607       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2608     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2609     if (isConstantOrConstantVector(C3))
2610       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2611   }
2612
2613   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2614   // use.
2615   {
2616     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2617
2618     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2619     if (N0.getOpcode() == ISD::SHL &&
2620         isConstantOrConstantVector(N0.getOperand(1)) &&
2621         N0.getNode()->hasOneUse()) {
2622       Sh = N0; Y = N1;
2623     } else if (N1.getOpcode() == ISD::SHL &&
2624                isConstantOrConstantVector(N1.getOperand(1)) &&
2625                N1.getNode()->hasOneUse()) {
2626       Sh = N1; Y = N0;
2627     }
2628
2629     if (Sh.getNode()) {
2630       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2631       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2632     }
2633   }
2634
2635   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2636   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2637       N0.getOpcode() == ISD::ADD &&
2638       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2639       isMulAddWithConstProfitable(N, N0, N1))
2640       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2641                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2642                                      N0.getOperand(0), N1),
2643                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2644                                      N0.getOperand(1), N1));
2645
2646   // reassociate mul
2647   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2648     return RMUL;
2649
2650   return SDValue();
2651 }
2652
2653 /// Return true if divmod libcall is available.
2654 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2655                                      const TargetLowering &TLI) {
2656   RTLIB::Libcall LC;
2657   EVT NodeType = Node->getValueType(0);
2658   if (!NodeType.isSimple())
2659     return false;
2660   switch (NodeType.getSimpleVT().SimpleTy) {
2661   default: return false; // No libcall for vector types.
2662   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2663   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2664   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2665   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2666   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2667   }
2668
2669   return TLI.getLibcallName(LC) != nullptr;
2670 }
2671
2672 /// Issue divrem if both quotient and remainder are needed.
2673 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2674   if (Node->use_empty())
2675     return SDValue(); // This is a dead node, leave it alone.
2676
2677   unsigned Opcode = Node->getOpcode();
2678   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2679   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2680
2681   // DivMod lib calls can still work on non-legal types if using lib-calls.
2682   EVT VT = Node->getValueType(0);
2683   if (VT.isVector() || !VT.isInteger())
2684     return SDValue();
2685
2686   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2687     return SDValue();
2688
2689   // If DIVREM is going to get expanded into a libcall,
2690   // but there is no libcall available, then don't combine.
2691   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2692       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2693     return SDValue();
2694
2695   // If div is legal, it's better to do the normal expansion
2696   unsigned OtherOpcode = 0;
2697   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2698     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2699     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2700       return SDValue();
2701   } else {
2702     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2703     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2704       return SDValue();
2705   }
2706
2707   SDValue Op0 = Node->getOperand(0);
2708   SDValue Op1 = Node->getOperand(1);
2709   SDValue combined;
2710   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2711          UE = Op0.getNode()->use_end(); UI != UE;) {
2712     SDNode *User = *UI++;
2713     if (User == Node || User->use_empty())
2714       continue;
2715     // Convert the other matching node(s), too;
2716     // otherwise, the DIVREM may get target-legalized into something
2717     // target-specific that we won't be able to recognize.
2718     unsigned UserOpc = User->getOpcode();
2719     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2720         User->getOperand(0) == Op0 &&
2721         User->getOperand(1) == Op1) {
2722       if (!combined) {
2723         if (UserOpc == OtherOpcode) {
2724           SDVTList VTs = DAG.getVTList(VT, VT);
2725           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2726         } else if (UserOpc == DivRemOpc) {
2727           combined = SDValue(User, 0);
2728         } else {
2729           assert(UserOpc == Opcode);
2730           continue;
2731         }
2732       }
2733       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2734         CombineTo(User, combined);
2735       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2736         CombineTo(User, combined.getValue(1));
2737     }
2738   }
2739   return combined;
2740 }
2741
2742 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2743   SDValue N0 = N->getOperand(0);
2744   SDValue N1 = N->getOperand(1);
2745   EVT VT = N->getValueType(0);
2746   SDLoc DL(N);
2747
2748   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2749     return DAG.getUNDEF(VT);
2750
2751   // undef / X -> 0
2752   // undef % X -> 0
2753   if (N0.isUndef())
2754     return DAG.getConstant(0, DL, VT);
2755
2756   return SDValue();
2757 }
2758
2759 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2760   SDValue N0 = N->getOperand(0);
2761   SDValue N1 = N->getOperand(1);
2762   EVT VT = N->getValueType(0);
2763
2764   // fold vector ops
2765   if (VT.isVector())
2766     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2767       return FoldedVOp;
2768
2769   SDLoc DL(N);
2770
2771   // fold (sdiv c1, c2) -> c1/c2
2772   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2773   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2774   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2775     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2776   // fold (sdiv X, 1) -> X
2777   if (N1C && N1C->isOne())
2778     return N0;
2779   // fold (sdiv X, -1) -> 0-X
2780   if (N1C && N1C->isAllOnesValue())
2781     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2782
2783   if (SDValue V = simplifyDivRem(N, DAG))
2784     return V;
2785
2786   if (SDValue NewSel = foldBinOpIntoSelect(N))
2787     return NewSel;
2788
2789   // If we know the sign bits of both operands are zero, strength reduce to a
2790   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2791   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2792     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2793
2794   // fold (sdiv X, pow2) -> simple ops after legalize
2795   // FIXME: We check for the exact bit here because the generic lowering gives
2796   // better results in that case. The target-specific lowering should learn how
2797   // to handle exact sdivs efficiently.
2798   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2799       !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2800                                     (-N1C->getAPIntValue()).isPowerOf2())) {
2801     // Target-specific implementation of sdiv x, pow2.
2802     if (SDValue Res = BuildSDIVPow2(N))
2803       return Res;
2804
2805     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2806
2807     // Splat the sign bit into the register
2808     SDValue SGN =
2809         DAG.getNode(ISD::SRA, DL, VT, N0,
2810                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2811                                     getShiftAmountTy(N0.getValueType())));
2812     AddToWorklist(SGN.getNode());
2813
2814     // Add (N0 < 0) ? abs2 - 1 : 0;
2815     SDValue SRL =
2816         DAG.getNode(ISD::SRL, DL, VT, SGN,
2817                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2818                                     getShiftAmountTy(SGN.getValueType())));
2819     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2820     AddToWorklist(SRL.getNode());
2821     AddToWorklist(ADD.getNode());    // Divide by pow2
2822     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2823                   DAG.getConstant(lg2, DL,
2824                                   getShiftAmountTy(ADD.getValueType())));
2825
2826     // If we're dividing by a positive value, we're done.  Otherwise, we must
2827     // negate the result.
2828     if (N1C->getAPIntValue().isNonNegative())
2829       return SRA;
2830
2831     AddToWorklist(SRA.getNode());
2832     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2833   }
2834
2835   // If integer divide is expensive and we satisfy the requirements, emit an
2836   // alternate sequence.  Targets may check function attributes for size/speed
2837   // trade-offs.
2838   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2839   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2840     if (SDValue Op = BuildSDIV(N))
2841       return Op;
2842
2843   // sdiv, srem -> sdivrem
2844   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2845   // true.  Otherwise, we break the simplification logic in visitREM().
2846   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2847     if (SDValue DivRem = useDivRem(N))
2848         return DivRem;
2849
2850   return SDValue();
2851 }
2852
2853 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2854   SDValue N0 = N->getOperand(0);
2855   SDValue N1 = N->getOperand(1);
2856   EVT VT = N->getValueType(0);
2857
2858   // fold vector ops
2859   if (VT.isVector())
2860     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2861       return FoldedVOp;
2862
2863   SDLoc DL(N);
2864
2865   // fold (udiv c1, c2) -> c1/c2
2866   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2867   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2868   if (N0C && N1C)
2869     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2870                                                     N0C, N1C))
2871       return Folded;
2872
2873   if (SDValue V = simplifyDivRem(N, DAG))
2874     return V;
2875
2876   if (SDValue NewSel = foldBinOpIntoSelect(N))
2877     return NewSel;
2878
2879   // fold (udiv x, (1 << c)) -> x >>u c
2880   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2881       DAG.isKnownToBeAPowerOfTwo(N1)) {
2882     SDValue LogBase2 = BuildLogBase2(N1, DL);
2883     AddToWorklist(LogBase2.getNode());
2884
2885     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2886     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2887     AddToWorklist(Trunc.getNode());
2888     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2889   }
2890
2891   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2892   if (N1.getOpcode() == ISD::SHL) {
2893     SDValue N10 = N1.getOperand(0);
2894     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2895         DAG.isKnownToBeAPowerOfTwo(N10)) {
2896       SDValue LogBase2 = BuildLogBase2(N10, DL);
2897       AddToWorklist(LogBase2.getNode());
2898
2899       EVT ADDVT = N1.getOperand(1).getValueType();
2900       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2901       AddToWorklist(Trunc.getNode());
2902       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2903       AddToWorklist(Add.getNode());
2904       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2905     }
2906   }
2907
2908   // fold (udiv x, c) -> alternate
2909   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2910   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2911     if (SDValue Op = BuildUDIV(N))
2912       return Op;
2913
2914   // sdiv, srem -> sdivrem
2915   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2916   // true.  Otherwise, we break the simplification logic in visitREM().
2917   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2918     if (SDValue DivRem = useDivRem(N))
2919         return DivRem;
2920
2921   return SDValue();
2922 }
2923
2924 // handles ISD::SREM and ISD::UREM
2925 SDValue DAGCombiner::visitREM(SDNode *N) {
2926   unsigned Opcode = N->getOpcode();
2927   SDValue N0 = N->getOperand(0);
2928   SDValue N1 = N->getOperand(1);
2929   EVT VT = N->getValueType(0);
2930   bool isSigned = (Opcode == ISD::SREM);
2931   SDLoc DL(N);
2932
2933   // fold (rem c1, c2) -> c1%c2
2934   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2935   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2936   if (N0C && N1C)
2937     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2938       return Folded;
2939
2940   if (SDValue V = simplifyDivRem(N, DAG))
2941     return V;
2942
2943   if (SDValue NewSel = foldBinOpIntoSelect(N))
2944     return NewSel;
2945
2946   if (isSigned) {
2947     // If we know the sign bits of both operands are zero, strength reduce to a
2948     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2949     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2950       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2951   } else {
2952     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
2953     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2954       // fold (urem x, pow2) -> (and x, pow2-1)
2955       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2956       AddToWorklist(Add.getNode());
2957       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2958     }
2959     if (N1.getOpcode() == ISD::SHL &&
2960         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2961       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2962       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2963       AddToWorklist(Add.getNode());
2964       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2965     }
2966   }
2967
2968   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2969
2970   // If X/C can be simplified by the division-by-constant logic, lower
2971   // X%C to the equivalent of X-X/C*C.
2972   // To avoid mangling nodes, this simplification requires that the combine()
2973   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2974   // against this by skipping the simplification if isIntDivCheap().  When
2975   // div is not cheap, combine will not return a DIVREM.  Regardless,
2976   // checking cheapness here makes sense since the simplification results in
2977   // fatter code.
2978   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2979     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2980     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2981     AddToWorklist(Div.getNode());
2982     SDValue OptimizedDiv = combine(Div.getNode());
2983     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2984       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2985              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2986       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2987       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2988       AddToWorklist(Mul.getNode());
2989       return Sub;
2990     }
2991   }
2992
2993   // sdiv, srem -> sdivrem
2994   if (SDValue DivRem = useDivRem(N))
2995     return DivRem.getValue(1);
2996
2997   return SDValue();
2998 }
2999
3000 SDValue DAGCombiner::visitMULHS(SDNode *N) {
3001   SDValue N0 = N->getOperand(0);
3002   SDValue N1 = N->getOperand(1);
3003   EVT VT = N->getValueType(0);
3004   SDLoc DL(N);
3005
3006   // fold (mulhs x, 0) -> 0
3007   if (isNullConstant(N1))
3008     return N1;
3009   // fold (mulhs x, 1) -> (sra x, size(x)-1)
3010   if (isOneConstant(N1)) {
3011     SDLoc DL(N);
3012     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3013                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3014                                        getShiftAmountTy(N0.getValueType())));
3015   }
3016   // fold (mulhs x, undef) -> 0
3017   if (N0.isUndef() || N1.isUndef())
3018     return DAG.getConstant(0, SDLoc(N), VT);
3019
3020   // If the type twice as wide is legal, transform the mulhs to a wider multiply
3021   // plus a shift.
3022   if (VT.isSimple() && !VT.isVector()) {
3023     MVT Simple = VT.getSimpleVT();
3024     unsigned SimpleSize = Simple.getSizeInBits();
3025     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3026     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3027       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3028       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3029       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3030       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3031             DAG.getConstant(SimpleSize, DL,
3032                             getShiftAmountTy(N1.getValueType())));
3033       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3034     }
3035   }
3036
3037   return SDValue();
3038 }
3039
3040 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3041   SDValue N0 = N->getOperand(0);
3042   SDValue N1 = N->getOperand(1);
3043   EVT VT = N->getValueType(0);
3044   SDLoc DL(N);
3045
3046   // fold (mulhu x, 0) -> 0
3047   if (isNullConstant(N1))
3048     return N1;
3049   // fold (mulhu x, 1) -> 0
3050   if (isOneConstant(N1))
3051     return DAG.getConstant(0, DL, N0.getValueType());
3052   // fold (mulhu x, undef) -> 0
3053   if (N0.isUndef() || N1.isUndef())
3054     return DAG.getConstant(0, DL, VT);
3055
3056   // If the type twice as wide is legal, transform the mulhu to a wider multiply
3057   // plus a shift.
3058   if (VT.isSimple() && !VT.isVector()) {
3059     MVT Simple = VT.getSimpleVT();
3060     unsigned SimpleSize = Simple.getSizeInBits();
3061     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3062     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3063       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3064       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3065       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3066       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3067             DAG.getConstant(SimpleSize, DL,
3068                             getShiftAmountTy(N1.getValueType())));
3069       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3070     }
3071   }
3072
3073   return SDValue();
3074 }
3075
3076 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3077 /// give the opcodes for the two computations that are being performed. Return
3078 /// true if a simplification was made.
3079 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3080                                                 unsigned HiOp) {
3081   // If the high half is not needed, just compute the low half.
3082   bool HiExists = N->hasAnyUseOfValue(1);
3083   if (!HiExists &&
3084       (!LegalOperations ||
3085        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3086     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3087     return CombineTo(N, Res, Res);
3088   }
3089
3090   // If the low half is not needed, just compute the high half.
3091   bool LoExists = N->hasAnyUseOfValue(0);
3092   if (!LoExists &&
3093       (!LegalOperations ||
3094        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3095     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3096     return CombineTo(N, Res, Res);
3097   }
3098
3099   // If both halves are used, return as it is.
3100   if (LoExists && HiExists)
3101     return SDValue();
3102
3103   // If the two computed results can be simplified separately, separate them.
3104   if (LoExists) {
3105     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3106     AddToWorklist(Lo.getNode());
3107     SDValue LoOpt = combine(Lo.getNode());
3108     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3109         (!LegalOperations ||
3110          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3111       return CombineTo(N, LoOpt, LoOpt);
3112   }
3113
3114   if (HiExists) {
3115     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3116     AddToWorklist(Hi.getNode());
3117     SDValue HiOpt = combine(Hi.getNode());
3118     if (HiOpt.getNode() && HiOpt != Hi &&
3119         (!LegalOperations ||
3120          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3121       return CombineTo(N, HiOpt, HiOpt);
3122   }
3123
3124   return SDValue();
3125 }
3126
3127 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3128   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3129     return Res;
3130
3131   EVT VT = N->getValueType(0);
3132   SDLoc DL(N);
3133
3134   // If the type is twice as wide is legal, transform the mulhu to a wider
3135   // multiply plus a shift.
3136   if (VT.isSimple() && !VT.isVector()) {
3137     MVT Simple = VT.getSimpleVT();
3138     unsigned SimpleSize = Simple.getSizeInBits();
3139     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3140     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3141       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3142       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3143       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3144       // Compute the high part as N1.
3145       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3146             DAG.getConstant(SimpleSize, DL,
3147                             getShiftAmountTy(Lo.getValueType())));
3148       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3149       // Compute the low part as N0.
3150       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3151       return CombineTo(N, Lo, Hi);
3152     }
3153   }
3154
3155   return SDValue();
3156 }
3157
3158 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3159   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3160     return Res;
3161
3162   EVT VT = N->getValueType(0);
3163   SDLoc DL(N);
3164
3165   // If the type is twice as wide is legal, transform the mulhu to a wider
3166   // multiply plus a shift.
3167   if (VT.isSimple() && !VT.isVector()) {
3168     MVT Simple = VT.getSimpleVT();
3169     unsigned SimpleSize = Simple.getSizeInBits();
3170     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3171     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3172       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3173       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3174       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3175       // Compute the high part as N1.
3176       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3177             DAG.getConstant(SimpleSize, DL,
3178                             getShiftAmountTy(Lo.getValueType())));
3179       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3180       // Compute the low part as N0.
3181       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3182       return CombineTo(N, Lo, Hi);
3183     }
3184   }
3185
3186   return SDValue();
3187 }
3188
3189 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3190   // (smulo x, 2) -> (saddo x, x)
3191   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3192     if (C2->getAPIntValue() == 2)
3193       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3194                          N->getOperand(0), N->getOperand(0));
3195
3196   return SDValue();
3197 }
3198
3199 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3200   // (umulo x, 2) -> (uaddo x, x)
3201   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3202     if (C2->getAPIntValue() == 2)
3203       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3204                          N->getOperand(0), N->getOperand(0));
3205
3206   return SDValue();
3207 }
3208
3209 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3210   SDValue N0 = N->getOperand(0);
3211   SDValue N1 = N->getOperand(1);
3212   EVT VT = N0.getValueType();
3213
3214   // fold vector ops
3215   if (VT.isVector())
3216     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3217       return FoldedVOp;
3218
3219   // fold (add c1, c2) -> c1+c2
3220   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3221   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3222   if (N0C && N1C)
3223     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3224
3225   // canonicalize constant to RHS
3226   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3227      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3228     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3229
3230   return SDValue();
3231 }
3232
3233 /// If this is a binary operator with two operands of the same opcode, try to
3234 /// simplify it.
3235 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3236   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3237   EVT VT = N0.getValueType();
3238   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3239
3240   // Bail early if none of these transforms apply.
3241   if (N0.getNumOperands() == 0) return SDValue();
3242
3243   // For each of OP in AND/OR/XOR:
3244   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3245   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3246   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3247   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3248   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3249   //
3250   // do not sink logical op inside of a vector extend, since it may combine
3251   // into a vsetcc.
3252   EVT Op0VT = N0.getOperand(0).getValueType();
3253   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3254        N0.getOpcode() == ISD::SIGN_EXTEND ||
3255        N0.getOpcode() == ISD::BSWAP ||
3256        // Avoid infinite looping with PromoteIntBinOp.
3257        (N0.getOpcode() == ISD::ANY_EXTEND &&
3258         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3259        (N0.getOpcode() == ISD::TRUNCATE &&
3260         (!TLI.isZExtFree(VT, Op0VT) ||
3261          !TLI.isTruncateFree(Op0VT, VT)) &&
3262         TLI.isTypeLegal(Op0VT))) &&
3263       !VT.isVector() &&
3264       Op0VT == N1.getOperand(0).getValueType() &&
3265       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3266     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3267                                  N0.getOperand(0).getValueType(),
3268                                  N0.getOperand(0), N1.getOperand(0));
3269     AddToWorklist(ORNode.getNode());
3270     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3271   }
3272
3273   // For each of OP in SHL/SRL/SRA/AND...
3274   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3275   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3276   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3277   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3278        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3279       N0.getOperand(1) == N1.getOperand(1)) {
3280     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3281                                  N0.getOperand(0).getValueType(),
3282                                  N0.getOperand(0), N1.getOperand(0));
3283     AddToWorklist(ORNode.getNode());
3284     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3285                        ORNode, N0.getOperand(1));
3286   }
3287
3288   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3289   // Only perform this optimization up until type legalization, before
3290   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3291   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3292   // we don't want to undo this promotion.
3293   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3294   // on scalars.
3295   if ((N0.getOpcode() == ISD::BITCAST ||
3296        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3297        Level <= AfterLegalizeTypes) {
3298     SDValue In0 = N0.getOperand(0);
3299     SDValue In1 = N1.getOperand(0);
3300     EVT In0Ty = In0.getValueType();
3301     EVT In1Ty = In1.getValueType();
3302     SDLoc DL(N);
3303     // If both incoming values are integers, and the original types are the
3304     // same.
3305     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3306       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3307       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3308       AddToWorklist(Op.getNode());
3309       return BC;
3310     }
3311   }
3312
3313   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3314   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3315   // If both shuffles use the same mask, and both shuffle within a single
3316   // vector, then it is worthwhile to move the swizzle after the operation.
3317   // The type-legalizer generates this pattern when loading illegal
3318   // vector types from memory. In many cases this allows additional shuffle
3319   // optimizations.
3320   // There are other cases where moving the shuffle after the xor/and/or
3321   // is profitable even if shuffles don't perform a swizzle.
3322   // If both shuffles use the same mask, and both shuffles have the same first
3323   // or second operand, then it might still be profitable to move the shuffle
3324   // after the xor/and/or operation.
3325   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3326     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3327     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3328
3329     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3330            "Inputs to shuffles are not the same type");
3331
3332     // Check that both shuffles use the same mask. The masks are known to be of
3333     // the same length because the result vector type is the same.
3334     // Check also that shuffles have only one use to avoid introducing extra
3335     // instructions.
3336     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3337         SVN0->getMask().equals(SVN1->getMask())) {
3338       SDValue ShOp = N0->getOperand(1);
3339
3340       // Don't try to fold this node if it requires introducing a
3341       // build vector of all zeros that might be illegal at this stage.
3342       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3343         if (!LegalTypes)
3344           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3345         else
3346           ShOp = SDValue();
3347       }
3348
3349       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3350       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3351       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3352       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3353         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3354                                       N0->getOperand(0), N1->getOperand(0));
3355         AddToWorklist(NewNode.getNode());
3356         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3357                                     SVN0->getMask());
3358       }
3359
3360       // Don't try to fold this node if it requires introducing a
3361       // build vector of all zeros that might be illegal at this stage.
3362       ShOp = N0->getOperand(0);
3363       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3364         if (!LegalTypes)
3365           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3366         else
3367           ShOp = SDValue();
3368       }
3369
3370       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3371       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3372       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3373       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3374         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3375                                       N0->getOperand(1), N1->getOperand(1));
3376         AddToWorklist(NewNode.getNode());
3377         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3378                                     SVN0->getMask());
3379       }
3380     }
3381   }
3382
3383   return SDValue();
3384 }
3385
3386 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3387 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3388                                        const SDLoc &DL) {
3389   SDValue LL, LR, RL, RR, N0CC, N1CC;
3390   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3391       !isSetCCEquivalent(N1, RL, RR, N1CC))
3392     return SDValue();
3393
3394   assert(N0.getValueType() == N1.getValueType() &&
3395          "Unexpected operand types for bitwise logic op");
3396   assert(LL.getValueType() == LR.getValueType() &&
3397          RL.getValueType() == RR.getValueType() &&
3398          "Unexpected operand types for setcc");
3399
3400   // If we're here post-legalization or the logic op type is not i1, the logic
3401   // op type must match a setcc result type. Also, all folds require new
3402   // operations on the left and right operands, so those types must match.
3403   EVT VT = N0.getValueType();
3404   EVT OpVT = LL.getValueType();
3405   if (LegalOperations || VT != MVT::i1)
3406     if (VT != getSetCCResultType(OpVT))
3407       return SDValue();
3408   if (OpVT != RL.getValueType())
3409     return SDValue();
3410
3411   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3412   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3413   bool IsInteger = OpVT.isInteger();
3414   if (LR == RR && CC0 == CC1 && IsInteger) {
3415     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3416     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3417
3418     // All bits clear?
3419     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3420     // All sign bits clear?
3421     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3422     // Any bits set?
3423     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3424     // Any sign bits set?
3425     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3426
3427     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3428     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3429     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3430     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3431     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3432       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3433       AddToWorklist(Or.getNode());
3434       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3435     }
3436
3437     // All bits set?
3438     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3439     // All sign bits set?
3440     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3441     // Any bits clear?
3442     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3443     // Any sign bits clear?
3444     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3445
3446     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3447     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3448     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3449     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3450     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3451       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3452       AddToWorklist(And.getNode());
3453       return DAG.getSetCC(DL, VT, And, LR, CC1);
3454     }
3455   }
3456
3457   // TODO: What is the 'or' equivalent of this fold?
3458   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3459   if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3460       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3461        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3462     SDValue One = DAG.getConstant(1, DL, OpVT);
3463     SDValue Two = DAG.getConstant(2, DL, OpVT);
3464     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3465     AddToWorklist(Add.getNode());
3466     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3467   }
3468
3469   // Try more general transforms if the predicates match and the only user of
3470   // the compares is the 'and' or 'or'.
3471   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3472       N0.hasOneUse() && N1.hasOneUse()) {
3473     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3474     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3475     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3476       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3477       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3478       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3479       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3480       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3481     }
3482   }
3483
3484   // Canonicalize equivalent operands to LL == RL.
3485   if (LL == RR && LR == RL) {
3486     CC1 = ISD::getSetCCSwappedOperands(CC1);
3487     std::swap(RL, RR);
3488   }
3489
3490   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3491   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3492   if (LL == RL && LR == RR) {
3493     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3494                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3495     if (NewCC != ISD::SETCC_INVALID &&
3496         (!LegalOperations ||
3497          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3498           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3499       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3500   }
3501
3502   return SDValue();
3503 }
3504
3505 /// This contains all DAGCombine rules which reduce two values combined by
3506 /// an And operation to a single value. This makes them reusable in the context
3507 /// of visitSELECT(). Rules involving constants are not included as
3508 /// visitSELECT() already handles those cases.
3509 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3510   EVT VT = N1.getValueType();
3511   SDLoc DL(N);
3512
3513   // fold (and x, undef) -> 0
3514   if (N0.isUndef() || N1.isUndef())
3515     return DAG.getConstant(0, DL, VT);
3516
3517   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3518     return V;
3519
3520   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3521       VT.getSizeInBits() <= 64) {
3522     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3523       APInt ADDC = ADDI->getAPIntValue();
3524       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3525         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3526         // immediate for an add, but it is legal if its top c2 bits are set,
3527         // transform the ADD so the immediate doesn't need to be materialized
3528         // in a register.
3529         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3530           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3531                                              SRLI->getZExtValue());
3532           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3533             ADDC |= Mask;
3534             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3535               SDLoc DL0(N0);
3536               SDValue NewAdd =
3537                 DAG.getNode(ISD::ADD, DL0, VT,
3538                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3539               CombineTo(N0.getNode(), NewAdd);
3540               // Return N so it doesn't get rechecked!
3541               return SDValue(N, 0);
3542             }
3543           }
3544         }
3545       }
3546     }
3547   }
3548
3549   // Reduce bit extract of low half of an integer to the narrower type.
3550   // (and (srl i64:x, K), KMask) ->
3551   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3552   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3553     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3554       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3555         unsigned Size = VT.getSizeInBits();
3556         const APInt &AndMask = CAnd->getAPIntValue();
3557         unsigned ShiftBits = CShift->getZExtValue();
3558
3559         // Bail out, this node will probably disappear anyway.
3560         if (ShiftBits == 0)
3561           return SDValue();
3562
3563         unsigned MaskBits = AndMask.countTrailingOnes();
3564         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3565
3566         if (AndMask.isMask() &&
3567             // Required bits must not span the two halves of the integer and
3568             // must fit in the half size type.
3569             (ShiftBits + MaskBits <= Size / 2) &&
3570             TLI.isNarrowingProfitable(VT, HalfVT) &&
3571             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3572             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3573             TLI.isTruncateFree(VT, HalfVT) &&
3574             TLI.isZExtFree(HalfVT, VT)) {
3575           // The isNarrowingProfitable is to avoid regressions on PPC and
3576           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3577           // on downstream users of this. Those patterns could probably be
3578           // extended to handle extensions mixed in.
3579
3580           SDValue SL(N0);
3581           assert(MaskBits <= Size);
3582
3583           // Extracting the highest bit of the low half.
3584           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3585           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3586                                       N0.getOperand(0));
3587
3588           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3589           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3590           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3591           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3592           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3593         }
3594       }
3595     }
3596   }
3597
3598   return SDValue();
3599 }
3600
3601 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3602                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3603                                    bool &NarrowLoad) {
3604   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3605
3606   if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3607     return false;
3608
3609   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3610   LoadedVT = LoadN->getMemoryVT();
3611
3612   if (ExtVT == LoadedVT &&
3613       (!LegalOperations ||
3614        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3615     // ZEXTLOAD will match without needing to change the size of the value being
3616     // loaded.
3617     NarrowLoad = false;
3618     return true;
3619   }
3620
3621   // Do not change the width of a volatile load.
3622   if (LoadN->isVolatile())
3623     return false;
3624
3625   // Do not generate loads of non-round integer types since these can
3626   // be expensive (and would be wrong if the type is not byte sized).
3627   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3628     return false;
3629
3630   if (LegalOperations &&
3631       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3632     return false;
3633
3634   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3635     return false;
3636
3637   NarrowLoad = true;
3638   return true;
3639 }
3640
3641 SDValue DAGCombiner::visitAND(SDNode *N) {
3642   SDValue N0 = N->getOperand(0);
3643   SDValue N1 = N->getOperand(1);
3644   EVT VT = N1.getValueType();
3645
3646   // x & x --> x
3647   if (N0 == N1)
3648     return N0;
3649
3650   // fold vector ops
3651   if (VT.isVector()) {
3652     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3653       return FoldedVOp;
3654
3655     // fold (and x, 0) -> 0, vector edition
3656     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3657       // do not return N0, because undef node may exist in N0
3658       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3659                              SDLoc(N), N0.getValueType());
3660     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3661       // do not return N1, because undef node may exist in N1
3662       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3663                              SDLoc(N), N1.getValueType());
3664
3665     // fold (and x, -1) -> x, vector edition
3666     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3667       return N1;
3668     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3669       return N0;
3670   }
3671
3672   // fold (and c1, c2) -> c1&c2
3673   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3674   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3675   if (N0C && N1C && !N1C->isOpaque())
3676     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3677   // canonicalize constant to RHS
3678   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3679      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3680     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3681   // fold (and x, -1) -> x
3682   if (isAllOnesConstant(N1))
3683     return N0;
3684   // if (and x, c) is known to be zero, return 0
3685   unsigned BitWidth = VT.getScalarSizeInBits();
3686   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3687                                    APInt::getAllOnesValue(BitWidth)))
3688     return DAG.getConstant(0, SDLoc(N), VT);
3689
3690   if (SDValue NewSel = foldBinOpIntoSelect(N))
3691     return NewSel;
3692
3693   // reassociate and
3694   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3695     return RAND;
3696   // fold (and (or x, C), D) -> D if (C & D) == D
3697   if (N1C && N0.getOpcode() == ISD::OR)
3698     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3699       if (N1C->getAPIntValue().isSubsetOf(ORI->getAPIntValue()))
3700         return N1;
3701   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3702   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3703     SDValue N0Op0 = N0.getOperand(0);
3704     APInt Mask = ~N1C->getAPIntValue();
3705     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3706     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3707       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3708                                  N0.getValueType(), N0Op0);
3709
3710       // Replace uses of the AND with uses of the Zero extend node.
3711       CombineTo(N, Zext);
3712
3713       // We actually want to replace all uses of the any_extend with the
3714       // zero_extend, to avoid duplicating things.  This will later cause this
3715       // AND to be folded.
3716       CombineTo(N0.getNode(), Zext);
3717       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3718     }
3719   }
3720   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3721   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3722   // already be zero by virtue of the width of the base type of the load.
3723   //
3724   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3725   // more cases.
3726   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3727        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3728        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3729        N0.getOperand(0).getResNo() == 0) ||
3730       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3731     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3732                                          N0 : N0.getOperand(0) );
3733
3734     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3735     // This can be a pure constant or a vector splat, in which case we treat the
3736     // vector as a scalar and use the splat value.
3737     APInt Constant = APInt::getNullValue(1);
3738     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3739       Constant = C->getAPIntValue();
3740     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3741       APInt SplatValue, SplatUndef;
3742       unsigned SplatBitSize;
3743       bool HasAnyUndefs;
3744       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3745                                              SplatBitSize, HasAnyUndefs);
3746       if (IsSplat) {
3747         // Undef bits can contribute to a possible optimisation if set, so
3748         // set them.
3749         SplatValue |= SplatUndef;
3750
3751         // The splat value may be something like "0x00FFFFFF", which means 0 for
3752         // the first vector value and FF for the rest, repeating. We need a mask
3753         // that will apply equally to all members of the vector, so AND all the
3754         // lanes of the constant together.
3755         EVT VT = Vector->getValueType(0);
3756         unsigned BitWidth = VT.getScalarSizeInBits();
3757
3758         // If the splat value has been compressed to a bitlength lower
3759         // than the size of the vector lane, we need to re-expand it to
3760         // the lane size.
3761         if (BitWidth > SplatBitSize)
3762           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3763                SplatBitSize < BitWidth;
3764                SplatBitSize = SplatBitSize * 2)
3765             SplatValue |= SplatValue.shl(SplatBitSize);
3766
3767         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3768         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3769         if (SplatBitSize % BitWidth == 0) {
3770           Constant = APInt::getAllOnesValue(BitWidth);
3771           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3772             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3773         }
3774       }
3775     }
3776
3777     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3778     // actually legal and isn't going to get expanded, else this is a false
3779     // optimisation.
3780     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3781                                                     Load->getValueType(0),
3782                                                     Load->getMemoryVT());
3783
3784     // Resize the constant to the same size as the original memory access before
3785     // extension. If it is still the AllOnesValue then this AND is completely
3786     // unneeded.
3787     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3788
3789     bool B;
3790     switch (Load->getExtensionType()) {
3791     default: B = false; break;
3792     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3793     case ISD::ZEXTLOAD:
3794     case ISD::NON_EXTLOAD: B = true; break;
3795     }
3796
3797     if (B && Constant.isAllOnesValue()) {
3798       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3799       // preserve semantics once we get rid of the AND.
3800       SDValue NewLoad(Load, 0);
3801
3802       // Fold the AND away. NewLoad may get replaced immediately.
3803       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3804
3805       if (Load->getExtensionType() == ISD::EXTLOAD) {
3806         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3807                               Load->getValueType(0), SDLoc(Load),
3808                               Load->getChain(), Load->getBasePtr(),
3809                               Load->getOffset(), Load->getMemoryVT(),
3810                               Load->getMemOperand());
3811         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3812         if (Load->getNumValues() == 3) {
3813           // PRE/POST_INC loads have 3 values.
3814           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3815                            NewLoad.getValue(2) };
3816           CombineTo(Load, To, 3, true);
3817         } else {
3818           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3819         }
3820       }
3821
3822       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3823     }
3824   }
3825
3826   // fold (and (load x), 255) -> (zextload x, i8)
3827   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3828   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3829   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3830                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3831                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3832     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3833     LoadSDNode *LN0 = HasAnyExt
3834       ? cast<LoadSDNode>(N0.getOperand(0))
3835       : cast<LoadSDNode>(N0);
3836     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3837         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3838       auto NarrowLoad = false;
3839       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3840       EVT ExtVT, LoadedVT;
3841       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3842                            NarrowLoad)) {
3843         if (!NarrowLoad) {
3844           SDValue NewLoad =
3845             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3846                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3847                            LN0->getMemOperand());
3848           AddToWorklist(N);
3849           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3850           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3851         } else {
3852           EVT PtrType = LN0->getOperand(1).getValueType();
3853
3854           unsigned Alignment = LN0->getAlignment();
3855           SDValue NewPtr = LN0->getBasePtr();
3856
3857           // For big endian targets, we need to add an offset to the pointer
3858           // to load the correct bytes.  For little endian systems, we merely
3859           // need to read fewer bytes from the same pointer.
3860           if (DAG.getDataLayout().isBigEndian()) {
3861             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3862             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3863             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3864             SDLoc DL(LN0);
3865             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3866                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3867             Alignment = MinAlign(Alignment, PtrOff);
3868           }
3869
3870           AddToWorklist(NewPtr.getNode());
3871
3872           SDValue Load = DAG.getExtLoad(
3873               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3874               LN0->getPointerInfo(), ExtVT, Alignment,
3875               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3876           AddToWorklist(N);
3877           CombineTo(LN0, Load, Load.getValue(1));
3878           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3879         }
3880       }
3881     }
3882   }
3883
3884   if (SDValue Combined = visitANDLike(N0, N1, N))
3885     return Combined;
3886
3887   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3888   if (N0.getOpcode() == N1.getOpcode())
3889     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3890       return Tmp;
3891
3892   // Masking the negated extension of a boolean is just the zero-extended
3893   // boolean:
3894   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3895   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3896   //
3897   // Note: the SimplifyDemandedBits fold below can make an information-losing
3898   // transform, and then we have no way to find this better fold.
3899   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3900     if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
3901       SDValue SubRHS = N0.getOperand(1);
3902       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3903           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3904         return SubRHS;
3905       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3906           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3907         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3908     }
3909   }
3910
3911   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3912   // fold (and (sra)) -> (and (srl)) when possible.
3913   if (SimplifyDemandedBits(SDValue(N, 0)))
3914     return SDValue(N, 0);
3915
3916   // fold (zext_inreg (extload x)) -> (zextload x)
3917   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3918     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3919     EVT MemVT = LN0->getMemoryVT();
3920     // If we zero all the possible extended bits, then we can turn this into
3921     // a zextload if we are running before legalize or the operation is legal.
3922     unsigned BitWidth = N1.getScalarValueSizeInBits();
3923     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3924                            BitWidth - MemVT.getScalarSizeInBits())) &&
3925         ((!LegalOperations && !LN0->isVolatile()) ||
3926          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3927       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3928                                        LN0->getChain(), LN0->getBasePtr(),
3929                                        MemVT, LN0->getMemOperand());
3930       AddToWorklist(N);
3931       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3932       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3933     }
3934   }
3935   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3936   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3937       N0.hasOneUse()) {
3938     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3939     EVT MemVT = LN0->getMemoryVT();
3940     // If we zero all the possible extended bits, then we can turn this into
3941     // a zextload if we are running before legalize or the operation is legal.
3942     unsigned BitWidth = N1.getScalarValueSizeInBits();
3943     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3944                            BitWidth - MemVT.getScalarSizeInBits())) &&
3945         ((!LegalOperations && !LN0->isVolatile()) ||
3946          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3947       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3948                                        LN0->getChain(), LN0->getBasePtr(),
3949                                        MemVT, LN0->getMemOperand());
3950       AddToWorklist(N);
3951       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3952       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3953     }
3954   }
3955   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3956   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3957     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3958                                            N0.getOperand(1), false))
3959       return BSwap;
3960   }
3961
3962   return SDValue();
3963 }
3964
3965 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3966 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3967                                         bool DemandHighBits) {
3968   if (!LegalOperations)
3969     return SDValue();
3970
3971   EVT VT = N->getValueType(0);
3972   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3973     return SDValue();
3974   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
3975     return SDValue();
3976
3977   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3978   bool LookPassAnd0 = false;
3979   bool LookPassAnd1 = false;
3980   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3981       std::swap(N0, N1);
3982   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3983       std::swap(N0, N1);
3984   if (N0.getOpcode() == ISD::AND) {
3985     if (!N0.getNode()->hasOneUse())
3986       return SDValue();
3987     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3988     if (!N01C || N01C->getZExtValue() != 0xFF00)
3989       return SDValue();
3990     N0 = N0.getOperand(0);
3991     LookPassAnd0 = true;
3992   }
3993
3994   if (N1.getOpcode() == ISD::AND) {
3995     if (!N1.getNode()->hasOneUse())
3996       return SDValue();
3997     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3998     if (!N11C || N11C->getZExtValue() != 0xFF)
3999       return SDValue();
4000     N1 = N1.getOperand(0);
4001     LookPassAnd1 = true;
4002   }
4003
4004   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
4005     std::swap(N0, N1);
4006   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
4007     return SDValue();
4008   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4009     return SDValue();
4010
4011   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4012   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4013   if (!N01C || !N11C)
4014     return SDValue();
4015   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4016     return SDValue();
4017
4018   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4019   SDValue N00 = N0->getOperand(0);
4020   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4021     if (!N00.getNode()->hasOneUse())
4022       return SDValue();
4023     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4024     if (!N001C || N001C->getZExtValue() != 0xFF)
4025       return SDValue();
4026     N00 = N00.getOperand(0);
4027     LookPassAnd0 = true;
4028   }
4029
4030   SDValue N10 = N1->getOperand(0);
4031   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4032     if (!N10.getNode()->hasOneUse())
4033       return SDValue();
4034     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4035     if (!N101C || N101C->getZExtValue() != 0xFF00)
4036       return SDValue();
4037     N10 = N10.getOperand(0);
4038     LookPassAnd1 = true;
4039   }
4040
4041   if (N00 != N10)
4042     return SDValue();
4043
4044   // Make sure everything beyond the low halfword gets set to zero since the SRL
4045   // 16 will clear the top bits.
4046   unsigned OpSizeInBits = VT.getSizeInBits();
4047   if (DemandHighBits && OpSizeInBits > 16) {
4048     // If the left-shift isn't masked out then the only way this is a bswap is
4049     // if all bits beyond the low 8 are 0. In that case the entire pattern
4050     // reduces to a left shift anyway: leave it for other parts of the combiner.
4051     if (!LookPassAnd0)
4052       return SDValue();
4053
4054     // However, if the right shift isn't masked out then it might be because
4055     // it's not needed. See if we can spot that too.
4056     if (!LookPassAnd1 &&
4057         !DAG.MaskedValueIsZero(
4058             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4059       return SDValue();
4060   }
4061
4062   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4063   if (OpSizeInBits > 16) {
4064     SDLoc DL(N);
4065     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4066                       DAG.getConstant(OpSizeInBits - 16, DL,
4067                                       getShiftAmountTy(VT)));
4068   }
4069   return Res;
4070 }
4071
4072 /// Return true if the specified node is an element that makes up a 32-bit
4073 /// packed halfword byteswap.
4074 /// ((x & 0x000000ff) << 8) |
4075 /// ((x & 0x0000ff00) >> 8) |
4076 /// ((x & 0x00ff0000) << 8) |
4077 /// ((x & 0xff000000) >> 8)
4078 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4079   if (!N.getNode()->hasOneUse())
4080     return false;
4081
4082   unsigned Opc = N.getOpcode();
4083   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4084     return false;
4085
4086   SDValue N0 = N.getOperand(0);
4087   unsigned Opc0 = N0.getOpcode();
4088   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4089     return false;
4090
4091   ConstantSDNode *N1C = nullptr;
4092   // SHL or SRL: look upstream for AND mask operand
4093   if (Opc == ISD::AND)
4094     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4095   else if (Opc0 == ISD::AND)
4096     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4097   if (!N1C)
4098     return false;
4099
4100   unsigned MaskByteOffset;
4101   switch (N1C->getZExtValue()) {
4102   default:
4103     return false;
4104   case 0xFF:       MaskByteOffset = 0; break;
4105   case 0xFF00:     MaskByteOffset = 1; break;
4106   case 0xFF0000:   MaskByteOffset = 2; break;
4107   case 0xFF000000: MaskByteOffset = 3; break;
4108   }
4109
4110   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4111   if (Opc == ISD::AND) {
4112     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4113       // (x >> 8) & 0xff
4114       // (x >> 8) & 0xff0000
4115       if (Opc0 != ISD::SRL)
4116         return false;
4117       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4118       if (!C || C->getZExtValue() != 8)
4119         return false;
4120     } else {
4121       // (x << 8) & 0xff00
4122       // (x << 8) & 0xff000000
4123       if (Opc0 != ISD::SHL)
4124         return false;
4125       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4126       if (!C || C->getZExtValue() != 8)
4127         return false;
4128     }
4129   } else if (Opc == ISD::SHL) {
4130     // (x & 0xff) << 8
4131     // (x & 0xff0000) << 8
4132     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4133       return false;
4134     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4135     if (!C || C->getZExtValue() != 8)
4136       return false;
4137   } else { // Opc == ISD::SRL
4138     // (x & 0xff00) >> 8
4139     // (x & 0xff000000) >> 8
4140     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4141       return false;
4142     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4143     if (!C || C->getZExtValue() != 8)
4144       return false;
4145   }
4146
4147   if (Parts[MaskByteOffset])
4148     return false;
4149
4150   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4151   return true;
4152 }
4153
4154 /// Match a 32-bit packed halfword bswap. That is
4155 /// ((x & 0x000000ff) << 8) |
4156 /// ((x & 0x0000ff00) >> 8) |
4157 /// ((x & 0x00ff0000) << 8) |
4158 /// ((x & 0xff000000) >> 8)
4159 /// => (rotl (bswap x), 16)
4160 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4161   if (!LegalOperations)
4162     return SDValue();
4163
4164   EVT VT = N->getValueType(0);
4165   if (VT != MVT::i32)
4166     return SDValue();
4167   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4168     return SDValue();
4169
4170   // Look for either
4171   // (or (or (and), (and)), (or (and), (and)))
4172   // (or (or (or (and), (and)), (and)), (and))
4173   if (N0.getOpcode() != ISD::OR)
4174     return SDValue();
4175   SDValue N00 = N0.getOperand(0);
4176   SDValue N01 = N0.getOperand(1);
4177   SDNode *Parts[4] = {};
4178
4179   if (N1.getOpcode() == ISD::OR &&
4180       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4181     // (or (or (and), (and)), (or (and), (and)))
4182     if (!isBSwapHWordElement(N00, Parts))
4183       return SDValue();
4184
4185     if (!isBSwapHWordElement(N01, Parts))
4186       return SDValue();
4187     SDValue N10 = N1.getOperand(0);
4188     if (!isBSwapHWordElement(N10, Parts))
4189       return SDValue();
4190     SDValue N11 = N1.getOperand(1);
4191     if (!isBSwapHWordElement(N11, Parts))
4192       return SDValue();
4193   } else {
4194     // (or (or (or (and), (and)), (and)), (and))
4195     if (!isBSwapHWordElement(N1, Parts))
4196       return SDValue();
4197     if (!isBSwapHWordElement(N01, Parts))
4198       return SDValue();
4199     if (N00.getOpcode() != ISD::OR)
4200       return SDValue();
4201     SDValue N000 = N00.getOperand(0);
4202     if (!isBSwapHWordElement(N000, Parts))
4203       return SDValue();
4204     SDValue N001 = N00.getOperand(1);
4205     if (!isBSwapHWordElement(N001, Parts))
4206       return SDValue();
4207   }
4208
4209   // Make sure the parts are all coming from the same node.
4210   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4211     return SDValue();
4212
4213   SDLoc DL(N);
4214   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4215                               SDValue(Parts[0], 0));
4216
4217   // Result of the bswap should be rotated by 16. If it's not legal, then
4218   // do  (x << 16) | (x >> 16).
4219   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4220   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4221     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4222   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4223     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4224   return DAG.getNode(ISD::OR, DL, VT,
4225                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4226                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4227 }
4228
4229 /// This contains all DAGCombine rules which reduce two values combined by
4230 /// an Or operation to a single value \see visitANDLike().
4231 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4232   EVT VT = N1.getValueType();
4233   SDLoc DL(N);
4234
4235   // fold (or x, undef) -> -1
4236   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4237     return DAG.getAllOnesConstant(DL, VT);
4238
4239   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4240     return V;
4241
4242   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4243   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4244       // Don't increase # computations.
4245       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4246     // We can only do this xform if we know that bits from X that are set in C2
4247     // but not in C1 are already zero.  Likewise for Y.
4248     if (const ConstantSDNode *N0O1C =
4249         getAsNonOpaqueConstant(N0.getOperand(1))) {
4250       if (const ConstantSDNode *N1O1C =
4251           getAsNonOpaqueConstant(N1.getOperand(1))) {
4252         // We can only do this xform if we know that bits from X that are set in
4253         // C2 but not in C1 are already zero.  Likewise for Y.
4254         const APInt &LHSMask = N0O1C->getAPIntValue();
4255         const APInt &RHSMask = N1O1C->getAPIntValue();
4256
4257         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4258             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4259           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4260                                   N0.getOperand(0), N1.getOperand(0));
4261           return DAG.getNode(ISD::AND, DL, VT, X,
4262                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4263         }
4264       }
4265     }
4266   }
4267
4268   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4269   if (N0.getOpcode() == ISD::AND &&
4270       N1.getOpcode() == ISD::AND &&
4271       N0.getOperand(0) == N1.getOperand(0) &&
4272       // Don't increase # computations.
4273       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4274     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4275                             N0.getOperand(1), N1.getOperand(1));
4276     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4277   }
4278
4279   return SDValue();
4280 }
4281
4282 SDValue DAGCombiner::visitOR(SDNode *N) {
4283   SDValue N0 = N->getOperand(0);
4284   SDValue N1 = N->getOperand(1);
4285   EVT VT = N1.getValueType();
4286
4287   // x | x --> x
4288   if (N0 == N1)
4289     return N0;
4290
4291   // fold vector ops
4292   if (VT.isVector()) {
4293     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4294       return FoldedVOp;
4295
4296     // fold (or x, 0) -> x, vector edition
4297     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4298       return N1;
4299     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4300       return N0;
4301
4302     // fold (or x, -1) -> -1, vector edition
4303     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4304       // do not return N0, because undef node may exist in N0
4305       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4306     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4307       // do not return N1, because undef node may exist in N1
4308       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4309
4310     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4311     // Do this only if the resulting shuffle is legal.
4312     if (isa<ShuffleVectorSDNode>(N0) &&
4313         isa<ShuffleVectorSDNode>(N1) &&
4314         // Avoid folding a node with illegal type.
4315         TLI.isTypeLegal(VT)) {
4316       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4317       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4318       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4319       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4320       // Ensure both shuffles have a zero input.
4321       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4322         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4323         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4324         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4325         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4326         bool CanFold = true;
4327         int NumElts = VT.getVectorNumElements();
4328         SmallVector<int, 4> Mask(NumElts);
4329
4330         for (int i = 0; i != NumElts; ++i) {
4331           int M0 = SV0->getMaskElt(i);
4332           int M1 = SV1->getMaskElt(i);
4333
4334           // Determine if either index is pointing to a zero vector.
4335           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4336           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4337
4338           // If one element is zero and the otherside is undef, keep undef.
4339           // This also handles the case that both are undef.
4340           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4341             Mask[i] = -1;
4342             continue;
4343           }
4344
4345           // Make sure only one of the elements is zero.
4346           if (M0Zero == M1Zero) {
4347             CanFold = false;
4348             break;
4349           }
4350
4351           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4352
4353           // We have a zero and non-zero element. If the non-zero came from
4354           // SV0 make the index a LHS index. If it came from SV1, make it
4355           // a RHS index. We need to mod by NumElts because we don't care
4356           // which operand it came from in the original shuffles.
4357           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4358         }
4359
4360         if (CanFold) {
4361           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4362           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4363
4364           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4365           if (!LegalMask) {
4366             std::swap(NewLHS, NewRHS);
4367             ShuffleVectorSDNode::commuteMask(Mask);
4368             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4369           }
4370
4371           if (LegalMask)
4372             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4373         }
4374       }
4375     }
4376   }
4377
4378   // fold (or c1, c2) -> c1|c2
4379   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4380   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4381   if (N0C && N1C && !N1C->isOpaque())
4382     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4383   // canonicalize constant to RHS
4384   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4385      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4386     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4387   // fold (or x, 0) -> x
4388   if (isNullConstant(N1))
4389     return N0;
4390   // fold (or x, -1) -> -1
4391   if (isAllOnesConstant(N1))
4392     return N1;
4393
4394   if (SDValue NewSel = foldBinOpIntoSelect(N))
4395     return NewSel;
4396
4397   // fold (or x, c) -> c iff (x & ~c) == 0
4398   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4399     return N1;
4400
4401   if (SDValue Combined = visitORLike(N0, N1, N))
4402     return Combined;
4403
4404   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4405   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4406     return BSwap;
4407   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4408     return BSwap;
4409
4410   // reassociate or
4411   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4412     return ROR;
4413
4414   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4415   // iff (c1 & c2) != 0.
4416   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4417     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4418       if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4419         if (SDValue COR =
4420                 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4421           return DAG.getNode(
4422               ISD::AND, SDLoc(N), VT,
4423               DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4424         return SDValue();
4425       }
4426     }
4427   }
4428
4429   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4430   if (N0.getOpcode() == N1.getOpcode())
4431     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4432       return Tmp;
4433
4434   // See if this is some rotate idiom.
4435   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4436     return SDValue(Rot, 0);
4437
4438   if (SDValue Load = MatchLoadCombine(N))
4439     return Load;
4440
4441   // Simplify the operands using demanded-bits information.
4442   if (SimplifyDemandedBits(SDValue(N, 0)))
4443     return SDValue(N, 0);
4444
4445   return SDValue();
4446 }
4447
4448 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4449 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4450   if (Op.getOpcode() == ISD::AND) {
4451     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4452       Mask = Op.getOperand(1);
4453       Op = Op.getOperand(0);
4454     } else {
4455       return false;
4456     }
4457   }
4458
4459   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4460     Shift = Op;
4461     return true;
4462   }
4463
4464   return false;
4465 }
4466
4467 // Return true if we can prove that, whenever Neg and Pos are both in the
4468 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4469 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4470 //
4471 //     (or (shift1 X, Neg), (shift2 X, Pos))
4472 //
4473 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4474 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4475 // to consider shift amounts with defined behavior.
4476 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4477   // If EltSize is a power of 2 then:
4478   //
4479   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4480   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4481   //
4482   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4483   // for the stronger condition:
4484   //
4485   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4486   //
4487   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4488   // we can just replace Neg with Neg' for the rest of the function.
4489   //
4490   // In other cases we check for the even stronger condition:
4491   //
4492   //     Neg == EltSize - Pos                                    [B]
4493   //
4494   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4495   // behavior if Pos == 0 (and consequently Neg == EltSize).
4496   //
4497   // We could actually use [A] whenever EltSize is a power of 2, but the
4498   // only extra cases that it would match are those uninteresting ones
4499   // where Neg and Pos are never in range at the same time.  E.g. for
4500   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4501   // as well as (sub 32, Pos), but:
4502   //
4503   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4504   //
4505   // always invokes undefined behavior for 32-bit X.
4506   //
4507   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4508   unsigned MaskLoBits = 0;
4509   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4510     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4511       if (NegC->getAPIntValue() == EltSize - 1) {
4512         Neg = Neg.getOperand(0);
4513         MaskLoBits = Log2_64(EltSize);
4514       }
4515     }
4516   }
4517
4518   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4519   if (Neg.getOpcode() != ISD::SUB)
4520     return false;
4521   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4522   if (!NegC)
4523     return false;
4524   SDValue NegOp1 = Neg.getOperand(1);
4525
4526   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4527   // Pos'.  The truncation is redundant for the purpose of the equality.
4528   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4529     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4530       if (PosC->getAPIntValue() == EltSize - 1)
4531         Pos = Pos.getOperand(0);
4532
4533   // The condition we need is now:
4534   //
4535   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4536   //
4537   // If NegOp1 == Pos then we need:
4538   //
4539   //              EltSize & Mask == NegC & Mask
4540   //
4541   // (because "x & Mask" is a truncation and distributes through subtraction).
4542   APInt Width;
4543   if (Pos == NegOp1)
4544     Width = NegC->getAPIntValue();
4545
4546   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4547   // Then the condition we want to prove becomes:
4548   //
4549   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4550   //
4551   // which, again because "x & Mask" is a truncation, becomes:
4552   //
4553   //                NegC & Mask == (EltSize - PosC) & Mask
4554   //             EltSize & Mask == (NegC + PosC) & Mask
4555   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4556     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4557       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4558     else
4559       return false;
4560   } else
4561     return false;
4562
4563   // Now we just need to check that EltSize & Mask == Width & Mask.
4564   if (MaskLoBits)
4565     // EltSize & Mask is 0 since Mask is EltSize - 1.
4566     return Width.getLoBits(MaskLoBits) == 0;
4567   return Width == EltSize;
4568 }
4569
4570 // A subroutine of MatchRotate used once we have found an OR of two opposite
4571 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4572 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4573 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4574 // Neg with outer conversions stripped away.
4575 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4576                                        SDValue Neg, SDValue InnerPos,
4577                                        SDValue InnerNeg, unsigned PosOpcode,
4578                                        unsigned NegOpcode, const SDLoc &DL) {
4579   // fold (or (shl x, (*ext y)),
4580   //          (srl x, (*ext (sub 32, y)))) ->
4581   //   (rotl x, y) or (rotr x, (sub 32, y))
4582   //
4583   // fold (or (shl x, (*ext (sub 32, y))),
4584   //          (srl x, (*ext y))) ->
4585   //   (rotr x, y) or (rotl x, (sub 32, y))
4586   EVT VT = Shifted.getValueType();
4587   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4588     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4589     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4590                        HasPos ? Pos : Neg).getNode();
4591   }
4592
4593   return nullptr;
4594 }
4595
4596 // if Left + Right == Sum (constant or constant splat vector)
4597 static bool sumMatchConstant(SDValue Left, SDValue Right, unsigned Sum,
4598                              SelectionDAG &DAG, const SDLoc &DL) {
4599   EVT ShiftVT = Left.getValueType();
4600   if (ShiftVT != Right.getValueType()) return false;
4601
4602   SDValue ShiftSum = DAG.FoldConstantArithmetic(ISD::ADD, DL, ShiftVT,
4603                          Left.getNode(), Right.getNode());
4604   if (!ShiftSum) return false;
4605
4606   ConstantSDNode *CSum = isConstOrConstSplat(ShiftSum);
4607   return CSum && CSum->getZExtValue() == Sum;
4608 }
4609
4610 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4611 // idioms for rotate, and if the target supports rotation instructions, generate
4612 // a rot[lr].
4613 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4614   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4615   EVT VT = LHS.getValueType();
4616   if (!TLI.isTypeLegal(VT)) return nullptr;
4617
4618   // The target must have at least one rotate flavor.
4619   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4620   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4621   if (!HasROTL && !HasROTR) return nullptr;
4622
4623   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4624   SDValue LHSShift;   // The shift.
4625   SDValue LHSMask;    // AND value if any.
4626   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4627     return nullptr; // Not part of a rotate.
4628
4629   SDValue RHSShift;   // The shift.
4630   SDValue RHSMask;    // AND value if any.
4631   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4632     return nullptr; // Not part of a rotate.
4633
4634   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4635     return nullptr;   // Not shifting the same value.
4636
4637   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4638     return nullptr;   // Shifts must disagree.
4639
4640   // Canonicalize shl to left side in a shl/srl pair.
4641   if (RHSShift.getOpcode() == ISD::SHL) {
4642     std::swap(LHS, RHS);
4643     std::swap(LHSShift, RHSShift);
4644     std::swap(LHSMask, RHSMask);
4645   }
4646
4647   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4648   SDValue LHSShiftArg = LHSShift.getOperand(0);
4649   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4650   SDValue RHSShiftArg = RHSShift.getOperand(0);
4651   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4652
4653   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4654   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4655   if (sumMatchConstant(LHSShiftAmt, RHSShiftAmt, EltSizeInBits, DAG, DL)) {
4656     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4657                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4658
4659     // If there is an AND of either shifted operand, apply it to the result.
4660     if (LHSMask.getNode() || RHSMask.getNode()) {
4661       SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
4662       SDValue Mask = AllOnes;
4663
4664       if (LHSMask.getNode()) {
4665         SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
4666         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4667                            DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
4668       }
4669       if (RHSMask.getNode()) {
4670         SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
4671         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4672                            DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
4673       }
4674
4675       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4676     }
4677
4678     return Rot.getNode();
4679   }
4680
4681   // If there is a mask here, and we have a variable shift, we can't be sure
4682   // that we're masking out the right stuff.
4683   if (LHSMask.getNode() || RHSMask.getNode())
4684     return nullptr;
4685
4686   // If the shift amount is sign/zext/any-extended just peel it off.
4687   SDValue LExtOp0 = LHSShiftAmt;
4688   SDValue RExtOp0 = RHSShiftAmt;
4689   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4690        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4691        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4692        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4693       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4694        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4695        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4696        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4697     LExtOp0 = LHSShiftAmt.getOperand(0);
4698     RExtOp0 = RHSShiftAmt.getOperand(0);
4699   }
4700
4701   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4702                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4703   if (TryL)
4704     return TryL;
4705
4706   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4707                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4708   if (TryR)
4709     return TryR;
4710
4711   return nullptr;
4712 }
4713
4714 namespace {
4715 /// Represents known origin of an individual byte in load combine pattern. The
4716 /// value of the byte is either constant zero or comes from memory.
4717 struct ByteProvider {
4718   // For constant zero providers Load is set to nullptr. For memory providers
4719   // Load represents the node which loads the byte from memory.
4720   // ByteOffset is the offset of the byte in the value produced by the load.
4721   LoadSDNode *Load;
4722   unsigned ByteOffset;
4723
4724   ByteProvider() : Load(nullptr), ByteOffset(0) {}
4725
4726   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4727     return ByteProvider(Load, ByteOffset);
4728   }
4729   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4730
4731   bool isConstantZero() const { return !Load; }
4732   bool isMemory() const { return Load; }
4733
4734   bool operator==(const ByteProvider &Other) const {
4735     return Other.Load == Load && Other.ByteOffset == ByteOffset;
4736   }
4737
4738 private:
4739   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4740       : Load(Load), ByteOffset(ByteOffset) {}
4741 };
4742
4743 /// Recursively traverses the expression calculating the origin of the requested
4744 /// byte of the given value. Returns None if the provider can't be calculated.
4745 ///
4746 /// For all the values except the root of the expression verifies that the value
4747 /// has exactly one use and if it's not true return None. This way if the origin
4748 /// of the byte is returned it's guaranteed that the values which contribute to
4749 /// the byte are not used outside of this expression.
4750 ///
4751 /// Because the parts of the expression are not allowed to have more than one
4752 /// use this function iterates over trees, not DAGs. So it never visits the same
4753 /// node more than once.
4754 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4755                                                    unsigned Depth,
4756                                                    bool Root = false) {
4757   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4758   if (Depth == 10)
4759     return None;
4760
4761   if (!Root && !Op.hasOneUse())
4762     return None;
4763
4764   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4765   unsigned BitWidth = Op.getValueSizeInBits();
4766   if (BitWidth % 8 != 0)
4767     return None;
4768   unsigned ByteWidth = BitWidth / 8;
4769   assert(Index < ByteWidth && "invalid index requested");
4770   (void) ByteWidth;
4771
4772   switch (Op.getOpcode()) {
4773   case ISD::OR: {
4774     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4775     if (!LHS)
4776       return None;
4777     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4778     if (!RHS)
4779       return None;
4780
4781     if (LHS->isConstantZero())
4782       return RHS;
4783     if (RHS->isConstantZero())
4784       return LHS;
4785     return None;
4786   }
4787   case ISD::SHL: {
4788     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4789     if (!ShiftOp)
4790       return None;
4791
4792     uint64_t BitShift = ShiftOp->getZExtValue();
4793     if (BitShift % 8 != 0)
4794       return None;
4795     uint64_t ByteShift = BitShift / 8;
4796
4797     return Index < ByteShift
4798                ? ByteProvider::getConstantZero()
4799                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4800                                        Depth + 1);
4801   }
4802   case ISD::ANY_EXTEND:
4803   case ISD::SIGN_EXTEND:
4804   case ISD::ZERO_EXTEND: {
4805     SDValue NarrowOp = Op->getOperand(0);
4806     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4807     if (NarrowBitWidth % 8 != 0)
4808       return None;
4809     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4810
4811     if (Index >= NarrowByteWidth)
4812       return Op.getOpcode() == ISD::ZERO_EXTEND
4813                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4814                  : None;
4815     return calculateByteProvider(NarrowOp, Index, Depth + 1);
4816   }
4817   case ISD::BSWAP:
4818     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4819                                  Depth + 1);
4820   case ISD::LOAD: {
4821     auto L = cast<LoadSDNode>(Op.getNode());
4822     if (L->isVolatile() || L->isIndexed())
4823       return None;
4824
4825     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4826     if (NarrowBitWidth % 8 != 0)
4827       return None;
4828     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4829
4830     if (Index >= NarrowByteWidth)
4831       return L->getExtensionType() == ISD::ZEXTLOAD
4832                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4833                  : None;
4834     return ByteProvider::getMemory(L, Index);
4835   }
4836   }
4837
4838   return None;
4839 }
4840 } // namespace
4841
4842 /// Match a pattern where a wide type scalar value is loaded by several narrow
4843 /// loads and combined by shifts and ors. Fold it into a single load or a load
4844 /// and a BSWAP if the targets supports it.
4845 ///
4846 /// Assuming little endian target:
4847 ///  i8 *a = ...
4848 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4849 /// =>
4850 ///  i32 val = *((i32)a)
4851 ///
4852 ///  i8 *a = ...
4853 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4854 /// =>
4855 ///  i32 val = BSWAP(*((i32)a))
4856 ///
4857 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4858 /// interact well with the worklist mechanism. When a part of the pattern is
4859 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4860 /// but the root node of the pattern which triggers the load combine is not
4861 /// necessarily a direct user of the changed node. For example, once the address
4862 /// of t28 load is reassociated load combine won't be triggered:
4863 ///             t25: i32 = add t4, Constant:i32<2>
4864 ///           t26: i64 = sign_extend t25
4865 ///        t27: i64 = add t2, t26
4866 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4867 ///     t29: i32 = zero_extend t28
4868 ///   t32: i32 = shl t29, Constant:i8<8>
4869 /// t33: i32 = or t23, t32
4870 /// As a possible fix visitLoad can check if the load can be a part of a load
4871 /// combine pattern and add corresponding OR roots to the worklist.
4872 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4873   assert(N->getOpcode() == ISD::OR &&
4874          "Can only match load combining against OR nodes");
4875
4876   // Handles simple types only
4877   EVT VT = N->getValueType(0);
4878   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4879     return SDValue();
4880   unsigned ByteWidth = VT.getSizeInBits() / 8;
4881
4882   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4883   // Before legalize we can introduce too wide illegal loads which will be later
4884   // split into legal sized loads. This enables us to combine i64 load by i8
4885   // patterns to a couple of i32 loads on 32 bit targets.
4886   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4887     return SDValue();
4888
4889   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4890     unsigned BW, unsigned i) { return i; };
4891   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4892     unsigned BW, unsigned i) { return BW - i - 1; };
4893
4894   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4895   auto MemoryByteOffset = [&] (ByteProvider P) {
4896     assert(P.isMemory() && "Must be a memory byte provider");
4897     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4898     assert(LoadBitWidth % 8 == 0 &&
4899            "can only analyze providers for individual bytes not bit");
4900     unsigned LoadByteWidth = LoadBitWidth / 8;
4901     return IsBigEndianTarget
4902             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4903             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4904   };
4905
4906   Optional<BaseIndexOffset> Base;
4907   SDValue Chain;
4908
4909   SmallSet<LoadSDNode *, 8> Loads;
4910   Optional<ByteProvider> FirstByteProvider;
4911   int64_t FirstOffset = INT64_MAX;
4912
4913   // Check if all the bytes of the OR we are looking at are loaded from the same
4914   // base address. Collect bytes offsets from Base address in ByteOffsets.
4915   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4916   for (unsigned i = 0; i < ByteWidth; i++) {
4917     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4918     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4919       return SDValue();
4920
4921     LoadSDNode *L = P->Load;
4922     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4923            "Must be enforced by calculateByteProvider");
4924     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4925
4926     // All loads must share the same chain
4927     SDValue LChain = L->getChain();
4928     if (!Chain)
4929       Chain = LChain;
4930     else if (Chain != LChain)
4931       return SDValue();
4932
4933     // Loads must share the same base address
4934     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4935     int64_t ByteOffsetFromBase = 0;
4936     if (!Base)
4937       Base = Ptr;
4938     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
4939       return SDValue();
4940
4941     // Calculate the offset of the current byte from the base address
4942     ByteOffsetFromBase += MemoryByteOffset(*P);
4943     ByteOffsets[i] = ByteOffsetFromBase;
4944
4945     // Remember the first byte load
4946     if (ByteOffsetFromBase < FirstOffset) {
4947       FirstByteProvider = P;
4948       FirstOffset = ByteOffsetFromBase;
4949     }
4950
4951     Loads.insert(L);
4952   }
4953   assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4954          "memory, so there must be at least one load which produces the value");
4955   assert(Base && "Base address of the accessed memory location must be set");
4956   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
4957
4958   // Check if the bytes of the OR we are looking at match with either big or
4959   // little endian value load
4960   bool BigEndian = true, LittleEndian = true;
4961   for (unsigned i = 0; i < ByteWidth; i++) {
4962     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
4963     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
4964     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
4965     if (!BigEndian && !LittleEndian)
4966       return SDValue();
4967   }
4968   assert((BigEndian != LittleEndian) && "should be either or");
4969   assert(FirstByteProvider && "must be set");
4970
4971   // Ensure that the first byte is loaded from zero offset of the first load.
4972   // So the combined value can be loaded from the first load address.
4973   if (MemoryByteOffset(*FirstByteProvider) != 0)
4974     return SDValue();
4975   LoadSDNode *FirstLoad = FirstByteProvider->Load;
4976
4977   // The node we are looking at matches with the pattern, check if we can
4978   // replace it with a single load and bswap if needed.
4979
4980   // If the load needs byte swap check if the target supports it
4981   bool NeedsBswap = IsBigEndianTarget != BigEndian;
4982
4983   // Before legalize we can introduce illegal bswaps which will be later
4984   // converted to an explicit bswap sequence. This way we end up with a single
4985   // load and byte shuffling instead of several loads and byte shuffling.
4986   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
4987     return SDValue();
4988
4989   // Check that a load of the wide type is both allowed and fast on the target
4990   bool Fast = false;
4991   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
4992                                         VT, FirstLoad->getAddressSpace(),
4993                                         FirstLoad->getAlignment(), &Fast);
4994   if (!Allowed || !Fast)
4995     return SDValue();
4996
4997   SDValue NewLoad =
4998       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
4999                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
5000
5001   // Transfer chain users from old loads to the new load.
5002   for (LoadSDNode *L : Loads)
5003     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
5004
5005   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5006 }
5007
5008 SDValue DAGCombiner::visitXOR(SDNode *N) {
5009   SDValue N0 = N->getOperand(0);
5010   SDValue N1 = N->getOperand(1);
5011   EVT VT = N0.getValueType();
5012
5013   // fold vector ops
5014   if (VT.isVector()) {
5015     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5016       return FoldedVOp;
5017
5018     // fold (xor x, 0) -> x, vector edition
5019     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5020       return N1;
5021     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5022       return N0;
5023   }
5024
5025   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5026   if (N0.isUndef() && N1.isUndef())
5027     return DAG.getConstant(0, SDLoc(N), VT);
5028   // fold (xor x, undef) -> undef
5029   if (N0.isUndef())
5030     return N0;
5031   if (N1.isUndef())
5032     return N1;
5033   // fold (xor c1, c2) -> c1^c2
5034   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5035   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5036   if (N0C && N1C)
5037     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5038   // canonicalize constant to RHS
5039   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5040      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5041     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5042   // fold (xor x, 0) -> x
5043   if (isNullConstant(N1))
5044     return N0;
5045
5046   if (SDValue NewSel = foldBinOpIntoSelect(N))
5047     return NewSel;
5048
5049   // reassociate xor
5050   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5051     return RXOR;
5052
5053   // fold !(x cc y) -> (x !cc y)
5054   SDValue LHS, RHS, CC;
5055   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5056     bool isInt = LHS.getValueType().isInteger();
5057     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5058                                                isInt);
5059
5060     if (!LegalOperations ||
5061         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5062       switch (N0.getOpcode()) {
5063       default:
5064         llvm_unreachable("Unhandled SetCC Equivalent!");
5065       case ISD::SETCC:
5066         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5067       case ISD::SELECT_CC:
5068         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5069                                N0.getOperand(3), NotCC);
5070       }
5071     }
5072   }
5073
5074   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5075   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5076       N0.getNode()->hasOneUse() &&
5077       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5078     SDValue V = N0.getOperand(0);
5079     SDLoc DL(N0);
5080     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5081                     DAG.getConstant(1, DL, V.getValueType()));
5082     AddToWorklist(V.getNode());
5083     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5084   }
5085
5086   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5087   if (isOneConstant(N1) && VT == MVT::i1 &&
5088       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5089     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5090     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5091       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5092       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5093       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5094       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5095       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5096     }
5097   }
5098   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5099   if (isAllOnesConstant(N1) &&
5100       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5101     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5102     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5103       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5104       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5105       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5106       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5107       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5108     }
5109   }
5110   // fold (xor (and x, y), y) -> (and (not x), y)
5111   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5112       N0->getOperand(1) == N1) {
5113     SDValue X = N0->getOperand(0);
5114     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5115     AddToWorklist(NotX.getNode());
5116     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5117   }
5118   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5119   if (N1C && N0.getOpcode() == ISD::XOR) {
5120     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5121       SDLoc DL(N);
5122       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5123                          DAG.getConstant(N1C->getAPIntValue() ^
5124                                          N00C->getAPIntValue(), DL, VT));
5125     }
5126     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5127       SDLoc DL(N);
5128       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5129                          DAG.getConstant(N1C->getAPIntValue() ^
5130                                          N01C->getAPIntValue(), DL, VT));
5131     }
5132   }
5133
5134   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5135   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5136   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5137       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5138       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5139     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5140       if (C->getAPIntValue() == (OpSizeInBits - 1))
5141         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5142   }
5143
5144   // fold (xor x, x) -> 0
5145   if (N0 == N1)
5146     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5147
5148   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5149   // Here is a concrete example of this equivalence:
5150   // i16   x ==  14
5151   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5152   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5153   //
5154   // =>
5155   //
5156   // i16     ~1      == 0b1111111111111110
5157   // i16 rol(~1, 14) == 0b1011111111111111
5158   //
5159   // Some additional tips to help conceptualize this transform:
5160   // - Try to see the operation as placing a single zero in a value of all ones.
5161   // - There exists no value for x which would allow the result to contain zero.
5162   // - Values of x larger than the bitwidth are undefined and do not require a
5163   //   consistent result.
5164   // - Pushing the zero left requires shifting one bits in from the right.
5165   // A rotate left of ~1 is a nice way of achieving the desired result.
5166   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5167       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5168     SDLoc DL(N);
5169     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5170                        N0.getOperand(1));
5171   }
5172
5173   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5174   if (N0.getOpcode() == N1.getOpcode())
5175     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5176       return Tmp;
5177
5178   // Simplify the expression using non-local knowledge.
5179   if (SimplifyDemandedBits(SDValue(N, 0)))
5180     return SDValue(N, 0);
5181
5182   return SDValue();
5183 }
5184
5185 /// Handle transforms common to the three shifts, when the shift amount is a
5186 /// constant.
5187 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5188   SDNode *LHS = N->getOperand(0).getNode();
5189   if (!LHS->hasOneUse()) return SDValue();
5190
5191   // We want to pull some binops through shifts, so that we have (and (shift))
5192   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5193   // thing happens with address calculations, so it's important to canonicalize
5194   // it.
5195   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5196
5197   switch (LHS->getOpcode()) {
5198   default: return SDValue();
5199   case ISD::OR:
5200   case ISD::XOR:
5201     HighBitSet = false; // We can only transform sra if the high bit is clear.
5202     break;
5203   case ISD::AND:
5204     HighBitSet = true;  // We can only transform sra if the high bit is set.
5205     break;
5206   case ISD::ADD:
5207     if (N->getOpcode() != ISD::SHL)
5208       return SDValue(); // only shl(add) not sr[al](add).
5209     HighBitSet = false; // We can only transform sra if the high bit is clear.
5210     break;
5211   }
5212
5213   // We require the RHS of the binop to be a constant and not opaque as well.
5214   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5215   if (!BinOpCst) return SDValue();
5216
5217   // FIXME: disable this unless the input to the binop is a shift by a constant
5218   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5219   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5220   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5221                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5222                  BinOpLHSVal->getOpcode() == ISD::SRL;
5223   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5224                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5225
5226   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5227       !isCopyOrSelect)
5228     return SDValue();
5229
5230   if (isCopyOrSelect && N->hasOneUse())
5231     return SDValue();
5232
5233   EVT VT = N->getValueType(0);
5234
5235   // If this is a signed shift right, and the high bit is modified by the
5236   // logical operation, do not perform the transformation. The highBitSet
5237   // boolean indicates the value of the high bit of the constant which would
5238   // cause it to be modified for this operation.
5239   if (N->getOpcode() == ISD::SRA) {
5240     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5241     if (BinOpRHSSignSet != HighBitSet)
5242       return SDValue();
5243   }
5244
5245   if (!TLI.isDesirableToCommuteWithShift(LHS))
5246     return SDValue();
5247
5248   // Fold the constants, shifting the binop RHS by the shift amount.
5249   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5250                                N->getValueType(0),
5251                                LHS->getOperand(1), N->getOperand(1));
5252   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5253
5254   // Create the new shift.
5255   SDValue NewShift = DAG.getNode(N->getOpcode(),
5256                                  SDLoc(LHS->getOperand(0)),
5257                                  VT, LHS->getOperand(0), N->getOperand(1));
5258
5259   // Create the new binop.
5260   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5261 }
5262
5263 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5264   assert(N->getOpcode() == ISD::TRUNCATE);
5265   assert(N->getOperand(0).getOpcode() == ISD::AND);
5266
5267   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5268   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5269     SDValue N01 = N->getOperand(0).getOperand(1);
5270     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5271       SDLoc DL(N);
5272       EVT TruncVT = N->getValueType(0);
5273       SDValue N00 = N->getOperand(0).getOperand(0);
5274       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5275       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5276       AddToWorklist(Trunc00.getNode());
5277       AddToWorklist(Trunc01.getNode());
5278       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5279     }
5280   }
5281
5282   return SDValue();
5283 }
5284
5285 SDValue DAGCombiner::visitRotate(SDNode *N) {
5286   SDLoc dl(N);
5287   SDValue N0 = N->getOperand(0);
5288   SDValue N1 = N->getOperand(1);
5289   EVT VT = N->getValueType(0);
5290   unsigned Bitsize = VT.getScalarSizeInBits();
5291
5292   // fold (rot x, 0) -> x
5293   if (isNullConstantOrNullSplatConstant(N1))
5294     return N0;
5295
5296   // fold (rot x, c) -> (rot x, c % BitSize)
5297   if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
5298     if (Cst->getAPIntValue().uge(Bitsize)) {
5299       uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
5300       return DAG.getNode(N->getOpcode(), dl, VT, N0,
5301                          DAG.getConstant(RotAmt, dl, N1.getValueType()));
5302     }
5303   }
5304
5305   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5306   if (N1.getOpcode() == ISD::TRUNCATE &&
5307       N1.getOperand(0).getOpcode() == ISD::AND) {
5308     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5309       return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
5310   }
5311
5312   unsigned NextOp = N0.getOpcode();
5313   // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
5314   if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
5315     SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
5316     SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
5317     if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
5318       EVT ShiftVT = C1->getValueType(0);
5319       bool SameSide = (N->getOpcode() == NextOp);
5320       unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
5321       if (SDValue CombinedShift =
5322               DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
5323         SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
5324         SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
5325             ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
5326             BitsizeC.getNode());
5327         return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
5328                            CombinedShiftNorm);
5329       }
5330     }
5331   }
5332   return SDValue();
5333 }
5334
5335 SDValue DAGCombiner::visitSHL(SDNode *N) {
5336   SDValue N0 = N->getOperand(0);
5337   SDValue N1 = N->getOperand(1);
5338   EVT VT = N0.getValueType();
5339   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5340
5341   // fold vector ops
5342   if (VT.isVector()) {
5343     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5344       return FoldedVOp;
5345
5346     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5347     // If setcc produces all-one true value then:
5348     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5349     if (N1CV && N1CV->isConstant()) {
5350       if (N0.getOpcode() == ISD::AND) {
5351         SDValue N00 = N0->getOperand(0);
5352         SDValue N01 = N0->getOperand(1);
5353         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5354
5355         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5356             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5357                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5358           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5359                                                      N01CV, N1CV))
5360             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5361         }
5362       }
5363     }
5364   }
5365
5366   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5367
5368   // fold (shl c1, c2) -> c1<<c2
5369   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5370   if (N0C && N1C && !N1C->isOpaque())
5371     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5372   // fold (shl 0, x) -> 0
5373   if (isNullConstantOrNullSplatConstant(N0))
5374     return N0;
5375   // fold (shl x, c >= size(x)) -> undef
5376   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5377     return DAG.getUNDEF(VT);
5378   // fold (shl x, 0) -> x
5379   if (N1C && N1C->isNullValue())
5380     return N0;
5381   // fold (shl undef, x) -> 0
5382   if (N0.isUndef())
5383     return DAG.getConstant(0, SDLoc(N), VT);
5384
5385   if (SDValue NewSel = foldBinOpIntoSelect(N))
5386     return NewSel;
5387
5388   // if (shl x, c) is known to be zero, return 0
5389   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5390                             APInt::getAllOnesValue(OpSizeInBits)))
5391     return DAG.getConstant(0, SDLoc(N), VT);
5392   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5393   if (N1.getOpcode() == ISD::TRUNCATE &&
5394       N1.getOperand(0).getOpcode() == ISD::AND) {
5395     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5396       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5397   }
5398
5399   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5400     return SDValue(N, 0);
5401
5402   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5403   if (N1C && N0.getOpcode() == ISD::SHL) {
5404     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5405       SDLoc DL(N);
5406       APInt c1 = N0C1->getAPIntValue();
5407       APInt c2 = N1C->getAPIntValue();
5408       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5409
5410       APInt Sum = c1 + c2;
5411       if (Sum.uge(OpSizeInBits))
5412         return DAG.getConstant(0, DL, VT);
5413
5414       return DAG.getNode(
5415           ISD::SHL, DL, VT, N0.getOperand(0),
5416           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5417     }
5418   }
5419
5420   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5421   // For this to be valid, the second form must not preserve any of the bits
5422   // that are shifted out by the inner shift in the first form.  This means
5423   // the outer shift size must be >= the number of bits added by the ext.
5424   // As a corollary, we don't care what kind of ext it is.
5425   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5426               N0.getOpcode() == ISD::ANY_EXTEND ||
5427               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5428       N0.getOperand(0).getOpcode() == ISD::SHL) {
5429     SDValue N0Op0 = N0.getOperand(0);
5430     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5431       APInt c1 = N0Op0C1->getAPIntValue();
5432       APInt c2 = N1C->getAPIntValue();
5433       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5434
5435       EVT InnerShiftVT = N0Op0.getValueType();
5436       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5437       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5438         SDLoc DL(N0);
5439         APInt Sum = c1 + c2;
5440         if (Sum.uge(OpSizeInBits))
5441           return DAG.getConstant(0, DL, VT);
5442
5443         return DAG.getNode(
5444             ISD::SHL, DL, VT,
5445             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5446             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5447       }
5448     }
5449   }
5450
5451   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5452   // Only fold this if the inner zext has no other uses to avoid increasing
5453   // the total number of instructions.
5454   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5455       N0.getOperand(0).getOpcode() == ISD::SRL) {
5456     SDValue N0Op0 = N0.getOperand(0);
5457     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5458       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5459         uint64_t c1 = N0Op0C1->getZExtValue();
5460         uint64_t c2 = N1C->getZExtValue();
5461         if (c1 == c2) {
5462           SDValue NewOp0 = N0.getOperand(0);
5463           EVT CountVT = NewOp0.getOperand(1).getValueType();
5464           SDLoc DL(N);
5465           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5466                                        NewOp0,
5467                                        DAG.getConstant(c2, DL, CountVT));
5468           AddToWorklist(NewSHL.getNode());
5469           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5470         }
5471       }
5472     }
5473   }
5474
5475   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5476   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5477   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5478       N0->getFlags().hasExact()) {
5479     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5480       uint64_t C1 = N0C1->getZExtValue();
5481       uint64_t C2 = N1C->getZExtValue();
5482       SDLoc DL(N);
5483       if (C1 <= C2)
5484         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5485                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5486       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5487                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5488     }
5489   }
5490
5491   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5492   //                               (and (srl x, (sub c1, c2), MASK)
5493   // Only fold this if the inner shift has no other uses -- if it does, folding
5494   // this will increase the total number of instructions.
5495   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5496     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5497       uint64_t c1 = N0C1->getZExtValue();
5498       if (c1 < OpSizeInBits) {
5499         uint64_t c2 = N1C->getZExtValue();
5500         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5501         SDValue Shift;
5502         if (c2 > c1) {
5503           Mask <<= c2 - c1;
5504           SDLoc DL(N);
5505           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5506                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5507         } else {
5508           Mask.lshrInPlace(c1 - c2);
5509           SDLoc DL(N);
5510           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5511                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5512         }
5513         SDLoc DL(N0);
5514         return DAG.getNode(ISD::AND, DL, VT, Shift,
5515                            DAG.getConstant(Mask, DL, VT));
5516       }
5517     }
5518   }
5519
5520   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5521   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5522       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5523     SDLoc DL(N);
5524     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5525     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5526     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5527   }
5528
5529   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5530   // Variant of version done on multiply, except mul by a power of 2 is turned
5531   // into a shift.
5532   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5533       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5534       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5535     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5536     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5537     AddToWorklist(Shl0.getNode());
5538     AddToWorklist(Shl1.getNode());
5539     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5540   }
5541
5542   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5543   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5544       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5545       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5546     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5547     if (isConstantOrConstantVector(Shl))
5548       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5549   }
5550
5551   if (N1C && !N1C->isOpaque())
5552     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5553       return NewSHL;
5554
5555   return SDValue();
5556 }
5557
5558 SDValue DAGCombiner::visitSRA(SDNode *N) {
5559   SDValue N0 = N->getOperand(0);
5560   SDValue N1 = N->getOperand(1);
5561   EVT VT = N0.getValueType();
5562   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5563
5564   // Arithmetic shifting an all-sign-bit value is a no-op.
5565   // fold (sra 0, x) -> 0
5566   // fold (sra -1, x) -> -1
5567   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5568     return N0;
5569
5570   // fold vector ops
5571   if (VT.isVector())
5572     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5573       return FoldedVOp;
5574
5575   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5576
5577   // fold (sra c1, c2) -> (sra c1, c2)
5578   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5579   if (N0C && N1C && !N1C->isOpaque())
5580     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5581   // fold (sra x, c >= size(x)) -> undef
5582   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5583     return DAG.getUNDEF(VT);
5584   // fold (sra x, 0) -> x
5585   if (N1C && N1C->isNullValue())
5586     return N0;
5587
5588   if (SDValue NewSel = foldBinOpIntoSelect(N))
5589     return NewSel;
5590
5591   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5592   // sext_inreg.
5593   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5594     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5595     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5596     if (VT.isVector())
5597       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5598                                ExtVT, VT.getVectorNumElements());
5599     if ((!LegalOperations ||
5600          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5601       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5602                          N0.getOperand(0), DAG.getValueType(ExtVT));
5603   }
5604
5605   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5606   if (N1C && N0.getOpcode() == ISD::SRA) {
5607     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5608       SDLoc DL(N);
5609       APInt c1 = N0C1->getAPIntValue();
5610       APInt c2 = N1C->getAPIntValue();
5611       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5612
5613       APInt Sum = c1 + c2;
5614       if (Sum.uge(OpSizeInBits))
5615         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5616
5617       return DAG.getNode(
5618           ISD::SRA, DL, VT, N0.getOperand(0),
5619           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5620     }
5621   }
5622
5623   // fold (sra (shl X, m), (sub result_size, n))
5624   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5625   // result_size - n != m.
5626   // If truncate is free for the target sext(shl) is likely to result in better
5627   // code.
5628   if (N0.getOpcode() == ISD::SHL && N1C) {
5629     // Get the two constanst of the shifts, CN0 = m, CN = n.
5630     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5631     if (N01C) {
5632       LLVMContext &Ctx = *DAG.getContext();
5633       // Determine what the truncate's result bitsize and type would be.
5634       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5635
5636       if (VT.isVector())
5637         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5638
5639       // Determine the residual right-shift amount.
5640       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5641
5642       // If the shift is not a no-op (in which case this should be just a sign
5643       // extend already), the truncated to type is legal, sign_extend is legal
5644       // on that type, and the truncate to that type is both legal and free,
5645       // perform the transform.
5646       if ((ShiftAmt > 0) &&
5647           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5648           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5649           TLI.isTruncateFree(VT, TruncVT)) {
5650
5651         SDLoc DL(N);
5652         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5653             getShiftAmountTy(N0.getOperand(0).getValueType()));
5654         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5655                                     N0.getOperand(0), Amt);
5656         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5657                                     Shift);
5658         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5659                            N->getValueType(0), Trunc);
5660       }
5661     }
5662   }
5663
5664   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5665   if (N1.getOpcode() == ISD::TRUNCATE &&
5666       N1.getOperand(0).getOpcode() == ISD::AND) {
5667     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5668       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5669   }
5670
5671   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5672   //      if c1 is equal to the number of bits the trunc removes
5673   if (N0.getOpcode() == ISD::TRUNCATE &&
5674       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5675        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5676       N0.getOperand(0).hasOneUse() &&
5677       N0.getOperand(0).getOperand(1).hasOneUse() &&
5678       N1C) {
5679     SDValue N0Op0 = N0.getOperand(0);
5680     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5681       unsigned LargeShiftVal = LargeShift->getZExtValue();
5682       EVT LargeVT = N0Op0.getValueType();
5683
5684       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5685         SDLoc DL(N);
5686         SDValue Amt =
5687           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5688                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5689         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5690                                   N0Op0.getOperand(0), Amt);
5691         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5692       }
5693     }
5694   }
5695
5696   // Simplify, based on bits shifted out of the LHS.
5697   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5698     return SDValue(N, 0);
5699
5700
5701   // If the sign bit is known to be zero, switch this to a SRL.
5702   if (DAG.SignBitIsZero(N0))
5703     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5704
5705   if (N1C && !N1C->isOpaque())
5706     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5707       return NewSRA;
5708
5709   return SDValue();
5710 }
5711
5712 SDValue DAGCombiner::visitSRL(SDNode *N) {
5713   SDValue N0 = N->getOperand(0);
5714   SDValue N1 = N->getOperand(1);
5715   EVT VT = N0.getValueType();
5716   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5717
5718   // fold vector ops
5719   if (VT.isVector())
5720     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5721       return FoldedVOp;
5722
5723   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5724
5725   // fold (srl c1, c2) -> c1 >>u c2
5726   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5727   if (N0C && N1C && !N1C->isOpaque())
5728     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5729   // fold (srl 0, x) -> 0
5730   if (isNullConstantOrNullSplatConstant(N0))
5731     return N0;
5732   // fold (srl x, c >= size(x)) -> undef
5733   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5734     return DAG.getUNDEF(VT);
5735   // fold (srl x, 0) -> x
5736   if (N1C && N1C->isNullValue())
5737     return N0;
5738
5739   if (SDValue NewSel = foldBinOpIntoSelect(N))
5740     return NewSel;
5741
5742   // if (srl x, c) is known to be zero, return 0
5743   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5744                                    APInt::getAllOnesValue(OpSizeInBits)))
5745     return DAG.getConstant(0, SDLoc(N), VT);
5746
5747   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5748   if (N1C && N0.getOpcode() == ISD::SRL) {
5749     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5750       SDLoc DL(N);
5751       APInt c1 = N0C1->getAPIntValue();
5752       APInt c2 = N1C->getAPIntValue();
5753       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5754
5755       APInt Sum = c1 + c2;
5756       if (Sum.uge(OpSizeInBits))
5757         return DAG.getConstant(0, DL, VT);
5758
5759       return DAG.getNode(
5760           ISD::SRL, DL, VT, N0.getOperand(0),
5761           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5762     }
5763   }
5764
5765   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5766   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5767       N0.getOperand(0).getOpcode() == ISD::SRL) {
5768     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5769       uint64_t c1 = N001C->getZExtValue();
5770       uint64_t c2 = N1C->getZExtValue();
5771       EVT InnerShiftVT = N0.getOperand(0).getValueType();
5772       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5773       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5774       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5775       if (c1 + OpSizeInBits == InnerShiftSize) {
5776         SDLoc DL(N0);
5777         if (c1 + c2 >= InnerShiftSize)
5778           return DAG.getConstant(0, DL, VT);
5779         return DAG.getNode(ISD::TRUNCATE, DL, VT,
5780                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5781                                        N0.getOperand(0).getOperand(0),
5782                                        DAG.getConstant(c1 + c2, DL,
5783                                                        ShiftCountVT)));
5784       }
5785     }
5786   }
5787
5788   // fold (srl (shl x, c), c) -> (and x, cst2)
5789   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5790       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5791     SDLoc DL(N);
5792     SDValue Mask =
5793         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5794     AddToWorklist(Mask.getNode());
5795     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5796   }
5797
5798   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5799   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5800     // Shifting in all undef bits?
5801     EVT SmallVT = N0.getOperand(0).getValueType();
5802     unsigned BitSize = SmallVT.getScalarSizeInBits();
5803     if (N1C->getZExtValue() >= BitSize)
5804       return DAG.getUNDEF(VT);
5805
5806     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5807       uint64_t ShiftAmt = N1C->getZExtValue();
5808       SDLoc DL0(N0);
5809       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5810                                        N0.getOperand(0),
5811                           DAG.getConstant(ShiftAmt, DL0,
5812                                           getShiftAmountTy(SmallVT)));
5813       AddToWorklist(SmallShift.getNode());
5814       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5815       SDLoc DL(N);
5816       return DAG.getNode(ISD::AND, DL, VT,
5817                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5818                          DAG.getConstant(Mask, DL, VT));
5819     }
5820   }
5821
5822   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
5823   // bit, which is unmodified by sra.
5824   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5825     if (N0.getOpcode() == ISD::SRA)
5826       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5827   }
5828
5829   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5830   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5831       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5832     KnownBits Known;
5833     DAG.computeKnownBits(N0.getOperand(0), Known);
5834
5835     // If any of the input bits are KnownOne, then the input couldn't be all
5836     // zeros, thus the result of the srl will always be zero.
5837     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5838
5839     // If all of the bits input the to ctlz node are known to be zero, then
5840     // the result of the ctlz is "32" and the result of the shift is one.
5841     APInt UnknownBits = ~Known.Zero;
5842     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5843
5844     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5845     if (UnknownBits.isPowerOf2()) {
5846       // Okay, we know that only that the single bit specified by UnknownBits
5847       // could be set on input to the CTLZ node. If this bit is set, the SRL
5848       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5849       // to an SRL/XOR pair, which is likely to simplify more.
5850       unsigned ShAmt = UnknownBits.countTrailingZeros();
5851       SDValue Op = N0.getOperand(0);
5852
5853       if (ShAmt) {
5854         SDLoc DL(N0);
5855         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5856                   DAG.getConstant(ShAmt, DL,
5857                                   getShiftAmountTy(Op.getValueType())));
5858         AddToWorklist(Op.getNode());
5859       }
5860
5861       SDLoc DL(N);
5862       return DAG.getNode(ISD::XOR, DL, VT,
5863                          Op, DAG.getConstant(1, DL, VT));
5864     }
5865   }
5866
5867   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5868   if (N1.getOpcode() == ISD::TRUNCATE &&
5869       N1.getOperand(0).getOpcode() == ISD::AND) {
5870     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5871       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5872   }
5873
5874   // fold operands of srl based on knowledge that the low bits are not
5875   // demanded.
5876   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5877     return SDValue(N, 0);
5878
5879   if (N1C && !N1C->isOpaque())
5880     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5881       return NewSRL;
5882
5883   // Attempt to convert a srl of a load into a narrower zero-extending load.
5884   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5885     return NarrowLoad;
5886
5887   // Here is a common situation. We want to optimize:
5888   //
5889   //   %a = ...
5890   //   %b = and i32 %a, 2
5891   //   %c = srl i32 %b, 1
5892   //   brcond i32 %c ...
5893   //
5894   // into
5895   //
5896   //   %a = ...
5897   //   %b = and %a, 2
5898   //   %c = setcc eq %b, 0
5899   //   brcond %c ...
5900   //
5901   // However when after the source operand of SRL is optimized into AND, the SRL
5902   // itself may not be optimized further. Look for it and add the BRCOND into
5903   // the worklist.
5904   if (N->hasOneUse()) {
5905     SDNode *Use = *N->use_begin();
5906     if (Use->getOpcode() == ISD::BRCOND)
5907       AddToWorklist(Use);
5908     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5909       // Also look pass the truncate.
5910       Use = *Use->use_begin();
5911       if (Use->getOpcode() == ISD::BRCOND)
5912         AddToWorklist(Use);
5913     }
5914   }
5915
5916   return SDValue();
5917 }
5918
5919 SDValue DAGCombiner::visitABS(SDNode *N) {
5920   SDValue N0 = N->getOperand(0);
5921   EVT VT = N->getValueType(0);
5922
5923   // fold (abs c1) -> c2
5924   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5925     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
5926   // fold (abs (abs x)) -> (abs x)
5927   if (N0.getOpcode() == ISD::ABS)
5928     return N0;
5929   // fold (abs x) -> x iff not-negative
5930   if (DAG.SignBitIsZero(N0))
5931     return N0;
5932   return SDValue();
5933 }
5934
5935 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5936   SDValue N0 = N->getOperand(0);
5937   EVT VT = N->getValueType(0);
5938
5939   // fold (bswap c1) -> c2
5940   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5941     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5942   // fold (bswap (bswap x)) -> x
5943   if (N0.getOpcode() == ISD::BSWAP)
5944     return N0->getOperand(0);
5945   return SDValue();
5946 }
5947
5948 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5949   SDValue N0 = N->getOperand(0);
5950   EVT VT = N->getValueType(0);
5951
5952   // fold (bitreverse c1) -> c2
5953   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5954     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
5955   // fold (bitreverse (bitreverse x)) -> x
5956   if (N0.getOpcode() == ISD::BITREVERSE)
5957     return N0.getOperand(0);
5958   return SDValue();
5959 }
5960
5961 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5962   SDValue N0 = N->getOperand(0);
5963   EVT VT = N->getValueType(0);
5964
5965   // fold (ctlz c1) -> c2
5966   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5967     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5968   return SDValue();
5969 }
5970
5971 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5972   SDValue N0 = N->getOperand(0);
5973   EVT VT = N->getValueType(0);
5974
5975   // fold (ctlz_zero_undef c1) -> c2
5976   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5977     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5978   return SDValue();
5979 }
5980
5981 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5982   SDValue N0 = N->getOperand(0);
5983   EVT VT = N->getValueType(0);
5984
5985   // fold (cttz c1) -> c2
5986   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5987     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5988   return SDValue();
5989 }
5990
5991 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5992   SDValue N0 = N->getOperand(0);
5993   EVT VT = N->getValueType(0);
5994
5995   // fold (cttz_zero_undef c1) -> c2
5996   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5997     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5998   return SDValue();
5999 }
6000
6001 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
6002   SDValue N0 = N->getOperand(0);
6003   EVT VT = N->getValueType(0);
6004
6005   // fold (ctpop c1) -> c2
6006   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6007     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6008   return SDValue();
6009 }
6010
6011
6012 /// \brief Generate Min/Max node
6013 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6014                                    SDValue RHS, SDValue True, SDValue False,
6015                                    ISD::CondCode CC, const TargetLowering &TLI,
6016                                    SelectionDAG &DAG) {
6017   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6018     return SDValue();
6019
6020   switch (CC) {
6021   case ISD::SETOLT:
6022   case ISD::SETOLE:
6023   case ISD::SETLT:
6024   case ISD::SETLE:
6025   case ISD::SETULT:
6026   case ISD::SETULE: {
6027     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6028     if (TLI.isOperationLegal(Opcode, VT))
6029       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6030     return SDValue();
6031   }
6032   case ISD::SETOGT:
6033   case ISD::SETOGE:
6034   case ISD::SETGT:
6035   case ISD::SETGE:
6036   case ISD::SETUGT:
6037   case ISD::SETUGE: {
6038     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6039     if (TLI.isOperationLegal(Opcode, VT))
6040       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6041     return SDValue();
6042   }
6043   default:
6044     return SDValue();
6045   }
6046 }
6047
6048 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6049   SDValue Cond = N->getOperand(0);
6050   SDValue N1 = N->getOperand(1);
6051   SDValue N2 = N->getOperand(2);
6052   EVT VT = N->getValueType(0);
6053   EVT CondVT = Cond.getValueType();
6054   SDLoc DL(N);
6055
6056   if (!VT.isInteger())
6057     return SDValue();
6058
6059   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6060   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6061   if (!C1 || !C2)
6062     return SDValue();
6063
6064   // Only do this before legalization to avoid conflicting with target-specific
6065   // transforms in the other direction (create a select from a zext/sext). There
6066   // is also a target-independent combine here in DAGCombiner in the other
6067   // direction for (select Cond, -1, 0) when the condition is not i1.
6068   if (CondVT == MVT::i1 && !LegalOperations) {
6069     if (C1->isNullValue() && C2->isOne()) {
6070       // select Cond, 0, 1 --> zext (!Cond)
6071       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6072       if (VT != MVT::i1)
6073         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6074       return NotCond;
6075     }
6076     if (C1->isNullValue() && C2->isAllOnesValue()) {
6077       // select Cond, 0, -1 --> sext (!Cond)
6078       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6079       if (VT != MVT::i1)
6080         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6081       return NotCond;
6082     }
6083     if (C1->isOne() && C2->isNullValue()) {
6084       // select Cond, 1, 0 --> zext (Cond)
6085       if (VT != MVT::i1)
6086         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6087       return Cond;
6088     }
6089     if (C1->isAllOnesValue() && C2->isNullValue()) {
6090       // select Cond, -1, 0 --> sext (Cond)
6091       if (VT != MVT::i1)
6092         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6093       return Cond;
6094     }
6095
6096     // For any constants that differ by 1, we can transform the select into an
6097     // extend and add. Use a target hook because some targets may prefer to
6098     // transform in the other direction.
6099     if (TLI.convertSelectOfConstantsToMath()) {
6100       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6101         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6102         if (VT != MVT::i1)
6103           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6104         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6105       }
6106       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6107         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6108         if (VT != MVT::i1)
6109           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6110         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6111       }
6112     }
6113
6114     return SDValue();
6115   }
6116
6117   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6118   // We can't do this reliably if integer based booleans have different contents
6119   // to floating point based booleans. This is because we can't tell whether we
6120   // have an integer-based boolean or a floating-point-based boolean unless we
6121   // can find the SETCC that produced it and inspect its operands. This is
6122   // fairly easy if C is the SETCC node, but it can potentially be
6123   // undiscoverable (or not reasonably discoverable). For example, it could be
6124   // in another basic block or it could require searching a complicated
6125   // expression.
6126   if (CondVT.isInteger() &&
6127       TLI.getBooleanContents(false, true) ==
6128           TargetLowering::ZeroOrOneBooleanContent &&
6129       TLI.getBooleanContents(false, false) ==
6130           TargetLowering::ZeroOrOneBooleanContent &&
6131       C1->isNullValue() && C2->isOne()) {
6132     SDValue NotCond =
6133         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6134     if (VT.bitsEq(CondVT))
6135       return NotCond;
6136     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6137   }
6138
6139   return SDValue();
6140 }
6141
6142 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6143   SDValue N0 = N->getOperand(0);
6144   SDValue N1 = N->getOperand(1);
6145   SDValue N2 = N->getOperand(2);
6146   EVT VT = N->getValueType(0);
6147   EVT VT0 = N0.getValueType();
6148   SDLoc DL(N);
6149
6150   // fold (select C, X, X) -> X
6151   if (N1 == N2)
6152     return N1;
6153
6154   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6155     // fold (select true, X, Y) -> X
6156     // fold (select false, X, Y) -> Y
6157     return !N0C->isNullValue() ? N1 : N2;
6158   }
6159
6160   // fold (select X, X, Y) -> (or X, Y)
6161   // fold (select X, 1, Y) -> (or C, Y)
6162   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6163     return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6164
6165   if (SDValue V = foldSelectOfConstants(N))
6166     return V;
6167
6168   // fold (select C, 0, X) -> (and (not C), X)
6169   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6170     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6171     AddToWorklist(NOTNode.getNode());
6172     return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6173   }
6174   // fold (select C, X, 1) -> (or (not C), X)
6175   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6176     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6177     AddToWorklist(NOTNode.getNode());
6178     return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6179   }
6180   // fold (select X, Y, X) -> (and X, Y)
6181   // fold (select X, Y, 0) -> (and X, Y)
6182   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6183     return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6184
6185   // If we can fold this based on the true/false value, do so.
6186   if (SimplifySelectOps(N, N1, N2))
6187     return SDValue(N, 0); // Don't revisit N.
6188
6189   if (VT0 == MVT::i1) {
6190     // The code in this block deals with the following 2 equivalences:
6191     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6192     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6193     // The target can specify its preferred form with the
6194     // shouldNormalizeToSelectSequence() callback. However we always transform
6195     // to the right anyway if we find the inner select exists in the DAG anyway
6196     // and we always transform to the left side if we know that we can further
6197     // optimize the combination of the conditions.
6198     bool normalizeToSequence =
6199         TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6200     // select (and Cond0, Cond1), X, Y
6201     //   -> select Cond0, (select Cond1, X, Y), Y
6202     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6203       SDValue Cond0 = N0->getOperand(0);
6204       SDValue Cond1 = N0->getOperand(1);
6205       SDValue InnerSelect =
6206           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6207       if (normalizeToSequence || !InnerSelect.use_empty())
6208         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6209                            InnerSelect, N2);
6210     }
6211     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6212     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6213       SDValue Cond0 = N0->getOperand(0);
6214       SDValue Cond1 = N0->getOperand(1);
6215       SDValue InnerSelect =
6216           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6217       if (normalizeToSequence || !InnerSelect.use_empty())
6218         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
6219                            InnerSelect);
6220     }
6221
6222     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6223     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6224       SDValue N1_0 = N1->getOperand(0);
6225       SDValue N1_1 = N1->getOperand(1);
6226       SDValue N1_2 = N1->getOperand(2);
6227       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6228         // Create the actual and node if we can generate good code for it.
6229         if (!normalizeToSequence) {
6230           SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
6231           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
6232         }
6233         // Otherwise see if we can optimize the "and" to a better pattern.
6234         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6235           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
6236                              N2);
6237       }
6238     }
6239     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6240     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6241       SDValue N2_0 = N2->getOperand(0);
6242       SDValue N2_1 = N2->getOperand(1);
6243       SDValue N2_2 = N2->getOperand(2);
6244       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6245         // Create the actual or node if we can generate good code for it.
6246         if (!normalizeToSequence) {
6247           SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
6248           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
6249         }
6250         // Otherwise see if we can optimize to a better pattern.
6251         if (SDValue Combined = visitORLike(N0, N2_0, N))
6252           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
6253                              N2_2);
6254       }
6255     }
6256   }
6257
6258   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6259   if (VT0 == MVT::i1) {
6260     if (N0->getOpcode() == ISD::XOR) {
6261       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6262         SDValue Cond0 = N0->getOperand(0);
6263         if (C->isOne())
6264           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1);
6265       }
6266     }
6267   }
6268
6269   // fold selects based on a setcc into other things, such as min/max/abs
6270   if (N0.getOpcode() == ISD::SETCC) {
6271     // select x, y (fcmp lt x, y) -> fminnum x, y
6272     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6273     //
6274     // This is OK if we don't care about what happens if either operand is a
6275     // NaN.
6276     //
6277
6278     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6279     // no signed zeros as well as no nans.
6280     const TargetOptions &Options = DAG.getTarget().Options;
6281     if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
6282         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6283       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6284
6285       if (SDValue FMinMax = combineMinNumMaxNum(
6286               DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
6287         return FMinMax;
6288     }
6289
6290     if ((!LegalOperations &&
6291          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6292         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6293       return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
6294                          N0.getOperand(1), N1, N2, N0.getOperand(2));
6295     return SimplifySelect(DL, N0, N1, N2);
6296   }
6297
6298   return SDValue();
6299 }
6300
6301 static
6302 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6303   SDLoc DL(N);
6304   EVT LoVT, HiVT;
6305   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6306
6307   // Split the inputs.
6308   SDValue Lo, Hi, LL, LH, RL, RH;
6309   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6310   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6311
6312   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6313   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6314
6315   return std::make_pair(Lo, Hi);
6316 }
6317
6318 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6319 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6320 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6321   SDLoc DL(N);
6322   SDValue Cond = N->getOperand(0);
6323   SDValue LHS = N->getOperand(1);
6324   SDValue RHS = N->getOperand(2);
6325   EVT VT = N->getValueType(0);
6326   int NumElems = VT.getVectorNumElements();
6327   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6328          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6329          Cond.getOpcode() == ISD::BUILD_VECTOR);
6330
6331   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6332   // binary ones here.
6333   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6334     return SDValue();
6335
6336   // We're sure we have an even number of elements due to the
6337   // concat_vectors we have as arguments to vselect.
6338   // Skip BV elements until we find one that's not an UNDEF
6339   // After we find an UNDEF element, keep looping until we get to half the
6340   // length of the BV and see if all the non-undef nodes are the same.
6341   ConstantSDNode *BottomHalf = nullptr;
6342   for (int i = 0; i < NumElems / 2; ++i) {
6343     if (Cond->getOperand(i)->isUndef())
6344       continue;
6345
6346     if (BottomHalf == nullptr)
6347       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6348     else if (Cond->getOperand(i).getNode() != BottomHalf)
6349       return SDValue();
6350   }
6351
6352   // Do the same for the second half of the BuildVector
6353   ConstantSDNode *TopHalf = nullptr;
6354   for (int i = NumElems / 2; i < NumElems; ++i) {
6355     if (Cond->getOperand(i)->isUndef())
6356       continue;
6357
6358     if (TopHalf == nullptr)
6359       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6360     else if (Cond->getOperand(i).getNode() != TopHalf)
6361       return SDValue();
6362   }
6363
6364   assert(TopHalf && BottomHalf &&
6365          "One half of the selector was all UNDEFs and the other was all the "
6366          "same value. This should have been addressed before this function.");
6367   return DAG.getNode(
6368       ISD::CONCAT_VECTORS, DL, VT,
6369       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6370       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6371 }
6372
6373 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6374
6375   if (Level >= AfterLegalizeTypes)
6376     return SDValue();
6377
6378   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6379   SDValue Mask = MSC->getMask();
6380   SDValue Data  = MSC->getValue();
6381   SDLoc DL(N);
6382
6383   // If the MSCATTER data type requires splitting and the mask is provided by a
6384   // SETCC, then split both nodes and its operands before legalization. This
6385   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6386   // and enables future optimizations (e.g. min/max pattern matching on X86).
6387   if (Mask.getOpcode() != ISD::SETCC)
6388     return SDValue();
6389
6390   // Check if any splitting is required.
6391   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6392       TargetLowering::TypeSplitVector)
6393     return SDValue();
6394   SDValue MaskLo, MaskHi, Lo, Hi;
6395   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6396
6397   EVT LoVT, HiVT;
6398   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6399
6400   SDValue Chain = MSC->getChain();
6401
6402   EVT MemoryVT = MSC->getMemoryVT();
6403   unsigned Alignment = MSC->getOriginalAlignment();
6404
6405   EVT LoMemVT, HiMemVT;
6406   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6407
6408   SDValue DataLo, DataHi;
6409   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6410
6411   SDValue BasePtr = MSC->getBasePtr();
6412   SDValue IndexLo, IndexHi;
6413   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6414
6415   MachineMemOperand *MMO = DAG.getMachineFunction().
6416     getMachineMemOperand(MSC->getPointerInfo(),
6417                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6418                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6419
6420   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6421   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6422                             DL, OpsLo, MMO);
6423
6424   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6425   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6426                             DL, OpsHi, MMO);
6427
6428   AddToWorklist(Lo.getNode());
6429   AddToWorklist(Hi.getNode());
6430
6431   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6432 }
6433
6434 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6435
6436   if (Level >= AfterLegalizeTypes)
6437     return SDValue();
6438
6439   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6440   SDValue Mask = MST->getMask();
6441   SDValue Data  = MST->getValue();
6442   EVT VT = Data.getValueType();
6443   SDLoc DL(N);
6444
6445   // If the MSTORE data type requires splitting and the mask is provided by a
6446   // SETCC, then split both nodes and its operands before legalization. This
6447   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6448   // and enables future optimizations (e.g. min/max pattern matching on X86).
6449   if (Mask.getOpcode() == ISD::SETCC) {
6450
6451     // Check if any splitting is required.
6452     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6453         TargetLowering::TypeSplitVector)
6454       return SDValue();
6455
6456     SDValue MaskLo, MaskHi, Lo, Hi;
6457     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6458
6459     SDValue Chain = MST->getChain();
6460     SDValue Ptr   = MST->getBasePtr();
6461
6462     EVT MemoryVT = MST->getMemoryVT();
6463     unsigned Alignment = MST->getOriginalAlignment();
6464
6465     // if Alignment is equal to the vector size,
6466     // take the half of it for the second part
6467     unsigned SecondHalfAlignment =
6468       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6469
6470     EVT LoMemVT, HiMemVT;
6471     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6472
6473     SDValue DataLo, DataHi;
6474     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6475
6476     MachineMemOperand *MMO = DAG.getMachineFunction().
6477       getMachineMemOperand(MST->getPointerInfo(),
6478                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6479                            Alignment, MST->getAAInfo(), MST->getRanges());
6480
6481     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6482                             MST->isTruncatingStore(),
6483                             MST->isCompressingStore());
6484
6485     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6486                                      MST->isCompressingStore());
6487
6488     MMO = DAG.getMachineFunction().
6489       getMachineMemOperand(MST->getPointerInfo(),
6490                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6491                            SecondHalfAlignment, MST->getAAInfo(),
6492                            MST->getRanges());
6493
6494     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6495                             MST->isTruncatingStore(),
6496                             MST->isCompressingStore());
6497
6498     AddToWorklist(Lo.getNode());
6499     AddToWorklist(Hi.getNode());
6500
6501     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6502   }
6503   return SDValue();
6504 }
6505
6506 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6507
6508   if (Level >= AfterLegalizeTypes)
6509     return SDValue();
6510
6511   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6512   SDValue Mask = MGT->getMask();
6513   SDLoc DL(N);
6514
6515   // If the MGATHER result requires splitting and the mask is provided by a
6516   // SETCC, then split both nodes and its operands before legalization. This
6517   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6518   // and enables future optimizations (e.g. min/max pattern matching on X86).
6519
6520   if (Mask.getOpcode() != ISD::SETCC)
6521     return SDValue();
6522
6523   EVT VT = N->getValueType(0);
6524
6525   // Check if any splitting is required.
6526   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6527       TargetLowering::TypeSplitVector)
6528     return SDValue();
6529
6530   SDValue MaskLo, MaskHi, Lo, Hi;
6531   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6532
6533   SDValue Src0 = MGT->getValue();
6534   SDValue Src0Lo, Src0Hi;
6535   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6536
6537   EVT LoVT, HiVT;
6538   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6539
6540   SDValue Chain = MGT->getChain();
6541   EVT MemoryVT = MGT->getMemoryVT();
6542   unsigned Alignment = MGT->getOriginalAlignment();
6543
6544   EVT LoMemVT, HiMemVT;
6545   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6546
6547   SDValue BasePtr = MGT->getBasePtr();
6548   SDValue Index = MGT->getIndex();
6549   SDValue IndexLo, IndexHi;
6550   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6551
6552   MachineMemOperand *MMO = DAG.getMachineFunction().
6553     getMachineMemOperand(MGT->getPointerInfo(),
6554                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6555                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6556
6557   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6558   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6559                             MMO);
6560
6561   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6562   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6563                             MMO);
6564
6565   AddToWorklist(Lo.getNode());
6566   AddToWorklist(Hi.getNode());
6567
6568   // Build a factor node to remember that this load is independent of the
6569   // other one.
6570   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6571                       Hi.getValue(1));
6572
6573   // Legalized the chain result - switch anything that used the old chain to
6574   // use the new one.
6575   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6576
6577   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6578
6579   SDValue RetOps[] = { GatherRes, Chain };
6580   return DAG.getMergeValues(RetOps, DL);
6581 }
6582
6583 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6584
6585   if (Level >= AfterLegalizeTypes)
6586     return SDValue();
6587
6588   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6589   SDValue Mask = MLD->getMask();
6590   SDLoc DL(N);
6591
6592   // If the MLOAD result requires splitting and the mask is provided by a
6593   // SETCC, then split both nodes and its operands before legalization. This
6594   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6595   // and enables future optimizations (e.g. min/max pattern matching on X86).
6596
6597   if (Mask.getOpcode() == ISD::SETCC) {
6598     EVT VT = N->getValueType(0);
6599
6600     // Check if any splitting is required.
6601     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6602         TargetLowering::TypeSplitVector)
6603       return SDValue();
6604
6605     SDValue MaskLo, MaskHi, Lo, Hi;
6606     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6607
6608     SDValue Src0 = MLD->getSrc0();
6609     SDValue Src0Lo, Src0Hi;
6610     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6611
6612     EVT LoVT, HiVT;
6613     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6614
6615     SDValue Chain = MLD->getChain();
6616     SDValue Ptr   = MLD->getBasePtr();
6617     EVT MemoryVT = MLD->getMemoryVT();
6618     unsigned Alignment = MLD->getOriginalAlignment();
6619
6620     // if Alignment is equal to the vector size,
6621     // take the half of it for the second part
6622     unsigned SecondHalfAlignment =
6623       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6624          Alignment/2 : Alignment;
6625
6626     EVT LoMemVT, HiMemVT;
6627     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6628
6629     MachineMemOperand *MMO = DAG.getMachineFunction().
6630     getMachineMemOperand(MLD->getPointerInfo(),
6631                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6632                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6633
6634     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6635                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6636
6637     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6638                                      MLD->isExpandingLoad());
6639
6640     MMO = DAG.getMachineFunction().
6641     getMachineMemOperand(MLD->getPointerInfo(),
6642                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6643                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6644
6645     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6646                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6647
6648     AddToWorklist(Lo.getNode());
6649     AddToWorklist(Hi.getNode());
6650
6651     // Build a factor node to remember that this load is independent of the
6652     // other one.
6653     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6654                         Hi.getValue(1));
6655
6656     // Legalized the chain result - switch anything that used the old chain to
6657     // use the new one.
6658     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6659
6660     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6661
6662     SDValue RetOps[] = { LoadRes, Chain };
6663     return DAG.getMergeValues(RetOps, DL);
6664   }
6665   return SDValue();
6666 }
6667
6668 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6669   SDValue N0 = N->getOperand(0);
6670   SDValue N1 = N->getOperand(1);
6671   SDValue N2 = N->getOperand(2);
6672   SDLoc DL(N);
6673
6674   // fold (vselect C, X, X) -> X
6675   if (N1 == N2)
6676     return N1;
6677
6678   // Canonicalize integer abs.
6679   // vselect (setg[te] X,  0),  X, -X ->
6680   // vselect (setgt    X, -1),  X, -X ->
6681   // vselect (setl[te] X,  0), -X,  X ->
6682   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6683   if (N0.getOpcode() == ISD::SETCC) {
6684     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6685     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6686     bool isAbs = false;
6687     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6688
6689     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6690          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6691         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6692       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6693     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6694              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6695       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6696
6697     if (isAbs) {
6698       EVT VT = LHS.getValueType();
6699       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
6700         return DAG.getNode(ISD::ABS, DL, VT, LHS);
6701
6702       SDValue Shift = DAG.getNode(
6703           ISD::SRA, DL, VT, LHS,
6704           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6705       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6706       AddToWorklist(Shift.getNode());
6707       AddToWorklist(Add.getNode());
6708       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6709     }
6710   }
6711
6712   if (SimplifySelectOps(N, N1, N2))
6713     return SDValue(N, 0);  // Don't revisit N.
6714
6715   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6716   if (ISD::isBuildVectorAllOnes(N0.getNode()))
6717     return N1;
6718   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6719   if (ISD::isBuildVectorAllZeros(N0.getNode()))
6720     return N2;
6721
6722   // The ConvertSelectToConcatVector function is assuming both the above
6723   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6724   // and addressed.
6725   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6726       N2.getOpcode() == ISD::CONCAT_VECTORS &&
6727       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6728     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6729       return CV;
6730   }
6731
6732   return SDValue();
6733 }
6734
6735 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6736   SDValue N0 = N->getOperand(0);
6737   SDValue N1 = N->getOperand(1);
6738   SDValue N2 = N->getOperand(2);
6739   SDValue N3 = N->getOperand(3);
6740   SDValue N4 = N->getOperand(4);
6741   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6742
6743   // fold select_cc lhs, rhs, x, x, cc -> x
6744   if (N2 == N3)
6745     return N2;
6746
6747   // Determine if the condition we're dealing with is constant
6748   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6749                                   CC, SDLoc(N), false)) {
6750     AddToWorklist(SCC.getNode());
6751
6752     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6753       if (!SCCC->isNullValue())
6754         return N2;    // cond always true -> true val
6755       else
6756         return N3;    // cond always false -> false val
6757     } else if (SCC->isUndef()) {
6758       // When the condition is UNDEF, just return the first operand. This is
6759       // coherent the DAG creation, no setcc node is created in this case
6760       return N2;
6761     } else if (SCC.getOpcode() == ISD::SETCC) {
6762       // Fold to a simpler select_cc
6763       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6764                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6765                          SCC.getOperand(2));
6766     }
6767   }
6768
6769   // If we can fold this based on the true/false value, do so.
6770   if (SimplifySelectOps(N, N2, N3))
6771     return SDValue(N, 0);  // Don't revisit N.
6772
6773   // fold select_cc into other things, such as min/max/abs
6774   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6775 }
6776
6777 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6778   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6779                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
6780                        SDLoc(N));
6781 }
6782
6783 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6784   SDValue LHS = N->getOperand(0);
6785   SDValue RHS = N->getOperand(1);
6786   SDValue Carry = N->getOperand(2);
6787   SDValue Cond = N->getOperand(3);
6788
6789   // If Carry is false, fold to a regular SETCC.
6790   if (Carry.getOpcode() == ISD::CARRY_FALSE)
6791     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6792
6793   return SDValue();
6794 }
6795
6796 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
6797   SDValue LHS = N->getOperand(0);
6798   SDValue RHS = N->getOperand(1);
6799   SDValue Carry = N->getOperand(2);
6800   SDValue Cond = N->getOperand(3);
6801
6802   // If Carry is false, fold to a regular SETCC.
6803   if (isNullConstant(Carry))
6804     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6805
6806   return SDValue();
6807 }
6808
6809 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6810 /// a build_vector of constants.
6811 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6812 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6813 /// Vector extends are not folded if operations are legal; this is to
6814 /// avoid introducing illegal build_vector dag nodes.
6815 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6816                                          SelectionDAG &DAG, bool LegalTypes,
6817                                          bool LegalOperations) {
6818   unsigned Opcode = N->getOpcode();
6819   SDValue N0 = N->getOperand(0);
6820   EVT VT = N->getValueType(0);
6821
6822   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6823          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6824          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6825          && "Expected EXTEND dag node in input!");
6826
6827   // fold (sext c1) -> c1
6828   // fold (zext c1) -> c1
6829   // fold (aext c1) -> c1
6830   if (isa<ConstantSDNode>(N0))
6831     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6832
6833   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6834   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6835   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6836   EVT SVT = VT.getScalarType();
6837   if (!(VT.isVector() &&
6838       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6839       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6840     return nullptr;
6841
6842   // We can fold this node into a build_vector.
6843   unsigned VTBits = SVT.getSizeInBits();
6844   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6845   SmallVector<SDValue, 8> Elts;
6846   unsigned NumElts = VT.getVectorNumElements();
6847   SDLoc DL(N);
6848
6849   for (unsigned i=0; i != NumElts; ++i) {
6850     SDValue Op = N0->getOperand(i);
6851     if (Op->isUndef()) {
6852       Elts.push_back(DAG.getUNDEF(SVT));
6853       continue;
6854     }
6855
6856     SDLoc DL(Op);
6857     // Get the constant value and if needed trunc it to the size of the type.
6858     // Nodes like build_vector might have constants wider than the scalar type.
6859     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6860     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6861       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6862     else
6863       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6864   }
6865
6866   return DAG.getBuildVector(VT, DL, Elts).getNode();
6867 }
6868
6869 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6870 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6871 // transformation. Returns true if extension are possible and the above
6872 // mentioned transformation is profitable.
6873 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6874                                     unsigned ExtOpc,
6875                                     SmallVectorImpl<SDNode *> &ExtendNodes,
6876                                     const TargetLowering &TLI) {
6877   bool HasCopyToRegUses = false;
6878   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6879   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6880                             UE = N0.getNode()->use_end();
6881        UI != UE; ++UI) {
6882     SDNode *User = *UI;
6883     if (User == N)
6884       continue;
6885     if (UI.getUse().getResNo() != N0.getResNo())
6886       continue;
6887     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6888     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6889       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6890       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6891         // Sign bits will be lost after a zext.
6892         return false;
6893       bool Add = false;
6894       for (unsigned i = 0; i != 2; ++i) {
6895         SDValue UseOp = User->getOperand(i);
6896         if (UseOp == N0)
6897           continue;
6898         if (!isa<ConstantSDNode>(UseOp))
6899           return false;
6900         Add = true;
6901       }
6902       if (Add)
6903         ExtendNodes.push_back(User);
6904       continue;
6905     }
6906     // If truncates aren't free and there are users we can't
6907     // extend, it isn't worthwhile.
6908     if (!isTruncFree)
6909       return false;
6910     // Remember if this value is live-out.
6911     if (User->getOpcode() == ISD::CopyToReg)
6912       HasCopyToRegUses = true;
6913   }
6914
6915   if (HasCopyToRegUses) {
6916     bool BothLiveOut = false;
6917     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6918          UI != UE; ++UI) {
6919       SDUse &Use = UI.getUse();
6920       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6921         BothLiveOut = true;
6922         break;
6923       }
6924     }
6925     if (BothLiveOut)
6926       // Both unextended and extended values are live out. There had better be
6927       // a good reason for the transformation.
6928       return ExtendNodes.size();
6929   }
6930   return true;
6931 }
6932
6933 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6934                                   SDValue Trunc, SDValue ExtLoad,
6935                                   const SDLoc &DL, ISD::NodeType ExtType) {
6936   // Extend SetCC uses if necessary.
6937   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6938     SDNode *SetCC = SetCCs[i];
6939     SmallVector<SDValue, 4> Ops;
6940
6941     for (unsigned j = 0; j != 2; ++j) {
6942       SDValue SOp = SetCC->getOperand(j);
6943       if (SOp == Trunc)
6944         Ops.push_back(ExtLoad);
6945       else
6946         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6947     }
6948
6949     Ops.push_back(SetCC->getOperand(2));
6950     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6951   }
6952 }
6953
6954 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6955 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6956   SDValue N0 = N->getOperand(0);
6957   EVT DstVT = N->getValueType(0);
6958   EVT SrcVT = N0.getValueType();
6959
6960   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6961           N->getOpcode() == ISD::ZERO_EXTEND) &&
6962          "Unexpected node type (not an extend)!");
6963
6964   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6965   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6966   //   (v8i32 (sext (v8i16 (load x))))
6967   // into:
6968   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6969   //                          (v4i32 (sextload (x + 16)))))
6970   // Where uses of the original load, i.e.:
6971   //   (v8i16 (load x))
6972   // are replaced with:
6973   //   (v8i16 (truncate
6974   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6975   //                            (v4i32 (sextload (x + 16)))))))
6976   //
6977   // This combine is only applicable to illegal, but splittable, vectors.
6978   // All legal types, and illegal non-vector types, are handled elsewhere.
6979   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6980   //
6981   if (N0->getOpcode() != ISD::LOAD)
6982     return SDValue();
6983
6984   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6985
6986   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6987       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6988       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6989     return SDValue();
6990
6991   SmallVector<SDNode *, 4> SetCCs;
6992   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6993     return SDValue();
6994
6995   ISD::LoadExtType ExtType =
6996       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6997
6998   // Try to split the vector types to get down to legal types.
6999   EVT SplitSrcVT = SrcVT;
7000   EVT SplitDstVT = DstVT;
7001   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
7002          SplitSrcVT.getVectorNumElements() > 1) {
7003     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
7004     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
7005   }
7006
7007   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7008     return SDValue();
7009
7010   SDLoc DL(N);
7011   const unsigned NumSplits =
7012       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7013   const unsigned Stride = SplitSrcVT.getStoreSize();
7014   SmallVector<SDValue, 4> Loads;
7015   SmallVector<SDValue, 4> Chains;
7016
7017   SDValue BasePtr = LN0->getBasePtr();
7018   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7019     const unsigned Offset = Idx * Stride;
7020     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7021
7022     SDValue SplitLoad = DAG.getExtLoad(
7023         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7024         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7025         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7026
7027     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7028                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7029
7030     Loads.push_back(SplitLoad.getValue(0));
7031     Chains.push_back(SplitLoad.getValue(1));
7032   }
7033
7034   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7035   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7036
7037   // Simplify TF.
7038   AddToWorklist(NewChain.getNode());
7039
7040   CombineTo(N, NewValue);
7041
7042   // Replace uses of the original load (before extension)
7043   // with a truncate of the concatenated sextloaded vectors.
7044   SDValue Trunc =
7045       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7046   CombineTo(N0.getNode(), Trunc, NewChain);
7047   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
7048                   (ISD::NodeType)N->getOpcode());
7049   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7050 }
7051
7052 /// If we're narrowing or widening the result of a vector select and the final
7053 /// size is the same size as a setcc (compare) feeding the select, then try to
7054 /// apply the cast operation to the select's operands because matching vector
7055 /// sizes for a select condition and other operands should be more efficient.
7056 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7057   unsigned CastOpcode = Cast->getOpcode();
7058   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7059           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7060           CastOpcode == ISD::FP_ROUND) &&
7061          "Unexpected opcode for vector select narrowing/widening");
7062
7063   // We only do this transform before legal ops because the pattern may be
7064   // obfuscated by target-specific operations after legalization. Do not create
7065   // an illegal select op, however, because that may be difficult to lower.
7066   EVT VT = Cast->getValueType(0);
7067   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7068     return SDValue();
7069
7070   SDValue VSel = Cast->getOperand(0);
7071   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7072       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7073     return SDValue();
7074
7075   // Does the setcc have the same vector size as the casted select?
7076   SDValue SetCC = VSel.getOperand(0);
7077   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7078   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7079     return SDValue();
7080
7081   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7082   SDValue A = VSel.getOperand(1);
7083   SDValue B = VSel.getOperand(2);
7084   SDValue CastA, CastB;
7085   SDLoc DL(Cast);
7086   if (CastOpcode == ISD::FP_ROUND) {
7087     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7088     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7089     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7090   } else {
7091     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7092     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7093   }
7094   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7095 }
7096
7097 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7098   SDValue N0 = N->getOperand(0);
7099   EVT VT = N->getValueType(0);
7100   SDLoc DL(N);
7101
7102   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7103                                               LegalOperations))
7104     return SDValue(Res, 0);
7105
7106   // fold (sext (sext x)) -> (sext x)
7107   // fold (sext (aext x)) -> (sext x)
7108   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7109     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7110
7111   if (N0.getOpcode() == ISD::TRUNCATE) {
7112     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7113     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7114     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7115       SDNode *oye = N0.getOperand(0).getNode();
7116       if (NarrowLoad.getNode() != N0.getNode()) {
7117         CombineTo(N0.getNode(), NarrowLoad);
7118         // CombineTo deleted the truncate, if needed, but not what's under it.
7119         AddToWorklist(oye);
7120       }
7121       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7122     }
7123
7124     // See if the value being truncated is already sign extended.  If so, just
7125     // eliminate the trunc/sext pair.
7126     SDValue Op = N0.getOperand(0);
7127     unsigned OpBits   = Op.getScalarValueSizeInBits();
7128     unsigned MidBits  = N0.getScalarValueSizeInBits();
7129     unsigned DestBits = VT.getScalarSizeInBits();
7130     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7131
7132     if (OpBits == DestBits) {
7133       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7134       // bits, it is already ready.
7135       if (NumSignBits > DestBits-MidBits)
7136         return Op;
7137     } else if (OpBits < DestBits) {
7138       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7139       // bits, just sext from i32.
7140       if (NumSignBits > OpBits-MidBits)
7141         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7142     } else {
7143       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7144       // bits, just truncate to i32.
7145       if (NumSignBits > OpBits-MidBits)
7146         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7147     }
7148
7149     // fold (sext (truncate x)) -> (sextinreg x).
7150     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7151                                                  N0.getValueType())) {
7152       if (OpBits < DestBits)
7153         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7154       else if (OpBits > DestBits)
7155         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7156       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7157                          DAG.getValueType(N0.getValueType()));
7158     }
7159   }
7160
7161   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7162   // Only generate vector extloads when 1) they're legal, and 2) they are
7163   // deemed desirable by the target.
7164   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7165       ((!LegalOperations && !VT.isVector() &&
7166         !cast<LoadSDNode>(N0)->isVolatile()) ||
7167        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7168     bool DoXform = true;
7169     SmallVector<SDNode*, 4> SetCCs;
7170     if (!N0.hasOneUse())
7171       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7172     if (VT.isVector())
7173       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7174     if (DoXform) {
7175       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7176       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7177                                        LN0->getBasePtr(), N0.getValueType(),
7178                                        LN0->getMemOperand());
7179       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7180                                   N0.getValueType(), ExtLoad);
7181       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7182       // If the load value is used only by N, replace it via CombineTo N.
7183       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7184       CombineTo(N, ExtLoad);
7185       if (NoReplaceTrunc)
7186         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7187       else
7188         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7189       return SDValue(N, 0);
7190     }
7191   }
7192
7193   // fold (sext (load x)) to multiple smaller sextloads.
7194   // Only on illegal but splittable vectors.
7195   if (SDValue ExtLoad = CombineExtLoad(N))
7196     return ExtLoad;
7197
7198   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7199   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7200   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7201       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7202     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7203     EVT MemVT = LN0->getMemoryVT();
7204     if ((!LegalOperations && !LN0->isVolatile()) ||
7205         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7206       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7207                                        LN0->getBasePtr(), MemVT,
7208                                        LN0->getMemOperand());
7209       CombineTo(N, ExtLoad);
7210       CombineTo(N0.getNode(),
7211                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7212                             N0.getValueType(), ExtLoad),
7213                 ExtLoad.getValue(1));
7214       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7215     }
7216   }
7217
7218   // fold (sext (and/or/xor (load x), cst)) ->
7219   //      (and/or/xor (sextload x), (sext cst))
7220   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7221        N0.getOpcode() == ISD::XOR) &&
7222       isa<LoadSDNode>(N0.getOperand(0)) &&
7223       N0.getOperand(1).getOpcode() == ISD::Constant &&
7224       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7225       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7226     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7227     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7228       bool DoXform = true;
7229       SmallVector<SDNode*, 4> SetCCs;
7230       if (!N0.hasOneUse())
7231         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7232                                           SetCCs, TLI);
7233       if (DoXform) {
7234         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7235                                          LN0->getChain(), LN0->getBasePtr(),
7236                                          LN0->getMemoryVT(),
7237                                          LN0->getMemOperand());
7238         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7239         Mask = Mask.sext(VT.getSizeInBits());
7240         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7241                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7242         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7243                                     SDLoc(N0.getOperand(0)),
7244                                     N0.getOperand(0).getValueType(), ExtLoad);
7245         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7246         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7247         CombineTo(N, And);
7248         if (NoReplaceTrunc)
7249           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7250         else
7251           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7252         return SDValue(N,0); // Return N so it doesn't get rechecked!
7253       }
7254     }
7255   }
7256
7257   if (N0.getOpcode() == ISD::SETCC) {
7258     SDValue N00 = N0.getOperand(0);
7259     SDValue N01 = N0.getOperand(1);
7260     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7261     EVT N00VT = N0.getOperand(0).getValueType();
7262
7263     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7264     // Only do this before legalize for now.
7265     if (VT.isVector() && !LegalOperations &&
7266         TLI.getBooleanContents(N00VT) ==
7267             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7268       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7269       // of the same size as the compared operands. Only optimize sext(setcc())
7270       // if this is the case.
7271       EVT SVT = getSetCCResultType(N00VT);
7272
7273       // We know that the # elements of the results is the same as the
7274       // # elements of the compare (and the # elements of the compare result
7275       // for that matter).  Check to see that they are the same size.  If so,
7276       // we know that the element size of the sext'd result matches the
7277       // element size of the compare operands.
7278       if (VT.getSizeInBits() == SVT.getSizeInBits())
7279         return DAG.getSetCC(DL, VT, N00, N01, CC);
7280
7281       // If the desired elements are smaller or larger than the source
7282       // elements, we can use a matching integer vector type and then
7283       // truncate/sign extend.
7284       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7285       if (SVT == MatchingVecType) {
7286         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7287         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7288       }
7289     }
7290
7291     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7292     // Here, T can be 1 or -1, depending on the type of the setcc and
7293     // getBooleanContents().
7294     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7295
7296     // To determine the "true" side of the select, we need to know the high bit
7297     // of the value returned by the setcc if it evaluates to true.
7298     // If the type of the setcc is i1, then the true case of the select is just
7299     // sext(i1 1), that is, -1.
7300     // If the type of the setcc is larger (say, i8) then the value of the high
7301     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7302     // of the appropriate width.
7303     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7304                                            : TLI.getConstTrueVal(DAG, VT, DL);
7305     SDValue Zero = DAG.getConstant(0, DL, VT);
7306     if (SDValue SCC =
7307             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7308       return SCC;
7309
7310     if (!VT.isVector()) {
7311       EVT SetCCVT = getSetCCResultType(N00VT);
7312       // Don't do this transform for i1 because there's a select transform
7313       // that would reverse it.
7314       // TODO: We should not do this transform at all without a target hook
7315       // because a sext is likely cheaper than a select?
7316       if (SetCCVT.getScalarSizeInBits() != 1 &&
7317           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7318         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7319         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7320       }
7321     }
7322   }
7323
7324   // fold (sext x) -> (zext x) if the sign bit is known zero.
7325   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7326       DAG.SignBitIsZero(N0))
7327     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7328
7329   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7330     return NewVSel;
7331
7332   return SDValue();
7333 }
7334
7335 // isTruncateOf - If N is a truncate of some other value, return true, record
7336 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7337 // This function computes KnownBits to avoid a duplicated call to
7338 // computeKnownBits in the caller.
7339 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7340                          KnownBits &Known) {
7341   if (N->getOpcode() == ISD::TRUNCATE) {
7342     Op = N->getOperand(0);
7343     DAG.computeKnownBits(Op, Known);
7344     return true;
7345   }
7346
7347   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7348       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7349     return false;
7350
7351   SDValue Op0 = N->getOperand(0);
7352   SDValue Op1 = N->getOperand(1);
7353   assert(Op0.getValueType() == Op1.getValueType());
7354
7355   if (isNullConstant(Op0))
7356     Op = Op1;
7357   else if (isNullConstant(Op1))
7358     Op = Op0;
7359   else
7360     return false;
7361
7362   DAG.computeKnownBits(Op, Known);
7363
7364   if (!(Known.Zero | 1).isAllOnesValue())
7365     return false;
7366
7367   return true;
7368 }
7369
7370 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7371   SDValue N0 = N->getOperand(0);
7372   EVT VT = N->getValueType(0);
7373
7374   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7375                                               LegalOperations))
7376     return SDValue(Res, 0);
7377
7378   // fold (zext (zext x)) -> (zext x)
7379   // fold (zext (aext x)) -> (zext x)
7380   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7381     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7382                        N0.getOperand(0));
7383
7384   // fold (zext (truncate x)) -> (zext x) or
7385   //      (zext (truncate x)) -> (truncate x)
7386   // This is valid when the truncated bits of x are already zero.
7387   // FIXME: We should extend this to work for vectors too.
7388   SDValue Op;
7389   KnownBits Known;
7390   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7391     APInt TruncatedBits =
7392       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7393       APInt(Op.getValueSizeInBits(), 0) :
7394       APInt::getBitsSet(Op.getValueSizeInBits(),
7395                         N0.getValueSizeInBits(),
7396                         std::min(Op.getValueSizeInBits(),
7397                                  VT.getSizeInBits()));
7398     if (TruncatedBits.isSubsetOf(Known.Zero))
7399       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7400   }
7401
7402   // fold (zext (truncate (load x))) -> (zext (smaller load x))
7403   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7404   if (N0.getOpcode() == ISD::TRUNCATE) {
7405     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7406       SDNode *oye = N0.getOperand(0).getNode();
7407       if (NarrowLoad.getNode() != N0.getNode()) {
7408         CombineTo(N0.getNode(), NarrowLoad);
7409         // CombineTo deleted the truncate, if needed, but not what's under it.
7410         AddToWorklist(oye);
7411       }
7412       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7413     }
7414   }
7415
7416   // fold (zext (truncate x)) -> (and x, mask)
7417   if (N0.getOpcode() == ISD::TRUNCATE) {
7418     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7419     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7420     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7421       SDNode *oye = N0.getOperand(0).getNode();
7422       if (NarrowLoad.getNode() != N0.getNode()) {
7423         CombineTo(N0.getNode(), NarrowLoad);
7424         // CombineTo deleted the truncate, if needed, but not what's under it.
7425         AddToWorklist(oye);
7426       }
7427       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7428     }
7429
7430     EVT SrcVT = N0.getOperand(0).getValueType();
7431     EVT MinVT = N0.getValueType();
7432
7433     // Try to mask before the extension to avoid having to generate a larger mask,
7434     // possibly over several sub-vectors.
7435     if (SrcVT.bitsLT(VT)) {
7436       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7437                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7438         SDValue Op = N0.getOperand(0);
7439         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7440         AddToWorklist(Op.getNode());
7441         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7442       }
7443     }
7444
7445     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7446       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7447       AddToWorklist(Op.getNode());
7448       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7449     }
7450   }
7451
7452   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7453   // if either of the casts is not free.
7454   if (N0.getOpcode() == ISD::AND &&
7455       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7456       N0.getOperand(1).getOpcode() == ISD::Constant &&
7457       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7458                            N0.getValueType()) ||
7459        !TLI.isZExtFree(N0.getValueType(), VT))) {
7460     SDValue X = N0.getOperand(0).getOperand(0);
7461     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7462     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7463     Mask = Mask.zext(VT.getSizeInBits());
7464     SDLoc DL(N);
7465     return DAG.getNode(ISD::AND, DL, VT,
7466                        X, DAG.getConstant(Mask, DL, VT));
7467   }
7468
7469   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7470   // Only generate vector extloads when 1) they're legal, and 2) they are
7471   // deemed desirable by the target.
7472   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7473       ((!LegalOperations && !VT.isVector() &&
7474         !cast<LoadSDNode>(N0)->isVolatile()) ||
7475        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7476     bool DoXform = true;
7477     SmallVector<SDNode*, 4> SetCCs;
7478     if (!N0.hasOneUse())
7479       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7480     if (VT.isVector())
7481       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7482     if (DoXform) {
7483       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7484       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7485                                        LN0->getChain(),
7486                                        LN0->getBasePtr(), N0.getValueType(),
7487                                        LN0->getMemOperand());
7488
7489       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7490                                   N0.getValueType(), ExtLoad);
7491       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
7492       // If the load value is used only by N, replace it via CombineTo N.
7493       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7494       CombineTo(N, ExtLoad);
7495       if (NoReplaceTrunc)
7496         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7497       else
7498         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7499       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7500     }
7501   }
7502
7503   // fold (zext (load x)) to multiple smaller zextloads.
7504   // Only on illegal but splittable vectors.
7505   if (SDValue ExtLoad = CombineExtLoad(N))
7506     return ExtLoad;
7507
7508   // fold (zext (and/or/xor (load x), cst)) ->
7509   //      (and/or/xor (zextload x), (zext cst))
7510   // Unless (and (load x) cst) will match as a zextload already and has
7511   // additional users.
7512   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7513        N0.getOpcode() == ISD::XOR) &&
7514       isa<LoadSDNode>(N0.getOperand(0)) &&
7515       N0.getOperand(1).getOpcode() == ISD::Constant &&
7516       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7517       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7518     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7519     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7520       bool DoXform = true;
7521       SmallVector<SDNode*, 4> SetCCs;
7522       if (!N0.hasOneUse()) {
7523         if (N0.getOpcode() == ISD::AND) {
7524           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7525           auto NarrowLoad = false;
7526           EVT LoadResultTy = AndC->getValueType(0);
7527           EVT ExtVT, LoadedVT;
7528           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7529                                NarrowLoad))
7530             DoXform = false;
7531         }
7532         if (DoXform)
7533           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7534                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7535       }
7536       if (DoXform) {
7537         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7538                                          LN0->getChain(), LN0->getBasePtr(),
7539                                          LN0->getMemoryVT(),
7540                                          LN0->getMemOperand());
7541         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7542         Mask = Mask.zext(VT.getSizeInBits());
7543         SDLoc DL(N);
7544         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7545                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7546         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7547                                     SDLoc(N0.getOperand(0)),
7548                                     N0.getOperand(0).getValueType(), ExtLoad);
7549         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND);
7550         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7551         CombineTo(N, And);
7552         if (NoReplaceTrunc)
7553           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7554         else
7555           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7556         return SDValue(N,0); // Return N so it doesn't get rechecked!
7557       }
7558     }
7559   }
7560
7561   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7562   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7563   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7564       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7565     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7566     EVT MemVT = LN0->getMemoryVT();
7567     if ((!LegalOperations && !LN0->isVolatile()) ||
7568         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7569       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7570                                        LN0->getChain(),
7571                                        LN0->getBasePtr(), MemVT,
7572                                        LN0->getMemOperand());
7573       CombineTo(N, ExtLoad);
7574       CombineTo(N0.getNode(),
7575                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7576                             ExtLoad),
7577                 ExtLoad.getValue(1));
7578       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7579     }
7580   }
7581
7582   if (N0.getOpcode() == ISD::SETCC) {
7583     // Only do this before legalize for now.
7584     if (!LegalOperations && VT.isVector() &&
7585         N0.getValueType().getVectorElementType() == MVT::i1) {
7586       EVT N00VT = N0.getOperand(0).getValueType();
7587       if (getSetCCResultType(N00VT) == N0.getValueType())
7588         return SDValue();
7589
7590       // We know that the # elements of the results is the same as the #
7591       // elements of the compare (and the # elements of the compare result for
7592       // that matter). Check to see that they are the same size. If so, we know
7593       // that the element size of the sext'd result matches the element size of
7594       // the compare operands.
7595       SDLoc DL(N);
7596       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7597       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7598         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7599         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7600                                      N0.getOperand(1), N0.getOperand(2));
7601         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7602       }
7603
7604       // If the desired elements are smaller or larger than the source
7605       // elements we can use a matching integer vector type and then
7606       // truncate/sign extend.
7607       EVT MatchingElementType = EVT::getIntegerVT(
7608           *DAG.getContext(), N00VT.getScalarSizeInBits());
7609       EVT MatchingVectorType = EVT::getVectorVT(
7610           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7611       SDValue VsetCC =
7612           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7613                       N0.getOperand(1), N0.getOperand(2));
7614       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7615                          VecOnes);
7616     }
7617
7618     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7619     SDLoc DL(N);
7620     if (SDValue SCC = SimplifySelectCC(
7621             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7622             DAG.getConstant(0, DL, VT),
7623             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7624       return SCC;
7625   }
7626
7627   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7628   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7629       isa<ConstantSDNode>(N0.getOperand(1)) &&
7630       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7631       N0.hasOneUse()) {
7632     SDValue ShAmt = N0.getOperand(1);
7633     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7634     if (N0.getOpcode() == ISD::SHL) {
7635       SDValue InnerZExt = N0.getOperand(0);
7636       // If the original shl may be shifting out bits, do not perform this
7637       // transformation.
7638       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7639         InnerZExt.getOperand(0).getValueSizeInBits();
7640       if (ShAmtVal > KnownZeroBits)
7641         return SDValue();
7642     }
7643
7644     SDLoc DL(N);
7645
7646     // Ensure that the shift amount is wide enough for the shifted value.
7647     if (VT.getSizeInBits() >= 256)
7648       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7649
7650     return DAG.getNode(N0.getOpcode(), DL, VT,
7651                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7652                        ShAmt);
7653   }
7654
7655   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7656     return NewVSel;
7657
7658   return SDValue();
7659 }
7660
7661 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7662   SDValue N0 = N->getOperand(0);
7663   EVT VT = N->getValueType(0);
7664
7665   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7666                                               LegalOperations))
7667     return SDValue(Res, 0);
7668
7669   // fold (aext (aext x)) -> (aext x)
7670   // fold (aext (zext x)) -> (zext x)
7671   // fold (aext (sext x)) -> (sext x)
7672   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
7673       N0.getOpcode() == ISD::ZERO_EXTEND ||
7674       N0.getOpcode() == ISD::SIGN_EXTEND)
7675     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7676
7677   // fold (aext (truncate (load x))) -> (aext (smaller load x))
7678   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7679   if (N0.getOpcode() == ISD::TRUNCATE) {
7680     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7681       SDNode *oye = N0.getOperand(0).getNode();
7682       if (NarrowLoad.getNode() != N0.getNode()) {
7683         CombineTo(N0.getNode(), NarrowLoad);
7684         // CombineTo deleted the truncate, if needed, but not what's under it.
7685         AddToWorklist(oye);
7686       }
7687       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7688     }
7689   }
7690
7691   // fold (aext (truncate x))
7692   if (N0.getOpcode() == ISD::TRUNCATE)
7693     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7694
7695   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7696   // if the trunc is not free.
7697   if (N0.getOpcode() == ISD::AND &&
7698       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7699       N0.getOperand(1).getOpcode() == ISD::Constant &&
7700       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7701                           N0.getValueType())) {
7702     SDLoc DL(N);
7703     SDValue X = N0.getOperand(0).getOperand(0);
7704     X = DAG.getAnyExtOrTrunc(X, DL, VT);
7705     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7706     Mask = Mask.zext(VT.getSizeInBits());
7707     return DAG.getNode(ISD::AND, DL, VT,
7708                        X, DAG.getConstant(Mask, DL, VT));
7709   }
7710
7711   // fold (aext (load x)) -> (aext (truncate (extload x)))
7712   // None of the supported targets knows how to perform load and any_ext
7713   // on vectors in one instruction.  We only perform this transformation on
7714   // scalars.
7715   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7716       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7717       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7718     bool DoXform = true;
7719     SmallVector<SDNode*, 4> SetCCs;
7720     if (!N0.hasOneUse())
7721       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7722     if (DoXform) {
7723       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7724       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7725                                        LN0->getChain(),
7726                                        LN0->getBasePtr(), N0.getValueType(),
7727                                        LN0->getMemOperand());
7728       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7729                                   N0.getValueType(), ExtLoad);
7730       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7731                       ISD::ANY_EXTEND);
7732       // If the load value is used only by N, replace it via CombineTo N.
7733       bool NoReplaceTrunc = N0.hasOneUse();
7734       CombineTo(N, ExtLoad); 
7735       if (NoReplaceTrunc)
7736         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7737       else
7738         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7739       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7740     }
7741   }
7742
7743   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7744   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7745   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
7746   if (N0.getOpcode() == ISD::LOAD &&
7747       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7748       N0.hasOneUse()) {
7749     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7750     ISD::LoadExtType ExtType = LN0->getExtensionType();
7751     EVT MemVT = LN0->getMemoryVT();
7752     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7753       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7754                                        VT, LN0->getChain(), LN0->getBasePtr(),
7755                                        MemVT, LN0->getMemOperand());
7756       CombineTo(N, ExtLoad);
7757       CombineTo(N0.getNode(),
7758                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7759                             N0.getValueType(), ExtLoad),
7760                 ExtLoad.getValue(1));
7761       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7762     }
7763   }
7764
7765   if (N0.getOpcode() == ISD::SETCC) {
7766     // For vectors:
7767     // aext(setcc) -> vsetcc
7768     // aext(setcc) -> truncate(vsetcc)
7769     // aext(setcc) -> aext(vsetcc)
7770     // Only do this before legalize for now.
7771     if (VT.isVector() && !LegalOperations) {
7772       EVT N0VT = N0.getOperand(0).getValueType();
7773         // We know that the # elements of the results is the same as the
7774         // # elements of the compare (and the # elements of the compare result
7775         // for that matter).  Check to see that they are the same size.  If so,
7776         // we know that the element size of the sext'd result matches the
7777         // element size of the compare operands.
7778       if (VT.getSizeInBits() == N0VT.getSizeInBits())
7779         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7780                              N0.getOperand(1),
7781                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
7782       // If the desired elements are smaller or larger than the source
7783       // elements we can use a matching integer vector type and then
7784       // truncate/any extend
7785       else {
7786         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7787         SDValue VsetCC =
7788           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7789                         N0.getOperand(1),
7790                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
7791         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7792       }
7793     }
7794
7795     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7796     SDLoc DL(N);
7797     if (SDValue SCC = SimplifySelectCC(
7798             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7799             DAG.getConstant(0, DL, VT),
7800             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7801       return SCC;
7802   }
7803
7804   return SDValue();
7805 }
7806
7807 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7808   SDValue N0 = N->getOperand(0);
7809   SDValue N1 = N->getOperand(1);
7810   EVT EVT = cast<VTSDNode>(N1)->getVT();
7811
7812   // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7813   if (N0.getOpcode() == ISD::AssertZext &&
7814       EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7815     return N0;
7816
7817   return SDValue();
7818 }
7819
7820 /// See if the specified operand can be simplified with the knowledge that only
7821 /// the bits specified by Mask are used.  If so, return the simpler operand,
7822 /// otherwise return a null SDValue.
7823 ///
7824 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
7825 /// simplify nodes with multiple uses more aggressively.)
7826 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7827   switch (V.getOpcode()) {
7828   default: break;
7829   case ISD::Constant: {
7830     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7831     assert(CV && "Const value should be ConstSDNode.");
7832     const APInt &CVal = CV->getAPIntValue();
7833     APInt NewVal = CVal & Mask;
7834     if (NewVal != CVal)
7835       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7836     break;
7837   }
7838   case ISD::OR:
7839   case ISD::XOR:
7840     // If the LHS or RHS don't contribute bits to the or, drop them.
7841     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7842       return V.getOperand(1);
7843     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7844       return V.getOperand(0);
7845     break;
7846   case ISD::SRL:
7847     // Only look at single-use SRLs.
7848     if (!V.getNode()->hasOneUse())
7849       break;
7850     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7851       // See if we can recursively simplify the LHS.
7852       unsigned Amt = RHSC->getZExtValue();
7853
7854       // Watch out for shift count overflow though.
7855       if (Amt >= Mask.getBitWidth()) break;
7856       APInt NewMask = Mask << Amt;
7857       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7858         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7859                            SimplifyLHS, V.getOperand(1));
7860     }
7861     break;
7862   case ISD::AND: {
7863     // X & -1 -> X (ignoring bits which aren't demanded).
7864     ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
7865     if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
7866       return V.getOperand(0);
7867     break;
7868   }
7869   }
7870   return SDValue();
7871 }
7872
7873 /// If the result of a wider load is shifted to right of N  bits and then
7874 /// truncated to a narrower type and where N is a multiple of number of bits of
7875 /// the narrower type, transform it to a narrower load from address + N / num of
7876 /// bits of new type. If the result is to be extended, also fold the extension
7877 /// to form a extending load.
7878 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7879   unsigned Opc = N->getOpcode();
7880
7881   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7882   SDValue N0 = N->getOperand(0);
7883   EVT VT = N->getValueType(0);
7884   EVT ExtVT = VT;
7885
7886   // This transformation isn't valid for vector loads.
7887   if (VT.isVector())
7888     return SDValue();
7889
7890   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7891   // extended to VT.
7892   if (Opc == ISD::SIGN_EXTEND_INREG) {
7893     ExtType = ISD::SEXTLOAD;
7894     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7895   } else if (Opc == ISD::SRL) {
7896     // Another special-case: SRL is basically zero-extending a narrower value.
7897     ExtType = ISD::ZEXTLOAD;
7898     N0 = SDValue(N, 0);
7899     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7900     if (!N01) return SDValue();
7901     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7902                               VT.getSizeInBits() - N01->getZExtValue());
7903   }
7904   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7905     return SDValue();
7906
7907   unsigned EVTBits = ExtVT.getSizeInBits();
7908
7909   // Do not generate loads of non-round integer types since these can
7910   // be expensive (and would be wrong if the type is not byte sized).
7911   if (!ExtVT.isRound())
7912     return SDValue();
7913
7914   unsigned ShAmt = 0;
7915   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7916     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7917       ShAmt = N01->getZExtValue();
7918       // Is the shift amount a multiple of size of VT?
7919       if ((ShAmt & (EVTBits-1)) == 0) {
7920         N0 = N0.getOperand(0);
7921         // Is the load width a multiple of size of VT?
7922         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7923           return SDValue();
7924       }
7925
7926       // At this point, we must have a load or else we can't do the transform.
7927       if (!isa<LoadSDNode>(N0)) return SDValue();
7928
7929       // Because a SRL must be assumed to *need* to zero-extend the high bits
7930       // (as opposed to anyext the high bits), we can't combine the zextload
7931       // lowering of SRL and an sextload.
7932       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7933         return SDValue();
7934
7935       // If the shift amount is larger than the input type then we're not
7936       // accessing any of the loaded bytes.  If the load was a zextload/extload
7937       // then the result of the shift+trunc is zero/undef (handled elsewhere).
7938       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7939         return SDValue();
7940     }
7941   }
7942
7943   // If the load is shifted left (and the result isn't shifted back right),
7944   // we can fold the truncate through the shift.
7945   unsigned ShLeftAmt = 0;
7946   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7947       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7948     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7949       ShLeftAmt = N01->getZExtValue();
7950       N0 = N0.getOperand(0);
7951     }
7952   }
7953
7954   // If we haven't found a load, we can't narrow it.  Don't transform one with
7955   // multiple uses, this would require adding a new load.
7956   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7957     return SDValue();
7958
7959   // Don't change the width of a volatile load.
7960   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7961   if (LN0->isVolatile())
7962     return SDValue();
7963
7964   // Verify that we are actually reducing a load width here.
7965   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7966     return SDValue();
7967
7968   // For the transform to be legal, the load must produce only two values
7969   // (the value loaded and the chain).  Don't transform a pre-increment
7970   // load, for example, which produces an extra value.  Otherwise the
7971   // transformation is not equivalent, and the downstream logic to replace
7972   // uses gets things wrong.
7973   if (LN0->getNumValues() > 2)
7974     return SDValue();
7975
7976   // If the load that we're shrinking is an extload and we're not just
7977   // discarding the extension we can't simply shrink the load. Bail.
7978   // TODO: It would be possible to merge the extensions in some cases.
7979   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7980       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7981     return SDValue();
7982
7983   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7984     return SDValue();
7985
7986   EVT PtrType = N0.getOperand(1).getValueType();
7987
7988   if (PtrType == MVT::Untyped || PtrType.isExtended())
7989     // It's not possible to generate a constant of extended or untyped type.
7990     return SDValue();
7991
7992   // For big endian targets, we need to adjust the offset to the pointer to
7993   // load the correct bytes.
7994   if (DAG.getDataLayout().isBigEndian()) {
7995     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7996     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7997     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7998   }
7999
8000   uint64_t PtrOff = ShAmt / 8;
8001   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
8002   SDLoc DL(LN0);
8003   // The original load itself didn't wrap, so an offset within it doesn't.
8004   SDNodeFlags Flags;
8005   Flags.setNoUnsignedWrap(true);
8006   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
8007                                PtrType, LN0->getBasePtr(),
8008                                DAG.getConstant(PtrOff, DL, PtrType),
8009                                Flags);
8010   AddToWorklist(NewPtr.getNode());
8011
8012   SDValue Load;
8013   if (ExtType == ISD::NON_EXTLOAD)
8014     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8015                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8016                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8017   else
8018     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8019                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8020                           NewAlign, LN0->getMemOperand()->getFlags(),
8021                           LN0->getAAInfo());
8022
8023   // Replace the old load's chain with the new load's chain.
8024   WorklistRemover DeadNodes(*this);
8025   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8026
8027   // Shift the result left, if we've swallowed a left shift.
8028   SDValue Result = Load;
8029   if (ShLeftAmt != 0) {
8030     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8031     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8032       ShImmTy = VT;
8033     // If the shift amount is as large as the result size (but, presumably,
8034     // no larger than the source) then the useful bits of the result are
8035     // zero; we can't simply return the shortened shift, because the result
8036     // of that operation is undefined.
8037     SDLoc DL(N0);
8038     if (ShLeftAmt >= VT.getSizeInBits())
8039       Result = DAG.getConstant(0, DL, VT);
8040     else
8041       Result = DAG.getNode(ISD::SHL, DL, VT,
8042                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8043   }
8044
8045   // Return the new loaded value.
8046   return Result;
8047 }
8048
8049 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8050   SDValue N0 = N->getOperand(0);
8051   SDValue N1 = N->getOperand(1);
8052   EVT VT = N->getValueType(0);
8053   EVT EVT = cast<VTSDNode>(N1)->getVT();
8054   unsigned VTBits = VT.getScalarSizeInBits();
8055   unsigned EVTBits = EVT.getScalarSizeInBits();
8056
8057   if (N0.isUndef())
8058     return DAG.getUNDEF(VT);
8059
8060   // fold (sext_in_reg c1) -> c1
8061   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8062     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8063
8064   // If the input is already sign extended, just drop the extension.
8065   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8066     return N0;
8067
8068   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8069   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8070       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8071     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8072                        N0.getOperand(0), N1);
8073
8074   // fold (sext_in_reg (sext x)) -> (sext x)
8075   // fold (sext_in_reg (aext x)) -> (sext x)
8076   // if x is small enough.
8077   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8078     SDValue N00 = N0.getOperand(0);
8079     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8080         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8081       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8082   }
8083
8084   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8085   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8086        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8087        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8088       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8089     if (!LegalOperations ||
8090         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8091       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8092   }
8093
8094   // fold (sext_in_reg (zext x)) -> (sext x)
8095   // iff we are extending the source sign bit.
8096   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8097     SDValue N00 = N0.getOperand(0);
8098     if (N00.getScalarValueSizeInBits() == EVTBits &&
8099         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8100       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8101   }
8102
8103   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8104   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8105     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8106
8107   // fold operands of sext_in_reg based on knowledge that the top bits are not
8108   // demanded.
8109   if (SimplifyDemandedBits(SDValue(N, 0)))
8110     return SDValue(N, 0);
8111
8112   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8113   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8114   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8115     return NarrowLoad;
8116
8117   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8118   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8119   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8120   if (N0.getOpcode() == ISD::SRL) {
8121     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8122       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8123         // We can turn this into an SRA iff the input to the SRL is already sign
8124         // extended enough.
8125         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8126         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8127           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8128                              N0.getOperand(0), N0.getOperand(1));
8129       }
8130   }
8131
8132   // fold (sext_inreg (extload x)) -> (sextload x)
8133   if (ISD::isEXTLoad(N0.getNode()) &&
8134       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8135       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8136       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8137        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8138     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8139     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8140                                      LN0->getChain(),
8141                                      LN0->getBasePtr(), EVT,
8142                                      LN0->getMemOperand());
8143     CombineTo(N, ExtLoad);
8144     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8145     AddToWorklist(ExtLoad.getNode());
8146     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8147   }
8148   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8149   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8150       N0.hasOneUse() &&
8151       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8152       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8153        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8154     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8155     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8156                                      LN0->getChain(),
8157                                      LN0->getBasePtr(), EVT,
8158                                      LN0->getMemOperand());
8159     CombineTo(N, ExtLoad);
8160     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8161     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8162   }
8163
8164   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8165   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8166     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8167                                            N0.getOperand(1), false))
8168       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8169                          BSwap, N1);
8170   }
8171
8172   return SDValue();
8173 }
8174
8175 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8176   SDValue N0 = N->getOperand(0);
8177   EVT VT = N->getValueType(0);
8178
8179   if (N0.isUndef())
8180     return DAG.getUNDEF(VT);
8181
8182   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8183                                               LegalOperations))
8184     return SDValue(Res, 0);
8185
8186   return SDValue();
8187 }
8188
8189 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8190   SDValue N0 = N->getOperand(0);
8191   EVT VT = N->getValueType(0);
8192
8193   if (N0.isUndef())
8194     return DAG.getUNDEF(VT);
8195
8196   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8197                                               LegalOperations))
8198     return SDValue(Res, 0);
8199
8200   return SDValue();
8201 }
8202
8203 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8204   SDValue N0 = N->getOperand(0);
8205   EVT VT = N->getValueType(0);
8206   bool isLE = DAG.getDataLayout().isLittleEndian();
8207
8208   // noop truncate
8209   if (N0.getValueType() == N->getValueType(0))
8210     return N0;
8211   // fold (truncate c1) -> c1
8212   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8213     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8214   // fold (truncate (truncate x)) -> (truncate x)
8215   if (N0.getOpcode() == ISD::TRUNCATE)
8216     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8217   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8218   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8219       N0.getOpcode() == ISD::SIGN_EXTEND ||
8220       N0.getOpcode() == ISD::ANY_EXTEND) {
8221     // if the source is smaller than the dest, we still need an extend.
8222     if (N0.getOperand(0).getValueType().bitsLT(VT))
8223       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8224     // if the source is larger than the dest, than we just need the truncate.
8225     if (N0.getOperand(0).getValueType().bitsGT(VT))
8226       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8227     // if the source and dest are the same type, we can drop both the extend
8228     // and the truncate.
8229     return N0.getOperand(0);
8230   }
8231
8232   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8233   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8234     return SDValue();
8235
8236   // Fold extract-and-trunc into a narrow extract. For example:
8237   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8238   //   i32 y = TRUNCATE(i64 x)
8239   //        -- becomes --
8240   //   v16i8 b = BITCAST (v2i64 val)
8241   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8242   //
8243   // Note: We only run this optimization after type legalization (which often
8244   // creates this pattern) and before operation legalization after which
8245   // we need to be more careful about the vector instructions that we generate.
8246   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8247       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8248
8249     EVT VecTy = N0.getOperand(0).getValueType();
8250     EVT ExTy = N0.getValueType();
8251     EVT TrTy = N->getValueType(0);
8252
8253     unsigned NumElem = VecTy.getVectorNumElements();
8254     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8255
8256     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8257     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8258
8259     SDValue EltNo = N0->getOperand(1);
8260     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8261       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8262       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8263       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8264
8265       SDLoc DL(N);
8266       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8267                          DAG.getBitcast(NVT, N0.getOperand(0)),
8268                          DAG.getConstant(Index, DL, IndexTy));
8269     }
8270   }
8271
8272   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8273   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8274     EVT SrcVT = N0.getValueType();
8275     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8276         TLI.isTruncateFree(SrcVT, VT)) {
8277       SDLoc SL(N0);
8278       SDValue Cond = N0.getOperand(0);
8279       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8280       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8281       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8282     }
8283   }
8284
8285   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8286   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8287       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8288       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8289     SDValue Amt = N0.getOperand(1);
8290     KnownBits Known;
8291     DAG.computeKnownBits(Amt, Known);
8292     unsigned Size = VT.getScalarSizeInBits();
8293     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8294       SDLoc SL(N);
8295       EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8296
8297       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8298       if (AmtVT != Amt.getValueType()) {
8299         Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8300         AddToWorklist(Amt.getNode());
8301       }
8302       return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8303     }
8304   }
8305
8306   // Fold a series of buildvector, bitcast, and truncate if possible.
8307   // For example fold
8308   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8309   //   (2xi32 (buildvector x, y)).
8310   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8311       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8312       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8313       N0.getOperand(0).hasOneUse()) {
8314
8315     SDValue BuildVect = N0.getOperand(0);
8316     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8317     EVT TruncVecEltTy = VT.getVectorElementType();
8318
8319     // Check that the element types match.
8320     if (BuildVectEltTy == TruncVecEltTy) {
8321       // Now we only need to compute the offset of the truncated elements.
8322       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8323       unsigned TruncVecNumElts = VT.getVectorNumElements();
8324       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8325
8326       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8327              "Invalid number of elements");
8328
8329       SmallVector<SDValue, 8> Opnds;
8330       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8331         Opnds.push_back(BuildVect.getOperand(i));
8332
8333       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8334     }
8335   }
8336
8337   // See if we can simplify the input to this truncate through knowledge that
8338   // only the low bits are being used.
8339   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8340   // Currently we only perform this optimization on scalars because vectors
8341   // may have different active low bits.
8342   if (!VT.isVector()) {
8343     if (SDValue Shorter =
8344             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
8345                                                      VT.getSizeInBits())))
8346       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8347   }
8348
8349   // fold (truncate (load x)) -> (smaller load x)
8350   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8351   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8352     if (SDValue Reduced = ReduceLoadWidth(N))
8353       return Reduced;
8354
8355     // Handle the case where the load remains an extending load even
8356     // after truncation.
8357     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8358       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8359       if (!LN0->isVolatile() &&
8360           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8361         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8362                                          VT, LN0->getChain(), LN0->getBasePtr(),
8363                                          LN0->getMemoryVT(),
8364                                          LN0->getMemOperand());
8365         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8366         return NewLoad;
8367       }
8368     }
8369   }
8370
8371   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8372   // where ... are all 'undef'.
8373   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8374     SmallVector<EVT, 8> VTs;
8375     SDValue V;
8376     unsigned Idx = 0;
8377     unsigned NumDefs = 0;
8378
8379     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8380       SDValue X = N0.getOperand(i);
8381       if (!X.isUndef()) {
8382         V = X;
8383         Idx = i;
8384         NumDefs++;
8385       }
8386       // Stop if more than one members are non-undef.
8387       if (NumDefs > 1)
8388         break;
8389       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8390                                      VT.getVectorElementType(),
8391                                      X.getValueType().getVectorNumElements()));
8392     }
8393
8394     if (NumDefs == 0)
8395       return DAG.getUNDEF(VT);
8396
8397     if (NumDefs == 1) {
8398       assert(V.getNode() && "The single defined operand is empty!");
8399       SmallVector<SDValue, 8> Opnds;
8400       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8401         if (i != Idx) {
8402           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8403           continue;
8404         }
8405         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8406         AddToWorklist(NV.getNode());
8407         Opnds.push_back(NV);
8408       }
8409       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8410     }
8411   }
8412
8413   // Fold truncate of a bitcast of a vector to an extract of the low vector
8414   // element.
8415   //
8416   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
8417   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8418     SDValue VecSrc = N0.getOperand(0);
8419     EVT SrcVT = VecSrc.getValueType();
8420     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8421         (!LegalOperations ||
8422          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8423       SDLoc SL(N);
8424
8425       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8426       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8427                          VecSrc, DAG.getConstant(0, SL, IdxVT));
8428     }
8429   }
8430
8431   // Simplify the operands using demanded-bits information.
8432   if (!VT.isVector() &&
8433       SimplifyDemandedBits(SDValue(N, 0)))
8434     return SDValue(N, 0);
8435
8436   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8437   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8438   // When the adde's carry is not used.
8439   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8440       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8441       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8442     SDLoc SL(N);
8443     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8444     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8445     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8446     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8447   }
8448
8449   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8450     return NewVSel;
8451
8452   return SDValue();
8453 }
8454
8455 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8456   SDValue Elt = N->getOperand(i);
8457   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8458     return Elt.getNode();
8459   return Elt.getOperand(Elt.getResNo()).getNode();
8460 }
8461
8462 /// build_pair (load, load) -> load
8463 /// if load locations are consecutive.
8464 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8465   assert(N->getOpcode() == ISD::BUILD_PAIR);
8466
8467   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8468   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8469   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8470       LD1->getAddressSpace() != LD2->getAddressSpace())
8471     return SDValue();
8472   EVT LD1VT = LD1->getValueType(0);
8473   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8474   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8475       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8476     unsigned Align = LD1->getAlignment();
8477     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8478         VT.getTypeForEVT(*DAG.getContext()));
8479
8480     if (NewAlign <= Align &&
8481         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8482       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8483                          LD1->getPointerInfo(), Align);
8484   }
8485
8486   return SDValue();
8487 }
8488
8489 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8490   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8491   // and Lo parts; on big-endian machines it doesn't.
8492   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8493 }
8494
8495 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8496                                     const TargetLowering &TLI) {
8497   // If this is not a bitcast to an FP type or if the target doesn't have
8498   // IEEE754-compliant FP logic, we're done.
8499   EVT VT = N->getValueType(0);
8500   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8501     return SDValue();
8502
8503   // TODO: Use splat values for the constant-checking below and remove this
8504   // restriction.
8505   SDValue N0 = N->getOperand(0);
8506   EVT SourceVT = N0.getValueType();
8507   if (SourceVT.isVector())
8508     return SDValue();
8509
8510   unsigned FPOpcode;
8511   APInt SignMask;
8512   switch (N0.getOpcode()) {
8513   case ISD::AND:
8514     FPOpcode = ISD::FABS;
8515     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8516     break;
8517   case ISD::XOR:
8518     FPOpcode = ISD::FNEG;
8519     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8520     break;
8521   // TODO: ISD::OR --> ISD::FNABS?
8522   default:
8523     return SDValue();
8524   }
8525
8526   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8527   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8528   SDValue LogicOp0 = N0.getOperand(0);
8529   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8530   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8531       LogicOp0.getOpcode() == ISD::BITCAST &&
8532       LogicOp0->getOperand(0).getValueType() == VT)
8533     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8534
8535   return SDValue();
8536 }
8537
8538 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8539   SDValue N0 = N->getOperand(0);
8540   EVT VT = N->getValueType(0);
8541
8542   if (N0.isUndef())
8543     return DAG.getUNDEF(VT);
8544
8545   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8546   // Only do this before legalize, since afterward the target may be depending
8547   // on the bitconvert.
8548   // First check to see if this is all constant.
8549   if (!LegalTypes &&
8550       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8551       VT.isVector()) {
8552     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8553
8554     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8555     assert(!DestEltVT.isVector() &&
8556            "Element type of vector ValueType must not be vector!");
8557     if (isSimple)
8558       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8559   }
8560
8561   // If the input is a constant, let getNode fold it.
8562   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8563     // If we can't allow illegal operations, we need to check that this is just
8564     // a fp -> int or int -> conversion and that the resulting operation will
8565     // be legal.
8566     if (!LegalOperations ||
8567         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8568          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8569         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8570          TLI.isOperationLegal(ISD::Constant, VT)))
8571       return DAG.getBitcast(VT, N0);
8572   }
8573
8574   // (conv (conv x, t1), t2) -> (conv x, t2)
8575   if (N0.getOpcode() == ISD::BITCAST)
8576     return DAG.getBitcast(VT, N0.getOperand(0));
8577
8578   // fold (conv (load x)) -> (load (conv*)x)
8579   // If the resultant load doesn't need a higher alignment than the original!
8580   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8581       // Do not change the width of a volatile load.
8582       !cast<LoadSDNode>(N0)->isVolatile() &&
8583       // Do not remove the cast if the types differ in endian layout.
8584       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8585           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8586       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8587       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8588     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8589     unsigned OrigAlign = LN0->getAlignment();
8590
8591     bool Fast = false;
8592     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8593                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8594         Fast) {
8595       SDValue Load =
8596           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8597                       LN0->getPointerInfo(), OrigAlign,
8598                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8599       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8600       return Load;
8601     }
8602   }
8603
8604   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8605     return V;
8606
8607   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8608   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8609   //
8610   // For ppc_fp128:
8611   // fold (bitcast (fneg x)) ->
8612   //     flipbit = signbit
8613   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8614   //
8615   // fold (bitcast (fabs x)) ->
8616   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8617   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8618   // This often reduces constant pool loads.
8619   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8620        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8621       N0.getNode()->hasOneUse() && VT.isInteger() &&
8622       !VT.isVector() && !N0.getValueType().isVector()) {
8623     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8624     AddToWorklist(NewConv.getNode());
8625
8626     SDLoc DL(N);
8627     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8628       assert(VT.getSizeInBits() == 128);
8629       SDValue SignBit = DAG.getConstant(
8630           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8631       SDValue FlipBit;
8632       if (N0.getOpcode() == ISD::FNEG) {
8633         FlipBit = SignBit;
8634         AddToWorklist(FlipBit.getNode());
8635       } else {
8636         assert(N0.getOpcode() == ISD::FABS);
8637         SDValue Hi =
8638             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8639                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8640                                               SDLoc(NewConv)));
8641         AddToWorklist(Hi.getNode());
8642         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8643         AddToWorklist(FlipBit.getNode());
8644       }
8645       SDValue FlipBits =
8646           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8647       AddToWorklist(FlipBits.getNode());
8648       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8649     }
8650     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8651     if (N0.getOpcode() == ISD::FNEG)
8652       return DAG.getNode(ISD::XOR, DL, VT,
8653                          NewConv, DAG.getConstant(SignBit, DL, VT));
8654     assert(N0.getOpcode() == ISD::FABS);
8655     return DAG.getNode(ISD::AND, DL, VT,
8656                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8657   }
8658
8659   // fold (bitconvert (fcopysign cst, x)) ->
8660   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8661   // Note that we don't handle (copysign x, cst) because this can always be
8662   // folded to an fneg or fabs.
8663   //
8664   // For ppc_fp128:
8665   // fold (bitcast (fcopysign cst, x)) ->
8666   //     flipbit = (and (extract_element
8667   //                     (xor (bitcast cst), (bitcast x)), 0),
8668   //                    signbit)
8669   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8670   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8671       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8672       VT.isInteger() && !VT.isVector()) {
8673     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8674     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8675     if (isTypeLegal(IntXVT)) {
8676       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8677       AddToWorklist(X.getNode());
8678
8679       // If X has a different width than the result/lhs, sext it or truncate it.
8680       unsigned VTWidth = VT.getSizeInBits();
8681       if (OrigXWidth < VTWidth) {
8682         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8683         AddToWorklist(X.getNode());
8684       } else if (OrigXWidth > VTWidth) {
8685         // To get the sign bit in the right place, we have to shift it right
8686         // before truncating.
8687         SDLoc DL(X);
8688         X = DAG.getNode(ISD::SRL, DL,
8689                         X.getValueType(), X,
8690                         DAG.getConstant(OrigXWidth-VTWidth, DL,
8691                                         X.getValueType()));
8692         AddToWorklist(X.getNode());
8693         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8694         AddToWorklist(X.getNode());
8695       }
8696
8697       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8698         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8699         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8700         AddToWorklist(Cst.getNode());
8701         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8702         AddToWorklist(X.getNode());
8703         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8704         AddToWorklist(XorResult.getNode());
8705         SDValue XorResult64 = DAG.getNode(
8706             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8707             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8708                                   SDLoc(XorResult)));
8709         AddToWorklist(XorResult64.getNode());
8710         SDValue FlipBit =
8711             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8712                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8713         AddToWorklist(FlipBit.getNode());
8714         SDValue FlipBits =
8715             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8716         AddToWorklist(FlipBits.getNode());
8717         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8718       }
8719       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8720       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8721                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
8722       AddToWorklist(X.getNode());
8723
8724       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8725       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8726                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8727       AddToWorklist(Cst.getNode());
8728
8729       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8730     }
8731   }
8732
8733   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8734   if (N0.getOpcode() == ISD::BUILD_PAIR)
8735     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8736       return CombineLD;
8737
8738   // Remove double bitcasts from shuffles - this is often a legacy of
8739   // XformToShuffleWithZero being used to combine bitmaskings (of
8740   // float vectors bitcast to integer vectors) into shuffles.
8741   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8742   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8743       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8744       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8745       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8746     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8747
8748     // If operands are a bitcast, peek through if it casts the original VT.
8749     // If operands are a constant, just bitcast back to original VT.
8750     auto PeekThroughBitcast = [&](SDValue Op) {
8751       if (Op.getOpcode() == ISD::BITCAST &&
8752           Op.getOperand(0).getValueType() == VT)
8753         return SDValue(Op.getOperand(0));
8754       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8755           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8756         return DAG.getBitcast(VT, Op);
8757       return SDValue();
8758     };
8759
8760     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8761     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8762     if (!(SV0 && SV1))
8763       return SDValue();
8764
8765     int MaskScale =
8766         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8767     SmallVector<int, 8> NewMask;
8768     for (int M : SVN->getMask())
8769       for (int i = 0; i != MaskScale; ++i)
8770         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8771
8772     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8773     if (!LegalMask) {
8774       std::swap(SV0, SV1);
8775       ShuffleVectorSDNode::commuteMask(NewMask);
8776       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8777     }
8778
8779     if (LegalMask)
8780       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8781   }
8782
8783   return SDValue();
8784 }
8785
8786 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8787   EVT VT = N->getValueType(0);
8788   return CombineConsecutiveLoads(N, VT);
8789 }
8790
8791 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8792 /// operands. DstEltVT indicates the destination element value type.
8793 SDValue DAGCombiner::
8794 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8795   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8796
8797   // If this is already the right type, we're done.
8798   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8799
8800   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8801   unsigned DstBitSize = DstEltVT.getSizeInBits();
8802
8803   // If this is a conversion of N elements of one type to N elements of another
8804   // type, convert each element.  This handles FP<->INT cases.
8805   if (SrcBitSize == DstBitSize) {
8806     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8807                               BV->getValueType(0).getVectorNumElements());
8808
8809     // Due to the FP element handling below calling this routine recursively,
8810     // we can end up with a scalar-to-vector node here.
8811     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8812       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8813                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8814
8815     SmallVector<SDValue, 8> Ops;
8816     for (SDValue Op : BV->op_values()) {
8817       // If the vector element type is not legal, the BUILD_VECTOR operands
8818       // are promoted and implicitly truncated.  Make that explicit here.
8819       if (Op.getValueType() != SrcEltVT)
8820         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8821       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8822       AddToWorklist(Ops.back().getNode());
8823     }
8824     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8825   }
8826
8827   // Otherwise, we're growing or shrinking the elements.  To avoid having to
8828   // handle annoying details of growing/shrinking FP values, we convert them to
8829   // int first.
8830   if (SrcEltVT.isFloatingPoint()) {
8831     // Convert the input float vector to a int vector where the elements are the
8832     // same sizes.
8833     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8834     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8835     SrcEltVT = IntVT;
8836   }
8837
8838   // Now we know the input is an integer vector.  If the output is a FP type,
8839   // convert to integer first, then to FP of the right size.
8840   if (DstEltVT.isFloatingPoint()) {
8841     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8842     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8843
8844     // Next, convert to FP elements of the same size.
8845     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8846   }
8847
8848   SDLoc DL(BV);
8849
8850   // Okay, we know the src/dst types are both integers of differing types.
8851   // Handling growing first.
8852   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8853   if (SrcBitSize < DstBitSize) {
8854     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8855
8856     SmallVector<SDValue, 8> Ops;
8857     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8858          i += NumInputsPerOutput) {
8859       bool isLE = DAG.getDataLayout().isLittleEndian();
8860       APInt NewBits = APInt(DstBitSize, 0);
8861       bool EltIsUndef = true;
8862       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8863         // Shift the previously computed bits over.
8864         NewBits <<= SrcBitSize;
8865         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8866         if (Op.isUndef()) continue;
8867         EltIsUndef = false;
8868
8869         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8870                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
8871       }
8872
8873       if (EltIsUndef)
8874         Ops.push_back(DAG.getUNDEF(DstEltVT));
8875       else
8876         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8877     }
8878
8879     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8880     return DAG.getBuildVector(VT, DL, Ops);
8881   }
8882
8883   // Finally, this must be the case where we are shrinking elements: each input
8884   // turns into multiple outputs.
8885   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8886   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8887                             NumOutputsPerInput*BV->getNumOperands());
8888   SmallVector<SDValue, 8> Ops;
8889
8890   for (const SDValue &Op : BV->op_values()) {
8891     if (Op.isUndef()) {
8892       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8893       continue;
8894     }
8895
8896     APInt OpVal = cast<ConstantSDNode>(Op)->
8897                   getAPIntValue().zextOrTrunc(SrcBitSize);
8898
8899     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8900       APInt ThisVal = OpVal.trunc(DstBitSize);
8901       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8902       OpVal.lshrInPlace(DstBitSize);
8903     }
8904
8905     // For big endian targets, swap the order of the pieces of each element.
8906     if (DAG.getDataLayout().isBigEndian())
8907       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8908   }
8909
8910   return DAG.getBuildVector(VT, DL, Ops);
8911 }
8912
8913 static bool isContractable(SDNode *N) {
8914   SDNodeFlags F = N->getFlags();
8915   return F.hasAllowContract() || F.hasUnsafeAlgebra();
8916 }
8917
8918 /// Try to perform FMA combining on a given FADD node.
8919 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8920   SDValue N0 = N->getOperand(0);
8921   SDValue N1 = N->getOperand(1);
8922   EVT VT = N->getValueType(0);
8923   SDLoc SL(N);
8924
8925   const TargetOptions &Options = DAG.getTarget().Options;
8926
8927   // Floating-point multiply-add with intermediate rounding.
8928   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8929
8930   // Floating-point multiply-add without intermediate rounding.
8931   bool HasFMA =
8932       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8933       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8934
8935   // No valid opcode, do not combine.
8936   if (!HasFMAD && !HasFMA)
8937     return SDValue();
8938
8939   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8940                               Options.UnsafeFPMath || HasFMAD);
8941   // If the addition is not contractable, do not combine.
8942   if (!AllowFusionGlobally && !isContractable(N))
8943     return SDValue();
8944
8945   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8946   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8947     return SDValue();
8948
8949   // Always prefer FMAD to FMA for precision.
8950   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8951   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8952   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8953
8954   // Is the node an FMUL and contractable either due to global flags or
8955   // SDNodeFlags.
8956   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8957     if (N.getOpcode() != ISD::FMUL)
8958       return false;
8959     return AllowFusionGlobally || isContractable(N.getNode());
8960   };
8961   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8962   // prefer to fold the multiply with fewer uses.
8963   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
8964     if (N0.getNode()->use_size() > N1.getNode()->use_size())
8965       std::swap(N0, N1);
8966   }
8967
8968   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8969   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8970     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8971                        N0.getOperand(0), N0.getOperand(1), N1);
8972   }
8973
8974   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8975   // Note: Commutes FADD operands.
8976   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
8977     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8978                        N1.getOperand(0), N1.getOperand(1), N0);
8979   }
8980
8981   // Look through FP_EXTEND nodes to do more combining.
8982   if (LookThroughFPExt) {
8983     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8984     if (N0.getOpcode() == ISD::FP_EXTEND) {
8985       SDValue N00 = N0.getOperand(0);
8986       if (isContractableFMUL(N00))
8987         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8988                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8989                                        N00.getOperand(0)),
8990                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8991                                        N00.getOperand(1)), N1);
8992     }
8993
8994     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8995     // Note: Commutes FADD operands.
8996     if (N1.getOpcode() == ISD::FP_EXTEND) {
8997       SDValue N10 = N1.getOperand(0);
8998       if (isContractableFMUL(N10))
8999         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9000                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9001                                        N10.getOperand(0)),
9002                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9003                                        N10.getOperand(1)), N0);
9004     }
9005   }
9006
9007   // More folding opportunities when target permits.
9008   if (Aggressive) {
9009     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9010     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9011     // are currently only supported on binary nodes.
9012     if (Options.UnsafeFPMath &&
9013         N0.getOpcode() == PreferredFusedOpcode &&
9014         N0.getOperand(2).getOpcode() == ISD::FMUL &&
9015         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9016       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9017                          N0.getOperand(0), N0.getOperand(1),
9018                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9019                                      N0.getOperand(2).getOperand(0),
9020                                      N0.getOperand(2).getOperand(1),
9021                                      N1));
9022     }
9023
9024     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9025     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9026     // are currently only supported on binary nodes.
9027     if (Options.UnsafeFPMath &&
9028         N1->getOpcode() == PreferredFusedOpcode &&
9029         N1.getOperand(2).getOpcode() == ISD::FMUL &&
9030         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9031       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9032                          N1.getOperand(0), N1.getOperand(1),
9033                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9034                                      N1.getOperand(2).getOperand(0),
9035                                      N1.getOperand(2).getOperand(1),
9036                                      N0));
9037     }
9038
9039     if (LookThroughFPExt) {
9040       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9041       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
9042       auto FoldFAddFMAFPExtFMul = [&] (
9043           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9044         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9045                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9046                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9047                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9048                                        Z));
9049       };
9050       if (N0.getOpcode() == PreferredFusedOpcode) {
9051         SDValue N02 = N0.getOperand(2);
9052         if (N02.getOpcode() == ISD::FP_EXTEND) {
9053           SDValue N020 = N02.getOperand(0);
9054           if (isContractableFMUL(N020))
9055             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9056                                         N020.getOperand(0), N020.getOperand(1),
9057                                         N1);
9058         }
9059       }
9060
9061       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9062       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9063       // FIXME: This turns two single-precision and one double-precision
9064       // operation into two double-precision operations, which might not be
9065       // interesting for all targets, especially GPUs.
9066       auto FoldFAddFPExtFMAFMul = [&] (
9067           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9068         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9069                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9070                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9071                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9072                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9073                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9074                                        Z));
9075       };
9076       if (N0.getOpcode() == ISD::FP_EXTEND) {
9077         SDValue N00 = N0.getOperand(0);
9078         if (N00.getOpcode() == PreferredFusedOpcode) {
9079           SDValue N002 = N00.getOperand(2);
9080           if (isContractableFMUL(N002))
9081             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9082                                         N002.getOperand(0), N002.getOperand(1),
9083                                         N1);
9084         }
9085       }
9086
9087       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9088       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9089       if (N1.getOpcode() == PreferredFusedOpcode) {
9090         SDValue N12 = N1.getOperand(2);
9091         if (N12.getOpcode() == ISD::FP_EXTEND) {
9092           SDValue N120 = N12.getOperand(0);
9093           if (isContractableFMUL(N120))
9094             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9095                                         N120.getOperand(0), N120.getOperand(1),
9096                                         N0);
9097         }
9098       }
9099
9100       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9101       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9102       // FIXME: This turns two single-precision and one double-precision
9103       // operation into two double-precision operations, which might not be
9104       // interesting for all targets, especially GPUs.
9105       if (N1.getOpcode() == ISD::FP_EXTEND) {
9106         SDValue N10 = N1.getOperand(0);
9107         if (N10.getOpcode() == PreferredFusedOpcode) {
9108           SDValue N102 = N10.getOperand(2);
9109           if (isContractableFMUL(N102))
9110             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9111                                         N102.getOperand(0), N102.getOperand(1),
9112                                         N0);
9113         }
9114       }
9115     }
9116   }
9117
9118   return SDValue();
9119 }
9120
9121 /// Try to perform FMA combining on a given FSUB node.
9122 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9123   SDValue N0 = N->getOperand(0);
9124   SDValue N1 = N->getOperand(1);
9125   EVT VT = N->getValueType(0);
9126   SDLoc SL(N);
9127
9128   const TargetOptions &Options = DAG.getTarget().Options;
9129   // Floating-point multiply-add with intermediate rounding.
9130   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9131
9132   // Floating-point multiply-add without intermediate rounding.
9133   bool HasFMA =
9134       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9135       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9136
9137   // No valid opcode, do not combine.
9138   if (!HasFMAD && !HasFMA)
9139     return SDValue();
9140
9141   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9142                               Options.UnsafeFPMath || HasFMAD);
9143   // If the subtraction is not contractable, do not combine.
9144   if (!AllowFusionGlobally && !isContractable(N))
9145     return SDValue();
9146
9147   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9148   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9149     return SDValue();
9150
9151   // Always prefer FMAD to FMA for precision.
9152   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9153   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9154   bool LookThroughFPExt = TLI.isFPExtFree(VT);
9155
9156   // Is the node an FMUL and contractable either due to global flags or
9157   // SDNodeFlags.
9158   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9159     if (N.getOpcode() != ISD::FMUL)
9160       return false;
9161     return AllowFusionGlobally || isContractable(N.getNode());
9162   };
9163
9164   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9165   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9166     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9167                        N0.getOperand(0), N0.getOperand(1),
9168                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9169   }
9170
9171   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9172   // Note: Commutes FSUB operands.
9173   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9174     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9175                        DAG.getNode(ISD::FNEG, SL, VT,
9176                                    N1.getOperand(0)),
9177                        N1.getOperand(1), N0);
9178
9179   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9180   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9181       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9182     SDValue N00 = N0.getOperand(0).getOperand(0);
9183     SDValue N01 = N0.getOperand(0).getOperand(1);
9184     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9185                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9186                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9187   }
9188
9189   // Look through FP_EXTEND nodes to do more combining.
9190   if (LookThroughFPExt) {
9191     // fold (fsub (fpext (fmul x, y)), z)
9192     //   -> (fma (fpext x), (fpext y), (fneg z))
9193     if (N0.getOpcode() == ISD::FP_EXTEND) {
9194       SDValue N00 = N0.getOperand(0);
9195       if (isContractableFMUL(N00))
9196         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9197                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9198                                        N00.getOperand(0)),
9199                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9200                                        N00.getOperand(1)),
9201                            DAG.getNode(ISD::FNEG, SL, VT, N1));
9202     }
9203
9204     // fold (fsub x, (fpext (fmul y, z)))
9205     //   -> (fma (fneg (fpext y)), (fpext z), x)
9206     // Note: Commutes FSUB operands.
9207     if (N1.getOpcode() == ISD::FP_EXTEND) {
9208       SDValue N10 = N1.getOperand(0);
9209       if (isContractableFMUL(N10))
9210         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9211                            DAG.getNode(ISD::FNEG, SL, VT,
9212                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9213                                                    N10.getOperand(0))),
9214                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9215                                        N10.getOperand(1)),
9216                            N0);
9217     }
9218
9219     // fold (fsub (fpext (fneg (fmul, x, y))), z)
9220     //   -> (fneg (fma (fpext x), (fpext y), z))
9221     // Note: This could be removed with appropriate canonicalization of the
9222     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9223     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9224     // from implementing the canonicalization in visitFSUB.
9225     if (N0.getOpcode() == ISD::FP_EXTEND) {
9226       SDValue N00 = N0.getOperand(0);
9227       if (N00.getOpcode() == ISD::FNEG) {
9228         SDValue N000 = N00.getOperand(0);
9229         if (isContractableFMUL(N000)) {
9230           return DAG.getNode(ISD::FNEG, SL, VT,
9231                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9232                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9233                                                      N000.getOperand(0)),
9234                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9235                                                      N000.getOperand(1)),
9236                                          N1));
9237         }
9238       }
9239     }
9240
9241     // fold (fsub (fneg (fpext (fmul, x, y))), z)
9242     //   -> (fneg (fma (fpext x)), (fpext y), z)
9243     // Note: This could be removed with appropriate canonicalization of the
9244     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9245     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9246     // from implementing the canonicalization in visitFSUB.
9247     if (N0.getOpcode() == ISD::FNEG) {
9248       SDValue N00 = N0.getOperand(0);
9249       if (N00.getOpcode() == ISD::FP_EXTEND) {
9250         SDValue N000 = N00.getOperand(0);
9251         if (isContractableFMUL(N000)) {
9252           return DAG.getNode(ISD::FNEG, SL, VT,
9253                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9254                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9255                                                      N000.getOperand(0)),
9256                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9257                                                      N000.getOperand(1)),
9258                                          N1));
9259         }
9260       }
9261     }
9262
9263   }
9264
9265   // More folding opportunities when target permits.
9266   if (Aggressive) {
9267     // fold (fsub (fma x, y, (fmul u, v)), z)
9268     //   -> (fma x, y (fma u, v, (fneg z)))
9269     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9270     // are currently only supported on binary nodes.
9271     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9272         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9273         N0.getOperand(2)->hasOneUse()) {
9274       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9275                          N0.getOperand(0), N0.getOperand(1),
9276                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9277                                      N0.getOperand(2).getOperand(0),
9278                                      N0.getOperand(2).getOperand(1),
9279                                      DAG.getNode(ISD::FNEG, SL, VT,
9280                                                  N1)));
9281     }
9282
9283     // fold (fsub x, (fma y, z, (fmul u, v)))
9284     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9285     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9286     // are currently only supported on binary nodes.
9287     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9288         isContractableFMUL(N1.getOperand(2))) {
9289       SDValue N20 = N1.getOperand(2).getOperand(0);
9290       SDValue N21 = N1.getOperand(2).getOperand(1);
9291       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9292                          DAG.getNode(ISD::FNEG, SL, VT,
9293                                      N1.getOperand(0)),
9294                          N1.getOperand(1),
9295                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9296                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9297
9298                                      N21, N0));
9299     }
9300
9301     if (LookThroughFPExt) {
9302       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9303       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9304       if (N0.getOpcode() == PreferredFusedOpcode) {
9305         SDValue N02 = N0.getOperand(2);
9306         if (N02.getOpcode() == ISD::FP_EXTEND) {
9307           SDValue N020 = N02.getOperand(0);
9308           if (isContractableFMUL(N020))
9309             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9310                                N0.getOperand(0), N0.getOperand(1),
9311                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9312                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9313                                                        N020.getOperand(0)),
9314                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9315                                                        N020.getOperand(1)),
9316                                            DAG.getNode(ISD::FNEG, SL, VT,
9317                                                        N1)));
9318         }
9319       }
9320
9321       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9322       //   -> (fma (fpext x), (fpext y),
9323       //           (fma (fpext u), (fpext v), (fneg z)))
9324       // FIXME: This turns two single-precision and one double-precision
9325       // operation into two double-precision operations, which might not be
9326       // interesting for all targets, especially GPUs.
9327       if (N0.getOpcode() == ISD::FP_EXTEND) {
9328         SDValue N00 = N0.getOperand(0);
9329         if (N00.getOpcode() == PreferredFusedOpcode) {
9330           SDValue N002 = N00.getOperand(2);
9331           if (isContractableFMUL(N002))
9332             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9333                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9334                                            N00.getOperand(0)),
9335                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9336                                            N00.getOperand(1)),
9337                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9338                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9339                                                        N002.getOperand(0)),
9340                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9341                                                        N002.getOperand(1)),
9342                                            DAG.getNode(ISD::FNEG, SL, VT,
9343                                                        N1)));
9344         }
9345       }
9346
9347       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9348       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9349       if (N1.getOpcode() == PreferredFusedOpcode &&
9350         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9351         SDValue N120 = N1.getOperand(2).getOperand(0);
9352         if (isContractableFMUL(N120)) {
9353           SDValue N1200 = N120.getOperand(0);
9354           SDValue N1201 = N120.getOperand(1);
9355           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9356                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9357                              N1.getOperand(1),
9358                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9359                                          DAG.getNode(ISD::FNEG, SL, VT,
9360                                              DAG.getNode(ISD::FP_EXTEND, SL,
9361                                                          VT, N1200)),
9362                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9363                                                      N1201),
9364                                          N0));
9365         }
9366       }
9367
9368       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9369       //   -> (fma (fneg (fpext y)), (fpext z),
9370       //           (fma (fneg (fpext u)), (fpext v), x))
9371       // FIXME: This turns two single-precision and one double-precision
9372       // operation into two double-precision operations, which might not be
9373       // interesting for all targets, especially GPUs.
9374       if (N1.getOpcode() == ISD::FP_EXTEND &&
9375         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9376         SDValue N100 = N1.getOperand(0).getOperand(0);
9377         SDValue N101 = N1.getOperand(0).getOperand(1);
9378         SDValue N102 = N1.getOperand(0).getOperand(2);
9379         if (isContractableFMUL(N102)) {
9380           SDValue N1020 = N102.getOperand(0);
9381           SDValue N1021 = N102.getOperand(1);
9382           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9383                              DAG.getNode(ISD::FNEG, SL, VT,
9384                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9385                                                      N100)),
9386                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9387                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9388                                          DAG.getNode(ISD::FNEG, SL, VT,
9389                                              DAG.getNode(ISD::FP_EXTEND, SL,
9390                                                          VT, N1020)),
9391                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9392                                                      N1021),
9393                                          N0));
9394         }
9395       }
9396     }
9397   }
9398
9399   return SDValue();
9400 }
9401
9402 /// Try to perform FMA combining on a given FMUL node based on the distributive
9403 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9404 /// subtraction instead of addition).
9405 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9406   SDValue N0 = N->getOperand(0);
9407   SDValue N1 = N->getOperand(1);
9408   EVT VT = N->getValueType(0);
9409   SDLoc SL(N);
9410
9411   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9412
9413   const TargetOptions &Options = DAG.getTarget().Options;
9414
9415   // The transforms below are incorrect when x == 0 and y == inf, because the
9416   // intermediate multiplication produces a nan.
9417   if (!Options.NoInfsFPMath)
9418     return SDValue();
9419
9420   // Floating-point multiply-add without intermediate rounding.
9421   bool HasFMA =
9422       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9423       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9424       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9425
9426   // Floating-point multiply-add with intermediate rounding. This can result
9427   // in a less precise result due to the changed rounding order.
9428   bool HasFMAD = Options.UnsafeFPMath &&
9429                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9430
9431   // No valid opcode, do not combine.
9432   if (!HasFMAD && !HasFMA)
9433     return SDValue();
9434
9435   // Always prefer FMAD to FMA for precision.
9436   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9437   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9438
9439   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9440   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9441   auto FuseFADD = [&](SDValue X, SDValue Y) {
9442     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9443       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9444       if (XC1 && XC1->isExactlyValue(+1.0))
9445         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9446       if (XC1 && XC1->isExactlyValue(-1.0))
9447         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9448                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9449     }
9450     return SDValue();
9451   };
9452
9453   if (SDValue FMA = FuseFADD(N0, N1))
9454     return FMA;
9455   if (SDValue FMA = FuseFADD(N1, N0))
9456     return FMA;
9457
9458   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9459   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9460   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9461   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9462   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9463     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9464       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9465       if (XC0 && XC0->isExactlyValue(+1.0))
9466         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9467                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9468                            Y);
9469       if (XC0 && XC0->isExactlyValue(-1.0))
9470         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9471                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9472                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9473
9474       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9475       if (XC1 && XC1->isExactlyValue(+1.0))
9476         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9477                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9478       if (XC1 && XC1->isExactlyValue(-1.0))
9479         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9480     }
9481     return SDValue();
9482   };
9483
9484   if (SDValue FMA = FuseFSUB(N0, N1))
9485     return FMA;
9486   if (SDValue FMA = FuseFSUB(N1, N0))
9487     return FMA;
9488
9489   return SDValue();
9490 }
9491
9492 static bool isFMulNegTwo(SDValue &N) {
9493   if (N.getOpcode() != ISD::FMUL)
9494     return false;
9495   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9496     return CFP->isExactlyValue(-2.0);
9497   return false;
9498 }
9499
9500 SDValue DAGCombiner::visitFADD(SDNode *N) {
9501   SDValue N0 = N->getOperand(0);
9502   SDValue N1 = N->getOperand(1);
9503   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9504   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9505   EVT VT = N->getValueType(0);
9506   SDLoc DL(N);
9507   const TargetOptions &Options = DAG.getTarget().Options;
9508   const SDNodeFlags Flags = N->getFlags();
9509
9510   // fold vector ops
9511   if (VT.isVector())
9512     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9513       return FoldedVOp;
9514
9515   // fold (fadd c1, c2) -> c1 + c2
9516   if (N0CFP && N1CFP)
9517     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9518
9519   // canonicalize constant to RHS
9520   if (N0CFP && !N1CFP)
9521     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9522
9523   if (SDValue NewSel = foldBinOpIntoSelect(N))
9524     return NewSel;
9525
9526   // fold (fadd A, (fneg B)) -> (fsub A, B)
9527   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9528       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9529     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9530                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9531
9532   // fold (fadd (fneg A), B) -> (fsub B, A)
9533   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9534       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9535     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9536                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9537
9538   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9539   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9540   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9541       (isFMulNegTwo(N1) && N1.hasOneUse())) {
9542     bool N1IsFMul = isFMulNegTwo(N1);
9543     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9544     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9545     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9546   }
9547
9548   // FIXME: Auto-upgrade the target/function-level option.
9549   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9550     // fold (fadd A, 0) -> A
9551     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9552       if (N1C->isZero())
9553         return N0;
9554   }
9555
9556   // If 'unsafe math' is enabled, fold lots of things.
9557   if (Options.UnsafeFPMath) {
9558     // No FP constant should be created after legalization as Instruction
9559     // Selection pass has a hard time dealing with FP constants.
9560     bool AllowNewConst = (Level < AfterLegalizeDAG);
9561
9562     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9563     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9564         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9565       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9566                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9567                                      Flags),
9568                          Flags);
9569
9570     // If allowed, fold (fadd (fneg x), x) -> 0.0
9571     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9572       return DAG.getConstantFP(0.0, DL, VT);
9573
9574     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9575     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9576       return DAG.getConstantFP(0.0, DL, VT);
9577
9578     // We can fold chains of FADD's of the same value into multiplications.
9579     // This transform is not safe in general because we are reducing the number
9580     // of rounding steps.
9581     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9582       if (N0.getOpcode() == ISD::FMUL) {
9583         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9584         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9585
9586         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9587         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9588           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9589                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9590           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9591         }
9592
9593         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9594         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9595             N1.getOperand(0) == N1.getOperand(1) &&
9596             N0.getOperand(0) == N1.getOperand(0)) {
9597           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9598                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9599           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9600         }
9601       }
9602
9603       if (N1.getOpcode() == ISD::FMUL) {
9604         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9605         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9606
9607         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9608         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9609           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9610                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9611           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9612         }
9613
9614         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9615         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9616             N0.getOperand(0) == N0.getOperand(1) &&
9617             N1.getOperand(0) == N0.getOperand(0)) {
9618           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9619                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9620           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9621         }
9622       }
9623
9624       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9625         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9626         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9627         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9628             (N0.getOperand(0) == N1)) {
9629           return DAG.getNode(ISD::FMUL, DL, VT,
9630                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9631         }
9632       }
9633
9634       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9635         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9636         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9637         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9638             N1.getOperand(0) == N0) {
9639           return DAG.getNode(ISD::FMUL, DL, VT,
9640                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9641         }
9642       }
9643
9644       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9645       if (AllowNewConst &&
9646           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9647           N0.getOperand(0) == N0.getOperand(1) &&
9648           N1.getOperand(0) == N1.getOperand(1) &&
9649           N0.getOperand(0) == N1.getOperand(0)) {
9650         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9651                            DAG.getConstantFP(4.0, DL, VT), Flags);
9652       }
9653     }
9654   } // enable-unsafe-fp-math
9655
9656   // FADD -> FMA combines:
9657   if (SDValue Fused = visitFADDForFMACombine(N)) {
9658     AddToWorklist(Fused.getNode());
9659     return Fused;
9660   }
9661   return SDValue();
9662 }
9663
9664 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9665   SDValue N0 = N->getOperand(0);
9666   SDValue N1 = N->getOperand(1);
9667   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9668   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9669   EVT VT = N->getValueType(0);
9670   SDLoc DL(N);
9671   const TargetOptions &Options = DAG.getTarget().Options;
9672   const SDNodeFlags Flags = N->getFlags();
9673
9674   // fold vector ops
9675   if (VT.isVector())
9676     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9677       return FoldedVOp;
9678
9679   // fold (fsub c1, c2) -> c1-c2
9680   if (N0CFP && N1CFP)
9681     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9682
9683   if (SDValue NewSel = foldBinOpIntoSelect(N))
9684     return NewSel;
9685
9686   // fold (fsub A, (fneg B)) -> (fadd A, B)
9687   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9688     return DAG.getNode(ISD::FADD, DL, VT, N0,
9689                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9690
9691   // FIXME: Auto-upgrade the target/function-level option.
9692   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
9693     // (fsub 0, B) -> -B
9694     if (N0CFP && N0CFP->isZero()) {
9695       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9696         return GetNegatedExpression(N1, DAG, LegalOperations);
9697       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9698         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9699     }
9700   }
9701
9702   // If 'unsafe math' is enabled, fold lots of things.
9703   if (Options.UnsafeFPMath) {
9704     // (fsub A, 0) -> A
9705     if (N1CFP && N1CFP->isZero())
9706       return N0;
9707
9708     // (fsub x, x) -> 0.0
9709     if (N0 == N1)
9710       return DAG.getConstantFP(0.0f, DL, VT);
9711
9712     // (fsub x, (fadd x, y)) -> (fneg y)
9713     // (fsub x, (fadd y, x)) -> (fneg y)
9714     if (N1.getOpcode() == ISD::FADD) {
9715       SDValue N10 = N1->getOperand(0);
9716       SDValue N11 = N1->getOperand(1);
9717
9718       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9719         return GetNegatedExpression(N11, DAG, LegalOperations);
9720
9721       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9722         return GetNegatedExpression(N10, DAG, LegalOperations);
9723     }
9724   }
9725
9726   // FSUB -> FMA combines:
9727   if (SDValue Fused = visitFSUBForFMACombine(N)) {
9728     AddToWorklist(Fused.getNode());
9729     return Fused;
9730   }
9731
9732   return SDValue();
9733 }
9734
9735 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9736   SDValue N0 = N->getOperand(0);
9737   SDValue N1 = N->getOperand(1);
9738   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9739   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9740   EVT VT = N->getValueType(0);
9741   SDLoc DL(N);
9742   const TargetOptions &Options = DAG.getTarget().Options;
9743   const SDNodeFlags Flags = N->getFlags();
9744
9745   // fold vector ops
9746   if (VT.isVector()) {
9747     // This just handles C1 * C2 for vectors. Other vector folds are below.
9748     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9749       return FoldedVOp;
9750   }
9751
9752   // fold (fmul c1, c2) -> c1*c2
9753   if (N0CFP && N1CFP)
9754     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9755
9756   // canonicalize constant to RHS
9757   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9758      !isConstantFPBuildVectorOrConstantFP(N1))
9759     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9760
9761   // fold (fmul A, 1.0) -> A
9762   if (N1CFP && N1CFP->isExactlyValue(1.0))
9763     return N0;
9764
9765   if (SDValue NewSel = foldBinOpIntoSelect(N))
9766     return NewSel;
9767
9768   if (Options.UnsafeFPMath) {
9769     // fold (fmul A, 0) -> 0
9770     if (N1CFP && N1CFP->isZero())
9771       return N1;
9772
9773     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9774     if (N0.getOpcode() == ISD::FMUL) {
9775       // Fold scalars or any vector constants (not just splats).
9776       // This fold is done in general by InstCombine, but extra fmul insts
9777       // may have been generated during lowering.
9778       SDValue N00 = N0.getOperand(0);
9779       SDValue N01 = N0.getOperand(1);
9780       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9781       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9782       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9783
9784       // Check 1: Make sure that the first operand of the inner multiply is NOT
9785       // a constant. Otherwise, we may induce infinite looping.
9786       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9787         // Check 2: Make sure that the second operand of the inner multiply and
9788         // the second operand of the outer multiply are constants.
9789         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9790             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9791           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9792           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9793         }
9794       }
9795     }
9796
9797     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9798     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9799     // during an early run of DAGCombiner can prevent folding with fmuls
9800     // inserted during lowering.
9801     if (N0.getOpcode() == ISD::FADD &&
9802         (N0.getOperand(0) == N0.getOperand(1)) &&
9803         N0.hasOneUse()) {
9804       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9805       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9806       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9807     }
9808   }
9809
9810   // fold (fmul X, 2.0) -> (fadd X, X)
9811   if (N1CFP && N1CFP->isExactlyValue(+2.0))
9812     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9813
9814   // fold (fmul X, -1.0) -> (fneg X)
9815   if (N1CFP && N1CFP->isExactlyValue(-1.0))
9816     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9817       return DAG.getNode(ISD::FNEG, DL, VT, N0);
9818
9819   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9820   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9821     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9822       // Both can be negated for free, check to see if at least one is cheaper
9823       // negated.
9824       if (LHSNeg == 2 || RHSNeg == 2)
9825         return DAG.getNode(ISD::FMUL, DL, VT,
9826                            GetNegatedExpression(N0, DAG, LegalOperations),
9827                            GetNegatedExpression(N1, DAG, LegalOperations),
9828                            Flags);
9829     }
9830   }
9831
9832   // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
9833   // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
9834   if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
9835       (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
9836       TLI.isOperationLegal(ISD::FABS, VT)) {
9837     SDValue Select = N0, X = N1;
9838     if (Select.getOpcode() != ISD::SELECT)
9839       std::swap(Select, X);
9840
9841     SDValue Cond = Select.getOperand(0);
9842     auto TrueOpnd  = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
9843     auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
9844
9845     if (TrueOpnd && FalseOpnd &&
9846         Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
9847         isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
9848         cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
9849       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9850       switch (CC) {
9851       default: break;
9852       case ISD::SETOLT:
9853       case ISD::SETULT:
9854       case ISD::SETOLE:
9855       case ISD::SETULE:
9856       case ISD::SETLT:
9857       case ISD::SETLE:
9858         std::swap(TrueOpnd, FalseOpnd);
9859         // Fall through
9860       case ISD::SETOGT:
9861       case ISD::SETUGT:
9862       case ISD::SETOGE:
9863       case ISD::SETUGE:
9864       case ISD::SETGT:
9865       case ISD::SETGE:
9866         if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
9867             TLI.isOperationLegal(ISD::FNEG, VT))
9868           return DAG.getNode(ISD::FNEG, DL, VT,
9869                    DAG.getNode(ISD::FABS, DL, VT, X));
9870         if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
9871           return DAG.getNode(ISD::FABS, DL, VT, X);
9872
9873         break;
9874       }
9875     }
9876   }
9877
9878   // FMUL -> FMA combines:
9879   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9880     AddToWorklist(Fused.getNode());
9881     return Fused;
9882   }
9883
9884   return SDValue();
9885 }
9886
9887 SDValue DAGCombiner::visitFMA(SDNode *N) {
9888   SDValue N0 = N->getOperand(0);
9889   SDValue N1 = N->getOperand(1);
9890   SDValue N2 = N->getOperand(2);
9891   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9892   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9893   EVT VT = N->getValueType(0);
9894   SDLoc DL(N);
9895   const TargetOptions &Options = DAG.getTarget().Options;
9896
9897   // Constant fold FMA.
9898   if (isa<ConstantFPSDNode>(N0) &&
9899       isa<ConstantFPSDNode>(N1) &&
9900       isa<ConstantFPSDNode>(N2)) {
9901     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9902   }
9903
9904   if (Options.UnsafeFPMath) {
9905     if (N0CFP && N0CFP->isZero())
9906       return N2;
9907     if (N1CFP && N1CFP->isZero())
9908       return N2;
9909   }
9910   // TODO: The FMA node should have flags that propagate to these nodes.
9911   if (N0CFP && N0CFP->isExactlyValue(1.0))
9912     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9913   if (N1CFP && N1CFP->isExactlyValue(1.0))
9914     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9915
9916   // Canonicalize (fma c, x, y) -> (fma x, c, y)
9917   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9918      !isConstantFPBuildVectorOrConstantFP(N1))
9919     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9920
9921   // TODO: FMA nodes should have flags that propagate to the created nodes.
9922   // For now, create a Flags object for use with all unsafe math transforms.
9923   SDNodeFlags Flags;
9924   Flags.setUnsafeAlgebra(true);
9925
9926   if (Options.UnsafeFPMath) {
9927     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9928     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9929         isConstantFPBuildVectorOrConstantFP(N1) &&
9930         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9931       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9932                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9933                                      Flags), Flags);
9934     }
9935
9936     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9937     if (N0.getOpcode() == ISD::FMUL &&
9938         isConstantFPBuildVectorOrConstantFP(N1) &&
9939         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9940       return DAG.getNode(ISD::FMA, DL, VT,
9941                          N0.getOperand(0),
9942                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9943                                      Flags),
9944                          N2);
9945     }
9946   }
9947
9948   // (fma x, 1, y) -> (fadd x, y)
9949   // (fma x, -1, y) -> (fadd (fneg x), y)
9950   if (N1CFP) {
9951     if (N1CFP->isExactlyValue(1.0))
9952       // TODO: The FMA node should have flags that propagate to this node.
9953       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9954
9955     if (N1CFP->isExactlyValue(-1.0) &&
9956         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9957       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9958       AddToWorklist(RHSNeg.getNode());
9959       // TODO: The FMA node should have flags that propagate to this node.
9960       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9961     }
9962   }
9963
9964   if (Options.UnsafeFPMath) {
9965     // (fma x, c, x) -> (fmul x, (c+1))
9966     if (N1CFP && N0 == N2) {
9967       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9968                          DAG.getNode(ISD::FADD, DL, VT, N1,
9969                                      DAG.getConstantFP(1.0, DL, VT), Flags),
9970                          Flags);
9971     }
9972
9973     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9974     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9975       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9976                          DAG.getNode(ISD::FADD, DL, VT, N1,
9977                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
9978                          Flags);
9979     }
9980   }
9981
9982   return SDValue();
9983 }
9984
9985 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9986 // reciprocal.
9987 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9988 // Notice that this is not always beneficial. One reason is different targets
9989 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9990 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9991 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9992 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9993   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9994   const SDNodeFlags Flags = N->getFlags();
9995   if (!UnsafeMath && !Flags.hasAllowReciprocal())
9996     return SDValue();
9997
9998   // Skip if current node is a reciprocal.
9999   SDValue N0 = N->getOperand(0);
10000   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10001   if (N0CFP && N0CFP->isExactlyValue(1.0))
10002     return SDValue();
10003
10004   // Exit early if the target does not want this transform or if there can't
10005   // possibly be enough uses of the divisor to make the transform worthwhile.
10006   SDValue N1 = N->getOperand(1);
10007   unsigned MinUses = TLI.combineRepeatedFPDivisors();
10008   if (!MinUses || N1->use_size() < MinUses)
10009     return SDValue();
10010
10011   // Find all FDIV users of the same divisor.
10012   // Use a set because duplicates may be present in the user list.
10013   SetVector<SDNode *> Users;
10014   for (auto *U : N1->uses()) {
10015     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
10016       // This division is eligible for optimization only if global unsafe math
10017       // is enabled or if this division allows reciprocal formation.
10018       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
10019         Users.insert(U);
10020     }
10021   }
10022
10023   // Now that we have the actual number of divisor uses, make sure it meets
10024   // the minimum threshold specified by the target.
10025   if (Users.size() < MinUses)
10026     return SDValue();
10027
10028   EVT VT = N->getValueType(0);
10029   SDLoc DL(N);
10030   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10031   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10032
10033   // Dividend / Divisor -> Dividend * Reciprocal
10034   for (auto *U : Users) {
10035     SDValue Dividend = U->getOperand(0);
10036     if (Dividend != FPOne) {
10037       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10038                                     Reciprocal, Flags);
10039       CombineTo(U, NewNode);
10040     } else if (U != Reciprocal.getNode()) {
10041       // In the absence of fast-math-flags, this user node is always the
10042       // same node as Reciprocal, but with FMF they may be different nodes.
10043       CombineTo(U, Reciprocal);
10044     }
10045   }
10046   return SDValue(N, 0);  // N was replaced.
10047 }
10048
10049 SDValue DAGCombiner::visitFDIV(SDNode *N) {
10050   SDValue N0 = N->getOperand(0);
10051   SDValue N1 = N->getOperand(1);
10052   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10053   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10054   EVT VT = N->getValueType(0);
10055   SDLoc DL(N);
10056   const TargetOptions &Options = DAG.getTarget().Options;
10057   SDNodeFlags Flags = N->getFlags();
10058
10059   // fold vector ops
10060   if (VT.isVector())
10061     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10062       return FoldedVOp;
10063
10064   // fold (fdiv c1, c2) -> c1/c2
10065   if (N0CFP && N1CFP)
10066     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10067
10068   if (SDValue NewSel = foldBinOpIntoSelect(N))
10069     return NewSel;
10070
10071   if (Options.UnsafeFPMath) {
10072     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10073     if (N1CFP) {
10074       // Compute the reciprocal 1.0 / c2.
10075       const APFloat &N1APF = N1CFP->getValueAPF();
10076       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10077       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10078       // Only do the transform if the reciprocal is a legal fp immediate that
10079       // isn't too nasty (eg NaN, denormal, ...).
10080       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10081           (!LegalOperations ||
10082            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10083            // backend)... we should handle this gracefully after Legalize.
10084            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
10085            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
10086            TLI.isFPImmLegal(Recip, VT)))
10087         return DAG.getNode(ISD::FMUL, DL, VT, N0,
10088                            DAG.getConstantFP(Recip, DL, VT), Flags);
10089     }
10090
10091     // If this FDIV is part of a reciprocal square root, it may be folded
10092     // into a target-specific square root estimate instruction.
10093     if (N1.getOpcode() == ISD::FSQRT) {
10094       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10095         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10096       }
10097     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10098                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10099       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10100                                           Flags)) {
10101         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10102         AddToWorklist(RV.getNode());
10103         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10104       }
10105     } else if (N1.getOpcode() == ISD::FP_ROUND &&
10106                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10107       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10108                                           Flags)) {
10109         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10110         AddToWorklist(RV.getNode());
10111         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10112       }
10113     } else if (N1.getOpcode() == ISD::FMUL) {
10114       // Look through an FMUL. Even though this won't remove the FDIV directly,
10115       // it's still worthwhile to get rid of the FSQRT if possible.
10116       SDValue SqrtOp;
10117       SDValue OtherOp;
10118       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10119         SqrtOp = N1.getOperand(0);
10120         OtherOp = N1.getOperand(1);
10121       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10122         SqrtOp = N1.getOperand(1);
10123         OtherOp = N1.getOperand(0);
10124       }
10125       if (SqrtOp.getNode()) {
10126         // We found a FSQRT, so try to make this fold:
10127         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10128         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10129           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10130           AddToWorklist(RV.getNode());
10131           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10132         }
10133       }
10134     }
10135
10136     // Fold into a reciprocal estimate and multiply instead of a real divide.
10137     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10138       AddToWorklist(RV.getNode());
10139       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10140     }
10141   }
10142
10143   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10144   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10145     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10146       // Both can be negated for free, check to see if at least one is cheaper
10147       // negated.
10148       if (LHSNeg == 2 || RHSNeg == 2)
10149         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10150                            GetNegatedExpression(N0, DAG, LegalOperations),
10151                            GetNegatedExpression(N1, DAG, LegalOperations),
10152                            Flags);
10153     }
10154   }
10155
10156   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10157     return CombineRepeatedDivisors;
10158
10159   return SDValue();
10160 }
10161
10162 SDValue DAGCombiner::visitFREM(SDNode *N) {
10163   SDValue N0 = N->getOperand(0);
10164   SDValue N1 = N->getOperand(1);
10165   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10166   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10167   EVT VT = N->getValueType(0);
10168
10169   // fold (frem c1, c2) -> fmod(c1,c2)
10170   if (N0CFP && N1CFP)
10171     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10172
10173   if (SDValue NewSel = foldBinOpIntoSelect(N))
10174     return NewSel;
10175
10176   return SDValue();
10177 }
10178
10179 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10180   if (!DAG.getTarget().Options.UnsafeFPMath)
10181     return SDValue();
10182
10183   SDValue N0 = N->getOperand(0);
10184   if (TLI.isFsqrtCheap(N0, DAG))
10185     return SDValue();
10186
10187   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10188   // For now, create a Flags object for use with all unsafe math transforms.
10189   SDNodeFlags Flags;
10190   Flags.setUnsafeAlgebra(true);
10191   return buildSqrtEstimate(N0, Flags);
10192 }
10193
10194 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10195 /// copysign(x, fp_round(y)) -> copysign(x, y)
10196 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10197   SDValue N1 = N->getOperand(1);
10198   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10199        N1.getOpcode() == ISD::FP_ROUND)) {
10200     // Do not optimize out type conversion of f128 type yet.
10201     // For some targets like x86_64, configuration is changed to keep one f128
10202     // value in one SSE register, but instruction selection cannot handle
10203     // FCOPYSIGN on SSE registers yet.
10204     EVT N1VT = N1->getValueType(0);
10205     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10206     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10207   }
10208   return false;
10209 }
10210
10211 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10212   SDValue N0 = N->getOperand(0);
10213   SDValue N1 = N->getOperand(1);
10214   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10215   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10216   EVT VT = N->getValueType(0);
10217
10218   if (N0CFP && N1CFP) // Constant fold
10219     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10220
10221   if (N1CFP) {
10222     const APFloat &V = N1CFP->getValueAPF();
10223     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10224     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10225     if (!V.isNegative()) {
10226       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10227         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10228     } else {
10229       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10230         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10231                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10232     }
10233   }
10234
10235   // copysign(fabs(x), y) -> copysign(x, y)
10236   // copysign(fneg(x), y) -> copysign(x, y)
10237   // copysign(copysign(x,z), y) -> copysign(x, y)
10238   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10239       N0.getOpcode() == ISD::FCOPYSIGN)
10240     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10241
10242   // copysign(x, abs(y)) -> abs(x)
10243   if (N1.getOpcode() == ISD::FABS)
10244     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10245
10246   // copysign(x, copysign(y,z)) -> copysign(x, z)
10247   if (N1.getOpcode() == ISD::FCOPYSIGN)
10248     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10249
10250   // copysign(x, fp_extend(y)) -> copysign(x, y)
10251   // copysign(x, fp_round(y)) -> copysign(x, y)
10252   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10253     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10254
10255   return SDValue();
10256 }
10257
10258 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10259   SDValue N0 = N->getOperand(0);
10260   EVT VT = N->getValueType(0);
10261   EVT OpVT = N0.getValueType();
10262
10263   // fold (sint_to_fp c1) -> c1fp
10264   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10265       // ...but only if the target supports immediate floating-point values
10266       (!LegalOperations ||
10267        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10268     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10269
10270   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10271   // but UINT_TO_FP is legal on this target, try to convert.
10272   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10273       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10274     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10275     if (DAG.SignBitIsZero(N0))
10276       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10277   }
10278
10279   // The next optimizations are desirable only if SELECT_CC can be lowered.
10280   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10281     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10282     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10283         !VT.isVector() &&
10284         (!LegalOperations ||
10285          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10286       SDLoc DL(N);
10287       SDValue Ops[] =
10288         { N0.getOperand(0), N0.getOperand(1),
10289           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10290           N0.getOperand(2) };
10291       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10292     }
10293
10294     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10295     //      (select_cc x, y, 1.0, 0.0,, cc)
10296     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10297         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10298         (!LegalOperations ||
10299          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10300       SDLoc DL(N);
10301       SDValue Ops[] =
10302         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10303           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10304           N0.getOperand(0).getOperand(2) };
10305       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10306     }
10307   }
10308
10309   return SDValue();
10310 }
10311
10312 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10313   SDValue N0 = N->getOperand(0);
10314   EVT VT = N->getValueType(0);
10315   EVT OpVT = N0.getValueType();
10316
10317   // fold (uint_to_fp c1) -> c1fp
10318   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10319       // ...but only if the target supports immediate floating-point values
10320       (!LegalOperations ||
10321        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10322     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10323
10324   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10325   // but SINT_TO_FP is legal on this target, try to convert.
10326   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10327       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10328     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10329     if (DAG.SignBitIsZero(N0))
10330       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10331   }
10332
10333   // The next optimizations are desirable only if SELECT_CC can be lowered.
10334   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10335     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10336
10337     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10338         (!LegalOperations ||
10339          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10340       SDLoc DL(N);
10341       SDValue Ops[] =
10342         { N0.getOperand(0), N0.getOperand(1),
10343           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10344           N0.getOperand(2) };
10345       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10346     }
10347   }
10348
10349   return SDValue();
10350 }
10351
10352 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10353 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10354   SDValue N0 = N->getOperand(0);
10355   EVT VT = N->getValueType(0);
10356
10357   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10358     return SDValue();
10359
10360   SDValue Src = N0.getOperand(0);
10361   EVT SrcVT = Src.getValueType();
10362   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10363   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10364
10365   // We can safely assume the conversion won't overflow the output range,
10366   // because (for example) (uint8_t)18293.f is undefined behavior.
10367
10368   // Since we can assume the conversion won't overflow, our decision as to
10369   // whether the input will fit in the float should depend on the minimum
10370   // of the input range and output range.
10371
10372   // This means this is also safe for a signed input and unsigned output, since
10373   // a negative input would lead to undefined behavior.
10374   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10375   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10376   unsigned ActualSize = std::min(InputSize, OutputSize);
10377   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10378
10379   // We can only fold away the float conversion if the input range can be
10380   // represented exactly in the float range.
10381   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10382     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10383       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10384                                                        : ISD::ZERO_EXTEND;
10385       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10386     }
10387     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10388       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10389     return DAG.getBitcast(VT, Src);
10390   }
10391   return SDValue();
10392 }
10393
10394 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10395   SDValue N0 = N->getOperand(0);
10396   EVT VT = N->getValueType(0);
10397
10398   // fold (fp_to_sint c1fp) -> c1
10399   if (isConstantFPBuildVectorOrConstantFP(N0))
10400     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10401
10402   return FoldIntToFPToInt(N, DAG);
10403 }
10404
10405 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10406   SDValue N0 = N->getOperand(0);
10407   EVT VT = N->getValueType(0);
10408
10409   // fold (fp_to_uint c1fp) -> c1
10410   if (isConstantFPBuildVectorOrConstantFP(N0))
10411     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10412
10413   return FoldIntToFPToInt(N, DAG);
10414 }
10415
10416 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10417   SDValue N0 = N->getOperand(0);
10418   SDValue N1 = N->getOperand(1);
10419   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10420   EVT VT = N->getValueType(0);
10421
10422   // fold (fp_round c1fp) -> c1fp
10423   if (N0CFP)
10424     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10425
10426   // fold (fp_round (fp_extend x)) -> x
10427   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10428     return N0.getOperand(0);
10429
10430   // fold (fp_round (fp_round x)) -> (fp_round x)
10431   if (N0.getOpcode() == ISD::FP_ROUND) {
10432     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10433     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10434
10435     // Skip this folding if it results in an fp_round from f80 to f16.
10436     //
10437     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10438     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10439     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10440     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10441     // x86.
10442     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10443       return SDValue();
10444
10445     // If the first fp_round isn't a value preserving truncation, it might
10446     // introduce a tie in the second fp_round, that wouldn't occur in the
10447     // single-step fp_round we want to fold to.
10448     // In other words, double rounding isn't the same as rounding.
10449     // Also, this is a value preserving truncation iff both fp_round's are.
10450     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10451       SDLoc DL(N);
10452       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10453                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10454     }
10455   }
10456
10457   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10458   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10459     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10460                               N0.getOperand(0), N1);
10461     AddToWorklist(Tmp.getNode());
10462     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10463                        Tmp, N0.getOperand(1));
10464   }
10465
10466   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10467     return NewVSel;
10468
10469   return SDValue();
10470 }
10471
10472 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10473   SDValue N0 = N->getOperand(0);
10474   EVT VT = N->getValueType(0);
10475   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10476   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10477
10478   // fold (fp_round_inreg c1fp) -> c1fp
10479   if (N0CFP && isTypeLegal(EVT)) {
10480     SDLoc DL(N);
10481     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10482     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10483   }
10484
10485   return SDValue();
10486 }
10487
10488 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10489   SDValue N0 = N->getOperand(0);
10490   EVT VT = N->getValueType(0);
10491
10492   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10493   if (N->hasOneUse() &&
10494       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10495     return SDValue();
10496
10497   // fold (fp_extend c1fp) -> c1fp
10498   if (isConstantFPBuildVectorOrConstantFP(N0))
10499     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10500
10501   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10502   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10503       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10504     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10505
10506   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10507   // value of X.
10508   if (N0.getOpcode() == ISD::FP_ROUND
10509       && N0.getConstantOperandVal(1) == 1) {
10510     SDValue In = N0.getOperand(0);
10511     if (In.getValueType() == VT) return In;
10512     if (VT.bitsLT(In.getValueType()))
10513       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10514                          In, N0.getOperand(1));
10515     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10516   }
10517
10518   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10519   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10520        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10521     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10522     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10523                                      LN0->getChain(),
10524                                      LN0->getBasePtr(), N0.getValueType(),
10525                                      LN0->getMemOperand());
10526     CombineTo(N, ExtLoad);
10527     CombineTo(N0.getNode(),
10528               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10529                           N0.getValueType(), ExtLoad,
10530                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10531               ExtLoad.getValue(1));
10532     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10533   }
10534
10535   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10536     return NewVSel;
10537
10538   return SDValue();
10539 }
10540
10541 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10542   SDValue N0 = N->getOperand(0);
10543   EVT VT = N->getValueType(0);
10544
10545   // fold (fceil c1) -> fceil(c1)
10546   if (isConstantFPBuildVectorOrConstantFP(N0))
10547     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10548
10549   return SDValue();
10550 }
10551
10552 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10553   SDValue N0 = N->getOperand(0);
10554   EVT VT = N->getValueType(0);
10555
10556   // fold (ftrunc c1) -> ftrunc(c1)
10557   if (isConstantFPBuildVectorOrConstantFP(N0))
10558     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10559
10560   return SDValue();
10561 }
10562
10563 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10564   SDValue N0 = N->getOperand(0);
10565   EVT VT = N->getValueType(0);
10566
10567   // fold (ffloor c1) -> ffloor(c1)
10568   if (isConstantFPBuildVectorOrConstantFP(N0))
10569     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10570
10571   return SDValue();
10572 }
10573
10574 // FIXME: FNEG and FABS have a lot in common; refactor.
10575 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10576   SDValue N0 = N->getOperand(0);
10577   EVT VT = N->getValueType(0);
10578
10579   // Constant fold FNEG.
10580   if (isConstantFPBuildVectorOrConstantFP(N0))
10581     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10582
10583   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10584                          &DAG.getTarget().Options))
10585     return GetNegatedExpression(N0, DAG, LegalOperations);
10586
10587   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10588   // constant pool values.
10589   if (!TLI.isFNegFree(VT) &&
10590       N0.getOpcode() == ISD::BITCAST &&
10591       N0.getNode()->hasOneUse()) {
10592     SDValue Int = N0.getOperand(0);
10593     EVT IntVT = Int.getValueType();
10594     if (IntVT.isInteger() && !IntVT.isVector()) {
10595       APInt SignMask;
10596       if (N0.getValueType().isVector()) {
10597         // For a vector, get a mask such as 0x80... per scalar element
10598         // and splat it.
10599         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10600         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10601       } else {
10602         // For a scalar, just generate 0x80...
10603         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10604       }
10605       SDLoc DL0(N0);
10606       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10607                         DAG.getConstant(SignMask, DL0, IntVT));
10608       AddToWorklist(Int.getNode());
10609       return DAG.getBitcast(VT, Int);
10610     }
10611   }
10612
10613   // (fneg (fmul c, x)) -> (fmul -c, x)
10614   if (N0.getOpcode() == ISD::FMUL &&
10615       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10616     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10617     if (CFP1) {
10618       APFloat CVal = CFP1->getValueAPF();
10619       CVal.changeSign();
10620       if (Level >= AfterLegalizeDAG &&
10621           (TLI.isFPImmLegal(CVal, VT) ||
10622            TLI.isOperationLegal(ISD::ConstantFP, VT)))
10623         return DAG.getNode(
10624             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10625             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10626             N0->getFlags());
10627     }
10628   }
10629
10630   return SDValue();
10631 }
10632
10633 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10634   SDValue N0 = N->getOperand(0);
10635   SDValue N1 = N->getOperand(1);
10636   EVT VT = N->getValueType(0);
10637   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10638   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10639
10640   if (N0CFP && N1CFP) {
10641     const APFloat &C0 = N0CFP->getValueAPF();
10642     const APFloat &C1 = N1CFP->getValueAPF();
10643     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10644   }
10645
10646   // Canonicalize to constant on RHS.
10647   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10648      !isConstantFPBuildVectorOrConstantFP(N1))
10649     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10650
10651   return SDValue();
10652 }
10653
10654 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10655   SDValue N0 = N->getOperand(0);
10656   SDValue N1 = N->getOperand(1);
10657   EVT VT = N->getValueType(0);
10658   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10659   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10660
10661   if (N0CFP && N1CFP) {
10662     const APFloat &C0 = N0CFP->getValueAPF();
10663     const APFloat &C1 = N1CFP->getValueAPF();
10664     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10665   }
10666
10667   // Canonicalize to constant on RHS.
10668   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10669      !isConstantFPBuildVectorOrConstantFP(N1))
10670     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10671
10672   return SDValue();
10673 }
10674
10675 SDValue DAGCombiner::visitFABS(SDNode *N) {
10676   SDValue N0 = N->getOperand(0);
10677   EVT VT = N->getValueType(0);
10678
10679   // fold (fabs c1) -> fabs(c1)
10680   if (isConstantFPBuildVectorOrConstantFP(N0))
10681     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10682
10683   // fold (fabs (fabs x)) -> (fabs x)
10684   if (N0.getOpcode() == ISD::FABS)
10685     return N->getOperand(0);
10686
10687   // fold (fabs (fneg x)) -> (fabs x)
10688   // fold (fabs (fcopysign x, y)) -> (fabs x)
10689   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10690     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10691
10692   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10693   // constant pool values.
10694   if (!TLI.isFAbsFree(VT) &&
10695       N0.getOpcode() == ISD::BITCAST &&
10696       N0.getNode()->hasOneUse()) {
10697     SDValue Int = N0.getOperand(0);
10698     EVT IntVT = Int.getValueType();
10699     if (IntVT.isInteger() && !IntVT.isVector()) {
10700       APInt SignMask;
10701       if (N0.getValueType().isVector()) {
10702         // For a vector, get a mask such as 0x7f... per scalar element
10703         // and splat it.
10704         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10705         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10706       } else {
10707         // For a scalar, just generate 0x7f...
10708         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10709       }
10710       SDLoc DL(N0);
10711       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10712                         DAG.getConstant(SignMask, DL, IntVT));
10713       AddToWorklist(Int.getNode());
10714       return DAG.getBitcast(N->getValueType(0), Int);
10715     }
10716   }
10717
10718   return SDValue();
10719 }
10720
10721 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10722   SDValue Chain = N->getOperand(0);
10723   SDValue N1 = N->getOperand(1);
10724   SDValue N2 = N->getOperand(2);
10725
10726   // If N is a constant we could fold this into a fallthrough or unconditional
10727   // branch. However that doesn't happen very often in normal code, because
10728   // Instcombine/SimplifyCFG should have handled the available opportunities.
10729   // If we did this folding here, it would be necessary to update the
10730   // MachineBasicBlock CFG, which is awkward.
10731
10732   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10733   // on the target.
10734   if (N1.getOpcode() == ISD::SETCC &&
10735       TLI.isOperationLegalOrCustom(ISD::BR_CC,
10736                                    N1.getOperand(0).getValueType())) {
10737     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10738                        Chain, N1.getOperand(2),
10739                        N1.getOperand(0), N1.getOperand(1), N2);
10740   }
10741
10742   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10743       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10744        (N1.getOperand(0).hasOneUse() &&
10745         N1.getOperand(0).getOpcode() == ISD::SRL))) {
10746     SDNode *Trunc = nullptr;
10747     if (N1.getOpcode() == ISD::TRUNCATE) {
10748       // Look pass the truncate.
10749       Trunc = N1.getNode();
10750       N1 = N1.getOperand(0);
10751     }
10752
10753     // Match this pattern so that we can generate simpler code:
10754     //
10755     //   %a = ...
10756     //   %b = and i32 %a, 2
10757     //   %c = srl i32 %b, 1
10758     //   brcond i32 %c ...
10759     //
10760     // into
10761     //
10762     //   %a = ...
10763     //   %b = and i32 %a, 2
10764     //   %c = setcc eq %b, 0
10765     //   brcond %c ...
10766     //
10767     // This applies only when the AND constant value has one bit set and the
10768     // SRL constant is equal to the log2 of the AND constant. The back-end is
10769     // smart enough to convert the result into a TEST/JMP sequence.
10770     SDValue Op0 = N1.getOperand(0);
10771     SDValue Op1 = N1.getOperand(1);
10772
10773     if (Op0.getOpcode() == ISD::AND &&
10774         Op1.getOpcode() == ISD::Constant) {
10775       SDValue AndOp1 = Op0.getOperand(1);
10776
10777       if (AndOp1.getOpcode() == ISD::Constant) {
10778         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10779
10780         if (AndConst.isPowerOf2() &&
10781             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10782           SDLoc DL(N);
10783           SDValue SetCC =
10784             DAG.getSetCC(DL,
10785                          getSetCCResultType(Op0.getValueType()),
10786                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10787                          ISD::SETNE);
10788
10789           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10790                                           MVT::Other, Chain, SetCC, N2);
10791           // Don't add the new BRCond into the worklist or else SimplifySelectCC
10792           // will convert it back to (X & C1) >> C2.
10793           CombineTo(N, NewBRCond, false);
10794           // Truncate is dead.
10795           if (Trunc)
10796             deleteAndRecombine(Trunc);
10797           // Replace the uses of SRL with SETCC
10798           WorklistRemover DeadNodes(*this);
10799           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10800           deleteAndRecombine(N1.getNode());
10801           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10802         }
10803       }
10804     }
10805
10806     if (Trunc)
10807       // Restore N1 if the above transformation doesn't match.
10808       N1 = N->getOperand(1);
10809   }
10810
10811   // Transform br(xor(x, y)) -> br(x != y)
10812   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10813   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10814     SDNode *TheXor = N1.getNode();
10815     SDValue Op0 = TheXor->getOperand(0);
10816     SDValue Op1 = TheXor->getOperand(1);
10817     if (Op0.getOpcode() == Op1.getOpcode()) {
10818       // Avoid missing important xor optimizations.
10819       if (SDValue Tmp = visitXOR(TheXor)) {
10820         if (Tmp.getNode() != TheXor) {
10821           DEBUG(dbgs() << "\nReplacing.8 ";
10822                 TheXor->dump(&DAG);
10823                 dbgs() << "\nWith: ";
10824                 Tmp.getNode()->dump(&DAG);
10825                 dbgs() << '\n');
10826           WorklistRemover DeadNodes(*this);
10827           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10828           deleteAndRecombine(TheXor);
10829           return DAG.getNode(ISD::BRCOND, SDLoc(N),
10830                              MVT::Other, Chain, Tmp, N2);
10831         }
10832
10833         // visitXOR has changed XOR's operands or replaced the XOR completely,
10834         // bail out.
10835         return SDValue(N, 0);
10836       }
10837     }
10838
10839     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10840       bool Equal = false;
10841       if (isOneConstant(Op0) && Op0.hasOneUse() &&
10842           Op0.getOpcode() == ISD::XOR) {
10843         TheXor = Op0.getNode();
10844         Equal = true;
10845       }
10846
10847       EVT SetCCVT = N1.getValueType();
10848       if (LegalTypes)
10849         SetCCVT = getSetCCResultType(SetCCVT);
10850       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10851                                    SetCCVT,
10852                                    Op0, Op1,
10853                                    Equal ? ISD::SETEQ : ISD::SETNE);
10854       // Replace the uses of XOR with SETCC
10855       WorklistRemover DeadNodes(*this);
10856       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10857       deleteAndRecombine(N1.getNode());
10858       return DAG.getNode(ISD::BRCOND, SDLoc(N),
10859                          MVT::Other, Chain, SetCC, N2);
10860     }
10861   }
10862
10863   return SDValue();
10864 }
10865
10866 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10867 //
10868 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10869   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10870   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10871
10872   // If N is a constant we could fold this into a fallthrough or unconditional
10873   // branch. However that doesn't happen very often in normal code, because
10874   // Instcombine/SimplifyCFG should have handled the available opportunities.
10875   // If we did this folding here, it would be necessary to update the
10876   // MachineBasicBlock CFG, which is awkward.
10877
10878   // Use SimplifySetCC to simplify SETCC's.
10879   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10880                                CondLHS, CondRHS, CC->get(), SDLoc(N),
10881                                false);
10882   if (Simp.getNode()) AddToWorklist(Simp.getNode());
10883
10884   // fold to a simpler setcc
10885   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10886     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10887                        N->getOperand(0), Simp.getOperand(2),
10888                        Simp.getOperand(0), Simp.getOperand(1),
10889                        N->getOperand(4));
10890
10891   return SDValue();
10892 }
10893
10894 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10895 /// and that N may be folded in the load / store addressing mode.
10896 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10897                                     SelectionDAG &DAG,
10898                                     const TargetLowering &TLI) {
10899   EVT VT;
10900   unsigned AS;
10901
10902   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
10903     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10904       return false;
10905     VT = LD->getMemoryVT();
10906     AS = LD->getAddressSpace();
10907   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
10908     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10909       return false;
10910     VT = ST->getMemoryVT();
10911     AS = ST->getAddressSpace();
10912   } else
10913     return false;
10914
10915   TargetLowering::AddrMode AM;
10916   if (N->getOpcode() == ISD::ADD) {
10917     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10918     if (Offset)
10919       // [reg +/- imm]
10920       AM.BaseOffs = Offset->getSExtValue();
10921     else
10922       // [reg +/- reg]
10923       AM.Scale = 1;
10924   } else if (N->getOpcode() == ISD::SUB) {
10925     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10926     if (Offset)
10927       // [reg +/- imm]
10928       AM.BaseOffs = -Offset->getSExtValue();
10929     else
10930       // [reg +/- reg]
10931       AM.Scale = 1;
10932   } else
10933     return false;
10934
10935   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10936                                    VT.getTypeForEVT(*DAG.getContext()), AS);
10937 }
10938
10939 /// Try turning a load/store into a pre-indexed load/store when the base
10940 /// pointer is an add or subtract and it has other uses besides the load/store.
10941 /// After the transformation, the new indexed load/store has effectively folded
10942 /// the add/subtract in and all of its other uses are redirected to the
10943 /// new load/store.
10944 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10945   if (Level < AfterLegalizeDAG)
10946     return false;
10947
10948   bool isLoad = true;
10949   SDValue Ptr;
10950   EVT VT;
10951   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10952     if (LD->isIndexed())
10953       return false;
10954     VT = LD->getMemoryVT();
10955     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10956         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10957       return false;
10958     Ptr = LD->getBasePtr();
10959   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10960     if (ST->isIndexed())
10961       return false;
10962     VT = ST->getMemoryVT();
10963     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10964         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10965       return false;
10966     Ptr = ST->getBasePtr();
10967     isLoad = false;
10968   } else {
10969     return false;
10970   }
10971
10972   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10973   // out.  There is no reason to make this a preinc/predec.
10974   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10975       Ptr.getNode()->hasOneUse())
10976     return false;
10977
10978   // Ask the target to do addressing mode selection.
10979   SDValue BasePtr;
10980   SDValue Offset;
10981   ISD::MemIndexedMode AM = ISD::UNINDEXED;
10982   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10983     return false;
10984
10985   // Backends without true r+i pre-indexed forms may need to pass a
10986   // constant base with a variable offset so that constant coercion
10987   // will work with the patterns in canonical form.
10988   bool Swapped = false;
10989   if (isa<ConstantSDNode>(BasePtr)) {
10990     std::swap(BasePtr, Offset);
10991     Swapped = true;
10992   }
10993
10994   // Don't create a indexed load / store with zero offset.
10995   if (isNullConstant(Offset))
10996     return false;
10997
10998   // Try turning it into a pre-indexed load / store except when:
10999   // 1) The new base ptr is a frame index.
11000   // 2) If N is a store and the new base ptr is either the same as or is a
11001   //    predecessor of the value being stored.
11002   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
11003   //    that would create a cycle.
11004   // 4) All uses are load / store ops that use it as old base ptr.
11005
11006   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
11007   // (plus the implicit offset) to a register to preinc anyway.
11008   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11009     return false;
11010
11011   // Check #2.
11012   if (!isLoad) {
11013     SDValue Val = cast<StoreSDNode>(N)->getValue();
11014     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
11015       return false;
11016   }
11017
11018   // Caches for hasPredecessorHelper.
11019   SmallPtrSet<const SDNode *, 32> Visited;
11020   SmallVector<const SDNode *, 16> Worklist;
11021   Worklist.push_back(N);
11022
11023   // If the offset is a constant, there may be other adds of constants that
11024   // can be folded with this one. We should do this to avoid having to keep
11025   // a copy of the original base pointer.
11026   SmallVector<SDNode *, 16> OtherUses;
11027   if (isa<ConstantSDNode>(Offset))
11028     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11029                               UE = BasePtr.getNode()->use_end();
11030          UI != UE; ++UI) {
11031       SDUse &Use = UI.getUse();
11032       // Skip the use that is Ptr and uses of other results from BasePtr's
11033       // node (important for nodes that return multiple results).
11034       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11035         continue;
11036
11037       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11038         continue;
11039
11040       if (Use.getUser()->getOpcode() != ISD::ADD &&
11041           Use.getUser()->getOpcode() != ISD::SUB) {
11042         OtherUses.clear();
11043         break;
11044       }
11045
11046       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11047       if (!isa<ConstantSDNode>(Op1)) {
11048         OtherUses.clear();
11049         break;
11050       }
11051
11052       // FIXME: In some cases, we can be smarter about this.
11053       if (Op1.getValueType() != Offset.getValueType()) {
11054         OtherUses.clear();
11055         break;
11056       }
11057
11058       OtherUses.push_back(Use.getUser());
11059     }
11060
11061   if (Swapped)
11062     std::swap(BasePtr, Offset);
11063
11064   // Now check for #3 and #4.
11065   bool RealUse = false;
11066
11067   for (SDNode *Use : Ptr.getNode()->uses()) {
11068     if (Use == N)
11069       continue;
11070     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11071       return false;
11072
11073     // If Ptr may be folded in addressing mode of other use, then it's
11074     // not profitable to do this transformation.
11075     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11076       RealUse = true;
11077   }
11078
11079   if (!RealUse)
11080     return false;
11081
11082   SDValue Result;
11083   if (isLoad)
11084     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11085                                 BasePtr, Offset, AM);
11086   else
11087     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11088                                  BasePtr, Offset, AM);
11089   ++PreIndexedNodes;
11090   ++NodesCombined;
11091   DEBUG(dbgs() << "\nReplacing.4 ";
11092         N->dump(&DAG);
11093         dbgs() << "\nWith: ";
11094         Result.getNode()->dump(&DAG);
11095         dbgs() << '\n');
11096   WorklistRemover DeadNodes(*this);
11097   if (isLoad) {
11098     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11099     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11100   } else {
11101     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11102   }
11103
11104   // Finally, since the node is now dead, remove it from the graph.
11105   deleteAndRecombine(N);
11106
11107   if (Swapped)
11108     std::swap(BasePtr, Offset);
11109
11110   // Replace other uses of BasePtr that can be updated to use Ptr
11111   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11112     unsigned OffsetIdx = 1;
11113     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11114       OffsetIdx = 0;
11115     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11116            BasePtr.getNode() && "Expected BasePtr operand");
11117
11118     // We need to replace ptr0 in the following expression:
11119     //   x0 * offset0 + y0 * ptr0 = t0
11120     // knowing that
11121     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11122     //
11123     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11124     // indexed load/store and the expression that needs to be re-written.
11125     //
11126     // Therefore, we have:
11127     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11128
11129     ConstantSDNode *CN =
11130       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11131     int X0, X1, Y0, Y1;
11132     const APInt &Offset0 = CN->getAPIntValue();
11133     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11134
11135     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11136     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11137     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11138     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11139
11140     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11141
11142     APInt CNV = Offset0;
11143     if (X0 < 0) CNV = -CNV;
11144     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11145     else CNV = CNV - Offset1;
11146
11147     SDLoc DL(OtherUses[i]);
11148
11149     // We can now generate the new expression.
11150     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11151     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11152
11153     SDValue NewUse = DAG.getNode(Opcode,
11154                                  DL,
11155                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11156     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11157     deleteAndRecombine(OtherUses[i]);
11158   }
11159
11160   // Replace the uses of Ptr with uses of the updated base value.
11161   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11162   deleteAndRecombine(Ptr.getNode());
11163
11164   return true;
11165 }
11166
11167 /// Try to combine a load/store with a add/sub of the base pointer node into a
11168 /// post-indexed load/store. The transformation folded the add/subtract into the
11169 /// new indexed load/store effectively and all of its uses are redirected to the
11170 /// new load/store.
11171 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11172   if (Level < AfterLegalizeDAG)
11173     return false;
11174
11175   bool isLoad = true;
11176   SDValue Ptr;
11177   EVT VT;
11178   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11179     if (LD->isIndexed())
11180       return false;
11181     VT = LD->getMemoryVT();
11182     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11183         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11184       return false;
11185     Ptr = LD->getBasePtr();
11186   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11187     if (ST->isIndexed())
11188       return false;
11189     VT = ST->getMemoryVT();
11190     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11191         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11192       return false;
11193     Ptr = ST->getBasePtr();
11194     isLoad = false;
11195   } else {
11196     return false;
11197   }
11198
11199   if (Ptr.getNode()->hasOneUse())
11200     return false;
11201
11202   for (SDNode *Op : Ptr.getNode()->uses()) {
11203     if (Op == N ||
11204         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11205       continue;
11206
11207     SDValue BasePtr;
11208     SDValue Offset;
11209     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11210     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11211       // Don't create a indexed load / store with zero offset.
11212       if (isNullConstant(Offset))
11213         continue;
11214
11215       // Try turning it into a post-indexed load / store except when
11216       // 1) All uses are load / store ops that use it as base ptr (and
11217       //    it may be folded as addressing mmode).
11218       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11219       //    nor a successor of N. Otherwise, if Op is folded that would
11220       //    create a cycle.
11221
11222       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11223         continue;
11224
11225       // Check for #1.
11226       bool TryNext = false;
11227       for (SDNode *Use : BasePtr.getNode()->uses()) {
11228         if (Use == Ptr.getNode())
11229           continue;
11230
11231         // If all the uses are load / store addresses, then don't do the
11232         // transformation.
11233         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11234           bool RealUse = false;
11235           for (SDNode *UseUse : Use->uses()) {
11236             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11237               RealUse = true;
11238           }
11239
11240           if (!RealUse) {
11241             TryNext = true;
11242             break;
11243           }
11244         }
11245       }
11246
11247       if (TryNext)
11248         continue;
11249
11250       // Check for #2
11251       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11252         SDValue Result = isLoad
11253           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11254                                BasePtr, Offset, AM)
11255           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11256                                 BasePtr, Offset, AM);
11257         ++PostIndexedNodes;
11258         ++NodesCombined;
11259         DEBUG(dbgs() << "\nReplacing.5 ";
11260               N->dump(&DAG);
11261               dbgs() << "\nWith: ";
11262               Result.getNode()->dump(&DAG);
11263               dbgs() << '\n');
11264         WorklistRemover DeadNodes(*this);
11265         if (isLoad) {
11266           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11267           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11268         } else {
11269           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11270         }
11271
11272         // Finally, since the node is now dead, remove it from the graph.
11273         deleteAndRecombine(N);
11274
11275         // Replace the uses of Use with uses of the updated base value.
11276         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11277                                       Result.getValue(isLoad ? 1 : 0));
11278         deleteAndRecombine(Op);
11279         return true;
11280       }
11281     }
11282   }
11283
11284   return false;
11285 }
11286
11287 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11288 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11289   ISD::MemIndexedMode AM = LD->getAddressingMode();
11290   assert(AM != ISD::UNINDEXED);
11291   SDValue BP = LD->getOperand(1);
11292   SDValue Inc = LD->getOperand(2);
11293
11294   // Some backends use TargetConstants for load offsets, but don't expect
11295   // TargetConstants in general ADD nodes. We can convert these constants into
11296   // regular Constants (if the constant is not opaque).
11297   assert((Inc.getOpcode() != ISD::TargetConstant ||
11298           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11299          "Cannot split out indexing using opaque target constants");
11300   if (Inc.getOpcode() == ISD::TargetConstant) {
11301     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11302     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11303                           ConstInc->getValueType(0));
11304   }
11305
11306   unsigned Opc =
11307       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11308   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11309 }
11310
11311 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11312   LoadSDNode *LD  = cast<LoadSDNode>(N);
11313   SDValue Chain = LD->getChain();
11314   SDValue Ptr   = LD->getBasePtr();
11315
11316   // If load is not volatile and there are no uses of the loaded value (and
11317   // the updated indexed value in case of indexed loads), change uses of the
11318   // chain value into uses of the chain input (i.e. delete the dead load).
11319   if (!LD->isVolatile()) {
11320     if (N->getValueType(1) == MVT::Other) {
11321       // Unindexed loads.
11322       if (!N->hasAnyUseOfValue(0)) {
11323         // It's not safe to use the two value CombineTo variant here. e.g.
11324         // v1, chain2 = load chain1, loc
11325         // v2, chain3 = load chain2, loc
11326         // v3         = add v2, c
11327         // Now we replace use of chain2 with chain1.  This makes the second load
11328         // isomorphic to the one we are deleting, and thus makes this load live.
11329         DEBUG(dbgs() << "\nReplacing.6 ";
11330               N->dump(&DAG);
11331               dbgs() << "\nWith chain: ";
11332               Chain.getNode()->dump(&DAG);
11333               dbgs() << "\n");
11334         WorklistRemover DeadNodes(*this);
11335         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11336         AddUsersToWorklist(Chain.getNode());
11337         if (N->use_empty())
11338           deleteAndRecombine(N);
11339
11340         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11341       }
11342     } else {
11343       // Indexed loads.
11344       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11345
11346       // If this load has an opaque TargetConstant offset, then we cannot split
11347       // the indexing into an add/sub directly (that TargetConstant may not be
11348       // valid for a different type of node, and we cannot convert an opaque
11349       // target constant into a regular constant).
11350       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11351                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11352
11353       if (!N->hasAnyUseOfValue(0) &&
11354           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11355         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11356         SDValue Index;
11357         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11358           Index = SplitIndexingFromLoad(LD);
11359           // Try to fold the base pointer arithmetic into subsequent loads and
11360           // stores.
11361           AddUsersToWorklist(N);
11362         } else
11363           Index = DAG.getUNDEF(N->getValueType(1));
11364         DEBUG(dbgs() << "\nReplacing.7 ";
11365               N->dump(&DAG);
11366               dbgs() << "\nWith: ";
11367               Undef.getNode()->dump(&DAG);
11368               dbgs() << " and 2 other values\n");
11369         WorklistRemover DeadNodes(*this);
11370         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11371         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11372         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11373         deleteAndRecombine(N);
11374         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11375       }
11376     }
11377   }
11378
11379   // If this load is directly stored, replace the load value with the stored
11380   // value.
11381   // TODO: Handle store large -> read small portion.
11382   // TODO: Handle TRUNCSTORE/LOADEXT
11383   if (OptLevel != CodeGenOpt::None &&
11384       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11385     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11386       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11387       if (PrevST->getBasePtr() == Ptr &&
11388           PrevST->getValue().getValueType() == N->getValueType(0))
11389         return CombineTo(N, PrevST->getOperand(1), Chain);
11390     }
11391   }
11392
11393   // Try to infer better alignment information than the load already has.
11394   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11395     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11396       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11397         SDValue NewLoad = DAG.getExtLoad(
11398             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11399             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11400             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11401         if (NewLoad.getNode() != N)
11402           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11403       }
11404     }
11405   }
11406
11407   if (LD->isUnindexed()) {
11408     // Walk up chain skipping non-aliasing memory nodes.
11409     SDValue BetterChain = FindBetterChain(N, Chain);
11410
11411     // If there is a better chain.
11412     if (Chain != BetterChain) {
11413       SDValue ReplLoad;
11414
11415       // Replace the chain to void dependency.
11416       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11417         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11418                                BetterChain, Ptr, LD->getMemOperand());
11419       } else {
11420         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11421                                   LD->getValueType(0),
11422                                   BetterChain, Ptr, LD->getMemoryVT(),
11423                                   LD->getMemOperand());
11424       }
11425
11426       // Create token factor to keep old chain connected.
11427       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11428                                   MVT::Other, Chain, ReplLoad.getValue(1));
11429
11430       // Replace uses with load result and token factor
11431       return CombineTo(N, ReplLoad.getValue(0), Token);
11432     }
11433   }
11434
11435   // Try transforming N to an indexed load.
11436   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11437     return SDValue(N, 0);
11438
11439   // Try to slice up N to more direct loads if the slices are mapped to
11440   // different register banks or pairing can take place.
11441   if (SliceUpLoad(N))
11442     return SDValue(N, 0);
11443
11444   return SDValue();
11445 }
11446
11447 namespace {
11448 /// \brief Helper structure used to slice a load in smaller loads.
11449 /// Basically a slice is obtained from the following sequence:
11450 /// Origin = load Ty1, Base
11451 /// Shift = srl Ty1 Origin, CstTy Amount
11452 /// Inst = trunc Shift to Ty2
11453 ///
11454 /// Then, it will be rewritten into:
11455 /// Slice = load SliceTy, Base + SliceOffset
11456 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11457 ///
11458 /// SliceTy is deduced from the number of bits that are actually used to
11459 /// build Inst.
11460 struct LoadedSlice {
11461   /// \brief Helper structure used to compute the cost of a slice.
11462   struct Cost {
11463     /// Are we optimizing for code size.
11464     bool ForCodeSize;
11465     /// Various cost.
11466     unsigned Loads;
11467     unsigned Truncates;
11468     unsigned CrossRegisterBanksCopies;
11469     unsigned ZExts;
11470     unsigned Shift;
11471
11472     Cost(bool ForCodeSize = false)
11473         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11474           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11475
11476     /// \brief Get the cost of one isolated slice.
11477     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11478         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11479           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11480       EVT TruncType = LS.Inst->getValueType(0);
11481       EVT LoadedType = LS.getLoadedType();
11482       if (TruncType != LoadedType &&
11483           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11484         ZExts = 1;
11485     }
11486
11487     /// \brief Account for slicing gain in the current cost.
11488     /// Slicing provide a few gains like removing a shift or a
11489     /// truncate. This method allows to grow the cost of the original
11490     /// load with the gain from this slice.
11491     void addSliceGain(const LoadedSlice &LS) {
11492       // Each slice saves a truncate.
11493       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11494       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11495                               LS.Inst->getValueType(0)))
11496         ++Truncates;
11497       // If there is a shift amount, this slice gets rid of it.
11498       if (LS.Shift)
11499         ++Shift;
11500       // If this slice can merge a cross register bank copy, account for it.
11501       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11502         ++CrossRegisterBanksCopies;
11503     }
11504
11505     Cost &operator+=(const Cost &RHS) {
11506       Loads += RHS.Loads;
11507       Truncates += RHS.Truncates;
11508       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11509       ZExts += RHS.ZExts;
11510       Shift += RHS.Shift;
11511       return *this;
11512     }
11513
11514     bool operator==(const Cost &RHS) const {
11515       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11516              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11517              ZExts == RHS.ZExts && Shift == RHS.Shift;
11518     }
11519
11520     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11521
11522     bool operator<(const Cost &RHS) const {
11523       // Assume cross register banks copies are as expensive as loads.
11524       // FIXME: Do we want some more target hooks?
11525       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11526       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11527       // Unless we are optimizing for code size, consider the
11528       // expensive operation first.
11529       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11530         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11531       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11532              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11533     }
11534
11535     bool operator>(const Cost &RHS) const { return RHS < *this; }
11536
11537     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11538
11539     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11540   };
11541   // The last instruction that represent the slice. This should be a
11542   // truncate instruction.
11543   SDNode *Inst;
11544   // The original load instruction.
11545   LoadSDNode *Origin;
11546   // The right shift amount in bits from the original load.
11547   unsigned Shift;
11548   // The DAG from which Origin came from.
11549   // This is used to get some contextual information about legal types, etc.
11550   SelectionDAG *DAG;
11551
11552   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11553               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11554       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11555
11556   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11557   /// \return Result is \p BitWidth and has used bits set to 1 and
11558   ///         not used bits set to 0.
11559   APInt getUsedBits() const {
11560     // Reproduce the trunc(lshr) sequence:
11561     // - Start from the truncated value.
11562     // - Zero extend to the desired bit width.
11563     // - Shift left.
11564     assert(Origin && "No original load to compare against.");
11565     unsigned BitWidth = Origin->getValueSizeInBits(0);
11566     assert(Inst && "This slice is not bound to an instruction");
11567     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11568            "Extracted slice is bigger than the whole type!");
11569     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11570     UsedBits.setAllBits();
11571     UsedBits = UsedBits.zext(BitWidth);
11572     UsedBits <<= Shift;
11573     return UsedBits;
11574   }
11575
11576   /// \brief Get the size of the slice to be loaded in bytes.
11577   unsigned getLoadedSize() const {
11578     unsigned SliceSize = getUsedBits().countPopulation();
11579     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11580     return SliceSize / 8;
11581   }
11582
11583   /// \brief Get the type that will be loaded for this slice.
11584   /// Note: This may not be the final type for the slice.
11585   EVT getLoadedType() const {
11586     assert(DAG && "Missing context");
11587     LLVMContext &Ctxt = *DAG->getContext();
11588     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11589   }
11590
11591   /// \brief Get the alignment of the load used for this slice.
11592   unsigned getAlignment() const {
11593     unsigned Alignment = Origin->getAlignment();
11594     unsigned Offset = getOffsetFromBase();
11595     if (Offset != 0)
11596       Alignment = MinAlign(Alignment, Alignment + Offset);
11597     return Alignment;
11598   }
11599
11600   /// \brief Check if this slice can be rewritten with legal operations.
11601   bool isLegal() const {
11602     // An invalid slice is not legal.
11603     if (!Origin || !Inst || !DAG)
11604       return false;
11605
11606     // Offsets are for indexed load only, we do not handle that.
11607     if (!Origin->getOffset().isUndef())
11608       return false;
11609
11610     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11611
11612     // Check that the type is legal.
11613     EVT SliceType = getLoadedType();
11614     if (!TLI.isTypeLegal(SliceType))
11615       return false;
11616
11617     // Check that the load is legal for this type.
11618     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11619       return false;
11620
11621     // Check that the offset can be computed.
11622     // 1. Check its type.
11623     EVT PtrType = Origin->getBasePtr().getValueType();
11624     if (PtrType == MVT::Untyped || PtrType.isExtended())
11625       return false;
11626
11627     // 2. Check that it fits in the immediate.
11628     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11629       return false;
11630
11631     // 3. Check that the computation is legal.
11632     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11633       return false;
11634
11635     // Check that the zext is legal if it needs one.
11636     EVT TruncateType = Inst->getValueType(0);
11637     if (TruncateType != SliceType &&
11638         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11639       return false;
11640
11641     return true;
11642   }
11643
11644   /// \brief Get the offset in bytes of this slice in the original chunk of
11645   /// bits.
11646   /// \pre DAG != nullptr.
11647   uint64_t getOffsetFromBase() const {
11648     assert(DAG && "Missing context.");
11649     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11650     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11651     uint64_t Offset = Shift / 8;
11652     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11653     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11654            "The size of the original loaded type is not a multiple of a"
11655            " byte.");
11656     // If Offset is bigger than TySizeInBytes, it means we are loading all
11657     // zeros. This should have been optimized before in the process.
11658     assert(TySizeInBytes > Offset &&
11659            "Invalid shift amount for given loaded size");
11660     if (IsBigEndian)
11661       Offset = TySizeInBytes - Offset - getLoadedSize();
11662     return Offset;
11663   }
11664
11665   /// \brief Generate the sequence of instructions to load the slice
11666   /// represented by this object and redirect the uses of this slice to
11667   /// this new sequence of instructions.
11668   /// \pre this->Inst && this->Origin are valid Instructions and this
11669   /// object passed the legal check: LoadedSlice::isLegal returned true.
11670   /// \return The last instruction of the sequence used to load the slice.
11671   SDValue loadSlice() const {
11672     assert(Inst && Origin && "Unable to replace a non-existing slice.");
11673     const SDValue &OldBaseAddr = Origin->getBasePtr();
11674     SDValue BaseAddr = OldBaseAddr;
11675     // Get the offset in that chunk of bytes w.r.t. the endianness.
11676     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11677     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11678     if (Offset) {
11679       // BaseAddr = BaseAddr + Offset.
11680       EVT ArithType = BaseAddr.getValueType();
11681       SDLoc DL(Origin);
11682       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11683                               DAG->getConstant(Offset, DL, ArithType));
11684     }
11685
11686     // Create the type of the loaded slice according to its size.
11687     EVT SliceType = getLoadedType();
11688
11689     // Create the load for the slice.
11690     SDValue LastInst =
11691         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11692                      Origin->getPointerInfo().getWithOffset(Offset),
11693                      getAlignment(), Origin->getMemOperand()->getFlags());
11694     // If the final type is not the same as the loaded type, this means that
11695     // we have to pad with zero. Create a zero extend for that.
11696     EVT FinalType = Inst->getValueType(0);
11697     if (SliceType != FinalType)
11698       LastInst =
11699           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11700     return LastInst;
11701   }
11702
11703   /// \brief Check if this slice can be merged with an expensive cross register
11704   /// bank copy. E.g.,
11705   /// i = load i32
11706   /// f = bitcast i32 i to float
11707   bool canMergeExpensiveCrossRegisterBankCopy() const {
11708     if (!Inst || !Inst->hasOneUse())
11709       return false;
11710     SDNode *Use = *Inst->use_begin();
11711     if (Use->getOpcode() != ISD::BITCAST)
11712       return false;
11713     assert(DAG && "Missing context");
11714     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11715     EVT ResVT = Use->getValueType(0);
11716     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11717     const TargetRegisterClass *ArgRC =
11718         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11719     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11720       return false;
11721
11722     // At this point, we know that we perform a cross-register-bank copy.
11723     // Check if it is expensive.
11724     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11725     // Assume bitcasts are cheap, unless both register classes do not
11726     // explicitly share a common sub class.
11727     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11728       return false;
11729
11730     // Check if it will be merged with the load.
11731     // 1. Check the alignment constraint.
11732     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11733         ResVT.getTypeForEVT(*DAG->getContext()));
11734
11735     if (RequiredAlignment > getAlignment())
11736       return false;
11737
11738     // 2. Check that the load is a legal operation for that type.
11739     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11740       return false;
11741
11742     // 3. Check that we do not have a zext in the way.
11743     if (Inst->getValueType(0) != getLoadedType())
11744       return false;
11745
11746     return true;
11747   }
11748 };
11749 }
11750
11751 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11752 /// \p UsedBits looks like 0..0 1..1 0..0.
11753 static bool areUsedBitsDense(const APInt &UsedBits) {
11754   // If all the bits are one, this is dense!
11755   if (UsedBits.isAllOnesValue())
11756     return true;
11757
11758   // Get rid of the unused bits on the right.
11759   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11760   // Get rid of the unused bits on the left.
11761   if (NarrowedUsedBits.countLeadingZeros())
11762     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11763   // Check that the chunk of bits is completely used.
11764   return NarrowedUsedBits.isAllOnesValue();
11765 }
11766
11767 /// \brief Check whether or not \p First and \p Second are next to each other
11768 /// in memory. This means that there is no hole between the bits loaded
11769 /// by \p First and the bits loaded by \p Second.
11770 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11771                                      const LoadedSlice &Second) {
11772   assert(First.Origin == Second.Origin && First.Origin &&
11773          "Unable to match different memory origins.");
11774   APInt UsedBits = First.getUsedBits();
11775   assert((UsedBits & Second.getUsedBits()) == 0 &&
11776          "Slices are not supposed to overlap.");
11777   UsedBits |= Second.getUsedBits();
11778   return areUsedBitsDense(UsedBits);
11779 }
11780
11781 /// \brief Adjust the \p GlobalLSCost according to the target
11782 /// paring capabilities and the layout of the slices.
11783 /// \pre \p GlobalLSCost should account for at least as many loads as
11784 /// there is in the slices in \p LoadedSlices.
11785 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11786                                  LoadedSlice::Cost &GlobalLSCost) {
11787   unsigned NumberOfSlices = LoadedSlices.size();
11788   // If there is less than 2 elements, no pairing is possible.
11789   if (NumberOfSlices < 2)
11790     return;
11791
11792   // Sort the slices so that elements that are likely to be next to each
11793   // other in memory are next to each other in the list.
11794   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11795             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11796     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11797     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11798   });
11799   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11800   // First (resp. Second) is the first (resp. Second) potentially candidate
11801   // to be placed in a paired load.
11802   const LoadedSlice *First = nullptr;
11803   const LoadedSlice *Second = nullptr;
11804   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11805                 // Set the beginning of the pair.
11806                                                            First = Second) {
11807
11808     Second = &LoadedSlices[CurrSlice];
11809
11810     // If First is NULL, it means we start a new pair.
11811     // Get to the next slice.
11812     if (!First)
11813       continue;
11814
11815     EVT LoadedType = First->getLoadedType();
11816
11817     // If the types of the slices are different, we cannot pair them.
11818     if (LoadedType != Second->getLoadedType())
11819       continue;
11820
11821     // Check if the target supplies paired loads for this type.
11822     unsigned RequiredAlignment = 0;
11823     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11824       // move to the next pair, this type is hopeless.
11825       Second = nullptr;
11826       continue;
11827     }
11828     // Check if we meet the alignment requirement.
11829     if (RequiredAlignment > First->getAlignment())
11830       continue;
11831
11832     // Check that both loads are next to each other in memory.
11833     if (!areSlicesNextToEachOther(*First, *Second))
11834       continue;
11835
11836     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11837     --GlobalLSCost.Loads;
11838     // Move to the next pair.
11839     Second = nullptr;
11840   }
11841 }
11842
11843 /// \brief Check the profitability of all involved LoadedSlice.
11844 /// Currently, it is considered profitable if there is exactly two
11845 /// involved slices (1) which are (2) next to each other in memory, and
11846 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11847 ///
11848 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11849 /// the elements themselves.
11850 ///
11851 /// FIXME: When the cost model will be mature enough, we can relax
11852 /// constraints (1) and (2).
11853 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11854                                 const APInt &UsedBits, bool ForCodeSize) {
11855   unsigned NumberOfSlices = LoadedSlices.size();
11856   if (StressLoadSlicing)
11857     return NumberOfSlices > 1;
11858
11859   // Check (1).
11860   if (NumberOfSlices != 2)
11861     return false;
11862
11863   // Check (2).
11864   if (!areUsedBitsDense(UsedBits))
11865     return false;
11866
11867   // Check (3).
11868   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11869   // The original code has one big load.
11870   OrigCost.Loads = 1;
11871   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11872     const LoadedSlice &LS = LoadedSlices[CurrSlice];
11873     // Accumulate the cost of all the slices.
11874     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11875     GlobalSlicingCost += SliceCost;
11876
11877     // Account as cost in the original configuration the gain obtained
11878     // with the current slices.
11879     OrigCost.addSliceGain(LS);
11880   }
11881
11882   // If the target supports paired load, adjust the cost accordingly.
11883   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11884   return OrigCost > GlobalSlicingCost;
11885 }
11886
11887 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11888 /// operations, split it in the various pieces being extracted.
11889 ///
11890 /// This sort of thing is introduced by SROA.
11891 /// This slicing takes care not to insert overlapping loads.
11892 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11893 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11894   if (Level < AfterLegalizeDAG)
11895     return false;
11896
11897   LoadSDNode *LD = cast<LoadSDNode>(N);
11898   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11899       !LD->getValueType(0).isInteger())
11900     return false;
11901
11902   // Keep track of already used bits to detect overlapping values.
11903   // In that case, we will just abort the transformation.
11904   APInt UsedBits(LD->getValueSizeInBits(0), 0);
11905
11906   SmallVector<LoadedSlice, 4> LoadedSlices;
11907
11908   // Check if this load is used as several smaller chunks of bits.
11909   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11910   // of computation for each trunc.
11911   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11912        UI != UIEnd; ++UI) {
11913     // Skip the uses of the chain.
11914     if (UI.getUse().getResNo() != 0)
11915       continue;
11916
11917     SDNode *User = *UI;
11918     unsigned Shift = 0;
11919
11920     // Check if this is a trunc(lshr).
11921     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11922         isa<ConstantSDNode>(User->getOperand(1))) {
11923       Shift = User->getConstantOperandVal(1);
11924       User = *User->use_begin();
11925     }
11926
11927     // At this point, User is a Truncate, iff we encountered, trunc or
11928     // trunc(lshr).
11929     if (User->getOpcode() != ISD::TRUNCATE)
11930       return false;
11931
11932     // The width of the type must be a power of 2 and greater than 8-bits.
11933     // Otherwise the load cannot be represented in LLVM IR.
11934     // Moreover, if we shifted with a non-8-bits multiple, the slice
11935     // will be across several bytes. We do not support that.
11936     unsigned Width = User->getValueSizeInBits(0);
11937     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11938       return 0;
11939
11940     // Build the slice for this chain of computations.
11941     LoadedSlice LS(User, LD, Shift, &DAG);
11942     APInt CurrentUsedBits = LS.getUsedBits();
11943
11944     // Check if this slice overlaps with another.
11945     if ((CurrentUsedBits & UsedBits) != 0)
11946       return false;
11947     // Update the bits used globally.
11948     UsedBits |= CurrentUsedBits;
11949
11950     // Check if the new slice would be legal.
11951     if (!LS.isLegal())
11952       return false;
11953
11954     // Record the slice.
11955     LoadedSlices.push_back(LS);
11956   }
11957
11958   // Abort slicing if it does not seem to be profitable.
11959   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11960     return false;
11961
11962   ++SlicedLoads;
11963
11964   // Rewrite each chain to use an independent load.
11965   // By construction, each chain can be represented by a unique load.
11966
11967   // Prepare the argument for the new token factor for all the slices.
11968   SmallVector<SDValue, 8> ArgChains;
11969   for (SmallVectorImpl<LoadedSlice>::const_iterator
11970            LSIt = LoadedSlices.begin(),
11971            LSItEnd = LoadedSlices.end();
11972        LSIt != LSItEnd; ++LSIt) {
11973     SDValue SliceInst = LSIt->loadSlice();
11974     CombineTo(LSIt->Inst, SliceInst, true);
11975     if (SliceInst.getOpcode() != ISD::LOAD)
11976       SliceInst = SliceInst.getOperand(0);
11977     assert(SliceInst->getOpcode() == ISD::LOAD &&
11978            "It takes more than a zext to get to the loaded slice!!");
11979     ArgChains.push_back(SliceInst.getValue(1));
11980   }
11981
11982   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11983                               ArgChains);
11984   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11985   AddToWorklist(Chain.getNode());
11986   return true;
11987 }
11988
11989 /// Check to see if V is (and load (ptr), imm), where the load is having
11990 /// specific bytes cleared out.  If so, return the byte size being masked out
11991 /// and the shift amount.
11992 static std::pair<unsigned, unsigned>
11993 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11994   std::pair<unsigned, unsigned> Result(0, 0);
11995
11996   // Check for the structure we're looking for.
11997   if (V->getOpcode() != ISD::AND ||
11998       !isa<ConstantSDNode>(V->getOperand(1)) ||
11999       !ISD::isNormalLoad(V->getOperand(0).getNode()))
12000     return Result;
12001
12002   // Check the chain and pointer.
12003   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
12004   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
12005
12006   // The store should be chained directly to the load or be an operand of a
12007   // tokenfactor.
12008   if (LD == Chain.getNode())
12009     ; // ok.
12010   else if (Chain->getOpcode() != ISD::TokenFactor)
12011     return Result; // Fail.
12012   else {
12013     bool isOk = false;
12014     for (const SDValue &ChainOp : Chain->op_values())
12015       if (ChainOp.getNode() == LD) {
12016         isOk = true;
12017         break;
12018       }
12019     if (!isOk) return Result;
12020   }
12021
12022   // This only handles simple types.
12023   if (V.getValueType() != MVT::i16 &&
12024       V.getValueType() != MVT::i32 &&
12025       V.getValueType() != MVT::i64)
12026     return Result;
12027
12028   // Check the constant mask.  Invert it so that the bits being masked out are
12029   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
12030   // follow the sign bit for uniformity.
12031   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12032   unsigned NotMaskLZ = countLeadingZeros(NotMask);
12033   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
12034   unsigned NotMaskTZ = countTrailingZeros(NotMask);
12035   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
12036   if (NotMaskLZ == 64) return Result;  // All zero mask.
12037
12038   // See if we have a continuous run of bits.  If so, we have 0*1+0*
12039   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12040     return Result;
12041
12042   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12043   if (V.getValueType() != MVT::i64 && NotMaskLZ)
12044     NotMaskLZ -= 64-V.getValueSizeInBits();
12045
12046   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12047   switch (MaskedBytes) {
12048   case 1:
12049   case 2:
12050   case 4: break;
12051   default: return Result; // All one mask, or 5-byte mask.
12052   }
12053
12054   // Verify that the first bit starts at a multiple of mask so that the access
12055   // is aligned the same as the access width.
12056   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12057
12058   Result.first = MaskedBytes;
12059   Result.second = NotMaskTZ/8;
12060   return Result;
12061 }
12062
12063
12064 /// Check to see if IVal is something that provides a value as specified by
12065 /// MaskInfo. If so, replace the specified store with a narrower store of
12066 /// truncated IVal.
12067 static SDNode *
12068 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12069                                 SDValue IVal, StoreSDNode *St,
12070                                 DAGCombiner *DC) {
12071   unsigned NumBytes = MaskInfo.first;
12072   unsigned ByteShift = MaskInfo.second;
12073   SelectionDAG &DAG = DC->getDAG();
12074
12075   // Check to see if IVal is all zeros in the part being masked in by the 'or'
12076   // that uses this.  If not, this is not a replacement.
12077   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12078                                   ByteShift*8, (ByteShift+NumBytes)*8);
12079   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12080
12081   // Check that it is legal on the target to do this.  It is legal if the new
12082   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12083   // legalization.
12084   MVT VT = MVT::getIntegerVT(NumBytes*8);
12085   if (!DC->isTypeLegal(VT))
12086     return nullptr;
12087
12088   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
12089   // shifted by ByteShift and truncated down to NumBytes.
12090   if (ByteShift) {
12091     SDLoc DL(IVal);
12092     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12093                        DAG.getConstant(ByteShift*8, DL,
12094                                     DC->getShiftAmountTy(IVal.getValueType())));
12095   }
12096
12097   // Figure out the offset for the store and the alignment of the access.
12098   unsigned StOffset;
12099   unsigned NewAlign = St->getAlignment();
12100
12101   if (DAG.getDataLayout().isLittleEndian())
12102     StOffset = ByteShift;
12103   else
12104     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12105
12106   SDValue Ptr = St->getBasePtr();
12107   if (StOffset) {
12108     SDLoc DL(IVal);
12109     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12110                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12111     NewAlign = MinAlign(NewAlign, StOffset);
12112   }
12113
12114   // Truncate down to the new size.
12115   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12116
12117   ++OpsNarrowed;
12118   return DAG
12119       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12120                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12121       .getNode();
12122 }
12123
12124
12125 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12126 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12127 /// narrowing the load and store if it would end up being a win for performance
12128 /// or code size.
12129 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12130   StoreSDNode *ST  = cast<StoreSDNode>(N);
12131   if (ST->isVolatile())
12132     return SDValue();
12133
12134   SDValue Chain = ST->getChain();
12135   SDValue Value = ST->getValue();
12136   SDValue Ptr   = ST->getBasePtr();
12137   EVT VT = Value.getValueType();
12138
12139   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12140     return SDValue();
12141
12142   unsigned Opc = Value.getOpcode();
12143
12144   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12145   // is a byte mask indicating a consecutive number of bytes, check to see if
12146   // Y is known to provide just those bytes.  If so, we try to replace the
12147   // load + replace + store sequence with a single (narrower) store, which makes
12148   // the load dead.
12149   if (Opc == ISD::OR) {
12150     std::pair<unsigned, unsigned> MaskedLoad;
12151     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12152     if (MaskedLoad.first)
12153       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12154                                                   Value.getOperand(1), ST,this))
12155         return SDValue(NewST, 0);
12156
12157     // Or is commutative, so try swapping X and Y.
12158     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12159     if (MaskedLoad.first)
12160       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12161                                                   Value.getOperand(0), ST,this))
12162         return SDValue(NewST, 0);
12163   }
12164
12165   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12166       Value.getOperand(1).getOpcode() != ISD::Constant)
12167     return SDValue();
12168
12169   SDValue N0 = Value.getOperand(0);
12170   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12171       Chain == SDValue(N0.getNode(), 1)) {
12172     LoadSDNode *LD = cast<LoadSDNode>(N0);
12173     if (LD->getBasePtr() != Ptr ||
12174         LD->getPointerInfo().getAddrSpace() !=
12175         ST->getPointerInfo().getAddrSpace())
12176       return SDValue();
12177
12178     // Find the type to narrow it the load / op / store to.
12179     SDValue N1 = Value.getOperand(1);
12180     unsigned BitWidth = N1.getValueSizeInBits();
12181     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12182     if (Opc == ISD::AND)
12183       Imm ^= APInt::getAllOnesValue(BitWidth);
12184     if (Imm == 0 || Imm.isAllOnesValue())
12185       return SDValue();
12186     unsigned ShAmt = Imm.countTrailingZeros();
12187     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12188     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12189     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12190     // The narrowing should be profitable, the load/store operation should be
12191     // legal (or custom) and the store size should be equal to the NewVT width.
12192     while (NewBW < BitWidth &&
12193            (NewVT.getStoreSizeInBits() != NewBW ||
12194             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12195             !TLI.isNarrowingProfitable(VT, NewVT))) {
12196       NewBW = NextPowerOf2(NewBW);
12197       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12198     }
12199     if (NewBW >= BitWidth)
12200       return SDValue();
12201
12202     // If the lsb changed does not start at the type bitwidth boundary,
12203     // start at the previous one.
12204     if (ShAmt % NewBW)
12205       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12206     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12207                                    std::min(BitWidth, ShAmt + NewBW));
12208     if ((Imm & Mask) == Imm) {
12209       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12210       if (Opc == ISD::AND)
12211         NewImm ^= APInt::getAllOnesValue(NewBW);
12212       uint64_t PtrOff = ShAmt / 8;
12213       // For big endian targets, we need to adjust the offset to the pointer to
12214       // load the correct bytes.
12215       if (DAG.getDataLayout().isBigEndian())
12216         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12217
12218       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12219       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12220       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12221         return SDValue();
12222
12223       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12224                                    Ptr.getValueType(), Ptr,
12225                                    DAG.getConstant(PtrOff, SDLoc(LD),
12226                                                    Ptr.getValueType()));
12227       SDValue NewLD =
12228           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12229                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12230                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12231       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12232                                    DAG.getConstant(NewImm, SDLoc(Value),
12233                                                    NewVT));
12234       SDValue NewST =
12235           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12236                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12237
12238       AddToWorklist(NewPtr.getNode());
12239       AddToWorklist(NewLD.getNode());
12240       AddToWorklist(NewVal.getNode());
12241       WorklistRemover DeadNodes(*this);
12242       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12243       ++OpsNarrowed;
12244       return NewST;
12245     }
12246   }
12247
12248   return SDValue();
12249 }
12250
12251 /// For a given floating point load / store pair, if the load value isn't used
12252 /// by any other operations, then consider transforming the pair to integer
12253 /// load / store operations if the target deems the transformation profitable.
12254 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12255   StoreSDNode *ST  = cast<StoreSDNode>(N);
12256   SDValue Chain = ST->getChain();
12257   SDValue Value = ST->getValue();
12258   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12259       Value.hasOneUse() &&
12260       Chain == SDValue(Value.getNode(), 1)) {
12261     LoadSDNode *LD = cast<LoadSDNode>(Value);
12262     EVT VT = LD->getMemoryVT();
12263     if (!VT.isFloatingPoint() ||
12264         VT != ST->getMemoryVT() ||
12265         LD->isNonTemporal() ||
12266         ST->isNonTemporal() ||
12267         LD->getPointerInfo().getAddrSpace() != 0 ||
12268         ST->getPointerInfo().getAddrSpace() != 0)
12269       return SDValue();
12270
12271     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12272     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12273         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12274         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12275         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12276       return SDValue();
12277
12278     unsigned LDAlign = LD->getAlignment();
12279     unsigned STAlign = ST->getAlignment();
12280     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12281     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12282     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12283       return SDValue();
12284
12285     SDValue NewLD =
12286         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12287                     LD->getPointerInfo(), LDAlign);
12288
12289     SDValue NewST =
12290         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12291                      ST->getPointerInfo(), STAlign);
12292
12293     AddToWorklist(NewLD.getNode());
12294     AddToWorklist(NewST.getNode());
12295     WorklistRemover DeadNodes(*this);
12296     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12297     ++LdStFP2Int;
12298     return NewST;
12299   }
12300
12301   return SDValue();
12302 }
12303
12304 // This is a helper function for visitMUL to check the profitability
12305 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12306 // MulNode is the original multiply, AddNode is (add x, c1),
12307 // and ConstNode is c2.
12308 //
12309 // If the (add x, c1) has multiple uses, we could increase
12310 // the number of adds if we make this transformation.
12311 // It would only be worth doing this if we can remove a
12312 // multiply in the process. Check for that here.
12313 // To illustrate:
12314 //     (A + c1) * c3
12315 //     (A + c2) * c3
12316 // We're checking for cases where we have common "c3 * A" expressions.
12317 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12318                                               SDValue &AddNode,
12319                                               SDValue &ConstNode) {
12320   APInt Val;
12321
12322   // If the add only has one use, this would be OK to do.
12323   if (AddNode.getNode()->hasOneUse())
12324     return true;
12325
12326   // Walk all the users of the constant with which we're multiplying.
12327   for (SDNode *Use : ConstNode->uses()) {
12328
12329     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12330       continue;
12331
12332     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12333       SDNode *OtherOp;
12334       SDNode *MulVar = AddNode.getOperand(0).getNode();
12335
12336       // OtherOp is what we're multiplying against the constant.
12337       if (Use->getOperand(0) == ConstNode)
12338         OtherOp = Use->getOperand(1).getNode();
12339       else
12340         OtherOp = Use->getOperand(0).getNode();
12341
12342       // Check to see if multiply is with the same operand of our "add".
12343       //
12344       //     ConstNode  = CONST
12345       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12346       //     ...
12347       //     AddNode  = (A + c1)  <-- MulVar is A.
12348       //         = AddNode * ConstNode   <-- current visiting instruction.
12349       //
12350       // If we make this transformation, we will have a common
12351       // multiply (ConstNode * A) that we can save.
12352       if (OtherOp == MulVar)
12353         return true;
12354
12355       // Now check to see if a future expansion will give us a common
12356       // multiply.
12357       //
12358       //     ConstNode  = CONST
12359       //     AddNode    = (A + c1)
12360       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12361       //     ...
12362       //     OtherOp = (A + c2)
12363       //     Use     = OtherOp * ConstNode <-- visiting Use.
12364       //
12365       // If we make this transformation, we will have a common
12366       // multiply (CONST * A) after we also do the same transformation
12367       // to the "t2" instruction.
12368       if (OtherOp->getOpcode() == ISD::ADD &&
12369           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12370           OtherOp->getOperand(0).getNode() == MulVar)
12371         return true;
12372     }
12373   }
12374
12375   // Didn't find a case where this would be profitable.
12376   return false;
12377 }
12378
12379 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12380                                          unsigned NumStores) {
12381   SmallVector<SDValue, 8> Chains;
12382   SmallPtrSet<const SDNode *, 8> Visited;
12383   SDLoc StoreDL(StoreNodes[0].MemNode);
12384
12385   for (unsigned i = 0; i < NumStores; ++i) {
12386     Visited.insert(StoreNodes[i].MemNode);
12387   }
12388
12389   // don't include nodes that are children
12390   for (unsigned i = 0; i < NumStores; ++i) {
12391     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12392       Chains.push_back(StoreNodes[i].MemNode->getChain());
12393   }
12394
12395   assert(Chains.size() > 0 && "Chain should have generated a chain");
12396   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12397 }
12398
12399 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12400     SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
12401     bool IsConstantSrc, bool UseVector, bool UseTrunc) {
12402   // Make sure we have something to merge.
12403   if (NumStores < 2)
12404     return false;
12405
12406   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12407
12408   // The latest Node in the DAG.
12409   SDLoc DL(StoreNodes[0].MemNode);
12410
12411   SDValue StoredVal;
12412   if (UseVector) {
12413     bool IsVec = MemVT.isVector();
12414     unsigned Elts = NumStores;
12415     if (IsVec) {
12416       // When merging vector stores, get the total number of elements.
12417       Elts *= MemVT.getVectorNumElements();
12418     }
12419     // Get the type for the merged vector store.
12420     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12421     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
12422
12423     if (IsConstantSrc) {
12424       SmallVector<SDValue, 8> BuildVector;
12425       for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
12426         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12427         SDValue Val = St->getValue();
12428         if (MemVT.getScalarType().isInteger())
12429           if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
12430             Val = DAG.getConstant(
12431                 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
12432                 SDLoc(CFP), MemVT);
12433         BuildVector.push_back(Val);
12434       }
12435       StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
12436     } else {
12437       SmallVector<SDValue, 8> Ops;
12438       for (unsigned i = 0; i < NumStores; ++i) {
12439         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12440         SDValue Val = St->getValue();
12441         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
12442         if (Val.getValueType() != MemVT)
12443           return false;
12444         Ops.push_back(Val);
12445       }
12446
12447       // Build the extracted vector elements back into a vector.
12448       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
12449                               DL, Ty, Ops);    }
12450   } else {
12451     // We should always use a vector store when merging extracted vector
12452     // elements, so this path implies a store of constants.
12453     assert(IsConstantSrc && "Merged vector elements should use vector store");
12454
12455     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12456     APInt StoreInt(SizeInBits, 0);
12457
12458     // Construct a single integer constant which is made of the smaller
12459     // constant inputs.
12460     bool IsLE = DAG.getDataLayout().isLittleEndian();
12461     for (unsigned i = 0; i < NumStores; ++i) {
12462       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12463       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12464
12465       SDValue Val = St->getValue();
12466       StoreInt <<= ElementSizeBytes * 8;
12467       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12468         StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits);
12469       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12470         StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits);
12471       } else {
12472         llvm_unreachable("Invalid constant element type");
12473       }
12474     }
12475
12476     // Create the new Load and Store operations.
12477     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12478     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12479   }
12480
12481   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12482   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12483
12484   // make sure we use trunc store if it's necessary to be legal.
12485   SDValue NewStore;
12486   if (UseVector || !UseTrunc) {
12487     NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
12488                             FirstInChain->getPointerInfo(),
12489                             FirstInChain->getAlignment());
12490   } else { // Must be realized as a trunc store
12491     EVT LegalizedStoredValueTy =
12492         TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
12493     unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
12494     ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
12495     SDValue ExtendedStoreVal =
12496         DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
12497                         LegalizedStoredValueTy);
12498     NewStore = DAG.getTruncStore(
12499         NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
12500         FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
12501         FirstInChain->getAlignment(),
12502         FirstInChain->getMemOperand()->getFlags());
12503   }
12504
12505   // Replace all merged stores with the new store.
12506   for (unsigned i = 0; i < NumStores; ++i)
12507     CombineTo(StoreNodes[i].MemNode, NewStore);
12508
12509   AddToWorklist(NewChain.getNode());
12510   return true;
12511 }
12512
12513 void DAGCombiner::getStoreMergeCandidates(
12514     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12515   // This holds the base pointer, index, and the offset in bytes from the base
12516   // pointer.
12517   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12518   EVT MemVT = St->getMemoryVT();
12519
12520   // We must have a base and an offset.
12521   if (!BasePtr.getBase().getNode())
12522     return;
12523
12524   // Do not handle stores to undef base pointers.
12525   if (BasePtr.getBase().isUndef())
12526     return;
12527
12528   bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
12529                        isa<ConstantFPSDNode>(St->getValue());
12530   bool IsExtractVecSrc =
12531       (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12532        St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
12533   bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
12534   BaseIndexOffset LBasePtr;
12535   // Match on loadbaseptr if relevant.
12536   if (IsLoadSrc)
12537     LBasePtr = BaseIndexOffset::match(
12538         cast<LoadSDNode>(St->getValue())->getBasePtr(), DAG);
12539
12540   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
12541                             int64_t &Offset) -> bool {
12542     if (Other->isVolatile() || Other->isIndexed())
12543       return false;
12544     // We can merge constant floats to equivalent integers
12545     if (Other->getMemoryVT() != MemVT)
12546       if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) &&
12547             isa<ConstantFPSDNode>(Other->getValue())))
12548         return false;
12549     if (IsLoadSrc) {
12550       // The Load's Base Ptr must also match
12551       if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Other->getValue())) {
12552         auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG);
12553         if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
12554           return false;
12555       } else
12556         return false;
12557     }
12558     if (IsConstantSrc)
12559       if (!(isa<ConstantSDNode>(Other->getValue()) ||
12560             isa<ConstantFPSDNode>(Other->getValue())))
12561         return false;
12562     if (IsExtractVecSrc)
12563       if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12564             Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR))
12565         return false;
12566     Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12567     return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
12568   };
12569   // We looking for a root node which is an ancestor to all mergable
12570   // stores. We search up through a load, to our root and then down
12571   // through all children. For instance we will find Store{1,2,3} if
12572   // St is Store1, Store2. or Store3 where the root is not a load
12573   // which always true for nonvolatile ops. TODO: Expand
12574   // the search to find all valid candidates through multiple layers of loads.
12575   //
12576   // Root
12577   // |-------|-------|
12578   // Load    Load    Store3
12579   // |       |
12580   // Store1   Store2
12581   //
12582   // FIXME: We should be able to climb and
12583   // descend TokenFactors to find candidates as well.
12584
12585   SDNode *RootNode = (St->getChain()).getNode();
12586
12587   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12588     RootNode = Ldn->getChain().getNode();
12589     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12590       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12591         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12592           if (I2.getOperandNo() == 0)
12593             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12594               BaseIndexOffset Ptr;
12595               int64_t PtrDiff;
12596               if (CandidateMatch(OtherST, Ptr, PtrDiff))
12597                 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12598             }
12599   } else
12600     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12601       if (I.getOperandNo() == 0)
12602         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12603           BaseIndexOffset Ptr;
12604           int64_t PtrDiff;
12605           if (CandidateMatch(OtherST, Ptr, PtrDiff))
12606             StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12607         }
12608 }
12609
12610 // We need to check that merging these stores does not cause a loop in
12611 // the DAG. Any store candidate may depend on another candidate
12612 // indirectly through its operand (we already consider dependencies
12613 // through the chain). Check in parallel by searching up from
12614 // non-chain operands of candidates.
12615
12616 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12617     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12618
12619   // FIXME: We should be able to truncate a full search of
12620   // predecessors by doing a BFS and keeping tabs the originating
12621   // stores from which worklist nodes come from in a similar way to
12622   // TokenFactor simplfication.
12623
12624   SmallPtrSet<const SDNode *, 16> Visited;
12625   SmallVector<const SDNode *, 8> Worklist;
12626   unsigned int Max = 8192;
12627   // Search Ops of store candidates.
12628   for (unsigned i = 0; i < NumStores; ++i) {
12629     SDNode *n = StoreNodes[i].MemNode;
12630     // Potential loops may happen only through non-chain operands
12631     for (unsigned j = 1; j < n->getNumOperands(); ++j)
12632       Worklist.push_back(n->getOperand(j).getNode());
12633   }
12634   // Search through DAG. We can stop early if we find a store node.
12635   for (unsigned i = 0; i < NumStores; ++i) {
12636     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
12637                                      Max))
12638       return false;
12639     // Check if we ended early, failing conservatively if so.
12640     if (Visited.size() >= Max)
12641       return false;
12642   }
12643   return true;
12644 }
12645
12646 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12647   if (OptLevel == CodeGenOpt::None)
12648     return false;
12649
12650   EVT MemVT = St->getMemoryVT();
12651   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12652
12653   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12654     return false;
12655
12656   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12657       Attribute::NoImplicitFloat);
12658
12659   // This function cannot currently deal with non-byte-sized memory sizes.
12660   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12661     return false;
12662
12663   if (!MemVT.isSimple())
12664     return false;
12665
12666   // Perform an early exit check. Do not bother looking at stored values that
12667   // are not constants, loads, or extracted vector elements.
12668   SDValue StoredVal = St->getValue();
12669   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12670   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12671                        isa<ConstantFPSDNode>(StoredVal);
12672   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12673                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12674
12675   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12676     return false;
12677
12678   // Don't merge vectors into wider vectors if the source data comes from loads.
12679   // TODO: This restriction can be lifted by using logic similar to the
12680   // ExtractVecSrc case.
12681   if (MemVT.isVector() && IsLoadSrc)
12682     return false;
12683
12684   SmallVector<MemOpLink, 8> StoreNodes;
12685   // Find potential store merge candidates by searching through chain sub-DAG
12686   getStoreMergeCandidates(St, StoreNodes);
12687
12688   // Check if there is anything to merge.
12689   if (StoreNodes.size() < 2)
12690     return false;
12691
12692   // Sort the memory operands according to their distance from the
12693   // base pointer.
12694   std::sort(StoreNodes.begin(), StoreNodes.end(),
12695             [](MemOpLink LHS, MemOpLink RHS) {
12696               return LHS.OffsetFromBase < RHS.OffsetFromBase;
12697             });
12698
12699   // Store Merge attempts to merge the lowest stores. This generally
12700   // works out as if successful, as the remaining stores are checked
12701   // after the first collection of stores is merged. However, in the
12702   // case that a non-mergeable store is found first, e.g., {p[-2],
12703   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12704   // mergeable cases. To prevent this, we prune such stores from the
12705   // front of StoreNodes here.
12706
12707   bool RV = false;
12708   while (StoreNodes.size() > 1) {
12709     unsigned StartIdx = 0;
12710     while ((StartIdx + 1 < StoreNodes.size()) &&
12711            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12712                StoreNodes[StartIdx + 1].OffsetFromBase)
12713       ++StartIdx;
12714
12715     // Bail if we don't have enough candidates to merge.
12716     if (StartIdx + 1 >= StoreNodes.size())
12717       return RV;
12718
12719     if (StartIdx)
12720       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12721
12722     // Scan the memory operations on the chain and find the first
12723     // non-consecutive store memory address.
12724     unsigned NumConsecutiveStores = 1;
12725     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12726     // Check that the addresses are consecutive starting from the second
12727     // element in the list of stores.
12728     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12729       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12730       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12731         break;
12732       NumConsecutiveStores = i + 1;
12733     }
12734
12735     if (NumConsecutiveStores < 2) {
12736       StoreNodes.erase(StoreNodes.begin(),
12737                        StoreNodes.begin() + NumConsecutiveStores);
12738       continue;
12739     }
12740
12741     // Check that we can merge these candidates without causing a cycle
12742     if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
12743                                                   NumConsecutiveStores)) {
12744       StoreNodes.erase(StoreNodes.begin(),
12745                        StoreNodes.begin() + NumConsecutiveStores);
12746       continue;
12747     }
12748
12749     // The node with the lowest store address.
12750     LLVMContext &Context = *DAG.getContext();
12751     const DataLayout &DL = DAG.getDataLayout();
12752
12753     // Store the constants into memory as one consecutive store.
12754     if (IsConstantSrc) {
12755       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12756       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12757       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12758       unsigned LastLegalType = 1;
12759       unsigned LastLegalVectorType = 1;
12760       bool LastIntegerTrunc = false;
12761       bool NonZero = false;
12762       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12763         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12764         SDValue StoredVal = ST->getValue();
12765
12766         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12767           NonZero |= !C->isNullValue();
12768         } else if (ConstantFPSDNode *C =
12769                        dyn_cast<ConstantFPSDNode>(StoredVal)) {
12770           NonZero |= !C->getConstantFPValue()->isNullValue();
12771         } else {
12772           // Non-constant.
12773           break;
12774         }
12775
12776         // Find a legal type for the constant store.
12777         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12778         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12779         bool IsFast = false;
12780         if (TLI.isTypeLegal(StoreTy) &&
12781             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
12782             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12783                                    FirstStoreAlign, &IsFast) &&
12784             IsFast) {
12785           LastIntegerTrunc = false;
12786           LastLegalType = i + 1;
12787           // Or check whether a truncstore is legal.
12788         } else if (TLI.getTypeAction(Context, StoreTy) ==
12789                    TargetLowering::TypePromoteInteger) {
12790           EVT LegalizedStoredValueTy =
12791               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12792           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12793               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
12794               TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12795                                      FirstStoreAS, FirstStoreAlign, &IsFast) &&
12796               IsFast) {
12797             LastIntegerTrunc = true;
12798             LastLegalType = i + 1;
12799           }
12800         }
12801
12802         // We only use vectors if the constant is known to be zero or the target
12803         // allows it and the function is not marked with the noimplicitfloat
12804         // attribute.
12805         if ((!NonZero ||
12806              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12807             !NoVectors) {
12808           // Find a legal type for the vector store.
12809           unsigned Elts = i + 1;
12810           if (MemVT.isVector()) {
12811             // When merging vector stores, get the total number of elements.
12812             Elts *= MemVT.getVectorNumElements();
12813           }
12814           EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
12815           if (TLI.isTypeLegal(Ty) &&
12816               TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
12817               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12818                                      FirstStoreAlign, &IsFast) &&
12819               IsFast)
12820             LastLegalVectorType = i + 1;
12821         }
12822       }
12823
12824       // Check if we found a legal integer type that creates a meaningful merge.
12825       if (LastLegalType < 2 && LastLegalVectorType < 2) {
12826         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12827         continue;
12828       }
12829
12830       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12831       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12832
12833       bool Merged = MergeStoresOfConstantsOrVecElts(
12834           StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
12835       if (!Merged) {
12836         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12837         continue;
12838       }
12839       // Remove merged stores for next iteration.
12840       RV = true;
12841       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12842       continue;
12843     }
12844
12845     // When extracting multiple vector elements, try to store them
12846     // in one vector store rather than a sequence of scalar stores.
12847     if (IsExtractVecSrc) {
12848       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12849       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12850       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12851       unsigned NumStoresToMerge = 1;
12852       bool IsVec = MemVT.isVector();
12853       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12854         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12855         unsigned StoreValOpcode = St->getValue().getOpcode();
12856         // This restriction could be loosened.
12857         // Bail out if any stored values are not elements extracted from a
12858         // vector. It should be possible to handle mixed sources, but load
12859         // sources need more careful handling (see the block of code below that
12860         // handles consecutive loads).
12861         if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12862             StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12863           return RV;
12864
12865         // Find a legal type for the vector store.
12866         unsigned Elts = i + 1;
12867         if (IsVec) {
12868           // When merging vector stores, get the total number of elements.
12869           Elts *= MemVT.getVectorNumElements();
12870         }
12871         EVT Ty =
12872             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12873         bool IsFast;
12874         if (TLI.isTypeLegal(Ty) &&
12875             TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
12876             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12877                                    FirstStoreAlign, &IsFast) &&
12878             IsFast)
12879           NumStoresToMerge = i + 1;
12880       }
12881
12882       bool Merged = MergeStoresOfConstantsOrVecElts(
12883           StoreNodes, MemVT, NumStoresToMerge, false, true, false);
12884       if (!Merged) {
12885         StoreNodes.erase(StoreNodes.begin(),
12886                          StoreNodes.begin() + NumStoresToMerge);
12887         continue;
12888       }
12889       // Remove merged stores for next iteration.
12890       StoreNodes.erase(StoreNodes.begin(),
12891                        StoreNodes.begin() + NumStoresToMerge);
12892       RV = true;
12893       continue;
12894     }
12895
12896     // Below we handle the case of multiple consecutive stores that
12897     // come from multiple consecutive loads. We merge them into a single
12898     // wide load and a single wide store.
12899
12900     // Look for load nodes which are used by the stored values.
12901     SmallVector<MemOpLink, 8> LoadNodes;
12902
12903     // Find acceptable loads. Loads need to have the same chain (token factor),
12904     // must not be zext, volatile, indexed, and they must be consecutive.
12905     BaseIndexOffset LdBasePtr;
12906     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12907       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12908       LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12909       if (!Ld)
12910         break;
12911
12912       // Loads must only have one use.
12913       if (!Ld->hasNUsesOfValue(1, 0))
12914         break;
12915
12916       // The memory operands must not be volatile.
12917       if (Ld->isVolatile() || Ld->isIndexed())
12918         break;
12919
12920       // We do not accept ext loads.
12921       if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12922         break;
12923
12924       // The stored memory type must be the same.
12925       if (Ld->getMemoryVT() != MemVT)
12926         break;
12927
12928       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12929       // If this is not the first ptr that we check.
12930       int64_t LdOffset = 0;
12931       if (LdBasePtr.getBase().getNode()) {
12932         // The base ptr must be the same.
12933         if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
12934           break;
12935       } else {
12936         // Check that all other base pointers are the same as this one.
12937         LdBasePtr = LdPtr;
12938       }
12939
12940       // We found a potential memory operand to merge.
12941       LoadNodes.push_back(MemOpLink(Ld, LdOffset));
12942     }
12943
12944     if (LoadNodes.size() < 2) {
12945       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12946       continue;
12947     }
12948
12949     // If we have load/store pair instructions and we only have two values,
12950     // don't bother merging.
12951     unsigned RequiredAlignment;
12952     if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12953         StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
12954       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
12955       continue;
12956     }
12957     LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12958     unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12959     unsigned FirstStoreAlign = FirstInChain->getAlignment();
12960     LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12961     unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12962     unsigned FirstLoadAlign = FirstLoad->getAlignment();
12963
12964     // Scan the memory operations on the chain and find the first
12965     // non-consecutive load memory address. These variables hold the index in
12966     // the store node array.
12967     unsigned LastConsecutiveLoad = 1;
12968     // This variable refers to the size and not index in the array.
12969     unsigned LastLegalVectorType = 1;
12970     unsigned LastLegalIntegerType = 1;
12971     bool isDereferenceable = true;
12972     bool DoIntegerTruncate = false;
12973     StartAddress = LoadNodes[0].OffsetFromBase;
12974     SDValue FirstChain = FirstLoad->getChain();
12975     for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12976       // All loads must share the same chain.
12977       if (LoadNodes[i].MemNode->getChain() != FirstChain)
12978         break;
12979
12980       int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12981       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12982         break;
12983       LastConsecutiveLoad = i;
12984
12985       if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
12986         isDereferenceable = false;
12987
12988       // Find a legal type for the vector store.
12989       EVT StoreTy = EVT::getVectorVT(Context, MemVT, i + 1);
12990       bool IsFastSt, IsFastLd;
12991       if (TLI.isTypeLegal(StoreTy) &&
12992           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
12993           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12994                                  FirstStoreAlign, &IsFastSt) &&
12995           IsFastSt &&
12996           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12997                                  FirstLoadAlign, &IsFastLd) &&
12998           IsFastLd) {
12999         LastLegalVectorType = i + 1;
13000       }
13001
13002       // Find a legal type for the integer store.
13003       unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13004       StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13005       if (TLI.isTypeLegal(StoreTy) &&
13006           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13007           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13008                                  FirstStoreAlign, &IsFastSt) &&
13009           IsFastSt &&
13010           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13011                                  FirstLoadAlign, &IsFastLd) &&
13012           IsFastLd) {
13013         LastLegalIntegerType = i + 1;
13014         DoIntegerTruncate = false;
13015         // Or check whether a truncstore and extload is legal.
13016       } else if (TLI.getTypeAction(Context, StoreTy) ==
13017                  TargetLowering::TypePromoteInteger) {
13018         EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
13019         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13020             TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13021             TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
13022                                StoreTy) &&
13023             TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
13024                                StoreTy) &&
13025             TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
13026             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
13027                                    FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
13028             IsFastSt &&
13029             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13030                                    FirstLoadAlign, &IsFastLd) &&
13031             IsFastLd) {
13032           LastLegalIntegerType = i + 1;
13033           DoIntegerTruncate = true;
13034         }
13035       }
13036     }
13037
13038     // Only use vector types if the vector type is larger than the integer type.
13039     // If they are the same, use integers.
13040     bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
13041     unsigned LastLegalType =
13042         std::max(LastLegalVectorType, LastLegalIntegerType);
13043
13044     // We add +1 here because the LastXXX variables refer to location while
13045     // the NumElem refers to array/index size.
13046     unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
13047     NumElem = std::min(LastLegalType, NumElem);
13048
13049     if (NumElem < 2) {
13050       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
13051       continue;
13052     }
13053
13054     // Find if it is better to use vectors or integers to load and store
13055     // to memory.
13056     EVT JointMemOpVT;
13057     if (UseVectorTy) {
13058       JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
13059     } else {
13060       unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
13061       JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
13062     }
13063
13064     SDLoc LoadDL(LoadNodes[0].MemNode);
13065     SDLoc StoreDL(StoreNodes[0].MemNode);
13066
13067     // The merged loads are required to have the same incoming chain, so
13068     // using the first's chain is acceptable.
13069
13070     SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
13071     AddToWorklist(NewStoreChain.getNode());
13072
13073     MachineMemOperand::Flags MMOFlags = isDereferenceable ?
13074                                           MachineMemOperand::MODereferenceable:
13075                                           MachineMemOperand::MONone;
13076
13077     SDValue NewLoad, NewStore;
13078     if (UseVectorTy || !DoIntegerTruncate) {
13079       NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
13080                             FirstLoad->getBasePtr(),
13081                             FirstLoad->getPointerInfo(), FirstLoadAlign,
13082                             MMOFlags);
13083       NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
13084                               FirstInChain->getBasePtr(),
13085                               FirstInChain->getPointerInfo(), FirstStoreAlign);
13086     } else { // This must be the truncstore/extload case
13087       EVT ExtendedTy =
13088           TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
13089       NewLoad =
13090           DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13091                          FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13092                          JointMemOpVT, FirstLoadAlign, MMOFlags);
13093       NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13094                                    FirstInChain->getBasePtr(),
13095                                    FirstInChain->getPointerInfo(), JointMemOpVT,
13096                                    FirstInChain->getAlignment(),
13097                                    FirstInChain->getMemOperand()->getFlags());
13098     }
13099
13100     // Transfer chain users from old loads to the new load.
13101     for (unsigned i = 0; i < NumElem; ++i) {
13102       LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13103       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13104                                     SDValue(NewLoad.getNode(), 1));
13105     }
13106
13107     // Replace the all stores with the new store.
13108     for (unsigned i = 0; i < NumElem; ++i)
13109       CombineTo(StoreNodes[i].MemNode, NewStore);
13110     RV = true;
13111     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13112     continue;
13113   }
13114   return RV;
13115 }
13116
13117 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13118   SDLoc SL(ST);
13119   SDValue ReplStore;
13120
13121   // Replace the chain to avoid dependency.
13122   if (ST->isTruncatingStore()) {
13123     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13124                                   ST->getBasePtr(), ST->getMemoryVT(),
13125                                   ST->getMemOperand());
13126   } else {
13127     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13128                              ST->getMemOperand());
13129   }
13130
13131   // Create token to keep both nodes around.
13132   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13133                               MVT::Other, ST->getChain(), ReplStore);
13134
13135   // Make sure the new and old chains are cleaned up.
13136   AddToWorklist(Token.getNode());
13137
13138   // Don't add users to work list.
13139   return CombineTo(ST, Token, false);
13140 }
13141
13142 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13143   SDValue Value = ST->getValue();
13144   if (Value.getOpcode() == ISD::TargetConstantFP)
13145     return SDValue();
13146
13147   SDLoc DL(ST);
13148
13149   SDValue Chain = ST->getChain();
13150   SDValue Ptr = ST->getBasePtr();
13151
13152   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13153
13154   // NOTE: If the original store is volatile, this transform must not increase
13155   // the number of stores.  For example, on x86-32 an f64 can be stored in one
13156   // processor operation but an i64 (which is not legal) requires two.  So the
13157   // transform should not be done in this case.
13158
13159   SDValue Tmp;
13160   switch (CFP->getSimpleValueType(0).SimpleTy) {
13161   default:
13162     llvm_unreachable("Unknown FP type");
13163   case MVT::f16:    // We don't do this for these yet.
13164   case MVT::f80:
13165   case MVT::f128:
13166   case MVT::ppcf128:
13167     return SDValue();
13168   case MVT::f32:
13169     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13170         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13171       ;
13172       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13173                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13174                             MVT::i32);
13175       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13176     }
13177
13178     return SDValue();
13179   case MVT::f64:
13180     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13181          !ST->isVolatile()) ||
13182         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13183       ;
13184       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13185                             getZExtValue(), SDLoc(CFP), MVT::i64);
13186       return DAG.getStore(Chain, DL, Tmp,
13187                           Ptr, ST->getMemOperand());
13188     }
13189
13190     if (!ST->isVolatile() &&
13191         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13192       // Many FP stores are not made apparent until after legalize, e.g. for
13193       // argument passing.  Since this is so common, custom legalize the
13194       // 64-bit integer store into two 32-bit stores.
13195       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13196       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13197       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13198       if (DAG.getDataLayout().isBigEndian())
13199         std::swap(Lo, Hi);
13200
13201       unsigned Alignment = ST->getAlignment();
13202       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13203       AAMDNodes AAInfo = ST->getAAInfo();
13204
13205       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13206                                  ST->getAlignment(), MMOFlags, AAInfo);
13207       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13208                         DAG.getConstant(4, DL, Ptr.getValueType()));
13209       Alignment = MinAlign(Alignment, 4U);
13210       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13211                                  ST->getPointerInfo().getWithOffset(4),
13212                                  Alignment, MMOFlags, AAInfo);
13213       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13214                          St0, St1);
13215     }
13216
13217     return SDValue();
13218   }
13219 }
13220
13221 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13222   StoreSDNode *ST  = cast<StoreSDNode>(N);
13223   SDValue Chain = ST->getChain();
13224   SDValue Value = ST->getValue();
13225   SDValue Ptr   = ST->getBasePtr();
13226
13227   // If this is a store of a bit convert, store the input value if the
13228   // resultant store does not need a higher alignment than the original.
13229   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13230       ST->isUnindexed()) {
13231     EVT SVT = Value.getOperand(0).getValueType();
13232     if (((!LegalOperations && !ST->isVolatile()) ||
13233          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13234         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13235       unsigned OrigAlign = ST->getAlignment();
13236       bool Fast = false;
13237       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13238                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13239           Fast) {
13240         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13241                             ST->getPointerInfo(), OrigAlign,
13242                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13243       }
13244     }
13245   }
13246
13247   // Turn 'store undef, Ptr' -> nothing.
13248   if (Value.isUndef() && ST->isUnindexed())
13249     return Chain;
13250
13251   // Try to infer better alignment information than the store already has.
13252   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13253     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13254       if (Align > ST->getAlignment()) {
13255         SDValue NewStore =
13256             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13257                               ST->getMemoryVT(), Align,
13258                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13259         if (NewStore.getNode() != N)
13260           return CombineTo(ST, NewStore, true);
13261       }
13262     }
13263   }
13264
13265   // Try transforming a pair floating point load / store ops to integer
13266   // load / store ops.
13267   if (SDValue NewST = TransformFPLoadStorePair(N))
13268     return NewST;
13269
13270   if (ST->isUnindexed()) {
13271     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13272     // adjacent stores.
13273     if (findBetterNeighborChains(ST)) {
13274       // replaceStoreChain uses CombineTo, which handled all of the worklist
13275       // manipulation. Return the original node to not do anything else.
13276       return SDValue(ST, 0);
13277     }
13278     Chain = ST->getChain();
13279   }
13280
13281   // FIXME: is there such a thing as a truncating indexed store?
13282   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13283       Value.getValueType().isInteger()) {
13284     // See if we can simplify the input to this truncstore with knowledge that
13285     // only the low bits are being used.  For example:
13286     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13287     SDValue Shorter = GetDemandedBits(
13288         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13289                                     ST->getMemoryVT().getScalarSizeInBits()));
13290     AddToWorklist(Value.getNode());
13291     if (Shorter.getNode())
13292       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13293                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13294
13295     // Otherwise, see if we can simplify the operation with
13296     // SimplifyDemandedBits, which only works if the value has a single use.
13297     if (SimplifyDemandedBits(
13298             Value,
13299             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13300                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13301       // Re-visit the store if anything changed and the store hasn't been merged
13302       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13303       // node back to the worklist if necessary, but we also need to re-visit
13304       // the Store node itself.
13305       if (N->getOpcode() != ISD::DELETED_NODE)
13306         AddToWorklist(N);
13307       return SDValue(N, 0);
13308     }
13309   }
13310
13311   // If this is a load followed by a store to the same location, then the store
13312   // is dead/noop.
13313   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13314     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13315         ST->isUnindexed() && !ST->isVolatile() &&
13316         // There can't be any side effects between the load and store, such as
13317         // a call or store.
13318         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13319       // The store is dead, remove it.
13320       return Chain;
13321     }
13322   }
13323
13324   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13325     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13326         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13327         ST->getMemoryVT() == ST1->getMemoryVT()) {
13328       // If this is a store followed by a store with the same value to the same
13329       // location, then the store is dead/noop.
13330       if (ST1->getValue() == Value) {
13331         // The store is dead, remove it.
13332         return Chain;
13333       }
13334
13335       // If this is a store who's preceeding store to the same location
13336       // and no one other node is chained to that store we can effectively
13337       // drop the store. Do not remove stores to undef as they may be used as
13338       // data sinks.
13339       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13340           !ST1->getBasePtr().isUndef()) {
13341         // ST1 is fully overwritten and can be elided. Combine with it's chain
13342         // value.
13343         CombineTo(ST1, ST1->getChain());
13344         return SDValue();
13345       }
13346     }
13347   }
13348
13349   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13350   // truncating store.  We can do this even if this is already a truncstore.
13351   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13352       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13353       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13354                             ST->getMemoryVT())) {
13355     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13356                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
13357   }
13358
13359   // Only perform this optimization before the types are legal, because we
13360   // don't want to perform this optimization on every DAGCombine invocation.
13361   if ((TLI.mergeStoresAfterLegalization()) ? Level == AfterLegalizeDAG
13362                                            : !LegalTypes) {
13363     for (;;) {
13364       // There can be multiple store sequences on the same chain.
13365       // Keep trying to merge store sequences until we are unable to do so
13366       // or until we merge the last store on the chain.
13367       bool Changed = MergeConsecutiveStores(ST);
13368       if (!Changed) break;
13369       // Return N as merge only uses CombineTo and no worklist clean
13370       // up is necessary.
13371       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13372         return SDValue(N, 0);
13373     }
13374   }
13375
13376   // Try transforming N to an indexed store.
13377   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13378     return SDValue(N, 0);
13379
13380   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13381   //
13382   // Make sure to do this only after attempting to merge stores in order to
13383   //  avoid changing the types of some subset of stores due to visit order,
13384   //  preventing their merging.
13385   if (isa<ConstantFPSDNode>(ST->getValue())) {
13386     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13387       return NewSt;
13388   }
13389
13390   if (SDValue NewSt = splitMergedValStore(ST))
13391     return NewSt;
13392
13393   return ReduceLoadOpStoreWidth(N);
13394 }
13395
13396 /// For the instruction sequence of store below, F and I values
13397 /// are bundled together as an i64 value before being stored into memory.
13398 /// Sometimes it is more efficent to generate separate stores for F and I,
13399 /// which can remove the bitwise instructions or sink them to colder places.
13400 ///
13401 ///   (store (or (zext (bitcast F to i32) to i64),
13402 ///              (shl (zext I to i64), 32)), addr)  -->
13403 ///   (store F, addr) and (store I, addr+4)
13404 ///
13405 /// Similarly, splitting for other merged store can also be beneficial, like:
13406 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13407 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13408 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13409 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13410 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13411 ///
13412 /// We allow each target to determine specifically which kind of splitting is
13413 /// supported.
13414 ///
13415 /// The store patterns are commonly seen from the simple code snippet below
13416 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13417 ///   void goo(const std::pair<int, float> &);
13418 ///   hoo() {
13419 ///     ...
13420 ///     goo(std::make_pair(tmp, ftmp));
13421 ///     ...
13422 ///   }
13423 ///
13424 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13425   if (OptLevel == CodeGenOpt::None)
13426     return SDValue();
13427
13428   SDValue Val = ST->getValue();
13429   SDLoc DL(ST);
13430
13431   // Match OR operand.
13432   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13433     return SDValue();
13434
13435   // Match SHL operand and get Lower and Higher parts of Val.
13436   SDValue Op1 = Val.getOperand(0);
13437   SDValue Op2 = Val.getOperand(1);
13438   SDValue Lo, Hi;
13439   if (Op1.getOpcode() != ISD::SHL) {
13440     std::swap(Op1, Op2);
13441     if (Op1.getOpcode() != ISD::SHL)
13442       return SDValue();
13443   }
13444   Lo = Op2;
13445   Hi = Op1.getOperand(0);
13446   if (!Op1.hasOneUse())
13447     return SDValue();
13448
13449   // Match shift amount to HalfValBitSize.
13450   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13451   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13452   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13453     return SDValue();
13454
13455   // Lo and Hi are zero-extended from int with size less equal than 32
13456   // to i64.
13457   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13458       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13459       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13460       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13461       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13462       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13463     return SDValue();
13464
13465   // Use the EVT of low and high parts before bitcast as the input
13466   // of target query.
13467   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13468                   ? Lo.getOperand(0).getValueType()
13469                   : Lo.getValueType();
13470   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13471                    ? Hi.getOperand(0).getValueType()
13472                    : Hi.getValueType();
13473   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13474     return SDValue();
13475
13476   // Start to split store.
13477   unsigned Alignment = ST->getAlignment();
13478   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13479   AAMDNodes AAInfo = ST->getAAInfo();
13480
13481   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13482   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13483   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13484   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13485
13486   SDValue Chain = ST->getChain();
13487   SDValue Ptr = ST->getBasePtr();
13488   // Lower value store.
13489   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13490                              ST->getAlignment(), MMOFlags, AAInfo);
13491   Ptr =
13492       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13493                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13494   // Higher value store.
13495   SDValue St1 =
13496       DAG.getStore(St0, DL, Hi, Ptr,
13497                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13498                    Alignment / 2, MMOFlags, AAInfo);
13499   return St1;
13500 }
13501
13502 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13503   SDValue InVec = N->getOperand(0);
13504   SDValue InVal = N->getOperand(1);
13505   SDValue EltNo = N->getOperand(2);
13506   SDLoc DL(N);
13507
13508   // If the inserted element is an UNDEF, just use the input vector.
13509   if (InVal.isUndef())
13510     return InVec;
13511
13512   EVT VT = InVec.getValueType();
13513
13514   // Check that we know which element is being inserted
13515   if (!isa<ConstantSDNode>(EltNo))
13516     return SDValue();
13517   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13518
13519   // Canonicalize insert_vector_elt dag nodes.
13520   // Example:
13521   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13522   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13523   //
13524   // Do this only if the child insert_vector node has one use; also
13525   // do this only if indices are both constants and Idx1 < Idx0.
13526   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13527       && isa<ConstantSDNode>(InVec.getOperand(2))) {
13528     unsigned OtherElt = InVec.getConstantOperandVal(2);
13529     if (Elt < OtherElt) {
13530       // Swap nodes.
13531       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13532                                   InVec.getOperand(0), InVal, EltNo);
13533       AddToWorklist(NewOp.getNode());
13534       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13535                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13536     }
13537   }
13538
13539   // If we can't generate a legal BUILD_VECTOR, exit
13540   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13541     return SDValue();
13542
13543   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13544   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
13545   // vector elements.
13546   SmallVector<SDValue, 8> Ops;
13547   // Do not combine these two vectors if the output vector will not replace
13548   // the input vector.
13549   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13550     Ops.append(InVec.getNode()->op_begin(),
13551                InVec.getNode()->op_end());
13552   } else if (InVec.isUndef()) {
13553     unsigned NElts = VT.getVectorNumElements();
13554     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13555   } else {
13556     return SDValue();
13557   }
13558
13559   // Insert the element
13560   if (Elt < Ops.size()) {
13561     // All the operands of BUILD_VECTOR must have the same type;
13562     // we enforce that here.
13563     EVT OpVT = Ops[0].getValueType();
13564     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13565   }
13566
13567   // Return the new vector
13568   return DAG.getBuildVector(VT, DL, Ops);
13569 }
13570
13571 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13572     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13573   assert(!OriginalLoad->isVolatile());
13574
13575   EVT ResultVT = EVE->getValueType(0);
13576   EVT VecEltVT = InVecVT.getVectorElementType();
13577   unsigned Align = OriginalLoad->getAlignment();
13578   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13579       VecEltVT.getTypeForEVT(*DAG.getContext()));
13580
13581   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13582     return SDValue();
13583
13584   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13585     ISD::NON_EXTLOAD : ISD::EXTLOAD;
13586   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13587     return SDValue();
13588
13589   Align = NewAlign;
13590
13591   SDValue NewPtr = OriginalLoad->getBasePtr();
13592   SDValue Offset;
13593   EVT PtrType = NewPtr.getValueType();
13594   MachinePointerInfo MPI;
13595   SDLoc DL(EVE);
13596   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13597     int Elt = ConstEltNo->getZExtValue();
13598     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13599     Offset = DAG.getConstant(PtrOff, DL, PtrType);
13600     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13601   } else {
13602     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13603     Offset = DAG.getNode(
13604         ISD::MUL, DL, PtrType, Offset,
13605         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13606     MPI = OriginalLoad->getPointerInfo();
13607   }
13608   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13609
13610   // The replacement we need to do here is a little tricky: we need to
13611   // replace an extractelement of a load with a load.
13612   // Use ReplaceAllUsesOfValuesWith to do the replacement.
13613   // Note that this replacement assumes that the extractvalue is the only
13614   // use of the load; that's okay because we don't want to perform this
13615   // transformation in other cases anyway.
13616   SDValue Load;
13617   SDValue Chain;
13618   if (ResultVT.bitsGT(VecEltVT)) {
13619     // If the result type of vextract is wider than the load, then issue an
13620     // extending load instead.
13621     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13622                                                   VecEltVT)
13623                                    ? ISD::ZEXTLOAD
13624                                    : ISD::EXTLOAD;
13625     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13626                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13627                           Align, OriginalLoad->getMemOperand()->getFlags(),
13628                           OriginalLoad->getAAInfo());
13629     Chain = Load.getValue(1);
13630   } else {
13631     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13632                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13633                        OriginalLoad->getAAInfo());
13634     Chain = Load.getValue(1);
13635     if (ResultVT.bitsLT(VecEltVT))
13636       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13637     else
13638       Load = DAG.getBitcast(ResultVT, Load);
13639   }
13640   WorklistRemover DeadNodes(*this);
13641   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13642   SDValue To[] = { Load, Chain };
13643   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13644   // Since we're explicitly calling ReplaceAllUses, add the new node to the
13645   // worklist explicitly as well.
13646   AddToWorklist(Load.getNode());
13647   AddUsersToWorklist(Load.getNode()); // Add users too
13648   // Make sure to revisit this node to clean it up; it will usually be dead.
13649   AddToWorklist(EVE);
13650   ++OpsNarrowed;
13651   return SDValue(EVE, 0);
13652 }
13653
13654 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13655   // (vextract (scalar_to_vector val, 0) -> val
13656   SDValue InVec = N->getOperand(0);
13657   EVT VT = InVec.getValueType();
13658   EVT NVT = N->getValueType(0);
13659
13660   if (InVec.isUndef())
13661     return DAG.getUNDEF(NVT);
13662
13663   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13664     // Check if the result type doesn't match the inserted element type. A
13665     // SCALAR_TO_VECTOR may truncate the inserted element and the
13666     // EXTRACT_VECTOR_ELT may widen the extracted vector.
13667     SDValue InOp = InVec.getOperand(0);
13668     if (InOp.getValueType() != NVT) {
13669       assert(InOp.getValueType().isInteger() && NVT.isInteger());
13670       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13671     }
13672     return InOp;
13673   }
13674
13675   SDValue EltNo = N->getOperand(1);
13676   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13677
13678   // extract_vector_elt (build_vector x, y), 1 -> y
13679   if (ConstEltNo &&
13680       InVec.getOpcode() == ISD::BUILD_VECTOR &&
13681       TLI.isTypeLegal(VT) &&
13682       (InVec.hasOneUse() ||
13683        TLI.aggressivelyPreferBuildVectorSources(VT))) {
13684     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13685     EVT InEltVT = Elt.getValueType();
13686
13687     // Sometimes build_vector's scalar input types do not match result type.
13688     if (NVT == InEltVT)
13689       return Elt;
13690
13691     // TODO: It may be useful to truncate if free if the build_vector implicitly
13692     // converts.
13693   }
13694
13695   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
13696   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13697       ConstEltNo->isNullValue() && VT.isInteger()) {
13698     SDValue BCSrc = InVec.getOperand(0);
13699     if (BCSrc.getValueType().isScalarInteger())
13700       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13701   }
13702
13703   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13704   //
13705   // This only really matters if the index is non-constant since other combines
13706   // on the constant elements already work.
13707   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13708       EltNo == InVec.getOperand(2)) {
13709     SDValue Elt = InVec.getOperand(1);
13710     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13711   }
13712
13713   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13714   // We only perform this optimization before the op legalization phase because
13715   // we may introduce new vector instructions which are not backed by TD
13716   // patterns. For example on AVX, extracting elements from a wide vector
13717   // without using extract_subvector. However, if we can find an underlying
13718   // scalar value, then we can always use that.
13719   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13720     int NumElem = VT.getVectorNumElements();
13721     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13722     // Find the new index to extract from.
13723     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13724
13725     // Extracting an undef index is undef.
13726     if (OrigElt == -1)
13727       return DAG.getUNDEF(NVT);
13728
13729     // Select the right vector half to extract from.
13730     SDValue SVInVec;
13731     if (OrigElt < NumElem) {
13732       SVInVec = InVec->getOperand(0);
13733     } else {
13734       SVInVec = InVec->getOperand(1);
13735       OrigElt -= NumElem;
13736     }
13737
13738     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13739       SDValue InOp = SVInVec.getOperand(OrigElt);
13740       if (InOp.getValueType() != NVT) {
13741         assert(InOp.getValueType().isInteger() && NVT.isInteger());
13742         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13743       }
13744
13745       return InOp;
13746     }
13747
13748     // FIXME: We should handle recursing on other vector shuffles and
13749     // scalar_to_vector here as well.
13750
13751     if (!LegalOperations) {
13752       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13753       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13754                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13755     }
13756   }
13757
13758   bool BCNumEltsChanged = false;
13759   EVT ExtVT = VT.getVectorElementType();
13760   EVT LVT = ExtVT;
13761
13762   // If the result of load has to be truncated, then it's not necessarily
13763   // profitable.
13764   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13765     return SDValue();
13766
13767   if (InVec.getOpcode() == ISD::BITCAST) {
13768     // Don't duplicate a load with other uses.
13769     if (!InVec.hasOneUse())
13770       return SDValue();
13771
13772     EVT BCVT = InVec.getOperand(0).getValueType();
13773     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13774       return SDValue();
13775     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13776       BCNumEltsChanged = true;
13777     InVec = InVec.getOperand(0);
13778     ExtVT = BCVT.getVectorElementType();
13779   }
13780
13781   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13782   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13783       ISD::isNormalLoad(InVec.getNode()) &&
13784       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13785     SDValue Index = N->getOperand(1);
13786     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13787       if (!OrigLoad->isVolatile()) {
13788         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13789                                                              OrigLoad);
13790       }
13791     }
13792   }
13793
13794   // Perform only after legalization to ensure build_vector / vector_shuffle
13795   // optimizations have already been done.
13796   if (!LegalOperations) return SDValue();
13797
13798   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13799   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13800   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13801
13802   if (ConstEltNo) {
13803     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13804
13805     LoadSDNode *LN0 = nullptr;
13806     const ShuffleVectorSDNode *SVN = nullptr;
13807     if (ISD::isNormalLoad(InVec.getNode())) {
13808       LN0 = cast<LoadSDNode>(InVec);
13809     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13810                InVec.getOperand(0).getValueType() == ExtVT &&
13811                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13812       // Don't duplicate a load with other uses.
13813       if (!InVec.hasOneUse())
13814         return SDValue();
13815
13816       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13817     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13818       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13819       // =>
13820       // (load $addr+1*size)
13821
13822       // Don't duplicate a load with other uses.
13823       if (!InVec.hasOneUse())
13824         return SDValue();
13825
13826       // If the bit convert changed the number of elements, it is unsafe
13827       // to examine the mask.
13828       if (BCNumEltsChanged)
13829         return SDValue();
13830
13831       // Select the input vector, guarding against out of range extract vector.
13832       unsigned NumElems = VT.getVectorNumElements();
13833       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13834       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13835
13836       if (InVec.getOpcode() == ISD::BITCAST) {
13837         // Don't duplicate a load with other uses.
13838         if (!InVec.hasOneUse())
13839           return SDValue();
13840
13841         InVec = InVec.getOperand(0);
13842       }
13843       if (ISD::isNormalLoad(InVec.getNode())) {
13844         LN0 = cast<LoadSDNode>(InVec);
13845         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13846         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13847       }
13848     }
13849
13850     // Make sure we found a non-volatile load and the extractelement is
13851     // the only use.
13852     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13853       return SDValue();
13854
13855     // If Idx was -1 above, Elt is going to be -1, so just return undef.
13856     if (Elt == -1)
13857       return DAG.getUNDEF(LVT);
13858
13859     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13860   }
13861
13862   return SDValue();
13863 }
13864
13865 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13866 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13867   // We perform this optimization post type-legalization because
13868   // the type-legalizer often scalarizes integer-promoted vectors.
13869   // Performing this optimization before may create bit-casts which
13870   // will be type-legalized to complex code sequences.
13871   // We perform this optimization only before the operation legalizer because we
13872   // may introduce illegal operations.
13873   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13874     return SDValue();
13875
13876   unsigned NumInScalars = N->getNumOperands();
13877   SDLoc DL(N);
13878   EVT VT = N->getValueType(0);
13879
13880   // Check to see if this is a BUILD_VECTOR of a bunch of values
13881   // which come from any_extend or zero_extend nodes. If so, we can create
13882   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13883   // optimizations. We do not handle sign-extend because we can't fill the sign
13884   // using shuffles.
13885   EVT SourceType = MVT::Other;
13886   bool AllAnyExt = true;
13887
13888   for (unsigned i = 0; i != NumInScalars; ++i) {
13889     SDValue In = N->getOperand(i);
13890     // Ignore undef inputs.
13891     if (In.isUndef()) continue;
13892
13893     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
13894     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13895
13896     // Abort if the element is not an extension.
13897     if (!ZeroExt && !AnyExt) {
13898       SourceType = MVT::Other;
13899       break;
13900     }
13901
13902     // The input is a ZeroExt or AnyExt. Check the original type.
13903     EVT InTy = In.getOperand(0).getValueType();
13904
13905     // Check that all of the widened source types are the same.
13906     if (SourceType == MVT::Other)
13907       // First time.
13908       SourceType = InTy;
13909     else if (InTy != SourceType) {
13910       // Multiple income types. Abort.
13911       SourceType = MVT::Other;
13912       break;
13913     }
13914
13915     // Check if all of the extends are ANY_EXTENDs.
13916     AllAnyExt &= AnyExt;
13917   }
13918
13919   // In order to have valid types, all of the inputs must be extended from the
13920   // same source type and all of the inputs must be any or zero extend.
13921   // Scalar sizes must be a power of two.
13922   EVT OutScalarTy = VT.getScalarType();
13923   bool ValidTypes = SourceType != MVT::Other &&
13924                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13925                  isPowerOf2_32(SourceType.getSizeInBits());
13926
13927   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13928   // turn into a single shuffle instruction.
13929   if (!ValidTypes)
13930     return SDValue();
13931
13932   bool isLE = DAG.getDataLayout().isLittleEndian();
13933   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13934   assert(ElemRatio > 1 && "Invalid element size ratio");
13935   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13936                                DAG.getConstant(0, DL, SourceType);
13937
13938   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13939   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13940
13941   // Populate the new build_vector
13942   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13943     SDValue Cast = N->getOperand(i);
13944     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13945             Cast.getOpcode() == ISD::ZERO_EXTEND ||
13946             Cast.isUndef()) && "Invalid cast opcode");
13947     SDValue In;
13948     if (Cast.isUndef())
13949       In = DAG.getUNDEF(SourceType);
13950     else
13951       In = Cast->getOperand(0);
13952     unsigned Index = isLE ? (i * ElemRatio) :
13953                             (i * ElemRatio + (ElemRatio - 1));
13954
13955     assert(Index < Ops.size() && "Invalid index");
13956     Ops[Index] = In;
13957   }
13958
13959   // The type of the new BUILD_VECTOR node.
13960   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13961   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13962          "Invalid vector size");
13963   // Check if the new vector type is legal.
13964   if (!isTypeLegal(VecVT)) return SDValue();
13965
13966   // Make the new BUILD_VECTOR.
13967   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13968
13969   // The new BUILD_VECTOR node has the potential to be further optimized.
13970   AddToWorklist(BV.getNode());
13971   // Bitcast to the desired type.
13972   return DAG.getBitcast(VT, BV);
13973 }
13974
13975 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13976   EVT VT = N->getValueType(0);
13977
13978   unsigned NumInScalars = N->getNumOperands();
13979   SDLoc DL(N);
13980
13981   EVT SrcVT = MVT::Other;
13982   unsigned Opcode = ISD::DELETED_NODE;
13983   unsigned NumDefs = 0;
13984
13985   for (unsigned i = 0; i != NumInScalars; ++i) {
13986     SDValue In = N->getOperand(i);
13987     unsigned Opc = In.getOpcode();
13988
13989     if (Opc == ISD::UNDEF)
13990       continue;
13991
13992     // If all scalar values are floats and converted from integers.
13993     if (Opcode == ISD::DELETED_NODE &&
13994         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13995       Opcode = Opc;
13996     }
13997
13998     if (Opc != Opcode)
13999       return SDValue();
14000
14001     EVT InVT = In.getOperand(0).getValueType();
14002
14003     // If all scalar values are typed differently, bail out. It's chosen to
14004     // simplify BUILD_VECTOR of integer types.
14005     if (SrcVT == MVT::Other)
14006       SrcVT = InVT;
14007     if (SrcVT != InVT)
14008       return SDValue();
14009     NumDefs++;
14010   }
14011
14012   // If the vector has just one element defined, it's not worth to fold it into
14013   // a vectorized one.
14014   if (NumDefs < 2)
14015     return SDValue();
14016
14017   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
14018          && "Should only handle conversion from integer to float.");
14019   assert(SrcVT != MVT::Other && "Cannot determine source type!");
14020
14021   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
14022
14023   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
14024     return SDValue();
14025
14026   // Just because the floating-point vector type is legal does not necessarily
14027   // mean that the corresponding integer vector type is.
14028   if (!isTypeLegal(NVT))
14029     return SDValue();
14030
14031   SmallVector<SDValue, 8> Opnds;
14032   for (unsigned i = 0; i != NumInScalars; ++i) {
14033     SDValue In = N->getOperand(i);
14034
14035     if (In.isUndef())
14036       Opnds.push_back(DAG.getUNDEF(SrcVT));
14037     else
14038       Opnds.push_back(In.getOperand(0));
14039   }
14040   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
14041   AddToWorklist(BV.getNode());
14042
14043   return DAG.getNode(Opcode, DL, VT, BV);
14044 }
14045
14046 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
14047                                            ArrayRef<int> VectorMask,
14048                                            SDValue VecIn1, SDValue VecIn2,
14049                                            unsigned LeftIdx) {
14050   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14051   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
14052
14053   EVT VT = N->getValueType(0);
14054   EVT InVT1 = VecIn1.getValueType();
14055   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
14056
14057   unsigned Vec2Offset = InVT1.getVectorNumElements();
14058   unsigned NumElems = VT.getVectorNumElements();
14059   unsigned ShuffleNumElems = NumElems;
14060
14061   // We can't generate a shuffle node with mismatched input and output types.
14062   // Try to make the types match the type of the output.
14063   if (InVT1 != VT || InVT2 != VT) {
14064     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
14065       // If the output vector length is a multiple of both input lengths,
14066       // we can concatenate them and pad the rest with undefs.
14067       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
14068       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
14069       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
14070       ConcatOps[0] = VecIn1;
14071       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
14072       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14073       VecIn2 = SDValue();
14074     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
14075       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
14076         return SDValue();
14077
14078       if (!VecIn2.getNode()) {
14079         // If we only have one input vector, and it's twice the size of the
14080         // output, split it in two.
14081         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
14082                              DAG.getConstant(NumElems, DL, IdxTy));
14083         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
14084         // Since we now have shorter input vectors, adjust the offset of the
14085         // second vector's start.
14086         Vec2Offset = NumElems;
14087       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
14088         // VecIn1 is wider than the output, and we have another, possibly
14089         // smaller input. Pad the smaller input with undefs, shuffle at the
14090         // input vector width, and extract the output.
14091         // The shuffle type is different than VT, so check legality again.
14092         if (LegalOperations &&
14093             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14094           return SDValue();
14095
14096         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14097         // lower it back into a BUILD_VECTOR. So if the inserted type is
14098         // illegal, don't even try.
14099         if (InVT1 != InVT2) {
14100           if (!TLI.isTypeLegal(InVT2))
14101             return SDValue();
14102           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14103                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14104         }
14105         ShuffleNumElems = NumElems * 2;
14106       } else {
14107         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14108         // than VecIn1. We can't handle this for now - this case will disappear
14109         // when we start sorting the vectors by type.
14110         return SDValue();
14111       }
14112     } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
14113                InVT1.getSizeInBits() == VT.getSizeInBits()) {
14114       SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
14115       ConcatOps[0] = VecIn2;
14116       VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14117     } else {
14118       // TODO: Support cases where the length mismatch isn't exactly by a
14119       // factor of 2.
14120       // TODO: Move this check upwards, so that if we have bad type
14121       // mismatches, we don't create any DAG nodes.
14122       return SDValue();
14123     }
14124   }
14125
14126   // Initialize mask to undef.
14127   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14128
14129   // Only need to run up to the number of elements actually used, not the
14130   // total number of elements in the shuffle - if we are shuffling a wider
14131   // vector, the high lanes should be set to undef.
14132   for (unsigned i = 0; i != NumElems; ++i) {
14133     if (VectorMask[i] <= 0)
14134       continue;
14135
14136     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14137     if (VectorMask[i] == (int)LeftIdx) {
14138       Mask[i] = ExtIndex;
14139     } else if (VectorMask[i] == (int)LeftIdx + 1) {
14140       Mask[i] = Vec2Offset + ExtIndex;
14141     }
14142   }
14143
14144   // The type the input vectors may have changed above.
14145   InVT1 = VecIn1.getValueType();
14146
14147   // If we already have a VecIn2, it should have the same type as VecIn1.
14148   // If we don't, get an undef/zero vector of the appropriate type.
14149   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14150   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
14151
14152   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14153   if (ShuffleNumElems > NumElems)
14154     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14155
14156   return Shuffle;
14157 }
14158
14159 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14160 // operations. If the types of the vectors we're extracting from allow it,
14161 // turn this into a vector_shuffle node.
14162 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14163   SDLoc DL(N);
14164   EVT VT = N->getValueType(0);
14165
14166   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14167   if (!isTypeLegal(VT))
14168     return SDValue();
14169
14170   // May only combine to shuffle after legalize if shuffle is legal.
14171   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14172     return SDValue();
14173
14174   bool UsesZeroVector = false;
14175   unsigned NumElems = N->getNumOperands();
14176
14177   // Record, for each element of the newly built vector, which input vector
14178   // that element comes from. -1 stands for undef, 0 for the zero vector,
14179   // and positive values for the input vectors.
14180   // VectorMask maps each element to its vector number, and VecIn maps vector
14181   // numbers to their initial SDValues.
14182
14183   SmallVector<int, 8> VectorMask(NumElems, -1);
14184   SmallVector<SDValue, 8> VecIn;
14185   VecIn.push_back(SDValue());
14186
14187   for (unsigned i = 0; i != NumElems; ++i) {
14188     SDValue Op = N->getOperand(i);
14189
14190     if (Op.isUndef())
14191       continue;
14192
14193     // See if we can use a blend with a zero vector.
14194     // TODO: Should we generalize this to a blend with an arbitrary constant
14195     // vector?
14196     if (isNullConstant(Op) || isNullFPConstant(Op)) {
14197       UsesZeroVector = true;
14198       VectorMask[i] = 0;
14199       continue;
14200     }
14201
14202     // Not an undef or zero. If the input is something other than an
14203     // EXTRACT_VECTOR_ELT with a constant index, bail out.
14204     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14205         !isa<ConstantSDNode>(Op.getOperand(1)))
14206       return SDValue();
14207
14208     SDValue ExtractedFromVec = Op.getOperand(0);
14209
14210     // All inputs must have the same element type as the output.
14211     if (VT.getVectorElementType() !=
14212         ExtractedFromVec.getValueType().getVectorElementType())
14213       return SDValue();
14214
14215     // Have we seen this input vector before?
14216     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14217     // a map back from SDValues to numbers isn't worth it.
14218     unsigned Idx = std::distance(
14219         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14220     if (Idx == VecIn.size())
14221       VecIn.push_back(ExtractedFromVec);
14222
14223     VectorMask[i] = Idx;
14224   }
14225
14226   // If we didn't find at least one input vector, bail out.
14227   if (VecIn.size() < 2)
14228     return SDValue();
14229
14230   // TODO: We want to sort the vectors by descending length, so that adjacent
14231   // pairs have similar length, and the longer vector is always first in the
14232   // pair.
14233
14234   // TODO: Should this fire if some of the input vectors has illegal type (like
14235   // it does now), or should we let legalization run its course first?
14236
14237   // Shuffle phase:
14238   // Take pairs of vectors, and shuffle them so that the result has elements
14239   // from these vectors in the correct places.
14240   // For example, given:
14241   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14242   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14243   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14244   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14245   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14246   // We will generate:
14247   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14248   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14249   SmallVector<SDValue, 4> Shuffles;
14250   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14251     unsigned LeftIdx = 2 * In + 1;
14252     SDValue VecLeft = VecIn[LeftIdx];
14253     SDValue VecRight =
14254         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14255
14256     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14257                                                 VecRight, LeftIdx))
14258       Shuffles.push_back(Shuffle);
14259     else
14260       return SDValue();
14261   }
14262
14263   // If we need the zero vector as an "ingredient" in the blend tree, add it
14264   // to the list of shuffles.
14265   if (UsesZeroVector)
14266     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14267                                       : DAG.getConstantFP(0.0, DL, VT));
14268
14269   // If we only have one shuffle, we're done.
14270   if (Shuffles.size() == 1)
14271     return Shuffles[0];
14272
14273   // Update the vector mask to point to the post-shuffle vectors.
14274   for (int &Vec : VectorMask)
14275     if (Vec == 0)
14276       Vec = Shuffles.size() - 1;
14277     else
14278       Vec = (Vec - 1) / 2;
14279
14280   // More than one shuffle. Generate a binary tree of blends, e.g. if from
14281   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14282   // generate:
14283   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14284   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14285   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14286   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14287   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14288   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14289   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14290
14291   // Make sure the initial size of the shuffle list is even.
14292   if (Shuffles.size() % 2)
14293     Shuffles.push_back(DAG.getUNDEF(VT));
14294
14295   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14296     if (CurSize % 2) {
14297       Shuffles[CurSize] = DAG.getUNDEF(VT);
14298       CurSize++;
14299     }
14300     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14301       int Left = 2 * In;
14302       int Right = 2 * In + 1;
14303       SmallVector<int, 8> Mask(NumElems, -1);
14304       for (unsigned i = 0; i != NumElems; ++i) {
14305         if (VectorMask[i] == Left) {
14306           Mask[i] = i;
14307           VectorMask[i] = In;
14308         } else if (VectorMask[i] == Right) {
14309           Mask[i] = i + NumElems;
14310           VectorMask[i] = In;
14311         }
14312       }
14313
14314       Shuffles[In] =
14315           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14316     }
14317   }
14318
14319   return Shuffles[0];
14320 }
14321
14322 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14323 // operations which can be matched to a truncate.
14324 SDValue DAGCombiner::reduceBuildVecToTrunc(SDNode *N) {
14325   // TODO: Add support for big-endian.
14326   if (DAG.getDataLayout().isBigEndian())
14327     return SDValue();
14328   if (N->getNumOperands() < 2)
14329     return SDValue();
14330   SDLoc DL(N);
14331   EVT VT = N->getValueType(0);
14332   unsigned NumElems = N->getNumOperands();
14333
14334   if (!isTypeLegal(VT))
14335     return SDValue();
14336
14337   // If the input is something other than an EXTRACT_VECTOR_ELT with a constant
14338   // index, bail out.
14339   // TODO: Allow undef elements in some cases?
14340   if (any_of(N->ops(), [VT](SDValue Op) {
14341         return Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14342                !isa<ConstantSDNode>(Op.getOperand(1)) ||
14343                Op.getValueType() != VT.getVectorElementType();
14344       }))
14345     return SDValue();
14346
14347   // Helper for obtaining an EXTRACT_VECTOR_ELT's constant index
14348   auto GetExtractIdx = [](SDValue Extract) {
14349     return cast<ConstantSDNode>(Extract.getOperand(1))->getSExtValue();
14350   };
14351
14352   // The first BUILD_VECTOR operand must be an an extract from index zero
14353   // (assuming no undef and little-endian).
14354   if (GetExtractIdx(N->getOperand(0)) != 0)
14355     return SDValue();
14356
14357   // Compute the stride from the first index.
14358   int Stride = GetExtractIdx(N->getOperand(1));
14359   SDValue ExtractedFromVec = N->getOperand(0).getOperand(0);
14360
14361   // Proceed only if the stride and the types can be matched to a truncate.
14362   if ((Stride == 1 || !isPowerOf2_32(Stride)) ||
14363       (ExtractedFromVec.getValueType().getVectorNumElements() !=
14364        Stride * NumElems) ||
14365       (VT.getScalarSizeInBits() * Stride > 64))
14366     return SDValue();
14367
14368   // Check remaining operands are consistent with the computed stride.
14369   for (unsigned i = 1; i != NumElems; ++i) {
14370     SDValue Op = N->getOperand(i);
14371
14372     if ((Op.getOperand(0) != ExtractedFromVec) ||
14373         (GetExtractIdx(Op) != Stride * i))
14374       return SDValue();
14375   }
14376
14377   // All checks were ok, construct the truncate.
14378   LLVMContext &Ctx = *DAG.getContext();
14379   EVT NewVT = VT.getVectorVT(
14380       Ctx, EVT::getIntegerVT(Ctx, VT.getScalarSizeInBits() * Stride), NumElems);
14381   EVT TruncVT =
14382       VT.isFloatingPoint() ? VT.changeVectorElementTypeToInteger() : VT;
14383
14384   SDValue Res = DAG.getBitcast(NewVT, ExtractedFromVec);
14385   Res = DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, Res);
14386   return DAG.getBitcast(VT, Res);
14387 }
14388
14389 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14390   EVT VT = N->getValueType(0);
14391
14392   // A vector built entirely of undefs is undef.
14393   if (ISD::allOperandsUndef(N))
14394     return DAG.getUNDEF(VT);
14395
14396   // Check if we can express BUILD VECTOR via subvector extract.
14397   if (!LegalTypes && (N->getNumOperands() > 1)) {
14398     SDValue Op0 = N->getOperand(0);
14399     auto checkElem = [&](SDValue Op) -> uint64_t {
14400       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14401           (Op0.getOperand(0) == Op.getOperand(0)))
14402         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14403           return CNode->getZExtValue();
14404       return -1;
14405     };
14406
14407     int Offset = checkElem(Op0);
14408     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14409       if (Offset + i != checkElem(N->getOperand(i))) {
14410         Offset = -1;
14411         break;
14412       }
14413     }
14414
14415     if ((Offset == 0) &&
14416         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14417       return Op0.getOperand(0);
14418     if ((Offset != -1) &&
14419         ((Offset % N->getValueType(0).getVectorNumElements()) ==
14420          0)) // IDX must be multiple of output size.
14421       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14422                          Op0.getOperand(0), Op0.getOperand(1));
14423   }
14424
14425   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14426     return V;
14427
14428   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14429     return V;
14430
14431   if (TLI.isDesirableToCombineBuildVectorToTruncate())
14432     if (SDValue V = reduceBuildVecToTrunc(N))
14433       return V;
14434
14435   if (SDValue V = reduceBuildVecToShuffle(N))
14436     return V;
14437
14438   return SDValue();
14439 }
14440
14441 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14443   EVT OpVT = N->getOperand(0).getValueType();
14444
14445   // If the operands are legal vectors, leave them alone.
14446   if (TLI.isTypeLegal(OpVT))
14447     return SDValue();
14448
14449   SDLoc DL(N);
14450   EVT VT = N->getValueType(0);
14451   SmallVector<SDValue, 8> Ops;
14452
14453   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14454   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14455
14456   // Keep track of what we encounter.
14457   bool AnyInteger = false;
14458   bool AnyFP = false;
14459   for (const SDValue &Op : N->ops()) {
14460     if (ISD::BITCAST == Op.getOpcode() &&
14461         !Op.getOperand(0).getValueType().isVector())
14462       Ops.push_back(Op.getOperand(0));
14463     else if (ISD::UNDEF == Op.getOpcode())
14464       Ops.push_back(ScalarUndef);
14465     else
14466       return SDValue();
14467
14468     // Note whether we encounter an integer or floating point scalar.
14469     // If it's neither, bail out, it could be something weird like x86mmx.
14470     EVT LastOpVT = Ops.back().getValueType();
14471     if (LastOpVT.isFloatingPoint())
14472       AnyFP = true;
14473     else if (LastOpVT.isInteger())
14474       AnyInteger = true;
14475     else
14476       return SDValue();
14477   }
14478
14479   // If any of the operands is a floating point scalar bitcast to a vector,
14480   // use floating point types throughout, and bitcast everything.
14481   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14482   if (AnyFP) {
14483     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14484     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14485     if (AnyInteger) {
14486       for (SDValue &Op : Ops) {
14487         if (Op.getValueType() == SVT)
14488           continue;
14489         if (Op.isUndef())
14490           Op = ScalarUndef;
14491         else
14492           Op = DAG.getBitcast(SVT, Op);
14493       }
14494     }
14495   }
14496
14497   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14498                                VT.getSizeInBits() / SVT.getSizeInBits());
14499   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14500 }
14501
14502 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14503 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14504 // most two distinct vectors the same size as the result, attempt to turn this
14505 // into a legal shuffle.
14506 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14507   EVT VT = N->getValueType(0);
14508   EVT OpVT = N->getOperand(0).getValueType();
14509   int NumElts = VT.getVectorNumElements();
14510   int NumOpElts = OpVT.getVectorNumElements();
14511
14512   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14513   SmallVector<int, 8> Mask;
14514
14515   for (SDValue Op : N->ops()) {
14516     // Peek through any bitcast.
14517     while (Op.getOpcode() == ISD::BITCAST)
14518       Op = Op.getOperand(0);
14519
14520     // UNDEF nodes convert to UNDEF shuffle mask values.
14521     if (Op.isUndef()) {
14522       Mask.append((unsigned)NumOpElts, -1);
14523       continue;
14524     }
14525
14526     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14527       return SDValue();
14528
14529     // What vector are we extracting the subvector from and at what index?
14530     SDValue ExtVec = Op.getOperand(0);
14531
14532     // We want the EVT of the original extraction to correctly scale the
14533     // extraction index.
14534     EVT ExtVT = ExtVec.getValueType();
14535
14536     // Peek through any bitcast.
14537     while (ExtVec.getOpcode() == ISD::BITCAST)
14538       ExtVec = ExtVec.getOperand(0);
14539
14540     // UNDEF nodes convert to UNDEF shuffle mask values.
14541     if (ExtVec.isUndef()) {
14542       Mask.append((unsigned)NumOpElts, -1);
14543       continue;
14544     }
14545
14546     if (!isa<ConstantSDNode>(Op.getOperand(1)))
14547       return SDValue();
14548     int ExtIdx = Op.getConstantOperandVal(1);
14549
14550     // Ensure that we are extracting a subvector from a vector the same
14551     // size as the result.
14552     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14553       return SDValue();
14554
14555     // Scale the subvector index to account for any bitcast.
14556     int NumExtElts = ExtVT.getVectorNumElements();
14557     if (0 == (NumExtElts % NumElts))
14558       ExtIdx /= (NumExtElts / NumElts);
14559     else if (0 == (NumElts % NumExtElts))
14560       ExtIdx *= (NumElts / NumExtElts);
14561     else
14562       return SDValue();
14563
14564     // At most we can reference 2 inputs in the final shuffle.
14565     if (SV0.isUndef() || SV0 == ExtVec) {
14566       SV0 = ExtVec;
14567       for (int i = 0; i != NumOpElts; ++i)
14568         Mask.push_back(i + ExtIdx);
14569     } else if (SV1.isUndef() || SV1 == ExtVec) {
14570       SV1 = ExtVec;
14571       for (int i = 0; i != NumOpElts; ++i)
14572         Mask.push_back(i + ExtIdx + NumElts);
14573     } else {
14574       return SDValue();
14575     }
14576   }
14577
14578   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14579     return SDValue();
14580
14581   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14582                               DAG.getBitcast(VT, SV1), Mask);
14583 }
14584
14585 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14586   // If we only have one input vector, we don't need to do any concatenation.
14587   if (N->getNumOperands() == 1)
14588     return N->getOperand(0);
14589
14590   // Check if all of the operands are undefs.
14591   EVT VT = N->getValueType(0);
14592   if (ISD::allOperandsUndef(N))
14593     return DAG.getUNDEF(VT);
14594
14595   // Optimize concat_vectors where all but the first of the vectors are undef.
14596   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14597         return Op.isUndef();
14598       })) {
14599     SDValue In = N->getOperand(0);
14600     assert(In.getValueType().isVector() && "Must concat vectors");
14601
14602     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14603     if (In->getOpcode() == ISD::BITCAST &&
14604         !In->getOperand(0)->getValueType(0).isVector()) {
14605       SDValue Scalar = In->getOperand(0);
14606
14607       // If the bitcast type isn't legal, it might be a trunc of a legal type;
14608       // look through the trunc so we can still do the transform:
14609       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14610       if (Scalar->getOpcode() == ISD::TRUNCATE &&
14611           !TLI.isTypeLegal(Scalar.getValueType()) &&
14612           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14613         Scalar = Scalar->getOperand(0);
14614
14615       EVT SclTy = Scalar->getValueType(0);
14616
14617       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14618         return SDValue();
14619
14620       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14621       if (VNTNumElms < 2)
14622         return SDValue();
14623
14624       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14625       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14626         return SDValue();
14627
14628       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14629       return DAG.getBitcast(VT, Res);
14630     }
14631   }
14632
14633   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14634   // We have already tested above for an UNDEF only concatenation.
14635   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14636   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14637   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14638     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14639   };
14640   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14641     SmallVector<SDValue, 8> Opnds;
14642     EVT SVT = VT.getScalarType();
14643
14644     EVT MinVT = SVT;
14645     if (!SVT.isFloatingPoint()) {
14646       // If BUILD_VECTOR are from built from integer, they may have different
14647       // operand types. Get the smallest type and truncate all operands to it.
14648       bool FoundMinVT = false;
14649       for (const SDValue &Op : N->ops())
14650         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14651           EVT OpSVT = Op.getOperand(0)->getValueType(0);
14652           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14653           FoundMinVT = true;
14654         }
14655       assert(FoundMinVT && "Concat vector type mismatch");
14656     }
14657
14658     for (const SDValue &Op : N->ops()) {
14659       EVT OpVT = Op.getValueType();
14660       unsigned NumElts = OpVT.getVectorNumElements();
14661
14662       if (ISD::UNDEF == Op.getOpcode())
14663         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14664
14665       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14666         if (SVT.isFloatingPoint()) {
14667           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14668           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14669         } else {
14670           for (unsigned i = 0; i != NumElts; ++i)
14671             Opnds.push_back(
14672                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14673         }
14674       }
14675     }
14676
14677     assert(VT.getVectorNumElements() == Opnds.size() &&
14678            "Concat vector type mismatch");
14679     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14680   }
14681
14682   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14683   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14684     return V;
14685
14686   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14687   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14688     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14689       return V;
14690
14691   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14692   // nodes often generate nop CONCAT_VECTOR nodes.
14693   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14694   // place the incoming vectors at the exact same location.
14695   SDValue SingleSource = SDValue();
14696   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14697
14698   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14699     SDValue Op = N->getOperand(i);
14700
14701     if (Op.isUndef())
14702       continue;
14703
14704     // Check if this is the identity extract:
14705     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14706       return SDValue();
14707
14708     // Find the single incoming vector for the extract_subvector.
14709     if (SingleSource.getNode()) {
14710       if (Op.getOperand(0) != SingleSource)
14711         return SDValue();
14712     } else {
14713       SingleSource = Op.getOperand(0);
14714
14715       // Check the source type is the same as the type of the result.
14716       // If not, this concat may extend the vector, so we can not
14717       // optimize it away.
14718       if (SingleSource.getValueType() != N->getValueType(0))
14719         return SDValue();
14720     }
14721
14722     unsigned IdentityIndex = i * PartNumElem;
14723     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14724     // The extract index must be constant.
14725     if (!CS)
14726       return SDValue();
14727
14728     // Check that we are reading from the identity index.
14729     if (CS->getZExtValue() != IdentityIndex)
14730       return SDValue();
14731   }
14732
14733   if (SingleSource.getNode())
14734     return SingleSource;
14735
14736   return SDValue();
14737 }
14738
14739 /// If we are extracting a subvector produced by a wide binary operator with at
14740 /// at least one operand that was the result of a vector concatenation, then try
14741 /// to use the narrow vector operands directly to avoid the concatenation and
14742 /// extraction.
14743 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
14744   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
14745   // some of these bailouts with other transforms.
14746
14747   // The extract index must be a constant, so we can map it to a concat operand.
14748   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14749   if (!ExtractIndex)
14750     return SDValue();
14751
14752   // Only handle the case where we are doubling and then halving. A larger ratio
14753   // may require more than two narrow binops to replace the wide binop.
14754   EVT VT = Extract->getValueType(0);
14755   unsigned NumElems = VT.getVectorNumElements();
14756   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
14757          "Extract index is not a multiple of the vector length.");
14758   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
14759     return SDValue();
14760
14761   // We are looking for an optionally bitcasted wide vector binary operator
14762   // feeding an extract subvector.
14763   SDValue BinOp = Extract->getOperand(0);
14764   if (BinOp.getOpcode() == ISD::BITCAST)
14765     BinOp = BinOp.getOperand(0);
14766
14767   // TODO: The motivating case for this transform is an x86 AVX1 target. That
14768   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
14769   // flavors, but no other 256-bit integer support. This could be extended to
14770   // handle any binop, but that may require fixing/adding other folds to avoid
14771   // codegen regressions.
14772   unsigned BOpcode = BinOp.getOpcode();
14773   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
14774     return SDValue();
14775
14776   // The binop must be a vector type, so we can chop it in half.
14777   EVT WideBVT = BinOp.getValueType();
14778   if (!WideBVT.isVector())
14779     return SDValue();
14780
14781   // Bail out if the target does not support a narrower version of the binop.
14782   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
14783                                    WideBVT.getVectorNumElements() / 2);
14784   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14785   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
14786     return SDValue();
14787
14788   // Peek through bitcasts of the binary operator operands if needed.
14789   SDValue LHS = BinOp.getOperand(0);
14790   if (LHS.getOpcode() == ISD::BITCAST)
14791     LHS = LHS.getOperand(0);
14792
14793   SDValue RHS = BinOp.getOperand(1);
14794   if (RHS.getOpcode() == ISD::BITCAST)
14795     RHS = RHS.getOperand(0);
14796
14797   // We need at least one concatenation operation of a binop operand to make
14798   // this transform worthwhile. The concat must double the input vector sizes.
14799   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
14800   bool ConcatL =
14801       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
14802   bool ConcatR =
14803       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
14804   if (!ConcatL && !ConcatR)
14805     return SDValue();
14806
14807   // If one of the binop operands was not the result of a concat, we must
14808   // extract a half-sized operand for our new narrow binop. We can't just reuse
14809   // the original extract index operand because we may have bitcasted.
14810   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
14811   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
14812   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
14813   SDLoc DL(Extract);
14814
14815   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
14816   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
14817   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
14818   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
14819                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14820                                     BinOp.getOperand(0),
14821                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14822
14823   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
14824                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14825                                     BinOp.getOperand(1),
14826                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14827
14828   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
14829   return DAG.getBitcast(VT, NarrowBinOp);
14830 }
14831
14832 /// If we are extracting a subvector from a wide vector load, convert to a
14833 /// narrow load to eliminate the extraction:
14834 /// (extract_subvector (load wide vector)) --> (load narrow vector)
14835 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
14836   // TODO: Add support for big-endian. The offset calculation must be adjusted.
14837   if (DAG.getDataLayout().isBigEndian())
14838     return SDValue();
14839
14840   // TODO: The one-use check is overly conservative. Check the cost of the
14841   // extract instead or remove that condition entirely.
14842   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
14843   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14844   if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
14845       !ExtIdx)
14846     return SDValue();
14847
14848   // The narrow load will be offset from the base address of the old load if
14849   // we are extracting from something besides index 0 (little-endian).
14850   EVT VT = Extract->getValueType(0);
14851   SDLoc DL(Extract);
14852   SDValue BaseAddr = Ld->getOperand(1);
14853   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
14854
14855   // TODO: Use "BaseIndexOffset" to make this more effective.
14856   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
14857   MachineFunction &MF = DAG.getMachineFunction();
14858   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
14859                                                    VT.getStoreSize());
14860   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
14861   DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
14862   return NewLd;
14863 }
14864
14865 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
14866   EVT NVT = N->getValueType(0);
14867   SDValue V = N->getOperand(0);
14868
14869   // Extract from UNDEF is UNDEF.
14870   if (V.isUndef())
14871     return DAG.getUNDEF(NVT);
14872
14873   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
14874     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
14875       return NarrowLoad;
14876
14877   // Combine:
14878   //    (extract_subvec (concat V1, V2, ...), i)
14879   // Into:
14880   //    Vi if possible
14881   // Only operand 0 is checked as 'concat' assumes all inputs of the same
14882   // type.
14883   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
14884       isa<ConstantSDNode>(N->getOperand(1)) &&
14885       V->getOperand(0).getValueType() == NVT) {
14886     unsigned Idx = N->getConstantOperandVal(1);
14887     unsigned NumElems = NVT.getVectorNumElements();
14888     assert((Idx % NumElems) == 0 &&
14889            "IDX in concat is not a multiple of the result vector length.");
14890     return V->getOperand(Idx / NumElems);
14891   }
14892
14893   // Skip bitcasting
14894   if (V->getOpcode() == ISD::BITCAST)
14895     V = V.getOperand(0);
14896
14897   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
14898     // Handle only simple case where vector being inserted and vector
14899     // being extracted are of same size.
14900     EVT SmallVT = V->getOperand(1).getValueType();
14901     if (!NVT.bitsEq(SmallVT))
14902       return SDValue();
14903
14904     // Only handle cases where both indexes are constants.
14905     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
14906     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
14907
14908     if (InsIdx && ExtIdx) {
14909       // Combine:
14910       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
14911       // Into:
14912       //    indices are equal or bit offsets are equal => V1
14913       //    otherwise => (extract_subvec V1, ExtIdx)
14914       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
14915           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
14916         return DAG.getBitcast(NVT, V->getOperand(1));
14917       return DAG.getNode(
14918           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
14919           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
14920           N->getOperand(1));
14921     }
14922   }
14923
14924   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
14925     return NarrowBOp;
14926
14927   return SDValue();
14928 }
14929
14930 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
14931                                                  SDValue V, SelectionDAG &DAG) {
14932   SDLoc DL(V);
14933   EVT VT = V.getValueType();
14934
14935   switch (V.getOpcode()) {
14936   default:
14937     return V;
14938
14939   case ISD::CONCAT_VECTORS: {
14940     EVT OpVT = V->getOperand(0).getValueType();
14941     int OpSize = OpVT.getVectorNumElements();
14942     SmallBitVector OpUsedElements(OpSize, false);
14943     bool FoundSimplification = false;
14944     SmallVector<SDValue, 4> NewOps;
14945     NewOps.reserve(V->getNumOperands());
14946     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
14947       SDValue Op = V->getOperand(i);
14948       bool OpUsed = false;
14949       for (int j = 0; j < OpSize; ++j)
14950         if (UsedElements[i * OpSize + j]) {
14951           OpUsedElements[j] = true;
14952           OpUsed = true;
14953         }
14954       NewOps.push_back(
14955           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
14956                  : DAG.getUNDEF(OpVT));
14957       FoundSimplification |= Op == NewOps.back();
14958       OpUsedElements.reset();
14959     }
14960     if (FoundSimplification)
14961       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
14962     return V;
14963   }
14964
14965   case ISD::INSERT_SUBVECTOR: {
14966     SDValue BaseV = V->getOperand(0);
14967     SDValue SubV = V->getOperand(1);
14968     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
14969     if (!IdxN)
14970       return V;
14971
14972     int SubSize = SubV.getValueType().getVectorNumElements();
14973     int Idx = IdxN->getZExtValue();
14974     bool SubVectorUsed = false;
14975     SmallBitVector SubUsedElements(SubSize, false);
14976     for (int i = 0; i < SubSize; ++i)
14977       if (UsedElements[i + Idx]) {
14978         SubVectorUsed = true;
14979         SubUsedElements[i] = true;
14980         UsedElements[i + Idx] = false;
14981       }
14982
14983     // Now recurse on both the base and sub vectors.
14984     SDValue SimplifiedSubV =
14985         SubVectorUsed
14986             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14987             : DAG.getUNDEF(SubV.getValueType());
14988     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14989     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14990       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14991                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14992     return V;
14993   }
14994   }
14995 }
14996
14997 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14998                                        SDValue N1, SelectionDAG &DAG) {
14999   EVT VT = SVN->getValueType(0);
15000   int NumElts = VT.getVectorNumElements();
15001   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
15002   for (int M : SVN->getMask())
15003     if (M >= 0 && M < NumElts)
15004       N0UsedElements[M] = true;
15005     else if (M >= NumElts)
15006       N1UsedElements[M - NumElts] = true;
15007
15008   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
15009   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
15010   if (S0 == N0 && S1 == N1)
15011     return SDValue();
15012
15013   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
15014 }
15015
15016 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
15017 // or turn a shuffle of a single concat into simpler shuffle then concat.
15018 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
15019   EVT VT = N->getValueType(0);
15020   unsigned NumElts = VT.getVectorNumElements();
15021
15022   SDValue N0 = N->getOperand(0);
15023   SDValue N1 = N->getOperand(1);
15024   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15025
15026   SmallVector<SDValue, 4> Ops;
15027   EVT ConcatVT = N0.getOperand(0).getValueType();
15028   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
15029   unsigned NumConcats = NumElts / NumElemsPerConcat;
15030
15031   // Special case: shuffle(concat(A,B)) can be more efficiently represented
15032   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
15033   // half vector elements.
15034   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
15035       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
15036                   SVN->getMask().end(), [](int i) { return i == -1; })) {
15037     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
15038                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
15039     N1 = DAG.getUNDEF(ConcatVT);
15040     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
15041   }
15042
15043   // Look at every vector that's inserted. We're looking for exact
15044   // subvector-sized copies from a concatenated vector
15045   for (unsigned I = 0; I != NumConcats; ++I) {
15046     // Make sure we're dealing with a copy.
15047     unsigned Begin = I * NumElemsPerConcat;
15048     bool AllUndef = true, NoUndef = true;
15049     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
15050       if (SVN->getMaskElt(J) >= 0)
15051         AllUndef = false;
15052       else
15053         NoUndef = false;
15054     }
15055
15056     if (NoUndef) {
15057       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
15058         return SDValue();
15059
15060       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
15061         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
15062           return SDValue();
15063
15064       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
15065       if (FirstElt < N0.getNumOperands())
15066         Ops.push_back(N0.getOperand(FirstElt));
15067       else
15068         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
15069
15070     } else if (AllUndef) {
15071       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
15072     } else { // Mixed with general masks and undefs, can't do optimization.
15073       return SDValue();
15074     }
15075   }
15076
15077   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15078 }
15079
15080 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15081 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15082 //
15083 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
15084 // a simplification in some sense, but it isn't appropriate in general: some
15085 // BUILD_VECTORs are substantially cheaper than others. The general case
15086 // of a BUILD_VECTOR requires inserting each element individually (or
15087 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
15088 // all constants is a single constant pool load.  A BUILD_VECTOR where each
15089 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
15090 // are undef lowers to a small number of element insertions.
15091 //
15092 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
15093 // We don't fold shuffles where one side is a non-zero constant, and we don't
15094 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
15095 // non-constant operands. This seems to work out reasonably well in practice.
15096 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
15097                                        SelectionDAG &DAG,
15098                                        const TargetLowering &TLI) {
15099   EVT VT = SVN->getValueType(0);
15100   unsigned NumElts = VT.getVectorNumElements();
15101   SDValue N0 = SVN->getOperand(0);
15102   SDValue N1 = SVN->getOperand(1);
15103
15104   if (!N0->hasOneUse() || !N1->hasOneUse())
15105     return SDValue();
15106   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
15107   // discussed above.
15108   if (!N1.isUndef()) {
15109     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
15110     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
15111     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
15112       return SDValue();
15113     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
15114       return SDValue();
15115   }
15116
15117   SmallVector<SDValue, 8> Ops;
15118   SmallSet<SDValue, 16> DuplicateOps;
15119   for (int M : SVN->getMask()) {
15120     SDValue Op = DAG.getUNDEF(VT.getScalarType());
15121     if (M >= 0) {
15122       int Idx = M < (int)NumElts ? M : M - NumElts;
15123       SDValue &S = (M < (int)NumElts ? N0 : N1);
15124       if (S.getOpcode() == ISD::BUILD_VECTOR) {
15125         Op = S.getOperand(Idx);
15126       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
15127         if (Idx == 0)
15128           Op = S.getOperand(0);
15129       } else {
15130         // Operand can't be combined - bail out.
15131         return SDValue();
15132       }
15133     }
15134
15135     // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
15136     // fine, but it's likely to generate low-quality code if the target can't
15137     // reconstruct an appropriate shuffle.
15138     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
15139       if (!DuplicateOps.insert(Op).second)
15140         return SDValue();
15141
15142     Ops.push_back(Op);
15143   }
15144   // BUILD_VECTOR requires all inputs to be of the same type, find the
15145   // maximum type and extend them all.
15146   EVT SVT = VT.getScalarType();
15147   if (SVT.isInteger())
15148     for (SDValue &Op : Ops)
15149       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
15150   if (SVT != VT.getScalarType())
15151     for (SDValue &Op : Ops)
15152       Op = TLI.isZExtFree(Op.getValueType(), SVT)
15153                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
15154                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
15155   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
15156 }
15157
15158 // Match shuffles that can be converted to any_vector_extend_in_reg.
15159 // This is often generated during legalization.
15160 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
15161 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
15162 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
15163                                             SelectionDAG &DAG,
15164                                             const TargetLowering &TLI,
15165                                             bool LegalOperations) {
15166   EVT VT = SVN->getValueType(0);
15167   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15168
15169   // TODO Add support for big-endian when we have a test case.
15170   if (!VT.isInteger() || IsBigEndian)
15171     return SDValue();
15172
15173   unsigned NumElts = VT.getVectorNumElements();
15174   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15175   ArrayRef<int> Mask = SVN->getMask();
15176   SDValue N0 = SVN->getOperand(0);
15177
15178   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15179   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15180     for (unsigned i = 0; i != NumElts; ++i) {
15181       if (Mask[i] < 0)
15182         continue;
15183       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15184         continue;
15185       return false;
15186     }
15187     return true;
15188   };
15189
15190   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15191   // power-of-2 extensions as they are the most likely.
15192   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15193     if (!isAnyExtend(Scale))
15194       continue;
15195
15196     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15197     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15198     if (!LegalOperations ||
15199         TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15200       return DAG.getBitcast(VT,
15201                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15202   }
15203
15204   return SDValue();
15205 }
15206
15207 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15208 // each source element of a large type into the lowest elements of a smaller
15209 // destination type. This is often generated during legalization.
15210 // If the source node itself was a '*_extend_vector_inreg' node then we should
15211 // then be able to remove it.
15212 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15213                                         SelectionDAG &DAG) {
15214   EVT VT = SVN->getValueType(0);
15215   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15216
15217   // TODO Add support for big-endian when we have a test case.
15218   if (!VT.isInteger() || IsBigEndian)
15219     return SDValue();
15220
15221   SDValue N0 = SVN->getOperand(0);
15222   while (N0.getOpcode() == ISD::BITCAST)
15223     N0 = N0.getOperand(0);
15224
15225   unsigned Opcode = N0.getOpcode();
15226   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15227       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15228       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15229     return SDValue();
15230
15231   SDValue N00 = N0.getOperand(0);
15232   ArrayRef<int> Mask = SVN->getMask();
15233   unsigned NumElts = VT.getVectorNumElements();
15234   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15235   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15236   unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
15237
15238   if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
15239     return SDValue();
15240   unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
15241
15242   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15243   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15244   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15245   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15246     for (unsigned i = 0; i != NumElts; ++i) {
15247       if (Mask[i] < 0)
15248         continue;
15249       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15250         continue;
15251       return false;
15252     }
15253     return true;
15254   };
15255
15256   // At the moment we just handle the case where we've truncated back to the
15257   // same size as before the extension.
15258   // TODO: handle more extension/truncation cases as cases arise.
15259   if (EltSizeInBits != ExtSrcSizeInBits)
15260     return SDValue();
15261
15262   // We can remove *extend_vector_inreg only if the truncation happens at
15263   // the same scale as the extension.
15264   if (isTruncate(ExtScale))
15265     return DAG.getBitcast(VT, N00);
15266
15267   return SDValue();
15268 }
15269
15270 // Combine shuffles of splat-shuffles of the form:
15271 // shuffle (shuffle V, undef, splat-mask), undef, M
15272 // If splat-mask contains undef elements, we need to be careful about
15273 // introducing undef's in the folded mask which are not the result of composing
15274 // the masks of the shuffles.
15275 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15276                                      ShuffleVectorSDNode *Splat,
15277                                      SelectionDAG &DAG) {
15278   ArrayRef<int> SplatMask = Splat->getMask();
15279   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
15280
15281   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15282   // every undef mask element in the splat-shuffle has a corresponding undef
15283   // element in the user-shuffle's mask or if the composition of mask elements
15284   // would result in undef.
15285   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15286   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15287   //   In this case it is not legal to simplify to the splat-shuffle because we
15288   //   may be exposing the users of the shuffle an undef element at index 1
15289   //   which was not there before the combine.
15290   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15291   //   In this case the composition of masks yields SplatMask, so it's ok to
15292   //   simplify to the splat-shuffle.
15293   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15294   //   In this case the composed mask includes all undef elements of SplatMask
15295   //   and in addition sets element zero to undef. It is safe to simplify to
15296   //   the splat-shuffle.
15297   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15298                                        ArrayRef<int> SplatMask) {
15299     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15300       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15301           SplatMask[UserMask[i]] != -1)
15302         return false;
15303     return true;
15304   };
15305   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15306     return SDValue(Splat, 0);
15307
15308   // Create a new shuffle with a mask that is composed of the two shuffles'
15309   // masks.
15310   SmallVector<int, 32> NewMask;
15311   for (int Idx : UserMask)
15312     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15313
15314   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15315                               Splat->getOperand(0), Splat->getOperand(1),
15316                               NewMask);
15317 }
15318
15319 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
15320   EVT VT = N->getValueType(0);
15321   unsigned NumElts = VT.getVectorNumElements();
15322
15323   SDValue N0 = N->getOperand(0);
15324   SDValue N1 = N->getOperand(1);
15325
15326   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
15327
15328   // Canonicalize shuffle undef, undef -> undef
15329   if (N0.isUndef() && N1.isUndef())
15330     return DAG.getUNDEF(VT);
15331
15332   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15333
15334   // Canonicalize shuffle v, v -> v, undef
15335   if (N0 == N1) {
15336     SmallVector<int, 8> NewMask;
15337     for (unsigned i = 0; i != NumElts; ++i) {
15338       int Idx = SVN->getMaskElt(i);
15339       if (Idx >= (int)NumElts) Idx -= NumElts;
15340       NewMask.push_back(Idx);
15341     }
15342     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
15343   }
15344
15345   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
15346   if (N0.isUndef())
15347     return DAG.getCommutedVectorShuffle(*SVN);
15348
15349   // Remove references to rhs if it is undef
15350   if (N1.isUndef()) {
15351     bool Changed = false;
15352     SmallVector<int, 8> NewMask;
15353     for (unsigned i = 0; i != NumElts; ++i) {
15354       int Idx = SVN->getMaskElt(i);
15355       if (Idx >= (int)NumElts) {
15356         Idx = -1;
15357         Changed = true;
15358       }
15359       NewMask.push_back(Idx);
15360     }
15361     if (Changed)
15362       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
15363   }
15364
15365   // A shuffle of a single vector that is a splat can always be folded.
15366   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
15367     if (N1->isUndef() && N0Shuf->isSplat())
15368       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
15369
15370   // If it is a splat, check if the argument vector is another splat or a
15371   // build_vector.
15372   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
15373     SDNode *V = N0.getNode();
15374
15375     // If this is a bit convert that changes the element type of the vector but
15376     // not the number of vector elements, look through it.  Be careful not to
15377     // look though conversions that change things like v4f32 to v2f64.
15378     if (V->getOpcode() == ISD::BITCAST) {
15379       SDValue ConvInput = V->getOperand(0);
15380       if (ConvInput.getValueType().isVector() &&
15381           ConvInput.getValueType().getVectorNumElements() == NumElts)
15382         V = ConvInput.getNode();
15383     }
15384
15385     if (V->getOpcode() == ISD::BUILD_VECTOR) {
15386       assert(V->getNumOperands() == NumElts &&
15387              "BUILD_VECTOR has wrong number of operands");
15388       SDValue Base;
15389       bool AllSame = true;
15390       for (unsigned i = 0; i != NumElts; ++i) {
15391         if (!V->getOperand(i).isUndef()) {
15392           Base = V->getOperand(i);
15393           break;
15394         }
15395       }
15396       // Splat of <u, u, u, u>, return <u, u, u, u>
15397       if (!Base.getNode())
15398         return N0;
15399       for (unsigned i = 0; i != NumElts; ++i) {
15400         if (V->getOperand(i) != Base) {
15401           AllSame = false;
15402           break;
15403         }
15404       }
15405       // Splat of <x, x, x, x>, return <x, x, x, x>
15406       if (AllSame)
15407         return N0;
15408
15409       // Canonicalize any other splat as a build_vector.
15410       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
15411       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
15412       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
15413
15414       // We may have jumped through bitcasts, so the type of the
15415       // BUILD_VECTOR may not match the type of the shuffle.
15416       if (V->getValueType(0) != VT)
15417         NewBV = DAG.getBitcast(VT, NewBV);
15418       return NewBV;
15419     }
15420   }
15421
15422   // There are various patterns used to build up a vector from smaller vectors,
15423   // subvectors, or elements. Scan chains of these and replace unused insertions
15424   // or components with undef.
15425   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
15426     return S;
15427
15428   // Match shuffles that can be converted to any_vector_extend_in_reg.
15429   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
15430     return V;
15431
15432   // Combine "truncate_vector_in_reg" style shuffles.
15433   if (SDValue V = combineTruncationShuffle(SVN, DAG))
15434     return V;
15435
15436   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
15437       Level < AfterLegalizeVectorOps &&
15438       (N1.isUndef() ||
15439       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
15440        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
15441     if (SDValue V = partitionShuffleOfConcats(N, DAG))
15442       return V;
15443   }
15444
15445   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15446   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15447   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15448     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
15449       return Res;
15450
15451   // If this shuffle only has a single input that is a bitcasted shuffle,
15452   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
15453   // back to their original types.
15454   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
15455       N1.isUndef() && Level < AfterLegalizeVectorOps &&
15456       TLI.isTypeLegal(VT)) {
15457
15458     // Peek through the bitcast only if there is one user.
15459     SDValue BC0 = N0;
15460     while (BC0.getOpcode() == ISD::BITCAST) {
15461       if (!BC0.hasOneUse())
15462         break;
15463       BC0 = BC0.getOperand(0);
15464     }
15465
15466     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
15467       if (Scale == 1)
15468         return SmallVector<int, 8>(Mask.begin(), Mask.end());
15469
15470       SmallVector<int, 8> NewMask;
15471       for (int M : Mask)
15472         for (int s = 0; s != Scale; ++s)
15473           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
15474       return NewMask;
15475     };
15476
15477     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
15478       EVT SVT = VT.getScalarType();
15479       EVT InnerVT = BC0->getValueType(0);
15480       EVT InnerSVT = InnerVT.getScalarType();
15481
15482       // Determine which shuffle works with the smaller scalar type.
15483       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
15484       EVT ScaleSVT = ScaleVT.getScalarType();
15485
15486       if (TLI.isTypeLegal(ScaleVT) &&
15487           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
15488           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
15489
15490         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15491         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15492
15493         // Scale the shuffle masks to the smaller scalar type.
15494         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
15495         SmallVector<int, 8> InnerMask =
15496             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
15497         SmallVector<int, 8> OuterMask =
15498             ScaleShuffleMask(SVN->getMask(), OuterScale);
15499
15500         // Merge the shuffle masks.
15501         SmallVector<int, 8> NewMask;
15502         for (int M : OuterMask)
15503           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
15504
15505         // Test for shuffle mask legality over both commutations.
15506         SDValue SV0 = BC0->getOperand(0);
15507         SDValue SV1 = BC0->getOperand(1);
15508         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15509         if (!LegalMask) {
15510           std::swap(SV0, SV1);
15511           ShuffleVectorSDNode::commuteMask(NewMask);
15512           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15513         }
15514
15515         if (LegalMask) {
15516           SV0 = DAG.getBitcast(ScaleVT, SV0);
15517           SV1 = DAG.getBitcast(ScaleVT, SV1);
15518           return DAG.getBitcast(
15519               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
15520         }
15521       }
15522     }
15523   }
15524
15525   // Canonicalize shuffles according to rules:
15526   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
15527   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
15528   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
15529   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
15530       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
15531       TLI.isTypeLegal(VT)) {
15532     // The incoming shuffle must be of the same type as the result of the
15533     // current shuffle.
15534     assert(N1->getOperand(0).getValueType() == VT &&
15535            "Shuffle types don't match");
15536
15537     SDValue SV0 = N1->getOperand(0);
15538     SDValue SV1 = N1->getOperand(1);
15539     bool HasSameOp0 = N0 == SV0;
15540     bool IsSV1Undef = SV1.isUndef();
15541     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
15542       // Commute the operands of this shuffle so that next rule
15543       // will trigger.
15544       return DAG.getCommutedVectorShuffle(*SVN);
15545   }
15546
15547   // Try to fold according to rules:
15548   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15549   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15550   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15551   // Don't try to fold shuffles with illegal type.
15552   // Only fold if this shuffle is the only user of the other shuffle.
15553   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
15554       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
15555     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
15556
15557     // Don't try to fold splats; they're likely to simplify somehow, or they
15558     // might be free.
15559     if (OtherSV->isSplat())
15560       return SDValue();
15561
15562     // The incoming shuffle must be of the same type as the result of the
15563     // current shuffle.
15564     assert(OtherSV->getOperand(0).getValueType() == VT &&
15565            "Shuffle types don't match");
15566
15567     SDValue SV0, SV1;
15568     SmallVector<int, 4> Mask;
15569     // Compute the combined shuffle mask for a shuffle with SV0 as the first
15570     // operand, and SV1 as the second operand.
15571     for (unsigned i = 0; i != NumElts; ++i) {
15572       int Idx = SVN->getMaskElt(i);
15573       if (Idx < 0) {
15574         // Propagate Undef.
15575         Mask.push_back(Idx);
15576         continue;
15577       }
15578
15579       SDValue CurrentVec;
15580       if (Idx < (int)NumElts) {
15581         // This shuffle index refers to the inner shuffle N0. Lookup the inner
15582         // shuffle mask to identify which vector is actually referenced.
15583         Idx = OtherSV->getMaskElt(Idx);
15584         if (Idx < 0) {
15585           // Propagate Undef.
15586           Mask.push_back(Idx);
15587           continue;
15588         }
15589
15590         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
15591                                            : OtherSV->getOperand(1);
15592       } else {
15593         // This shuffle index references an element within N1.
15594         CurrentVec = N1;
15595       }
15596
15597       // Simple case where 'CurrentVec' is UNDEF.
15598       if (CurrentVec.isUndef()) {
15599         Mask.push_back(-1);
15600         continue;
15601       }
15602
15603       // Canonicalize the shuffle index. We don't know yet if CurrentVec
15604       // will be the first or second operand of the combined shuffle.
15605       Idx = Idx % NumElts;
15606       if (!SV0.getNode() || SV0 == CurrentVec) {
15607         // Ok. CurrentVec is the left hand side.
15608         // Update the mask accordingly.
15609         SV0 = CurrentVec;
15610         Mask.push_back(Idx);
15611         continue;
15612       }
15613
15614       // Bail out if we cannot convert the shuffle pair into a single shuffle.
15615       if (SV1.getNode() && SV1 != CurrentVec)
15616         return SDValue();
15617
15618       // Ok. CurrentVec is the right hand side.
15619       // Update the mask accordingly.
15620       SV1 = CurrentVec;
15621       Mask.push_back(Idx + NumElts);
15622     }
15623
15624     // Check if all indices in Mask are Undef. In case, propagate Undef.
15625     bool isUndefMask = true;
15626     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
15627       isUndefMask &= Mask[i] < 0;
15628
15629     if (isUndefMask)
15630       return DAG.getUNDEF(VT);
15631
15632     if (!SV0.getNode())
15633       SV0 = DAG.getUNDEF(VT);
15634     if (!SV1.getNode())
15635       SV1 = DAG.getUNDEF(VT);
15636
15637     // Avoid introducing shuffles with illegal mask.
15638     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
15639       ShuffleVectorSDNode::commuteMask(Mask);
15640
15641       if (!TLI.isShuffleMaskLegal(Mask, VT))
15642         return SDValue();
15643
15644       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
15645       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
15646       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
15647       std::swap(SV0, SV1);
15648     }
15649
15650     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15651     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15652     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15653     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
15654   }
15655
15656   return SDValue();
15657 }
15658
15659 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
15660   SDValue InVal = N->getOperand(0);
15661   EVT VT = N->getValueType(0);
15662
15663   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
15664   // with a VECTOR_SHUFFLE.
15665   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15666     SDValue InVec = InVal->getOperand(0);
15667     SDValue EltNo = InVal->getOperand(1);
15668
15669     // FIXME: We could support implicit truncation if the shuffle can be
15670     // scaled to a smaller vector scalar type.
15671     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
15672     if (C0 && VT == InVec.getValueType() &&
15673         VT.getScalarType() == InVal.getValueType()) {
15674       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
15675       int Elt = C0->getZExtValue();
15676       NewMask[0] = Elt;
15677
15678       if (TLI.isShuffleMaskLegal(NewMask, VT))
15679         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
15680                                     NewMask);
15681     }
15682   }
15683
15684   return SDValue();
15685 }
15686
15687 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15688   EVT VT = N->getValueType(0);
15689   SDValue N0 = N->getOperand(0);
15690   SDValue N1 = N->getOperand(1);
15691   SDValue N2 = N->getOperand(2);
15692
15693   // If inserting an UNDEF, just return the original vector.
15694   if (N1.isUndef())
15695     return N0;
15696
15697   // If this is an insert of an extracted vector into an undef vector, we can
15698   // just use the input to the extract.
15699   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15700       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15701     return N1.getOperand(0);
15702
15703   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15704   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15705   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15706   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15707       N0.getOperand(1).getValueType() == N1.getValueType() &&
15708       N0.getOperand(2) == N2)
15709     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15710                        N1, N2);
15711
15712   if (!isa<ConstantSDNode>(N2))
15713     return SDValue();
15714
15715   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15716
15717   // Canonicalize insert_subvector dag nodes.
15718   // Example:
15719   // (insert_subvector (insert_subvector A, Idx0), Idx1)
15720   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15721   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15722       N1.getValueType() == N0.getOperand(1).getValueType() &&
15723       isa<ConstantSDNode>(N0.getOperand(2))) {
15724     unsigned OtherIdx = N0.getConstantOperandVal(2);
15725     if (InsIdx < OtherIdx) {
15726       // Swap nodes.
15727       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15728                                   N0.getOperand(0), N1, N2);
15729       AddToWorklist(NewOp.getNode());
15730       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15731                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15732     }
15733   }
15734
15735   // If the input vector is a concatenation, and the insert replaces
15736   // one of the pieces, we can optimize into a single concat_vectors.
15737   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15738       N0.getOperand(0).getValueType() == N1.getValueType()) {
15739     unsigned Factor = N1.getValueType().getVectorNumElements();
15740
15741     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15742     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15743
15744     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15745   }
15746
15747   return SDValue();
15748 }
15749
15750 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15751   SDValue N0 = N->getOperand(0);
15752
15753   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15754   if (N0->getOpcode() == ISD::FP16_TO_FP)
15755     return N0->getOperand(0);
15756
15757   return SDValue();
15758 }
15759
15760 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15761   SDValue N0 = N->getOperand(0);
15762
15763   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15764   if (N0->getOpcode() == ISD::AND) {
15765     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15766     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15767       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15768                          N0.getOperand(0));
15769     }
15770   }
15771
15772   return SDValue();
15773 }
15774
15775 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
15776 /// with the destination vector and a zero vector.
15777 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
15778 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
15779 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
15780   EVT VT = N->getValueType(0);
15781   SDValue LHS = N->getOperand(0);
15782   SDValue RHS = N->getOperand(1);
15783   SDLoc DL(N);
15784
15785   // Make sure we're not running after operation legalization where it
15786   // may have custom lowered the vector shuffles.
15787   if (LegalOperations)
15788     return SDValue();
15789
15790   if (N->getOpcode() != ISD::AND)
15791     return SDValue();
15792
15793   if (RHS.getOpcode() == ISD::BITCAST)
15794     RHS = RHS.getOperand(0);
15795
15796   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
15797     return SDValue();
15798
15799   EVT RVT = RHS.getValueType();
15800   unsigned NumElts = RHS.getNumOperands();
15801
15802   // Attempt to create a valid clear mask, splitting the mask into
15803   // sub elements and checking to see if each is
15804   // all zeros or all ones - suitable for shuffle masking.
15805   auto BuildClearMask = [&](int Split) {
15806     int NumSubElts = NumElts * Split;
15807     int NumSubBits = RVT.getScalarSizeInBits() / Split;
15808
15809     SmallVector<int, 8> Indices;
15810     for (int i = 0; i != NumSubElts; ++i) {
15811       int EltIdx = i / Split;
15812       int SubIdx = i % Split;
15813       SDValue Elt = RHS.getOperand(EltIdx);
15814       if (Elt.isUndef()) {
15815         Indices.push_back(-1);
15816         continue;
15817       }
15818
15819       APInt Bits;
15820       if (isa<ConstantSDNode>(Elt))
15821         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
15822       else if (isa<ConstantFPSDNode>(Elt))
15823         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
15824       else
15825         return SDValue();
15826
15827       // Extract the sub element from the constant bit mask.
15828       if (DAG.getDataLayout().isBigEndian()) {
15829         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
15830       } else {
15831         Bits.lshrInPlace(SubIdx * NumSubBits);
15832       }
15833
15834       if (Split > 1)
15835         Bits = Bits.trunc(NumSubBits);
15836
15837       if (Bits.isAllOnesValue())
15838         Indices.push_back(i);
15839       else if (Bits == 0)
15840         Indices.push_back(i + NumSubElts);
15841       else
15842         return SDValue();
15843     }
15844
15845     // Let's see if the target supports this vector_shuffle.
15846     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
15847     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
15848     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
15849       return SDValue();
15850
15851     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
15852     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
15853                                                    DAG.getBitcast(ClearVT, LHS),
15854                                                    Zero, Indices));
15855   };
15856
15857   // Determine maximum split level (byte level masking).
15858   int MaxSplit = 1;
15859   if (RVT.getScalarSizeInBits() % 8 == 0)
15860     MaxSplit = RVT.getScalarSizeInBits() / 8;
15861
15862   for (int Split = 1; Split <= MaxSplit; ++Split)
15863     if (RVT.getScalarSizeInBits() % Split == 0)
15864       if (SDValue S = BuildClearMask(Split))
15865         return S;
15866
15867   return SDValue();
15868 }
15869
15870 /// Visit a binary vector operation, like ADD.
15871 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
15872   assert(N->getValueType(0).isVector() &&
15873          "SimplifyVBinOp only works on vectors!");
15874
15875   SDValue LHS = N->getOperand(0);
15876   SDValue RHS = N->getOperand(1);
15877   SDValue Ops[] = {LHS, RHS};
15878
15879   // See if we can constant fold the vector operation.
15880   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
15881           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
15882     return Fold;
15883
15884   // Try to convert a constant mask AND into a shuffle clear mask.
15885   if (SDValue Shuffle = XformToShuffleWithZero(N))
15886     return Shuffle;
15887
15888   // Type legalization might introduce new shuffles in the DAG.
15889   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
15890   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
15891   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
15892       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
15893       LHS.getOperand(1).isUndef() &&
15894       RHS.getOperand(1).isUndef()) {
15895     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
15896     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
15897
15898     if (SVN0->getMask().equals(SVN1->getMask())) {
15899       EVT VT = N->getValueType(0);
15900       SDValue UndefVector = LHS.getOperand(1);
15901       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
15902                                      LHS.getOperand(0), RHS.getOperand(0),
15903                                      N->getFlags());
15904       AddUsersToWorklist(N);
15905       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
15906                                   SVN0->getMask());
15907     }
15908   }
15909
15910   return SDValue();
15911 }
15912
15913 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
15914                                     SDValue N2) {
15915   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
15916
15917   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
15918                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
15919
15920   // If we got a simplified select_cc node back from SimplifySelectCC, then
15921   // break it down into a new SETCC node, and a new SELECT node, and then return
15922   // the SELECT node, since we were called with a SELECT node.
15923   if (SCC.getNode()) {
15924     // Check to see if we got a select_cc back (to turn into setcc/select).
15925     // Otherwise, just return whatever node we got back, like fabs.
15926     if (SCC.getOpcode() == ISD::SELECT_CC) {
15927       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
15928                                   N0.getValueType(),
15929                                   SCC.getOperand(0), SCC.getOperand(1),
15930                                   SCC.getOperand(4));
15931       AddToWorklist(SETCC.getNode());
15932       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
15933                            SCC.getOperand(2), SCC.getOperand(3));
15934     }
15935
15936     return SCC;
15937   }
15938   return SDValue();
15939 }
15940
15941 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
15942 /// being selected between, see if we can simplify the select.  Callers of this
15943 /// should assume that TheSelect is deleted if this returns true.  As such, they
15944 /// should return the appropriate thing (e.g. the node) back to the top-level of
15945 /// the DAG combiner loop to avoid it being looked at.
15946 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
15947                                     SDValue RHS) {
15948
15949   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15950   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
15951   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
15952     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
15953       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
15954       SDValue Sqrt = RHS;
15955       ISD::CondCode CC;
15956       SDValue CmpLHS;
15957       const ConstantFPSDNode *Zero = nullptr;
15958
15959       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
15960         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
15961         CmpLHS = TheSelect->getOperand(0);
15962         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
15963       } else {
15964         // SELECT or VSELECT
15965         SDValue Cmp = TheSelect->getOperand(0);
15966         if (Cmp.getOpcode() == ISD::SETCC) {
15967           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
15968           CmpLHS = Cmp.getOperand(0);
15969           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
15970         }
15971       }
15972       if (Zero && Zero->isZero() &&
15973           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
15974           CC == ISD::SETULT || CC == ISD::SETLT)) {
15975         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15976         CombineTo(TheSelect, Sqrt);
15977         return true;
15978       }
15979     }
15980   }
15981   // Cannot simplify select with vector condition
15982   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
15983
15984   // If this is a select from two identical things, try to pull the operation
15985   // through the select.
15986   if (LHS.getOpcode() != RHS.getOpcode() ||
15987       !LHS.hasOneUse() || !RHS.hasOneUse())
15988     return false;
15989
15990   // If this is a load and the token chain is identical, replace the select
15991   // of two loads with a load through a select of the address to load from.
15992   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
15993   // constants have been dropped into the constant pool.
15994   if (LHS.getOpcode() == ISD::LOAD) {
15995     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
15996     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
15997
15998     // Token chains must be identical.
15999     if (LHS.getOperand(0) != RHS.getOperand(0) ||
16000         // Do not let this transformation reduce the number of volatile loads.
16001         LLD->isVolatile() || RLD->isVolatile() ||
16002         // FIXME: If either is a pre/post inc/dec load,
16003         // we'd need to split out the address adjustment.
16004         LLD->isIndexed() || RLD->isIndexed() ||
16005         // If this is an EXTLOAD, the VT's must match.
16006         LLD->getMemoryVT() != RLD->getMemoryVT() ||
16007         // If this is an EXTLOAD, the kind of extension must match.
16008         (LLD->getExtensionType() != RLD->getExtensionType() &&
16009          // The only exception is if one of the extensions is anyext.
16010          LLD->getExtensionType() != ISD::EXTLOAD &&
16011          RLD->getExtensionType() != ISD::EXTLOAD) ||
16012         // FIXME: this discards src value information.  This is
16013         // over-conservative. It would be beneficial to be able to remember
16014         // both potential memory locations.  Since we are discarding
16015         // src value info, don't do the transformation if the memory
16016         // locations are not in the default address space.
16017         LLD->getPointerInfo().getAddrSpace() != 0 ||
16018         RLD->getPointerInfo().getAddrSpace() != 0 ||
16019         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
16020                                       LLD->getBasePtr().getValueType()))
16021       return false;
16022
16023     // Check that the select condition doesn't reach either load.  If so,
16024     // folding this will induce a cycle into the DAG.  If not, this is safe to
16025     // xform, so create a select of the addresses.
16026     SDValue Addr;
16027     if (TheSelect->getOpcode() == ISD::SELECT) {
16028       SDNode *CondNode = TheSelect->getOperand(0).getNode();
16029       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
16030           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
16031         return false;
16032       // The loads must not depend on one another.
16033       if (LLD->isPredecessorOf(RLD) ||
16034           RLD->isPredecessorOf(LLD))
16035         return false;
16036       Addr = DAG.getSelect(SDLoc(TheSelect),
16037                            LLD->getBasePtr().getValueType(),
16038                            TheSelect->getOperand(0), LLD->getBasePtr(),
16039                            RLD->getBasePtr());
16040     } else {  // Otherwise SELECT_CC
16041       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
16042       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
16043
16044       if ((LLD->hasAnyUseOfValue(1) &&
16045            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
16046           (RLD->hasAnyUseOfValue(1) &&
16047            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
16048         return false;
16049
16050       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
16051                          LLD->getBasePtr().getValueType(),
16052                          TheSelect->getOperand(0),
16053                          TheSelect->getOperand(1),
16054                          LLD->getBasePtr(), RLD->getBasePtr(),
16055                          TheSelect->getOperand(4));
16056     }
16057
16058     SDValue Load;
16059     // It is safe to replace the two loads if they have different alignments,
16060     // but the new load must be the minimum (most restrictive) alignment of the
16061     // inputs.
16062     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
16063     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
16064     if (!RLD->isInvariant())
16065       MMOFlags &= ~MachineMemOperand::MOInvariant;
16066     if (!RLD->isDereferenceable())
16067       MMOFlags &= ~MachineMemOperand::MODereferenceable;
16068     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
16069       // FIXME: Discards pointer and AA info.
16070       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
16071                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
16072                          MMOFlags);
16073     } else {
16074       // FIXME: Discards pointer and AA info.
16075       Load = DAG.getExtLoad(
16076           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
16077                                                   : LLD->getExtensionType(),
16078           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
16079           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
16080     }
16081
16082     // Users of the select now use the result of the load.
16083     CombineTo(TheSelect, Load);
16084
16085     // Users of the old loads now use the new load's chain.  We know the
16086     // old-load value is dead now.
16087     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
16088     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
16089     return true;
16090   }
16091
16092   return false;
16093 }
16094
16095 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
16096 /// bitwise 'and'.
16097 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
16098                                             SDValue N1, SDValue N2, SDValue N3,
16099                                             ISD::CondCode CC) {
16100   // If this is a select where the false operand is zero and the compare is a
16101   // check of the sign bit, see if we can perform the "gzip trick":
16102   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
16103   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
16104   EVT XType = N0.getValueType();
16105   EVT AType = N2.getValueType();
16106   if (!isNullConstant(N3) || !XType.bitsGE(AType))
16107     return SDValue();
16108
16109   // If the comparison is testing for a positive value, we have to invert
16110   // the sign bit mask, so only do that transform if the target has a bitwise
16111   // 'and not' instruction (the invert is free).
16112   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
16113     // (X > -1) ? A : 0
16114     // (X >  0) ? X : 0 <-- This is canonical signed max.
16115     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
16116       return SDValue();
16117   } else if (CC == ISD::SETLT) {
16118     // (X <  0) ? A : 0
16119     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
16120     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
16121       return SDValue();
16122   } else {
16123     return SDValue();
16124   }
16125
16126   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
16127   // constant.
16128   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
16129   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16130   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
16131     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
16132     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
16133     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
16134     AddToWorklist(Shift.getNode());
16135
16136     if (XType.bitsGT(AType)) {
16137       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16138       AddToWorklist(Shift.getNode());
16139     }
16140
16141     if (CC == ISD::SETGT)
16142       Shift = DAG.getNOT(DL, Shift, AType);
16143
16144     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16145   }
16146
16147   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
16148   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
16149   AddToWorklist(Shift.getNode());
16150
16151   if (XType.bitsGT(AType)) {
16152     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16153     AddToWorklist(Shift.getNode());
16154   }
16155
16156   if (CC == ISD::SETGT)
16157     Shift = DAG.getNOT(DL, Shift, AType);
16158
16159   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16160 }
16161
16162 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
16163 /// where 'cond' is the comparison specified by CC.
16164 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
16165                                       SDValue N2, SDValue N3, ISD::CondCode CC,
16166                                       bool NotExtCompare) {
16167   // (x ? y : y) -> y.
16168   if (N2 == N3) return N2;
16169
16170   EVT VT = N2.getValueType();
16171   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
16172   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16173
16174   // Determine if the condition we're dealing with is constant
16175   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
16176                               N0, N1, CC, DL, false);
16177   if (SCC.getNode()) AddToWorklist(SCC.getNode());
16178
16179   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
16180     // fold select_cc true, x, y -> x
16181     // fold select_cc false, x, y -> y
16182     return !SCCC->isNullValue() ? N2 : N3;
16183   }
16184
16185   // Check to see if we can simplify the select into an fabs node
16186   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
16187     // Allow either -0.0 or 0.0
16188     if (CFP->isZero()) {
16189       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
16190       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
16191           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
16192           N2 == N3.getOperand(0))
16193         return DAG.getNode(ISD::FABS, DL, VT, N0);
16194
16195       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
16196       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
16197           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
16198           N2.getOperand(0) == N3)
16199         return DAG.getNode(ISD::FABS, DL, VT, N3);
16200     }
16201   }
16202
16203   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
16204   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
16205   // in it.  This is a win when the constant is not otherwise available because
16206   // it replaces two constant pool loads with one.  We only do this if the FP
16207   // type is known to be legal, because if it isn't, then we are before legalize
16208   // types an we want the other legalization to happen first (e.g. to avoid
16209   // messing with soft float) and if the ConstantFP is not legal, because if
16210   // it is legal, we may not need to store the FP constant in a constant pool.
16211   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
16212     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
16213       if (TLI.isTypeLegal(N2.getValueType()) &&
16214           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
16215                TargetLowering::Legal &&
16216            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
16217            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
16218           // If both constants have multiple uses, then we won't need to do an
16219           // extra load, they are likely around in registers for other users.
16220           (TV->hasOneUse() || FV->hasOneUse())) {
16221         Constant *Elts[] = {
16222           const_cast<ConstantFP*>(FV->getConstantFPValue()),
16223           const_cast<ConstantFP*>(TV->getConstantFPValue())
16224         };
16225         Type *FPTy = Elts[0]->getType();
16226         const DataLayout &TD = DAG.getDataLayout();
16227
16228         // Create a ConstantArray of the two constants.
16229         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
16230         SDValue CPIdx =
16231             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
16232                                 TD.getPrefTypeAlignment(FPTy));
16233         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
16234
16235         // Get the offsets to the 0 and 1 element of the array so that we can
16236         // select between them.
16237         SDValue Zero = DAG.getIntPtrConstant(0, DL);
16238         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
16239         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
16240
16241         SDValue Cond = DAG.getSetCC(DL,
16242                                     getSetCCResultType(N0.getValueType()),
16243                                     N0, N1, CC);
16244         AddToWorklist(Cond.getNode());
16245         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
16246                                           Cond, One, Zero);
16247         AddToWorklist(CstOffset.getNode());
16248         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
16249                             CstOffset);
16250         AddToWorklist(CPIdx.getNode());
16251         return DAG.getLoad(
16252             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
16253             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
16254             Alignment);
16255       }
16256     }
16257
16258   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
16259     return V;
16260
16261   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
16262   // where y is has a single bit set.
16263   // A plaintext description would be, we can turn the SELECT_CC into an AND
16264   // when the condition can be materialized as an all-ones register.  Any
16265   // single bit-test can be materialized as an all-ones register with
16266   // shift-left and shift-right-arith.
16267   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
16268       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
16269     SDValue AndLHS = N0->getOperand(0);
16270     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
16271     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
16272       // Shift the tested bit over the sign bit.
16273       const APInt &AndMask = ConstAndRHS->getAPIntValue();
16274       SDValue ShlAmt =
16275         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
16276                         getShiftAmountTy(AndLHS.getValueType()));
16277       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
16278
16279       // Now arithmetic right shift it all the way over, so the result is either
16280       // all-ones, or zero.
16281       SDValue ShrAmt =
16282         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
16283                         getShiftAmountTy(Shl.getValueType()));
16284       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
16285
16286       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
16287     }
16288   }
16289
16290   // fold select C, 16, 0 -> shl C, 4
16291   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
16292       TLI.getBooleanContents(N0.getValueType()) ==
16293           TargetLowering::ZeroOrOneBooleanContent) {
16294
16295     // If the caller doesn't want us to simplify this into a zext of a compare,
16296     // don't do it.
16297     if (NotExtCompare && N2C->isOne())
16298       return SDValue();
16299
16300     // Get a SetCC of the condition
16301     // NOTE: Don't create a SETCC if it's not legal on this target.
16302     if (!LegalOperations ||
16303         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
16304       SDValue Temp, SCC;
16305       // cast from setcc result type to select result type
16306       if (LegalTypes) {
16307         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
16308                             N0, N1, CC);
16309         if (N2.getValueType().bitsLT(SCC.getValueType()))
16310           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
16311                                         N2.getValueType());
16312         else
16313           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16314                              N2.getValueType(), SCC);
16315       } else {
16316         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
16317         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16318                            N2.getValueType(), SCC);
16319       }
16320
16321       AddToWorklist(SCC.getNode());
16322       AddToWorklist(Temp.getNode());
16323
16324       if (N2C->isOne())
16325         return Temp;
16326
16327       // shl setcc result by log2 n2c
16328       return DAG.getNode(
16329           ISD::SHL, DL, N2.getValueType(), Temp,
16330           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
16331                           getShiftAmountTy(Temp.getValueType())));
16332     }
16333   }
16334
16335   // Check to see if this is an integer abs.
16336   // select_cc setg[te] X,  0,  X, -X ->
16337   // select_cc setgt    X, -1,  X, -X ->
16338   // select_cc setl[te] X,  0, -X,  X ->
16339   // select_cc setlt    X,  1, -X,  X ->
16340   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
16341   if (N1C) {
16342     ConstantSDNode *SubC = nullptr;
16343     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
16344          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
16345         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
16346       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
16347     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
16348               (N1C->isOne() && CC == ISD::SETLT)) &&
16349              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
16350       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
16351
16352     EVT XType = N0.getValueType();
16353     if (SubC && SubC->isNullValue() && XType.isInteger()) {
16354       SDLoc DL(N0);
16355       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
16356                                   N0,
16357                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
16358                                          getShiftAmountTy(N0.getValueType())));
16359       SDValue Add = DAG.getNode(ISD::ADD, DL,
16360                                 XType, N0, Shift);
16361       AddToWorklist(Shift.getNode());
16362       AddToWorklist(Add.getNode());
16363       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
16364     }
16365   }
16366
16367   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
16368   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
16369   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
16370   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
16371   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
16372   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
16373   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
16374   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
16375   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
16376     SDValue ValueOnZero = N2;
16377     SDValue Count = N3;
16378     // If the condition is NE instead of E, swap the operands.
16379     if (CC == ISD::SETNE)
16380       std::swap(ValueOnZero, Count);
16381     // Check if the value on zero is a constant equal to the bits in the type.
16382     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
16383       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
16384         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
16385         // legal, combine to just cttz.
16386         if ((Count.getOpcode() == ISD::CTTZ ||
16387              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
16388             N0 == Count.getOperand(0) &&
16389             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
16390           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
16391         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
16392         // legal, combine to just ctlz.
16393         if ((Count.getOpcode() == ISD::CTLZ ||
16394              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
16395             N0 == Count.getOperand(0) &&
16396             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
16397           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
16398       }
16399     }
16400   }
16401
16402   return SDValue();
16403 }
16404
16405 /// This is a stub for TargetLowering::SimplifySetCC.
16406 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
16407                                    ISD::CondCode Cond, const SDLoc &DL,
16408                                    bool foldBooleans) {
16409   TargetLowering::DAGCombinerInfo
16410     DagCombineInfo(DAG, Level, false, this);
16411   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
16412 }
16413
16414 /// Given an ISD::SDIV node expressing a divide by constant, return
16415 /// a DAG expression to select that will generate the same value by multiplying
16416 /// by a magic number.
16417 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16418 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
16419   // when optimising for minimum size, we don't want to expand a div to a mul
16420   // and a shift.
16421   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16422     return SDValue();
16423
16424   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16425   if (!C)
16426     return SDValue();
16427
16428   // Avoid division by zero.
16429   if (C->isNullValue())
16430     return SDValue();
16431
16432   std::vector<SDNode*> Built;
16433   SDValue S =
16434       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16435
16436   for (SDNode *N : Built)
16437     AddToWorklist(N);
16438   return S;
16439 }
16440
16441 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
16442 /// DAG expression that will generate the same value by right shifting.
16443 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
16444   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16445   if (!C)
16446     return SDValue();
16447
16448   // Avoid division by zero.
16449   if (C->isNullValue())
16450     return SDValue();
16451
16452   std::vector<SDNode *> Built;
16453   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
16454
16455   for (SDNode *N : Built)
16456     AddToWorklist(N);
16457   return S;
16458 }
16459
16460 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
16461 /// expression that will generate the same value by multiplying by a magic
16462 /// number.
16463 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16464 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
16465   // when optimising for minimum size, we don't want to expand a div to a mul
16466   // and a shift.
16467   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16468     return SDValue();
16469
16470   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16471   if (!C)
16472     return SDValue();
16473
16474   // Avoid division by zero.
16475   if (C->isNullValue())
16476     return SDValue();
16477
16478   std::vector<SDNode*> Built;
16479   SDValue S =
16480       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16481
16482   for (SDNode *N : Built)
16483     AddToWorklist(N);
16484   return S;
16485 }
16486
16487 /// Determines the LogBase2 value for a non-null input value using the
16488 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
16489 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
16490   EVT VT = V.getValueType();
16491   unsigned EltBits = VT.getScalarSizeInBits();
16492   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
16493   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
16494   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
16495   return LogBase2;
16496 }
16497
16498 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16499 /// For the reciprocal, we need to find the zero of the function:
16500 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
16501 ///     =>
16502 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
16503 ///     does not require additional intermediate precision]
16504 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
16505   if (Level >= AfterLegalizeDAG)
16506     return SDValue();
16507
16508   // TODO: Handle half and/or extended types?
16509   EVT VT = Op.getValueType();
16510   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16511     return SDValue();
16512
16513   // If estimates are explicitly disabled for this function, we're done.
16514   MachineFunction &MF = DAG.getMachineFunction();
16515   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
16516   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16517     return SDValue();
16518
16519   // Estimates may be explicitly enabled for this type with a custom number of
16520   // refinement steps.
16521   int Iterations = TLI.getDivRefinementSteps(VT, MF);
16522   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
16523     AddToWorklist(Est.getNode());
16524
16525     if (Iterations) {
16526       EVT VT = Op.getValueType();
16527       SDLoc DL(Op);
16528       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
16529
16530       // Newton iterations: Est = Est + Est (1 - Arg * Est)
16531       for (int i = 0; i < Iterations; ++i) {
16532         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
16533         AddToWorklist(NewEst.getNode());
16534
16535         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
16536         AddToWorklist(NewEst.getNode());
16537
16538         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16539         AddToWorklist(NewEst.getNode());
16540
16541         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
16542         AddToWorklist(Est.getNode());
16543       }
16544     }
16545     return Est;
16546   }
16547
16548   return SDValue();
16549 }
16550
16551 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16552 /// For the reciprocal sqrt, we need to find the zero of the function:
16553 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16554 ///     =>
16555 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
16556 /// As a result, we precompute A/2 prior to the iteration loop.
16557 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
16558                                          unsigned Iterations,
16559                                          SDNodeFlags Flags, bool Reciprocal) {
16560   EVT VT = Arg.getValueType();
16561   SDLoc DL(Arg);
16562   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
16563
16564   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
16565   // this entire sequence requires only one FP constant.
16566   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
16567   AddToWorklist(HalfArg.getNode());
16568
16569   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
16570   AddToWorklist(HalfArg.getNode());
16571
16572   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
16573   for (unsigned i = 0; i < Iterations; ++i) {
16574     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
16575     AddToWorklist(NewEst.getNode());
16576
16577     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
16578     AddToWorklist(NewEst.getNode());
16579
16580     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
16581     AddToWorklist(NewEst.getNode());
16582
16583     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16584     AddToWorklist(Est.getNode());
16585   }
16586
16587   // If non-reciprocal square root is requested, multiply the result by Arg.
16588   if (!Reciprocal) {
16589     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
16590     AddToWorklist(Est.getNode());
16591   }
16592
16593   return Est;
16594 }
16595
16596 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16597 /// For the reciprocal sqrt, we need to find the zero of the function:
16598 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16599 ///     =>
16600 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
16601 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
16602                                          unsigned Iterations,
16603                                          SDNodeFlags Flags, bool Reciprocal) {
16604   EVT VT = Arg.getValueType();
16605   SDLoc DL(Arg);
16606   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
16607   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
16608
16609   // This routine must enter the loop below to work correctly
16610   // when (Reciprocal == false).
16611   assert(Iterations > 0);
16612
16613   // Newton iterations for reciprocal square root:
16614   // E = (E * -0.5) * ((A * E) * E + -3.0)
16615   for (unsigned i = 0; i < Iterations; ++i) {
16616     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
16617     AddToWorklist(AE.getNode());
16618
16619     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
16620     AddToWorklist(AEE.getNode());
16621
16622     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
16623     AddToWorklist(RHS.getNode());
16624
16625     // When calculating a square root at the last iteration build:
16626     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
16627     // (notice a common subexpression)
16628     SDValue LHS;
16629     if (Reciprocal || (i + 1) < Iterations) {
16630       // RSQRT: LHS = (E * -0.5)
16631       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
16632     } else {
16633       // SQRT: LHS = (A * E) * -0.5
16634       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
16635     }
16636     AddToWorklist(LHS.getNode());
16637
16638     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
16639     AddToWorklist(Est.getNode());
16640   }
16641
16642   return Est;
16643 }
16644
16645 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
16646 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
16647 /// Op can be zero.
16648 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
16649                                            bool Reciprocal) {
16650   if (Level >= AfterLegalizeDAG)
16651     return SDValue();
16652
16653   // TODO: Handle half and/or extended types?
16654   EVT VT = Op.getValueType();
16655   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16656     return SDValue();
16657
16658   // If estimates are explicitly disabled for this function, we're done.
16659   MachineFunction &MF = DAG.getMachineFunction();
16660   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
16661   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16662     return SDValue();
16663
16664   // Estimates may be explicitly enabled for this type with a custom number of
16665   // refinement steps.
16666   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
16667
16668   bool UseOneConstNR = false;
16669   if (SDValue Est =
16670       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
16671                           Reciprocal)) {
16672     AddToWorklist(Est.getNode());
16673
16674     if (Iterations) {
16675       Est = UseOneConstNR
16676             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16677             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16678
16679       if (!Reciprocal) {
16680         // Unfortunately, Est is now NaN if the input was exactly 0.0.
16681         // Select out this case and force the answer to 0.0.
16682         EVT VT = Op.getValueType();
16683         SDLoc DL(Op);
16684
16685         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16686         EVT CCVT = getSetCCResultType(VT);
16687         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16688         AddToWorklist(ZeroCmp.getNode());
16689
16690         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16691                           ZeroCmp, FPZero, Est);
16692         AddToWorklist(Est.getNode());
16693       }
16694     }
16695     return Est;
16696   }
16697
16698   return SDValue();
16699 }
16700
16701 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16702   return buildSqrtEstimateImpl(Op, Flags, true);
16703 }
16704
16705 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16706   return buildSqrtEstimateImpl(Op, Flags, false);
16707 }
16708
16709 /// Return true if base is a frame index, which is known not to alias with
16710 /// anything but itself.  Provides base object and offset as results.
16711 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16712                            const GlobalValue *&GV, const void *&CV) {
16713   // Assume it is a primitive operation.
16714   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16715
16716   // If it's an adding a simple constant then integrate the offset.
16717   if (Base.getOpcode() == ISD::ADD) {
16718     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16719       Base = Base.getOperand(0);
16720       Offset += C->getSExtValue();
16721     }
16722   }
16723
16724   // Return the underlying GlobalValue, and update the Offset.  Return false
16725   // for GlobalAddressSDNode since the same GlobalAddress may be represented
16726   // by multiple nodes with different offsets.
16727   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16728     GV = G->getGlobal();
16729     Offset += G->getOffset();
16730     return false;
16731   }
16732
16733   // Return the underlying Constant value, and update the Offset.  Return false
16734   // for ConstantSDNodes since the same constant pool entry may be represented
16735   // by multiple nodes with different offsets.
16736   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16737     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16738                                          : (const void *)C->getConstVal();
16739     Offset += C->getOffset();
16740     return false;
16741   }
16742   // If it's any of the following then it can't alias with anything but itself.
16743   return isa<FrameIndexSDNode>(Base);
16744 }
16745
16746 /// Return true if there is any possibility that the two addresses overlap.
16747 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16748   // If they are the same then they must be aliases.
16749   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16750
16751   // If they are both volatile then they cannot be reordered.
16752   if (Op0->isVolatile() && Op1->isVolatile()) return true;
16753
16754   // If one operation reads from invariant memory, and the other may store, they
16755   // cannot alias. These should really be checking the equivalent of mayWrite,
16756   // but it only matters for memory nodes other than load /store.
16757   if (Op0->isInvariant() && Op1->writeMem())
16758     return false;
16759
16760   if (Op1->isInvariant() && Op0->writeMem())
16761     return false;
16762
16763   unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16764   unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16765
16766   // Check for BaseIndexOffset matching.
16767   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
16768   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
16769   int64_t PtrDiff;
16770   if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
16771     return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
16772
16773   // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
16774   // able to calculate their relative offset if at least one arises
16775   // from an alloca. However, these allocas cannot overlap and we
16776   // can infer there is no alias.
16777   if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
16778     if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
16779       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16780       // If the base are the same frame index but the we couldn't find a
16781       // constant offset, (indices are different) be conservative.
16782       if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
16783                      !MFI.isFixedObjectIndex(B->getIndex())))
16784         return false;
16785     }
16786
16787   // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
16788   // modified to use BaseIndexOffset.
16789
16790   // Gather base node and offset information.
16791   SDValue Base0, Base1;
16792   int64_t Offset0, Offset1;
16793   const GlobalValue *GV0, *GV1;
16794   const void *CV0, *CV1;
16795   bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
16796                                       Base0, Offset0, GV0, CV0);
16797   bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
16798                                       Base1, Offset1, GV1, CV1);
16799
16800   // If they have the same base address, then check to see if they overlap.
16801   if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
16802     return !((Offset0 + NumBytes0) <= Offset1 ||
16803              (Offset1 + NumBytes1) <= Offset0);
16804
16805   // It is possible for different frame indices to alias each other, mostly
16806   // when tail call optimization reuses return address slots for arguments.
16807   // To catch this case, look up the actual index of frame indices to compute
16808   // the real alias relationship.
16809   if (IsFrameIndex0 && IsFrameIndex1) {
16810     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16811     Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
16812     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
16813     return !((Offset0 + NumBytes0) <= Offset1 ||
16814              (Offset1 + NumBytes1) <= Offset0);
16815   }
16816
16817   // Otherwise, if we know what the bases are, and they aren't identical, then
16818   // we know they cannot alias.
16819   if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
16820     return false;
16821
16822   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
16823   // compared to the size and offset of the access, we may be able to prove they
16824   // do not alias. This check is conservative for now to catch cases created by
16825   // splitting vector types.
16826   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
16827   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
16828   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
16829   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
16830   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
16831       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
16832     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
16833     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
16834
16835     // There is no overlap between these relatively aligned accesses of similar
16836     // size. Return no alias.
16837     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
16838         (OffAlign1 + NumBytes1) <= OffAlign0)
16839       return false;
16840   }
16841
16842   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
16843                    ? CombinerGlobalAA
16844                    : DAG.getSubtarget().useAA();
16845 #ifndef NDEBUG
16846   if (CombinerAAOnlyFunc.getNumOccurrences() &&
16847       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
16848     UseAA = false;
16849 #endif
16850
16851   if (UseAA && AA &&
16852       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
16853     // Use alias analysis information.
16854     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
16855     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
16856     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
16857     AliasResult AAResult =
16858         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
16859                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
16860                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
16861                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
16862     if (AAResult == NoAlias)
16863       return false;
16864   }
16865
16866   // Otherwise we have to assume they alias.
16867   return true;
16868 }
16869
16870 /// Walk up chain skipping non-aliasing memory nodes,
16871 /// looking for aliasing nodes and adding them to the Aliases vector.
16872 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
16873                                    SmallVectorImpl<SDValue> &Aliases) {
16874   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
16875   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
16876
16877   // Get alias information for node.
16878   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
16879
16880   // Starting off.
16881   Chains.push_back(OriginalChain);
16882   unsigned Depth = 0;
16883
16884   // Look at each chain and determine if it is an alias.  If so, add it to the
16885   // aliases list.  If not, then continue up the chain looking for the next
16886   // candidate.
16887   while (!Chains.empty()) {
16888     SDValue Chain = Chains.pop_back_val();
16889
16890     // For TokenFactor nodes, look at each operand and only continue up the
16891     // chain until we reach the depth limit.
16892     //
16893     // FIXME: The depth check could be made to return the last non-aliasing
16894     // chain we found before we hit a tokenfactor rather than the original
16895     // chain.
16896     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
16897       Aliases.clear();
16898       Aliases.push_back(OriginalChain);
16899       return;
16900     }
16901
16902     // Don't bother if we've been before.
16903     if (!Visited.insert(Chain.getNode()).second)
16904       continue;
16905
16906     switch (Chain.getOpcode()) {
16907     case ISD::EntryToken:
16908       // Entry token is ideal chain operand, but handled in FindBetterChain.
16909       break;
16910
16911     case ISD::LOAD:
16912     case ISD::STORE: {
16913       // Get alias information for Chain.
16914       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
16915           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
16916
16917       // If chain is alias then stop here.
16918       if (!(IsLoad && IsOpLoad) &&
16919           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
16920         Aliases.push_back(Chain);
16921       } else {
16922         // Look further up the chain.
16923         Chains.push_back(Chain.getOperand(0));
16924         ++Depth;
16925       }
16926       break;
16927     }
16928
16929     case ISD::TokenFactor:
16930       // We have to check each of the operands of the token factor for "small"
16931       // token factors, so we queue them up.  Adding the operands to the queue
16932       // (stack) in reverse order maintains the original order and increases the
16933       // likelihood that getNode will find a matching token factor (CSE.)
16934       if (Chain.getNumOperands() > 16) {
16935         Aliases.push_back(Chain);
16936         break;
16937       }
16938       for (unsigned n = Chain.getNumOperands(); n;)
16939         Chains.push_back(Chain.getOperand(--n));
16940       ++Depth;
16941       break;
16942
16943     case ISD::CopyFromReg:
16944       // Forward past CopyFromReg.
16945       Chains.push_back(Chain.getOperand(0));
16946       ++Depth;
16947       break;
16948
16949     default:
16950       // For all other instructions we will just have to take what we can get.
16951       Aliases.push_back(Chain);
16952       break;
16953     }
16954   }
16955 }
16956
16957 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
16958 /// (aliasing node.)
16959 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
16960   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
16961
16962   // Accumulate all the aliases to this node.
16963   GatherAllAliases(N, OldChain, Aliases);
16964
16965   // If no operands then chain to entry token.
16966   if (Aliases.size() == 0)
16967     return DAG.getEntryNode();
16968
16969   // If a single operand then chain to it.  We don't need to revisit it.
16970   if (Aliases.size() == 1)
16971     return Aliases[0];
16972
16973   // Construct a custom tailored token factor.
16974   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
16975 }
16976
16977 // This function tries to collect a bunch of potentially interesting
16978 // nodes to improve the chains of, all at once. This might seem
16979 // redundant, as this function gets called when visiting every store
16980 // node, so why not let the work be done on each store as it's visited?
16981 //
16982 // I believe this is mainly important because MergeConsecutiveStores
16983 // is unable to deal with merging stores of different sizes, so unless
16984 // we improve the chains of all the potential candidates up-front
16985 // before running MergeConsecutiveStores, it might only see some of
16986 // the nodes that will eventually be candidates, and then not be able
16987 // to go from a partially-merged state to the desired final
16988 // fully-merged state.
16989 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
16990   // This holds the base pointer, index, and the offset in bytes from the base
16991   // pointer.
16992   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
16993
16994   // We must have a base and an offset.
16995   if (!BasePtr.getBase().getNode())
16996     return false;
16997
16998   // Do not handle stores to undef base pointers.
16999   if (BasePtr.getBase().isUndef())
17000     return false;
17001
17002   SmallVector<StoreSDNode *, 8> ChainedStores;
17003   ChainedStores.push_back(St);
17004
17005   // Walk up the chain and look for nodes with offsets from the same
17006   // base pointer. Stop when reaching an instruction with a different kind
17007   // or instruction which has a different base pointer.
17008   StoreSDNode *Index = St;
17009   while (Index) {
17010     // If the chain has more than one use, then we can't reorder the mem ops.
17011     if (Index != St && !SDValue(Index, 0)->hasOneUse())
17012       break;
17013
17014     if (Index->isVolatile() || Index->isIndexed())
17015       break;
17016
17017     // Find the base pointer and offset for this memory node.
17018     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
17019
17020     // Check that the base pointer is the same as the original one.
17021     if (!BasePtr.equalBaseIndex(Ptr, DAG))
17022       break;
17023
17024     // Walk up the chain to find the next store node, ignoring any
17025     // intermediate loads. Any other kind of node will halt the loop.
17026     SDNode *NextInChain = Index->getChain().getNode();
17027     while (true) {
17028       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
17029         // We found a store node. Use it for the next iteration.
17030         if (STn->isVolatile() || STn->isIndexed()) {
17031           Index = nullptr;
17032           break;
17033         }
17034         ChainedStores.push_back(STn);
17035         Index = STn;
17036         break;
17037       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
17038         NextInChain = Ldn->getChain().getNode();
17039         continue;
17040       } else {
17041         Index = nullptr;
17042         break;
17043       }
17044     } // end while
17045   }
17046
17047   // At this point, ChainedStores lists all of the Store nodes
17048   // reachable by iterating up through chain nodes matching the above
17049   // conditions.  For each such store identified, try to find an
17050   // earlier chain to attach the store to which won't violate the
17051   // required ordering.
17052   bool MadeChangeToSt = false;
17053   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
17054
17055   for (StoreSDNode *ChainedStore : ChainedStores) {
17056     SDValue Chain = ChainedStore->getChain();
17057     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
17058
17059     if (Chain != BetterChain) {
17060       if (ChainedStore == St)
17061         MadeChangeToSt = true;
17062       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
17063     }
17064   }
17065
17066   // Do all replacements after finding the replacements to make to avoid making
17067   // the chains more complicated by introducing new TokenFactors.
17068   for (auto Replacement : BetterChains)
17069     replaceStoreChain(Replacement.first, Replacement.second);
17070
17071   return MadeChangeToSt;
17072 }
17073
17074 /// This is the entry point for the file.
17075 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
17076                            CodeGenOpt::Level OptLevel) {
17077   /// This is the main entry point to this class.
17078   DAGCombiner(*this, AA, OptLevel).Run(Level);
17079 }