]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r308421, and update
[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     // New replace instances of N0 and N1
1122     if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 &&
1123         NN0.getOpcode() != ISD::DELETED_NODE) {
1124       AddToWorklist(NN0.getNode());
1125       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1126     }
1127
1128     if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 &&
1129         NN1.getOpcode() != ISD::DELETED_NODE) {
1130       AddToWorklist(NN1.getNode());
1131       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1132     }
1133
1134     // Deal with Op being deleted.
1135     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1136       return RV;
1137   }
1138   return SDValue();
1139 }
1140
1141 /// Promote the specified integer shift operation if the target indicates it is
1142 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1143 /// i32 since i16 instructions are longer.
1144 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1145   if (!LegalOperations)
1146     return SDValue();
1147
1148   EVT VT = Op.getValueType();
1149   if (VT.isVector() || !VT.isInteger())
1150     return SDValue();
1151
1152   // If operation type is 'undesirable', e.g. i16 on x86, consider
1153   // promoting it.
1154   unsigned Opc = Op.getOpcode();
1155   if (TLI.isTypeDesirableForOp(Opc, VT))
1156     return SDValue();
1157
1158   EVT PVT = VT;
1159   // Consult target whether it is a good idea to promote this operation and
1160   // what's the right type to promote it to.
1161   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1162     assert(PVT != VT && "Don't know what type to promote to!");
1163
1164     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1165
1166     bool Replace = false;
1167     SDValue N0 = Op.getOperand(0);
1168     SDValue N1 = Op.getOperand(1);
1169     if (Opc == ISD::SRA)
1170       N0 = SExtPromoteOperand(N0, PVT);
1171     else if (Opc == ISD::SRL)
1172       N0 = ZExtPromoteOperand(N0, PVT);
1173     else
1174       N0 = PromoteOperand(N0, PVT, Replace);
1175
1176     if (!N0.getNode())
1177       return SDValue();
1178
1179     SDLoc DL(Op);
1180     SDValue RV =
1181         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1182
1183     AddToWorklist(N0.getNode());
1184     if (Replace)
1185       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1186
1187     // Deal with Op being deleted.
1188     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1189       return RV;
1190   }
1191   return SDValue();
1192 }
1193
1194 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1195   if (!LegalOperations)
1196     return SDValue();
1197
1198   EVT VT = Op.getValueType();
1199   if (VT.isVector() || !VT.isInteger())
1200     return SDValue();
1201
1202   // If operation type is 'undesirable', e.g. i16 on x86, consider
1203   // promoting it.
1204   unsigned Opc = Op.getOpcode();
1205   if (TLI.isTypeDesirableForOp(Opc, VT))
1206     return SDValue();
1207
1208   EVT PVT = VT;
1209   // Consult target whether it is a good idea to promote this operation and
1210   // what's the right type to promote it to.
1211   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1212     assert(PVT != VT && "Don't know what type to promote to!");
1213     // fold (aext (aext x)) -> (aext x)
1214     // fold (aext (zext x)) -> (zext x)
1215     // fold (aext (sext x)) -> (sext x)
1216     DEBUG(dbgs() << "\nPromoting ";
1217           Op.getNode()->dump(&DAG));
1218     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1219   }
1220   return SDValue();
1221 }
1222
1223 bool DAGCombiner::PromoteLoad(SDValue Op) {
1224   if (!LegalOperations)
1225     return false;
1226
1227   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1228     return false;
1229
1230   EVT VT = Op.getValueType();
1231   if (VT.isVector() || !VT.isInteger())
1232     return false;
1233
1234   // If operation type is 'undesirable', e.g. i16 on x86, consider
1235   // promoting it.
1236   unsigned Opc = Op.getOpcode();
1237   if (TLI.isTypeDesirableForOp(Opc, VT))
1238     return false;
1239
1240   EVT PVT = VT;
1241   // Consult target whether it is a good idea to promote this operation and
1242   // what's the right type to promote it to.
1243   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1244     assert(PVT != VT && "Don't know what type to promote to!");
1245
1246     SDLoc DL(Op);
1247     SDNode *N = Op.getNode();
1248     LoadSDNode *LD = cast<LoadSDNode>(N);
1249     EVT MemVT = LD->getMemoryVT();
1250     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1251       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1252                                                        : ISD::EXTLOAD)
1253       : LD->getExtensionType();
1254     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1255                                    LD->getChain(), LD->getBasePtr(),
1256                                    MemVT, LD->getMemOperand());
1257     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1258
1259     DEBUG(dbgs() << "\nPromoting ";
1260           N->dump(&DAG);
1261           dbgs() << "\nTo: ";
1262           Result.getNode()->dump(&DAG);
1263           dbgs() << '\n');
1264     WorklistRemover DeadNodes(*this);
1265     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1266     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1267     deleteAndRecombine(N);
1268     AddToWorklist(Result.getNode());
1269     return true;
1270   }
1271   return false;
1272 }
1273
1274 /// \brief Recursively delete a node which has no uses and any operands for
1275 /// which it is the only use.
1276 ///
1277 /// Note that this both deletes the nodes and removes them from the worklist.
1278 /// It also adds any nodes who have had a user deleted to the worklist as they
1279 /// may now have only one use and subject to other combines.
1280 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1281   if (!N->use_empty())
1282     return false;
1283
1284   SmallSetVector<SDNode *, 16> Nodes;
1285   Nodes.insert(N);
1286   do {
1287     N = Nodes.pop_back_val();
1288     if (!N)
1289       continue;
1290
1291     if (N->use_empty()) {
1292       for (const SDValue &ChildN : N->op_values())
1293         Nodes.insert(ChildN.getNode());
1294
1295       removeFromWorklist(N);
1296       DAG.DeleteNode(N);
1297     } else {
1298       AddToWorklist(N);
1299     }
1300   } while (!Nodes.empty());
1301   return true;
1302 }
1303
1304 //===----------------------------------------------------------------------===//
1305 //  Main DAG Combiner implementation
1306 //===----------------------------------------------------------------------===//
1307
1308 void DAGCombiner::Run(CombineLevel AtLevel) {
1309   // set the instance variables, so that the various visit routines may use it.
1310   Level = AtLevel;
1311   LegalOperations = Level >= AfterLegalizeVectorOps;
1312   LegalTypes = Level >= AfterLegalizeTypes;
1313
1314   // Add all the dag nodes to the worklist.
1315   for (SDNode &Node : DAG.allnodes())
1316     AddToWorklist(&Node);
1317
1318   // Create a dummy node (which is not added to allnodes), that adds a reference
1319   // to the root node, preventing it from being deleted, and tracking any
1320   // changes of the root.
1321   HandleSDNode Dummy(DAG.getRoot());
1322
1323   // While the worklist isn't empty, find a node and try to combine it.
1324   while (!WorklistMap.empty()) {
1325     SDNode *N;
1326     // The Worklist holds the SDNodes in order, but it may contain null entries.
1327     do {
1328       N = Worklist.pop_back_val();
1329     } while (!N);
1330
1331     bool GoodWorklistEntry = WorklistMap.erase(N);
1332     (void)GoodWorklistEntry;
1333     assert(GoodWorklistEntry &&
1334            "Found a worklist entry without a corresponding map entry!");
1335
1336     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1337     // N is deleted from the DAG, since they too may now be dead or may have a
1338     // reduced number of uses, allowing other xforms.
1339     if (recursivelyDeleteUnusedNodes(N))
1340       continue;
1341
1342     WorklistRemover DeadNodes(*this);
1343
1344     // If this combine is running after legalizing the DAG, re-legalize any
1345     // nodes pulled off the worklist.
1346     if (Level == AfterLegalizeDAG) {
1347       SmallSetVector<SDNode *, 16> UpdatedNodes;
1348       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1349
1350       for (SDNode *LN : UpdatedNodes) {
1351         AddToWorklist(LN);
1352         AddUsersToWorklist(LN);
1353       }
1354       if (!NIsValid)
1355         continue;
1356     }
1357
1358     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1359
1360     // Add any operands of the new node which have not yet been combined to the
1361     // worklist as well. Because the worklist uniques things already, this
1362     // won't repeatedly process the same operand.
1363     CombinedNodes.insert(N);
1364     for (const SDValue &ChildN : N->op_values())
1365       if (!CombinedNodes.count(ChildN.getNode()))
1366         AddToWorklist(ChildN.getNode());
1367
1368     SDValue RV = combine(N);
1369
1370     if (!RV.getNode())
1371       continue;
1372
1373     ++NodesCombined;
1374
1375     // If we get back the same node we passed in, rather than a new node or
1376     // zero, we know that the node must have defined multiple values and
1377     // CombineTo was used.  Since CombineTo takes care of the worklist
1378     // mechanics for us, we have no work to do in this case.
1379     if (RV.getNode() == N)
1380       continue;
1381
1382     assert(N->getOpcode() != ISD::DELETED_NODE &&
1383            RV.getOpcode() != ISD::DELETED_NODE &&
1384            "Node was deleted but visit returned new node!");
1385
1386     DEBUG(dbgs() << " ... into: ";
1387           RV.getNode()->dump(&DAG));
1388
1389     if (N->getNumValues() == RV.getNode()->getNumValues())
1390       DAG.ReplaceAllUsesWith(N, RV.getNode());
1391     else {
1392       assert(N->getValueType(0) == RV.getValueType() &&
1393              N->getNumValues() == 1 && "Type mismatch");
1394       DAG.ReplaceAllUsesWith(N, &RV);
1395     }
1396
1397     // Push the new node and any users onto the worklist
1398     AddToWorklist(RV.getNode());
1399     AddUsersToWorklist(RV.getNode());
1400
1401     // Finally, if the node is now dead, remove it from the graph.  The node
1402     // may not be dead if the replacement process recursively simplified to
1403     // something else needing this node. This will also take care of adding any
1404     // operands which have lost a user to the worklist.
1405     recursivelyDeleteUnusedNodes(N);
1406   }
1407
1408   // If the root changed (e.g. it was a dead load, update the root).
1409   DAG.setRoot(Dummy.getValue());
1410   DAG.RemoveDeadNodes();
1411 }
1412
1413 SDValue DAGCombiner::visit(SDNode *N) {
1414   switch (N->getOpcode()) {
1415   default: break;
1416   case ISD::TokenFactor:        return visitTokenFactor(N);
1417   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1418   case ISD::ADD:                return visitADD(N);
1419   case ISD::SUB:                return visitSUB(N);
1420   case ISD::ADDC:               return visitADDC(N);
1421   case ISD::UADDO:              return visitUADDO(N);
1422   case ISD::SUBC:               return visitSUBC(N);
1423   case ISD::USUBO:              return visitUSUBO(N);
1424   case ISD::ADDE:               return visitADDE(N);
1425   case ISD::ADDCARRY:           return visitADDCARRY(N);
1426   case ISD::SUBE:               return visitSUBE(N);
1427   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1428   case ISD::MUL:                return visitMUL(N);
1429   case ISD::SDIV:               return visitSDIV(N);
1430   case ISD::UDIV:               return visitUDIV(N);
1431   case ISD::SREM:
1432   case ISD::UREM:               return visitREM(N);
1433   case ISD::MULHU:              return visitMULHU(N);
1434   case ISD::MULHS:              return visitMULHS(N);
1435   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1436   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1437   case ISD::SMULO:              return visitSMULO(N);
1438   case ISD::UMULO:              return visitUMULO(N);
1439   case ISD::SMIN:
1440   case ISD::SMAX:
1441   case ISD::UMIN:
1442   case ISD::UMAX:               return visitIMINMAX(N);
1443   case ISD::AND:                return visitAND(N);
1444   case ISD::OR:                 return visitOR(N);
1445   case ISD::XOR:                return visitXOR(N);
1446   case ISD::SHL:                return visitSHL(N);
1447   case ISD::SRA:                return visitSRA(N);
1448   case ISD::SRL:                return visitSRL(N);
1449   case ISD::ROTR:
1450   case ISD::ROTL:               return visitRotate(N);
1451   case ISD::ABS:                return visitABS(N);
1452   case ISD::BSWAP:              return visitBSWAP(N);
1453   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1454   case ISD::CTLZ:               return visitCTLZ(N);
1455   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1456   case ISD::CTTZ:               return visitCTTZ(N);
1457   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1458   case ISD::CTPOP:              return visitCTPOP(N);
1459   case ISD::SELECT:             return visitSELECT(N);
1460   case ISD::VSELECT:            return visitVSELECT(N);
1461   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1462   case ISD::SETCC:              return visitSETCC(N);
1463   case ISD::SETCCE:             return visitSETCCE(N);
1464   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1465   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1466   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1467   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1468   case ISD::AssertZext:         return visitAssertZext(N);
1469   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1470   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1471   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1472   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1473   case ISD::BITCAST:            return visitBITCAST(N);
1474   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1475   case ISD::FADD:               return visitFADD(N);
1476   case ISD::FSUB:               return visitFSUB(N);
1477   case ISD::FMUL:               return visitFMUL(N);
1478   case ISD::FMA:                return visitFMA(N);
1479   case ISD::FDIV:               return visitFDIV(N);
1480   case ISD::FREM:               return visitFREM(N);
1481   case ISD::FSQRT:              return visitFSQRT(N);
1482   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1483   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1484   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1485   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1486   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1487   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1488   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1489   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1490   case ISD::FNEG:               return visitFNEG(N);
1491   case ISD::FABS:               return visitFABS(N);
1492   case ISD::FFLOOR:             return visitFFLOOR(N);
1493   case ISD::FMINNUM:            return visitFMINNUM(N);
1494   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1495   case ISD::FCEIL:              return visitFCEIL(N);
1496   case ISD::FTRUNC:             return visitFTRUNC(N);
1497   case ISD::BRCOND:             return visitBRCOND(N);
1498   case ISD::BR_CC:              return visitBR_CC(N);
1499   case ISD::LOAD:               return visitLOAD(N);
1500   case ISD::STORE:              return visitSTORE(N);
1501   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1502   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1503   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1504   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1505   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1506   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1507   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1508   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1509   case ISD::MGATHER:            return visitMGATHER(N);
1510   case ISD::MLOAD:              return visitMLOAD(N);
1511   case ISD::MSCATTER:           return visitMSCATTER(N);
1512   case ISD::MSTORE:             return visitMSTORE(N);
1513   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1514   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1515   }
1516   return SDValue();
1517 }
1518
1519 SDValue DAGCombiner::combine(SDNode *N) {
1520   SDValue RV = visit(N);
1521
1522   // If nothing happened, try a target-specific DAG combine.
1523   if (!RV.getNode()) {
1524     assert(N->getOpcode() != ISD::DELETED_NODE &&
1525            "Node was deleted but visit returned NULL!");
1526
1527     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1528         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1529
1530       // Expose the DAG combiner to the target combiner impls.
1531       TargetLowering::DAGCombinerInfo
1532         DagCombineInfo(DAG, Level, false, this);
1533
1534       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1535     }
1536   }
1537
1538   // If nothing happened still, try promoting the operation.
1539   if (!RV.getNode()) {
1540     switch (N->getOpcode()) {
1541     default: break;
1542     case ISD::ADD:
1543     case ISD::SUB:
1544     case ISD::MUL:
1545     case ISD::AND:
1546     case ISD::OR:
1547     case ISD::XOR:
1548       RV = PromoteIntBinOp(SDValue(N, 0));
1549       break;
1550     case ISD::SHL:
1551     case ISD::SRA:
1552     case ISD::SRL:
1553       RV = PromoteIntShiftOp(SDValue(N, 0));
1554       break;
1555     case ISD::SIGN_EXTEND:
1556     case ISD::ZERO_EXTEND:
1557     case ISD::ANY_EXTEND:
1558       RV = PromoteExtend(SDValue(N, 0));
1559       break;
1560     case ISD::LOAD:
1561       if (PromoteLoad(SDValue(N, 0)))
1562         RV = SDValue(N, 0);
1563       break;
1564     }
1565   }
1566
1567   // If N is a commutative binary node, try commuting it to enable more
1568   // sdisel CSE.
1569   if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1570       N->getNumValues() == 1) {
1571     SDValue N0 = N->getOperand(0);
1572     SDValue N1 = N->getOperand(1);
1573
1574     // Constant operands are canonicalized to RHS.
1575     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1576       SDValue Ops[] = {N1, N0};
1577       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1578                                             N->getFlags());
1579       if (CSENode)
1580         return SDValue(CSENode, 0);
1581     }
1582   }
1583
1584   return RV;
1585 }
1586
1587 /// Given a node, return its input chain if it has one, otherwise return a null
1588 /// sd operand.
1589 static SDValue getInputChainForNode(SDNode *N) {
1590   if (unsigned NumOps = N->getNumOperands()) {
1591     if (N->getOperand(0).getValueType() == MVT::Other)
1592       return N->getOperand(0);
1593     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1594       return N->getOperand(NumOps-1);
1595     for (unsigned i = 1; i < NumOps-1; ++i)
1596       if (N->getOperand(i).getValueType() == MVT::Other)
1597         return N->getOperand(i);
1598   }
1599   return SDValue();
1600 }
1601
1602 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1603   // If N has two operands, where one has an input chain equal to the other,
1604   // the 'other' chain is redundant.
1605   if (N->getNumOperands() == 2) {
1606     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1607       return N->getOperand(0);
1608     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1609       return N->getOperand(1);
1610   }
1611
1612   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1613   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1614   SmallPtrSet<SDNode*, 16> SeenOps;
1615   bool Changed = false;             // If we should replace this token factor.
1616
1617   // Start out with this token factor.
1618   TFs.push_back(N);
1619
1620   // Iterate through token factors.  The TFs grows when new token factors are
1621   // encountered.
1622   for (unsigned i = 0; i < TFs.size(); ++i) {
1623     SDNode *TF = TFs[i];
1624
1625     // Check each of the operands.
1626     for (const SDValue &Op : TF->op_values()) {
1627
1628       switch (Op.getOpcode()) {
1629       case ISD::EntryToken:
1630         // Entry tokens don't need to be added to the list. They are
1631         // redundant.
1632         Changed = true;
1633         break;
1634
1635       case ISD::TokenFactor:
1636         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1637           // Queue up for processing.
1638           TFs.push_back(Op.getNode());
1639           // Clean up in case the token factor is removed.
1640           AddToWorklist(Op.getNode());
1641           Changed = true;
1642           break;
1643         }
1644         LLVM_FALLTHROUGH;
1645
1646       default:
1647         // Only add if it isn't already in the list.
1648         if (SeenOps.insert(Op.getNode()).second)
1649           Ops.push_back(Op);
1650         else
1651           Changed = true;
1652         break;
1653       }
1654     }
1655   }
1656
1657   // Remove Nodes that are chained to another node in the list. Do so
1658   // by walking up chains breath-first stopping when we've seen
1659   // another operand. In general we must climb to the EntryNode, but we can exit
1660   // early if we find all remaining work is associated with just one operand as
1661   // no further pruning is possible.
1662
1663   // List of nodes to search through and original Ops from which they originate.
1664   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1665   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1666   SmallPtrSet<SDNode *, 16> SeenChains;
1667   bool DidPruneOps = false;
1668
1669   unsigned NumLeftToConsider = 0;
1670   for (const SDValue &Op : Ops) {
1671     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1672     OpWorkCount.push_back(1);
1673   }
1674
1675   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1676     // If this is an Op, we can remove the op from the list. Remark any
1677     // search associated with it as from the current OpNumber.
1678     if (SeenOps.count(Op) != 0) {
1679       Changed = true;
1680       DidPruneOps = true;
1681       unsigned OrigOpNumber = 0;
1682       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1683         OrigOpNumber++;
1684       assert((OrigOpNumber != Ops.size()) &&
1685              "expected to find TokenFactor Operand");
1686       // Re-mark worklist from OrigOpNumber to OpNumber
1687       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1688         if (Worklist[i].second == OrigOpNumber) {
1689           Worklist[i].second = OpNumber;
1690         }
1691       }
1692       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1693       OpWorkCount[OrigOpNumber] = 0;
1694       NumLeftToConsider--;
1695     }
1696     // Add if it's a new chain
1697     if (SeenChains.insert(Op).second) {
1698       OpWorkCount[OpNumber]++;
1699       Worklist.push_back(std::make_pair(Op, OpNumber));
1700     }
1701   };
1702
1703   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1704     // We need at least be consider at least 2 Ops to prune.
1705     if (NumLeftToConsider <= 1)
1706       break;
1707     auto CurNode = Worklist[i].first;
1708     auto CurOpNumber = Worklist[i].second;
1709     assert((OpWorkCount[CurOpNumber] > 0) &&
1710            "Node should not appear in worklist");
1711     switch (CurNode->getOpcode()) {
1712     case ISD::EntryToken:
1713       // Hitting EntryToken is the only way for the search to terminate without
1714       // hitting
1715       // another operand's search. Prevent us from marking this operand
1716       // considered.
1717       NumLeftToConsider++;
1718       break;
1719     case ISD::TokenFactor:
1720       for (const SDValue &Op : CurNode->op_values())
1721         AddToWorklist(i, Op.getNode(), CurOpNumber);
1722       break;
1723     case ISD::CopyFromReg:
1724     case ISD::CopyToReg:
1725       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1726       break;
1727     default:
1728       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1729         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1730       break;
1731     }
1732     OpWorkCount[CurOpNumber]--;
1733     if (OpWorkCount[CurOpNumber] == 0)
1734       NumLeftToConsider--;
1735   }
1736
1737   // If we've changed things around then replace token factor.
1738   if (Changed) {
1739     SDValue Result;
1740     if (Ops.empty()) {
1741       // The entry token is the only possible outcome.
1742       Result = DAG.getEntryNode();
1743     } else {
1744       if (DidPruneOps) {
1745         SmallVector<SDValue, 8> PrunedOps;
1746         //
1747         for (const SDValue &Op : Ops) {
1748           if (SeenChains.count(Op.getNode()) == 0)
1749             PrunedOps.push_back(Op);
1750         }
1751         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1752       } else {
1753         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1754       }
1755     }
1756     return Result;
1757   }
1758   return SDValue();
1759 }
1760
1761 /// MERGE_VALUES can always be eliminated.
1762 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1763   WorklistRemover DeadNodes(*this);
1764   // Replacing results may cause a different MERGE_VALUES to suddenly
1765   // be CSE'd with N, and carry its uses with it. Iterate until no
1766   // uses remain, to ensure that the node can be safely deleted.
1767   // First add the users of this node to the work list so that they
1768   // can be tried again once they have new operands.
1769   AddUsersToWorklist(N);
1770   do {
1771     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1772       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1773   } while (!N->use_empty());
1774   deleteAndRecombine(N);
1775   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1776 }
1777
1778 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1779 /// ConstantSDNode pointer else nullptr.
1780 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1781   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1782   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1783 }
1784
1785 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1786   auto BinOpcode = BO->getOpcode();
1787   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1788           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1789           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1790           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1791           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1792           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1793           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1794           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1795           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1796          "Unexpected binary operator");
1797
1798   // Bail out if any constants are opaque because we can't constant fold those.
1799   SDValue C1 = BO->getOperand(1);
1800   if (!isConstantOrConstantVector(C1, true) &&
1801       !isConstantFPBuildVectorOrConstantFP(C1))
1802     return SDValue();
1803
1804   // Don't do this unless the old select is going away. We want to eliminate the
1805   // binary operator, not replace a binop with a select.
1806   // TODO: Handle ISD::SELECT_CC.
1807   SDValue Sel = BO->getOperand(0);
1808   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1809     return SDValue();
1810
1811   SDValue CT = Sel.getOperand(1);
1812   if (!isConstantOrConstantVector(CT, true) &&
1813       !isConstantFPBuildVectorOrConstantFP(CT))
1814     return SDValue();
1815
1816   SDValue CF = Sel.getOperand(2);
1817   if (!isConstantOrConstantVector(CF, true) &&
1818       !isConstantFPBuildVectorOrConstantFP(CF))
1819     return SDValue();
1820
1821   // We have a select-of-constants followed by a binary operator with a
1822   // constant. Eliminate the binop by pulling the constant math into the select.
1823   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1824   EVT VT = Sel.getValueType();
1825   SDLoc DL(Sel);
1826   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1827   assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1828           isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1829          "Failed to constant fold a binop with constant operands");
1830
1831   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1832   assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1833           isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1834          "Failed to constant fold a binop with constant operands");
1835
1836   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1837 }
1838
1839 SDValue DAGCombiner::visitADD(SDNode *N) {
1840   SDValue N0 = N->getOperand(0);
1841   SDValue N1 = N->getOperand(1);
1842   EVT VT = N0.getValueType();
1843   SDLoc DL(N);
1844
1845   // fold vector ops
1846   if (VT.isVector()) {
1847     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1848       return FoldedVOp;
1849
1850     // fold (add x, 0) -> x, vector edition
1851     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1852       return N0;
1853     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1854       return N1;
1855   }
1856
1857   // fold (add x, undef) -> undef
1858   if (N0.isUndef())
1859     return N0;
1860
1861   if (N1.isUndef())
1862     return N1;
1863
1864   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1865     // canonicalize constant to RHS
1866     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1867       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1868     // fold (add c1, c2) -> c1+c2
1869     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1870                                       N1.getNode());
1871   }
1872
1873   // fold (add x, 0) -> x
1874   if (isNullConstant(N1))
1875     return N0;
1876
1877   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1878     // fold ((c1-A)+c2) -> (c1+c2)-A
1879     if (N0.getOpcode() == ISD::SUB &&
1880         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1881       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1882       return DAG.getNode(ISD::SUB, DL, VT,
1883                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1884                          N0.getOperand(1));
1885     }
1886
1887     // add (sext i1 X), 1 -> zext (not i1 X)
1888     // We don't transform this pattern:
1889     //   add (zext i1 X), -1 -> sext (not i1 X)
1890     // because most (?) targets generate better code for the zext form.
1891     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1892         isOneConstantOrOneSplatConstant(N1)) {
1893       SDValue X = N0.getOperand(0);
1894       if ((!LegalOperations ||
1895            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1896             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1897           X.getScalarValueSizeInBits() == 1) {
1898         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1899         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1900       }
1901     }
1902   }
1903
1904   if (SDValue NewSel = foldBinOpIntoSelect(N))
1905     return NewSel;
1906
1907   // reassociate add
1908   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1909     return RADD;
1910
1911   // fold ((0-A) + B) -> B-A
1912   if (N0.getOpcode() == ISD::SUB &&
1913       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1914     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1915
1916   // fold (A + (0-B)) -> A-B
1917   if (N1.getOpcode() == ISD::SUB &&
1918       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1919     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1920
1921   // fold (A+(B-A)) -> B
1922   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1923     return N1.getOperand(0);
1924
1925   // fold ((B-A)+A) -> B
1926   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1927     return N0.getOperand(0);
1928
1929   // fold (A+(B-(A+C))) to (B-C)
1930   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1931       N0 == N1.getOperand(1).getOperand(0))
1932     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1933                        N1.getOperand(1).getOperand(1));
1934
1935   // fold (A+(B-(C+A))) to (B-C)
1936   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1937       N0 == N1.getOperand(1).getOperand(1))
1938     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1939                        N1.getOperand(1).getOperand(0));
1940
1941   // fold (A+((B-A)+or-C)) to (B+or-C)
1942   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1943       N1.getOperand(0).getOpcode() == ISD::SUB &&
1944       N0 == N1.getOperand(0).getOperand(1))
1945     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1946                        N1.getOperand(1));
1947
1948   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1949   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1950     SDValue N00 = N0.getOperand(0);
1951     SDValue N01 = N0.getOperand(1);
1952     SDValue N10 = N1.getOperand(0);
1953     SDValue N11 = N1.getOperand(1);
1954
1955     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1956       return DAG.getNode(ISD::SUB, DL, VT,
1957                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1958                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1959   }
1960
1961   if (SimplifyDemandedBits(SDValue(N, 0)))
1962     return SDValue(N, 0);
1963
1964   // fold (a+b) -> (a|b) iff a and b share no bits.
1965   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1966       DAG.haveNoCommonBitsSet(N0, N1))
1967     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1968
1969   if (SDValue Combined = visitADDLike(N0, N1, N))
1970     return Combined;
1971
1972   if (SDValue Combined = visitADDLike(N1, N0, N))
1973     return Combined;
1974
1975   return SDValue();
1976 }
1977
1978 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
1979   bool Masked = false;
1980
1981   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
1982   while (true) {
1983     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
1984       V = V.getOperand(0);
1985       continue;
1986     }
1987
1988     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
1989       Masked = true;
1990       V = V.getOperand(0);
1991       continue;
1992     }
1993
1994     break;
1995   }
1996
1997   // If this is not a carry, return.
1998   if (V.getResNo() != 1)
1999     return SDValue();
2000
2001   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2002       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2003     return SDValue();
2004
2005   // If the result is masked, then no matter what kind of bool it is we can
2006   // return. If it isn't, then we need to make sure the bool type is either 0 or
2007   // 1 and not other values.
2008   if (Masked ||
2009       TLI.getBooleanContents(V.getValueType()) ==
2010           TargetLoweringBase::ZeroOrOneBooleanContent)
2011     return V;
2012
2013   return SDValue();
2014 }
2015
2016 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2017   EVT VT = N0.getValueType();
2018   SDLoc DL(LocReference);
2019
2020   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2021   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2022       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2023     return DAG.getNode(ISD::SUB, DL, VT, N0,
2024                        DAG.getNode(ISD::SHL, DL, VT,
2025                                    N1.getOperand(0).getOperand(1),
2026                                    N1.getOperand(1)));
2027
2028   if (N1.getOpcode() == ISD::AND) {
2029     SDValue AndOp0 = N1.getOperand(0);
2030     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2031     unsigned DestBits = VT.getScalarSizeInBits();
2032
2033     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2034     // and similar xforms where the inner op is either ~0 or 0.
2035     if (NumSignBits == DestBits &&
2036         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2037       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2038   }
2039
2040   // add (sext i1), X -> sub X, (zext i1)
2041   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2042       N0.getOperand(0).getValueType() == MVT::i1 &&
2043       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2044     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2045     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2046   }
2047
2048   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2049   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2050     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2051     if (TN->getVT() == MVT::i1) {
2052       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2053                                  DAG.getConstant(1, DL, VT));
2054       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2055     }
2056   }
2057
2058   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2059   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)))
2060     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2061                        N0, N1.getOperand(0), N1.getOperand(2));
2062
2063   // (add X, Carry) -> (addcarry X, 0, Carry)
2064   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2065     if (SDValue Carry = getAsCarry(TLI, N1))
2066       return DAG.getNode(ISD::ADDCARRY, DL,
2067                          DAG.getVTList(VT, Carry.getValueType()), N0,
2068                          DAG.getConstant(0, DL, VT), Carry);
2069
2070   return SDValue();
2071 }
2072
2073 SDValue DAGCombiner::visitADDC(SDNode *N) {
2074   SDValue N0 = N->getOperand(0);
2075   SDValue N1 = N->getOperand(1);
2076   EVT VT = N0.getValueType();
2077   SDLoc DL(N);
2078
2079   // If the flag result is dead, turn this into an ADD.
2080   if (!N->hasAnyUseOfValue(1))
2081     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2082                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2083
2084   // canonicalize constant to RHS.
2085   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2086   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2087   if (N0C && !N1C)
2088     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2089
2090   // fold (addc x, 0) -> x + no carry out
2091   if (isNullConstant(N1))
2092     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2093                                         DL, MVT::Glue));
2094
2095   // If it cannot overflow, transform into an add.
2096   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2097     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2098                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2099
2100   return SDValue();
2101 }
2102
2103 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2104   SDValue N0 = N->getOperand(0);
2105   SDValue N1 = N->getOperand(1);
2106   EVT VT = N0.getValueType();
2107   if (VT.isVector())
2108     return SDValue();
2109
2110   EVT CarryVT = N->getValueType(1);
2111   SDLoc DL(N);
2112
2113   // If the flag result is dead, turn this into an ADD.
2114   if (!N->hasAnyUseOfValue(1))
2115     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2116                      DAG.getUNDEF(CarryVT));
2117
2118   // canonicalize constant to RHS.
2119   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2120   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2121   if (N0C && !N1C)
2122     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2123
2124   // fold (uaddo x, 0) -> x + no carry out
2125   if (isNullConstant(N1))
2126     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2127
2128   // If it cannot overflow, transform into an add.
2129   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2130     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2131                      DAG.getConstant(0, DL, CarryVT));
2132
2133   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2134     return Combined;
2135
2136   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2137     return Combined;
2138
2139   return SDValue();
2140 }
2141
2142 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2143   auto VT = N0.getValueType();
2144
2145   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2146   // If Y + 1 cannot overflow.
2147   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2148     SDValue Y = N1.getOperand(0);
2149     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2150     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2151       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2152                          N1.getOperand(2));
2153   }
2154
2155   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2156   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2157     if (SDValue Carry = getAsCarry(TLI, N1))
2158       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2159                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2160
2161   return SDValue();
2162 }
2163
2164 SDValue DAGCombiner::visitADDE(SDNode *N) {
2165   SDValue N0 = N->getOperand(0);
2166   SDValue N1 = N->getOperand(1);
2167   SDValue CarryIn = N->getOperand(2);
2168
2169   // canonicalize constant to RHS
2170   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2171   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2172   if (N0C && !N1C)
2173     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2174                        N1, N0, CarryIn);
2175
2176   // fold (adde x, y, false) -> (addc x, y)
2177   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2178     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2179
2180   return SDValue();
2181 }
2182
2183 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2184   SDValue N0 = N->getOperand(0);
2185   SDValue N1 = N->getOperand(1);
2186   SDValue CarryIn = N->getOperand(2);
2187   SDLoc DL(N);
2188
2189   // canonicalize constant to RHS
2190   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2191   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2192   if (N0C && !N1C)
2193     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2194
2195   // fold (addcarry x, y, false) -> (uaddo x, y)
2196   if (isNullConstant(CarryIn))
2197     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2198
2199   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2200   if (isNullConstant(N0) && isNullConstant(N1)) {
2201     EVT VT = N0.getValueType();
2202     EVT CarryVT = CarryIn.getValueType();
2203     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2204     AddToWorklist(CarryExt.getNode());
2205     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2206                                     DAG.getConstant(1, DL, VT)),
2207                      DAG.getConstant(0, DL, CarryVT));
2208   }
2209
2210   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2211     return Combined;
2212
2213   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2214     return Combined;
2215
2216   return SDValue();
2217 }
2218
2219 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2220                                        SDNode *N) {
2221   // Iff the flag result is dead:
2222   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2223   if ((N0.getOpcode() == ISD::ADD ||
2224        (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2225       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2226     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2227                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2228
2229   /**
2230    * When one of the addcarry argument is itself a carry, we may be facing
2231    * a diamond carry propagation. In which case we try to transform the DAG
2232    * to ensure linear carry propagation if that is possible.
2233    *
2234    * We are trying to get:
2235    *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2236    */
2237   if (auto Y = getAsCarry(TLI, N1)) {
2238     /**
2239      *            (uaddo A, B)
2240      *             /       \
2241      *          Carry      Sum
2242      *            |          \
2243      *            | (addcarry *, 0, Z)
2244      *            |       /
2245      *             \   Carry
2246      *              |   /
2247      * (addcarry X, *, *)
2248      */
2249     if (Y.getOpcode() == ISD::UADDO &&
2250         CarryIn.getResNo() == 1 &&
2251         CarryIn.getOpcode() == ISD::ADDCARRY &&
2252         isNullConstant(CarryIn.getOperand(1)) &&
2253         CarryIn.getOperand(0) == Y.getValue(0)) {
2254       auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2255                               Y.getOperand(0), Y.getOperand(1),
2256                               CarryIn.getOperand(2));
2257       AddToWorklist(NewY.getNode());
2258       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2259                          DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2260                          NewY.getValue(1));
2261     }
2262   }
2263
2264   return SDValue();
2265 }
2266
2267 // Since it may not be valid to emit a fold to zero for vector initializers
2268 // check if we can before folding.
2269 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2270                              SelectionDAG &DAG, bool LegalOperations,
2271                              bool LegalTypes) {
2272   if (!VT.isVector())
2273     return DAG.getConstant(0, DL, VT);
2274   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2275     return DAG.getConstant(0, DL, VT);
2276   return SDValue();
2277 }
2278
2279 SDValue DAGCombiner::visitSUB(SDNode *N) {
2280   SDValue N0 = N->getOperand(0);
2281   SDValue N1 = N->getOperand(1);
2282   EVT VT = N0.getValueType();
2283   SDLoc DL(N);
2284
2285   // fold vector ops
2286   if (VT.isVector()) {
2287     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2288       return FoldedVOp;
2289
2290     // fold (sub x, 0) -> x, vector edition
2291     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2292       return N0;
2293   }
2294
2295   // fold (sub x, x) -> 0
2296   // FIXME: Refactor this and xor and other similar operations together.
2297   if (N0 == N1)
2298     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2299   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2300       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2301     // fold (sub c1, c2) -> c1-c2
2302     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2303                                       N1.getNode());
2304   }
2305
2306   if (SDValue NewSel = foldBinOpIntoSelect(N))
2307     return NewSel;
2308
2309   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2310
2311   // fold (sub x, c) -> (add x, -c)
2312   if (N1C) {
2313     return DAG.getNode(ISD::ADD, DL, VT, N0,
2314                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2315   }
2316
2317   if (isNullConstantOrNullSplatConstant(N0)) {
2318     unsigned BitWidth = VT.getScalarSizeInBits();
2319     // Right-shifting everything out but the sign bit followed by negation is
2320     // the same as flipping arithmetic/logical shift type without the negation:
2321     // -(X >>u 31) -> (X >>s 31)
2322     // -(X >>s 31) -> (X >>u 31)
2323     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2324       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2325       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2326         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2327         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2328           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2329       }
2330     }
2331
2332     // 0 - X --> 0 if the sub is NUW.
2333     if (N->getFlags().hasNoUnsignedWrap())
2334       return N0;
2335
2336     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2337       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2338       // N1 must be 0 because negating the minimum signed value is undefined.
2339       if (N->getFlags().hasNoSignedWrap())
2340         return N0;
2341
2342       // 0 - X --> X if X is 0 or the minimum signed value.
2343       return N1;
2344     }
2345   }
2346
2347   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2348   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2349     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2350
2351   // fold A-(A-B) -> B
2352   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2353     return N1.getOperand(1);
2354
2355   // fold (A+B)-A -> B
2356   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2357     return N0.getOperand(1);
2358
2359   // fold (A+B)-B -> A
2360   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2361     return N0.getOperand(0);
2362
2363   // fold C2-(A+C1) -> (C2-C1)-A
2364   if (N1.getOpcode() == ISD::ADD) {
2365     SDValue N11 = N1.getOperand(1);
2366     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2367         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2368       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2369       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2370     }
2371   }
2372
2373   // fold ((A+(B+or-C))-B) -> A+or-C
2374   if (N0.getOpcode() == ISD::ADD &&
2375       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2376        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2377       N0.getOperand(1).getOperand(0) == N1)
2378     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2379                        N0.getOperand(1).getOperand(1));
2380
2381   // fold ((A+(C+B))-B) -> A+C
2382   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2383       N0.getOperand(1).getOperand(1) == N1)
2384     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2385                        N0.getOperand(1).getOperand(0));
2386
2387   // fold ((A-(B-C))-C) -> A-B
2388   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2389       N0.getOperand(1).getOperand(1) == N1)
2390     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2391                        N0.getOperand(1).getOperand(0));
2392
2393   // If either operand of a sub is undef, the result is undef
2394   if (N0.isUndef())
2395     return N0;
2396   if (N1.isUndef())
2397     return N1;
2398
2399   // If the relocation model supports it, consider symbol offsets.
2400   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2401     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2402       // fold (sub Sym, c) -> Sym-c
2403       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2404         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2405                                     GA->getOffset() -
2406                                         (uint64_t)N1C->getSExtValue());
2407       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2408       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2409         if (GA->getGlobal() == GB->getGlobal())
2410           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2411                                  DL, VT);
2412     }
2413
2414   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2415   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2416     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2417     if (TN->getVT() == MVT::i1) {
2418       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2419                                  DAG.getConstant(1, DL, VT));
2420       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2421     }
2422   }
2423
2424   return SDValue();
2425 }
2426
2427 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2428   SDValue N0 = N->getOperand(0);
2429   SDValue N1 = N->getOperand(1);
2430   EVT VT = N0.getValueType();
2431   SDLoc DL(N);
2432
2433   // If the flag result is dead, turn this into an SUB.
2434   if (!N->hasAnyUseOfValue(1))
2435     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2436                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2437
2438   // fold (subc x, x) -> 0 + no borrow
2439   if (N0 == N1)
2440     return CombineTo(N, DAG.getConstant(0, DL, VT),
2441                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2442
2443   // fold (subc x, 0) -> x + no borrow
2444   if (isNullConstant(N1))
2445     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2446
2447   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2448   if (isAllOnesConstant(N0))
2449     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2450                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2451
2452   return SDValue();
2453 }
2454
2455 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2456   SDValue N0 = N->getOperand(0);
2457   SDValue N1 = N->getOperand(1);
2458   EVT VT = N0.getValueType();
2459   if (VT.isVector())
2460     return SDValue();
2461
2462   EVT CarryVT = N->getValueType(1);
2463   SDLoc DL(N);
2464
2465   // If the flag result is dead, turn this into an SUB.
2466   if (!N->hasAnyUseOfValue(1))
2467     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2468                      DAG.getUNDEF(CarryVT));
2469
2470   // fold (usubo x, x) -> 0 + no borrow
2471   if (N0 == N1)
2472     return CombineTo(N, DAG.getConstant(0, DL, VT),
2473                      DAG.getConstant(0, DL, CarryVT));
2474
2475   // fold (usubo x, 0) -> x + no borrow
2476   if (isNullConstant(N1))
2477     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2478
2479   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2480   if (isAllOnesConstant(N0))
2481     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2482                      DAG.getConstant(0, DL, CarryVT));
2483
2484   return SDValue();
2485 }
2486
2487 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2488   SDValue N0 = N->getOperand(0);
2489   SDValue N1 = N->getOperand(1);
2490   SDValue CarryIn = N->getOperand(2);
2491
2492   // fold (sube x, y, false) -> (subc x, y)
2493   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2494     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2495
2496   return SDValue();
2497 }
2498
2499 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2500   SDValue N0 = N->getOperand(0);
2501   SDValue N1 = N->getOperand(1);
2502   SDValue CarryIn = N->getOperand(2);
2503
2504   // fold (subcarry x, y, false) -> (usubo x, y)
2505   if (isNullConstant(CarryIn))
2506     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2507
2508   return SDValue();
2509 }
2510
2511 SDValue DAGCombiner::visitMUL(SDNode *N) {
2512   SDValue N0 = N->getOperand(0);
2513   SDValue N1 = N->getOperand(1);
2514   EVT VT = N0.getValueType();
2515
2516   // fold (mul x, undef) -> 0
2517   if (N0.isUndef() || N1.isUndef())
2518     return DAG.getConstant(0, SDLoc(N), VT);
2519
2520   bool N0IsConst = false;
2521   bool N1IsConst = false;
2522   bool N1IsOpaqueConst = false;
2523   bool N0IsOpaqueConst = false;
2524   APInt ConstValue0, ConstValue1;
2525   // fold vector ops
2526   if (VT.isVector()) {
2527     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2528       return FoldedVOp;
2529
2530     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2531     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2532   } else {
2533     N0IsConst = isa<ConstantSDNode>(N0);
2534     if (N0IsConst) {
2535       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2536       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2537     }
2538     N1IsConst = isa<ConstantSDNode>(N1);
2539     if (N1IsConst) {
2540       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2541       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2542     }
2543   }
2544
2545   // fold (mul c1, c2) -> c1*c2
2546   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2547     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2548                                       N0.getNode(), N1.getNode());
2549
2550   // canonicalize constant to RHS (vector doesn't have to splat)
2551   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2552      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2553     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2554   // fold (mul x, 0) -> 0
2555   if (N1IsConst && ConstValue1.isNullValue())
2556     return N1;
2557   // We require a splat of the entire scalar bit width for non-contiguous
2558   // bit patterns.
2559   bool IsFullSplat =
2560     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2561   // fold (mul x, 1) -> x
2562   if (N1IsConst && ConstValue1.isOneValue() && IsFullSplat)
2563     return N0;
2564
2565   if (SDValue NewSel = foldBinOpIntoSelect(N))
2566     return NewSel;
2567
2568   // fold (mul x, -1) -> 0-x
2569   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2570     SDLoc DL(N);
2571     return DAG.getNode(ISD::SUB, DL, VT,
2572                        DAG.getConstant(0, DL, VT), N0);
2573   }
2574   // fold (mul x, (1 << c)) -> x << c
2575   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2576       IsFullSplat) {
2577     SDLoc DL(N);
2578     return DAG.getNode(ISD::SHL, DL, VT, N0,
2579                        DAG.getConstant(ConstValue1.logBase2(), DL,
2580                                        getShiftAmountTy(N0.getValueType())));
2581   }
2582   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2583   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2584       IsFullSplat) {
2585     unsigned Log2Val = (-ConstValue1).logBase2();
2586     SDLoc DL(N);
2587     // FIXME: If the input is something that is easily negated (e.g. a
2588     // single-use add), we should put the negate there.
2589     return DAG.getNode(ISD::SUB, DL, VT,
2590                        DAG.getConstant(0, DL, VT),
2591                        DAG.getNode(ISD::SHL, DL, VT, N0,
2592                             DAG.getConstant(Log2Val, DL,
2593                                       getShiftAmountTy(N0.getValueType()))));
2594   }
2595
2596   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2597   if (N0.getOpcode() == ISD::SHL &&
2598       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2599       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2600     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2601     if (isConstantOrConstantVector(C3))
2602       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2603   }
2604
2605   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2606   // use.
2607   {
2608     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2609
2610     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2611     if (N0.getOpcode() == ISD::SHL &&
2612         isConstantOrConstantVector(N0.getOperand(1)) &&
2613         N0.getNode()->hasOneUse()) {
2614       Sh = N0; Y = N1;
2615     } else if (N1.getOpcode() == ISD::SHL &&
2616                isConstantOrConstantVector(N1.getOperand(1)) &&
2617                N1.getNode()->hasOneUse()) {
2618       Sh = N1; Y = N0;
2619     }
2620
2621     if (Sh.getNode()) {
2622       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2623       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2624     }
2625   }
2626
2627   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2628   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2629       N0.getOpcode() == ISD::ADD &&
2630       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2631       isMulAddWithConstProfitable(N, N0, N1))
2632       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2633                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2634                                      N0.getOperand(0), N1),
2635                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2636                                      N0.getOperand(1), N1));
2637
2638   // reassociate mul
2639   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2640     return RMUL;
2641
2642   return SDValue();
2643 }
2644
2645 /// Return true if divmod libcall is available.
2646 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2647                                      const TargetLowering &TLI) {
2648   RTLIB::Libcall LC;
2649   EVT NodeType = Node->getValueType(0);
2650   if (!NodeType.isSimple())
2651     return false;
2652   switch (NodeType.getSimpleVT().SimpleTy) {
2653   default: return false; // No libcall for vector types.
2654   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2655   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2656   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2657   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2658   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2659   }
2660
2661   return TLI.getLibcallName(LC) != nullptr;
2662 }
2663
2664 /// Issue divrem if both quotient and remainder are needed.
2665 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2666   if (Node->use_empty())
2667     return SDValue(); // This is a dead node, leave it alone.
2668
2669   unsigned Opcode = Node->getOpcode();
2670   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2671   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2672
2673   // DivMod lib calls can still work on non-legal types if using lib-calls.
2674   EVT VT = Node->getValueType(0);
2675   if (VT.isVector() || !VT.isInteger())
2676     return SDValue();
2677
2678   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2679     return SDValue();
2680
2681   // If DIVREM is going to get expanded into a libcall,
2682   // but there is no libcall available, then don't combine.
2683   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2684       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2685     return SDValue();
2686
2687   // If div is legal, it's better to do the normal expansion
2688   unsigned OtherOpcode = 0;
2689   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2690     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2691     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2692       return SDValue();
2693   } else {
2694     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2695     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2696       return SDValue();
2697   }
2698
2699   SDValue Op0 = Node->getOperand(0);
2700   SDValue Op1 = Node->getOperand(1);
2701   SDValue combined;
2702   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2703          UE = Op0.getNode()->use_end(); UI != UE;) {
2704     SDNode *User = *UI++;
2705     if (User == Node || User->use_empty())
2706       continue;
2707     // Convert the other matching node(s), too;
2708     // otherwise, the DIVREM may get target-legalized into something
2709     // target-specific that we won't be able to recognize.
2710     unsigned UserOpc = User->getOpcode();
2711     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2712         User->getOperand(0) == Op0 &&
2713         User->getOperand(1) == Op1) {
2714       if (!combined) {
2715         if (UserOpc == OtherOpcode) {
2716           SDVTList VTs = DAG.getVTList(VT, VT);
2717           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2718         } else if (UserOpc == DivRemOpc) {
2719           combined = SDValue(User, 0);
2720         } else {
2721           assert(UserOpc == Opcode);
2722           continue;
2723         }
2724       }
2725       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2726         CombineTo(User, combined);
2727       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2728         CombineTo(User, combined.getValue(1));
2729     }
2730   }
2731   return combined;
2732 }
2733
2734 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2735   SDValue N0 = N->getOperand(0);
2736   SDValue N1 = N->getOperand(1);
2737   EVT VT = N->getValueType(0);
2738   SDLoc DL(N);
2739
2740   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2741     return DAG.getUNDEF(VT);
2742
2743   // undef / X -> 0
2744   // undef % X -> 0
2745   if (N0.isUndef())
2746     return DAG.getConstant(0, DL, VT);
2747
2748   return SDValue();
2749 }
2750
2751 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2752   SDValue N0 = N->getOperand(0);
2753   SDValue N1 = N->getOperand(1);
2754   EVT VT = N->getValueType(0);
2755
2756   // fold vector ops
2757   if (VT.isVector())
2758     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2759       return FoldedVOp;
2760
2761   SDLoc DL(N);
2762
2763   // fold (sdiv c1, c2) -> c1/c2
2764   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2765   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2766   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2767     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2768   // fold (sdiv X, 1) -> X
2769   if (N1C && N1C->isOne())
2770     return N0;
2771   // fold (sdiv X, -1) -> 0-X
2772   if (N1C && N1C->isAllOnesValue())
2773     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2774
2775   if (SDValue V = simplifyDivRem(N, DAG))
2776     return V;
2777
2778   if (SDValue NewSel = foldBinOpIntoSelect(N))
2779     return NewSel;
2780
2781   // If we know the sign bits of both operands are zero, strength reduce to a
2782   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2783   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2784     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2785
2786   // fold (sdiv X, pow2) -> simple ops after legalize
2787   // FIXME: We check for the exact bit here because the generic lowering gives
2788   // better results in that case. The target-specific lowering should learn how
2789   // to handle exact sdivs efficiently.
2790   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2791       !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2792                                     (-N1C->getAPIntValue()).isPowerOf2())) {
2793     // Target-specific implementation of sdiv x, pow2.
2794     if (SDValue Res = BuildSDIVPow2(N))
2795       return Res;
2796
2797     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2798
2799     // Splat the sign bit into the register
2800     SDValue SGN =
2801         DAG.getNode(ISD::SRA, DL, VT, N0,
2802                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2803                                     getShiftAmountTy(N0.getValueType())));
2804     AddToWorklist(SGN.getNode());
2805
2806     // Add (N0 < 0) ? abs2 - 1 : 0;
2807     SDValue SRL =
2808         DAG.getNode(ISD::SRL, DL, VT, SGN,
2809                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2810                                     getShiftAmountTy(SGN.getValueType())));
2811     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2812     AddToWorklist(SRL.getNode());
2813     AddToWorklist(ADD.getNode());    // Divide by pow2
2814     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2815                   DAG.getConstant(lg2, DL,
2816                                   getShiftAmountTy(ADD.getValueType())));
2817
2818     // If we're dividing by a positive value, we're done.  Otherwise, we must
2819     // negate the result.
2820     if (N1C->getAPIntValue().isNonNegative())
2821       return SRA;
2822
2823     AddToWorklist(SRA.getNode());
2824     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2825   }
2826
2827   // If integer divide is expensive and we satisfy the requirements, emit an
2828   // alternate sequence.  Targets may check function attributes for size/speed
2829   // trade-offs.
2830   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2831   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2832     if (SDValue Op = BuildSDIV(N))
2833       return Op;
2834
2835   // sdiv, srem -> sdivrem
2836   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2837   // true.  Otherwise, we break the simplification logic in visitREM().
2838   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2839     if (SDValue DivRem = useDivRem(N))
2840         return DivRem;
2841
2842   return SDValue();
2843 }
2844
2845 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2846   SDValue N0 = N->getOperand(0);
2847   SDValue N1 = N->getOperand(1);
2848   EVT VT = N->getValueType(0);
2849
2850   // fold vector ops
2851   if (VT.isVector())
2852     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2853       return FoldedVOp;
2854
2855   SDLoc DL(N);
2856
2857   // fold (udiv c1, c2) -> c1/c2
2858   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2859   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2860   if (N0C && N1C)
2861     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2862                                                     N0C, N1C))
2863       return Folded;
2864
2865   if (SDValue V = simplifyDivRem(N, DAG))
2866     return V;
2867
2868   if (SDValue NewSel = foldBinOpIntoSelect(N))
2869     return NewSel;
2870
2871   // fold (udiv x, (1 << c)) -> x >>u c
2872   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2873       DAG.isKnownToBeAPowerOfTwo(N1)) {
2874     SDValue LogBase2 = BuildLogBase2(N1, DL);
2875     AddToWorklist(LogBase2.getNode());
2876
2877     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2878     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2879     AddToWorklist(Trunc.getNode());
2880     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2881   }
2882
2883   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2884   if (N1.getOpcode() == ISD::SHL) {
2885     SDValue N10 = N1.getOperand(0);
2886     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2887         DAG.isKnownToBeAPowerOfTwo(N10)) {
2888       SDValue LogBase2 = BuildLogBase2(N10, DL);
2889       AddToWorklist(LogBase2.getNode());
2890
2891       EVT ADDVT = N1.getOperand(1).getValueType();
2892       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2893       AddToWorklist(Trunc.getNode());
2894       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2895       AddToWorklist(Add.getNode());
2896       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2897     }
2898   }
2899
2900   // fold (udiv x, c) -> alternate
2901   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2902   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2903     if (SDValue Op = BuildUDIV(N))
2904       return Op;
2905
2906   // sdiv, srem -> sdivrem
2907   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2908   // true.  Otherwise, we break the simplification logic in visitREM().
2909   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2910     if (SDValue DivRem = useDivRem(N))
2911         return DivRem;
2912
2913   return SDValue();
2914 }
2915
2916 // handles ISD::SREM and ISD::UREM
2917 SDValue DAGCombiner::visitREM(SDNode *N) {
2918   unsigned Opcode = N->getOpcode();
2919   SDValue N0 = N->getOperand(0);
2920   SDValue N1 = N->getOperand(1);
2921   EVT VT = N->getValueType(0);
2922   bool isSigned = (Opcode == ISD::SREM);
2923   SDLoc DL(N);
2924
2925   // fold (rem c1, c2) -> c1%c2
2926   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2927   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2928   if (N0C && N1C)
2929     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2930       return Folded;
2931
2932   if (SDValue V = simplifyDivRem(N, DAG))
2933     return V;
2934
2935   if (SDValue NewSel = foldBinOpIntoSelect(N))
2936     return NewSel;
2937
2938   if (isSigned) {
2939     // If we know the sign bits of both operands are zero, strength reduce to a
2940     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2941     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2942       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2943   } else {
2944     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
2945     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2946       // fold (urem x, pow2) -> (and x, pow2-1)
2947       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2948       AddToWorklist(Add.getNode());
2949       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2950     }
2951     if (N1.getOpcode() == ISD::SHL &&
2952         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2953       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2954       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2955       AddToWorklist(Add.getNode());
2956       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2957     }
2958   }
2959
2960   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2961
2962   // If X/C can be simplified by the division-by-constant logic, lower
2963   // X%C to the equivalent of X-X/C*C.
2964   // To avoid mangling nodes, this simplification requires that the combine()
2965   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2966   // against this by skipping the simplification if isIntDivCheap().  When
2967   // div is not cheap, combine will not return a DIVREM.  Regardless,
2968   // checking cheapness here makes sense since the simplification results in
2969   // fatter code.
2970   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2971     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2972     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2973     AddToWorklist(Div.getNode());
2974     SDValue OptimizedDiv = combine(Div.getNode());
2975     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2976       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2977              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2978       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2979       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2980       AddToWorklist(Mul.getNode());
2981       return Sub;
2982     }
2983   }
2984
2985   // sdiv, srem -> sdivrem
2986   if (SDValue DivRem = useDivRem(N))
2987     return DivRem.getValue(1);
2988
2989   return SDValue();
2990 }
2991
2992 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2993   SDValue N0 = N->getOperand(0);
2994   SDValue N1 = N->getOperand(1);
2995   EVT VT = N->getValueType(0);
2996   SDLoc DL(N);
2997
2998   // fold (mulhs x, 0) -> 0
2999   if (isNullConstant(N1))
3000     return N1;
3001   // fold (mulhs x, 1) -> (sra x, size(x)-1)
3002   if (isOneConstant(N1)) {
3003     SDLoc DL(N);
3004     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3005                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3006                                        getShiftAmountTy(N0.getValueType())));
3007   }
3008   // fold (mulhs x, undef) -> 0
3009   if (N0.isUndef() || N1.isUndef())
3010     return DAG.getConstant(0, SDLoc(N), VT);
3011
3012   // If the type twice as wide is legal, transform the mulhs to a wider multiply
3013   // plus a shift.
3014   if (VT.isSimple() && !VT.isVector()) {
3015     MVT Simple = VT.getSimpleVT();
3016     unsigned SimpleSize = Simple.getSizeInBits();
3017     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3018     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3019       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3020       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3021       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3022       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3023             DAG.getConstant(SimpleSize, DL,
3024                             getShiftAmountTy(N1.getValueType())));
3025       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3026     }
3027   }
3028
3029   return SDValue();
3030 }
3031
3032 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3033   SDValue N0 = N->getOperand(0);
3034   SDValue N1 = N->getOperand(1);
3035   EVT VT = N->getValueType(0);
3036   SDLoc DL(N);
3037
3038   // fold (mulhu x, 0) -> 0
3039   if (isNullConstant(N1))
3040     return N1;
3041   // fold (mulhu x, 1) -> 0
3042   if (isOneConstant(N1))
3043     return DAG.getConstant(0, DL, N0.getValueType());
3044   // fold (mulhu x, undef) -> 0
3045   if (N0.isUndef() || N1.isUndef())
3046     return DAG.getConstant(0, DL, VT);
3047
3048   // If the type twice as wide is legal, transform the mulhu to a wider multiply
3049   // plus a shift.
3050   if (VT.isSimple() && !VT.isVector()) {
3051     MVT Simple = VT.getSimpleVT();
3052     unsigned SimpleSize = Simple.getSizeInBits();
3053     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3054     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3055       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3056       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3057       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3058       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3059             DAG.getConstant(SimpleSize, DL,
3060                             getShiftAmountTy(N1.getValueType())));
3061       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3062     }
3063   }
3064
3065   return SDValue();
3066 }
3067
3068 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3069 /// give the opcodes for the two computations that are being performed. Return
3070 /// true if a simplification was made.
3071 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3072                                                 unsigned HiOp) {
3073   // If the high half is not needed, just compute the low half.
3074   bool HiExists = N->hasAnyUseOfValue(1);
3075   if (!HiExists &&
3076       (!LegalOperations ||
3077        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3078     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3079     return CombineTo(N, Res, Res);
3080   }
3081
3082   // If the low half is not needed, just compute the high half.
3083   bool LoExists = N->hasAnyUseOfValue(0);
3084   if (!LoExists &&
3085       (!LegalOperations ||
3086        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3087     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3088     return CombineTo(N, Res, Res);
3089   }
3090
3091   // If both halves are used, return as it is.
3092   if (LoExists && HiExists)
3093     return SDValue();
3094
3095   // If the two computed results can be simplified separately, separate them.
3096   if (LoExists) {
3097     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3098     AddToWorklist(Lo.getNode());
3099     SDValue LoOpt = combine(Lo.getNode());
3100     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3101         (!LegalOperations ||
3102          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3103       return CombineTo(N, LoOpt, LoOpt);
3104   }
3105
3106   if (HiExists) {
3107     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3108     AddToWorklist(Hi.getNode());
3109     SDValue HiOpt = combine(Hi.getNode());
3110     if (HiOpt.getNode() && HiOpt != Hi &&
3111         (!LegalOperations ||
3112          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3113       return CombineTo(N, HiOpt, HiOpt);
3114   }
3115
3116   return SDValue();
3117 }
3118
3119 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3120   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3121     return Res;
3122
3123   EVT VT = N->getValueType(0);
3124   SDLoc DL(N);
3125
3126   // If the type is twice as wide is legal, transform the mulhu to a wider
3127   // multiply plus a shift.
3128   if (VT.isSimple() && !VT.isVector()) {
3129     MVT Simple = VT.getSimpleVT();
3130     unsigned SimpleSize = Simple.getSizeInBits();
3131     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3132     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3133       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3134       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3135       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3136       // Compute the high part as N1.
3137       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3138             DAG.getConstant(SimpleSize, DL,
3139                             getShiftAmountTy(Lo.getValueType())));
3140       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3141       // Compute the low part as N0.
3142       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3143       return CombineTo(N, Lo, Hi);
3144     }
3145   }
3146
3147   return SDValue();
3148 }
3149
3150 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3151   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3152     return Res;
3153
3154   EVT VT = N->getValueType(0);
3155   SDLoc DL(N);
3156
3157   // If the type is twice as wide is legal, transform the mulhu to a wider
3158   // multiply plus a shift.
3159   if (VT.isSimple() && !VT.isVector()) {
3160     MVT Simple = VT.getSimpleVT();
3161     unsigned SimpleSize = Simple.getSizeInBits();
3162     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3163     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3164       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3165       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3166       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3167       // Compute the high part as N1.
3168       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3169             DAG.getConstant(SimpleSize, DL,
3170                             getShiftAmountTy(Lo.getValueType())));
3171       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3172       // Compute the low part as N0.
3173       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3174       return CombineTo(N, Lo, Hi);
3175     }
3176   }
3177
3178   return SDValue();
3179 }
3180
3181 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3182   // (smulo x, 2) -> (saddo x, x)
3183   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3184     if (C2->getAPIntValue() == 2)
3185       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3186                          N->getOperand(0), N->getOperand(0));
3187
3188   return SDValue();
3189 }
3190
3191 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3192   // (umulo x, 2) -> (uaddo x, x)
3193   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3194     if (C2->getAPIntValue() == 2)
3195       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3196                          N->getOperand(0), N->getOperand(0));
3197
3198   return SDValue();
3199 }
3200
3201 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3202   SDValue N0 = N->getOperand(0);
3203   SDValue N1 = N->getOperand(1);
3204   EVT VT = N0.getValueType();
3205
3206   // fold vector ops
3207   if (VT.isVector())
3208     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3209       return FoldedVOp;
3210
3211   // fold (add c1, c2) -> c1+c2
3212   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3213   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3214   if (N0C && N1C)
3215     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3216
3217   // canonicalize constant to RHS
3218   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3219      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3220     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3221
3222   return SDValue();
3223 }
3224
3225 /// If this is a binary operator with two operands of the same opcode, try to
3226 /// simplify it.
3227 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3228   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3229   EVT VT = N0.getValueType();
3230   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3231
3232   // Bail early if none of these transforms apply.
3233   if (N0.getNumOperands() == 0) return SDValue();
3234
3235   // For each of OP in AND/OR/XOR:
3236   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3237   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3238   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3239   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3240   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3241   //
3242   // do not sink logical op inside of a vector extend, since it may combine
3243   // into a vsetcc.
3244   EVT Op0VT = N0.getOperand(0).getValueType();
3245   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3246        N0.getOpcode() == ISD::SIGN_EXTEND ||
3247        N0.getOpcode() == ISD::BSWAP ||
3248        // Avoid infinite looping with PromoteIntBinOp.
3249        (N0.getOpcode() == ISD::ANY_EXTEND &&
3250         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3251        (N0.getOpcode() == ISD::TRUNCATE &&
3252         (!TLI.isZExtFree(VT, Op0VT) ||
3253          !TLI.isTruncateFree(Op0VT, VT)) &&
3254         TLI.isTypeLegal(Op0VT))) &&
3255       !VT.isVector() &&
3256       Op0VT == N1.getOperand(0).getValueType() &&
3257       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3258     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3259                                  N0.getOperand(0).getValueType(),
3260                                  N0.getOperand(0), N1.getOperand(0));
3261     AddToWorklist(ORNode.getNode());
3262     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3263   }
3264
3265   // For each of OP in SHL/SRL/SRA/AND...
3266   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3267   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3268   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3269   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3270        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3271       N0.getOperand(1) == N1.getOperand(1)) {
3272     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3273                                  N0.getOperand(0).getValueType(),
3274                                  N0.getOperand(0), N1.getOperand(0));
3275     AddToWorklist(ORNode.getNode());
3276     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3277                        ORNode, N0.getOperand(1));
3278   }
3279
3280   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3281   // Only perform this optimization up until type legalization, before
3282   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3283   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3284   // we don't want to undo this promotion.
3285   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3286   // on scalars.
3287   if ((N0.getOpcode() == ISD::BITCAST ||
3288        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3289        Level <= AfterLegalizeTypes) {
3290     SDValue In0 = N0.getOperand(0);
3291     SDValue In1 = N1.getOperand(0);
3292     EVT In0Ty = In0.getValueType();
3293     EVT In1Ty = In1.getValueType();
3294     SDLoc DL(N);
3295     // If both incoming values are integers, and the original types are the
3296     // same.
3297     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3298       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3299       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3300       AddToWorklist(Op.getNode());
3301       return BC;
3302     }
3303   }
3304
3305   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3306   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3307   // If both shuffles use the same mask, and both shuffle within a single
3308   // vector, then it is worthwhile to move the swizzle after the operation.
3309   // The type-legalizer generates this pattern when loading illegal
3310   // vector types from memory. In many cases this allows additional shuffle
3311   // optimizations.
3312   // There are other cases where moving the shuffle after the xor/and/or
3313   // is profitable even if shuffles don't perform a swizzle.
3314   // If both shuffles use the same mask, and both shuffles have the same first
3315   // or second operand, then it might still be profitable to move the shuffle
3316   // after the xor/and/or operation.
3317   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3318     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3319     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3320
3321     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3322            "Inputs to shuffles are not the same type");
3323
3324     // Check that both shuffles use the same mask. The masks are known to be of
3325     // the same length because the result vector type is the same.
3326     // Check also that shuffles have only one use to avoid introducing extra
3327     // instructions.
3328     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3329         SVN0->getMask().equals(SVN1->getMask())) {
3330       SDValue ShOp = N0->getOperand(1);
3331
3332       // Don't try to fold this node if it requires introducing a
3333       // build vector of all zeros that might be illegal at this stage.
3334       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3335         if (!LegalTypes)
3336           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3337         else
3338           ShOp = SDValue();
3339       }
3340
3341       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3342       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3343       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3344       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3345         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3346                                       N0->getOperand(0), N1->getOperand(0));
3347         AddToWorklist(NewNode.getNode());
3348         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3349                                     SVN0->getMask());
3350       }
3351
3352       // Don't try to fold this node if it requires introducing a
3353       // build vector of all zeros that might be illegal at this stage.
3354       ShOp = N0->getOperand(0);
3355       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3356         if (!LegalTypes)
3357           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3358         else
3359           ShOp = SDValue();
3360       }
3361
3362       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3363       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3364       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3365       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3366         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3367                                       N0->getOperand(1), N1->getOperand(1));
3368         AddToWorklist(NewNode.getNode());
3369         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3370                                     SVN0->getMask());
3371       }
3372     }
3373   }
3374
3375   return SDValue();
3376 }
3377
3378 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3379 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3380                                        const SDLoc &DL) {
3381   SDValue LL, LR, RL, RR, N0CC, N1CC;
3382   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3383       !isSetCCEquivalent(N1, RL, RR, N1CC))
3384     return SDValue();
3385
3386   assert(N0.getValueType() == N1.getValueType() &&
3387          "Unexpected operand types for bitwise logic op");
3388   assert(LL.getValueType() == LR.getValueType() &&
3389          RL.getValueType() == RR.getValueType() &&
3390          "Unexpected operand types for setcc");
3391
3392   // If we're here post-legalization or the logic op type is not i1, the logic
3393   // op type must match a setcc result type. Also, all folds require new
3394   // operations on the left and right operands, so those types must match.
3395   EVT VT = N0.getValueType();
3396   EVT OpVT = LL.getValueType();
3397   if (LegalOperations || VT != MVT::i1)
3398     if (VT != getSetCCResultType(OpVT))
3399       return SDValue();
3400   if (OpVT != RL.getValueType())
3401     return SDValue();
3402
3403   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3404   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3405   bool IsInteger = OpVT.isInteger();
3406   if (LR == RR && CC0 == CC1 && IsInteger) {
3407     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3408     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3409
3410     // All bits clear?
3411     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3412     // All sign bits clear?
3413     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3414     // Any bits set?
3415     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3416     // Any sign bits set?
3417     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3418
3419     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3420     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3421     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3422     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3423     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3424       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3425       AddToWorklist(Or.getNode());
3426       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3427     }
3428
3429     // All bits set?
3430     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3431     // All sign bits set?
3432     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3433     // Any bits clear?
3434     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3435     // Any sign bits clear?
3436     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3437
3438     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3439     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3440     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3441     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3442     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3443       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3444       AddToWorklist(And.getNode());
3445       return DAG.getSetCC(DL, VT, And, LR, CC1);
3446     }
3447   }
3448
3449   // TODO: What is the 'or' equivalent of this fold?
3450   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3451   if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3452       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3453        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3454     SDValue One = DAG.getConstant(1, DL, OpVT);
3455     SDValue Two = DAG.getConstant(2, DL, OpVT);
3456     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3457     AddToWorklist(Add.getNode());
3458     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3459   }
3460
3461   // Try more general transforms if the predicates match and the only user of
3462   // the compares is the 'and' or 'or'.
3463   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3464       N0.hasOneUse() && N1.hasOneUse()) {
3465     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3466     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3467     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3468       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3469       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3470       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3471       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3472       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3473     }
3474   }
3475
3476   // Canonicalize equivalent operands to LL == RL.
3477   if (LL == RR && LR == RL) {
3478     CC1 = ISD::getSetCCSwappedOperands(CC1);
3479     std::swap(RL, RR);
3480   }
3481
3482   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3483   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3484   if (LL == RL && LR == RR) {
3485     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3486                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3487     if (NewCC != ISD::SETCC_INVALID &&
3488         (!LegalOperations ||
3489          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3490           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3491       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3492   }
3493
3494   return SDValue();
3495 }
3496
3497 /// This contains all DAGCombine rules which reduce two values combined by
3498 /// an And operation to a single value. This makes them reusable in the context
3499 /// of visitSELECT(). Rules involving constants are not included as
3500 /// visitSELECT() already handles those cases.
3501 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3502   EVT VT = N1.getValueType();
3503   SDLoc DL(N);
3504
3505   // fold (and x, undef) -> 0
3506   if (N0.isUndef() || N1.isUndef())
3507     return DAG.getConstant(0, DL, VT);
3508
3509   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3510     return V;
3511
3512   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3513       VT.getSizeInBits() <= 64) {
3514     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3515       APInt ADDC = ADDI->getAPIntValue();
3516       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3517         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3518         // immediate for an add, but it is legal if its top c2 bits are set,
3519         // transform the ADD so the immediate doesn't need to be materialized
3520         // in a register.
3521         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3522           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3523                                              SRLI->getZExtValue());
3524           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3525             ADDC |= Mask;
3526             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3527               SDLoc DL0(N0);
3528               SDValue NewAdd =
3529                 DAG.getNode(ISD::ADD, DL0, VT,
3530                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3531               CombineTo(N0.getNode(), NewAdd);
3532               // Return N so it doesn't get rechecked!
3533               return SDValue(N, 0);
3534             }
3535           }
3536         }
3537       }
3538     }
3539   }
3540
3541   // Reduce bit extract of low half of an integer to the narrower type.
3542   // (and (srl i64:x, K), KMask) ->
3543   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3544   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3545     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3546       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3547         unsigned Size = VT.getSizeInBits();
3548         const APInt &AndMask = CAnd->getAPIntValue();
3549         unsigned ShiftBits = CShift->getZExtValue();
3550
3551         // Bail out, this node will probably disappear anyway.
3552         if (ShiftBits == 0)
3553           return SDValue();
3554
3555         unsigned MaskBits = AndMask.countTrailingOnes();
3556         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3557
3558         if (AndMask.isMask() &&
3559             // Required bits must not span the two halves of the integer and
3560             // must fit in the half size type.
3561             (ShiftBits + MaskBits <= Size / 2) &&
3562             TLI.isNarrowingProfitable(VT, HalfVT) &&
3563             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3564             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3565             TLI.isTruncateFree(VT, HalfVT) &&
3566             TLI.isZExtFree(HalfVT, VT)) {
3567           // The isNarrowingProfitable is to avoid regressions on PPC and
3568           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3569           // on downstream users of this. Those patterns could probably be
3570           // extended to handle extensions mixed in.
3571
3572           SDValue SL(N0);
3573           assert(MaskBits <= Size);
3574
3575           // Extracting the highest bit of the low half.
3576           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3577           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3578                                       N0.getOperand(0));
3579
3580           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3581           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3582           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3583           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3584           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3585         }
3586       }
3587     }
3588   }
3589
3590   return SDValue();
3591 }
3592
3593 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3594                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3595                                    bool &NarrowLoad) {
3596   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3597
3598   if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3599     return false;
3600
3601   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3602   LoadedVT = LoadN->getMemoryVT();
3603
3604   if (ExtVT == LoadedVT &&
3605       (!LegalOperations ||
3606        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3607     // ZEXTLOAD will match without needing to change the size of the value being
3608     // loaded.
3609     NarrowLoad = false;
3610     return true;
3611   }
3612
3613   // Do not change the width of a volatile load.
3614   if (LoadN->isVolatile())
3615     return false;
3616
3617   // Do not generate loads of non-round integer types since these can
3618   // be expensive (and would be wrong if the type is not byte sized).
3619   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3620     return false;
3621
3622   if (LegalOperations &&
3623       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3624     return false;
3625
3626   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3627     return false;
3628
3629   NarrowLoad = true;
3630   return true;
3631 }
3632
3633 SDValue DAGCombiner::visitAND(SDNode *N) {
3634   SDValue N0 = N->getOperand(0);
3635   SDValue N1 = N->getOperand(1);
3636   EVT VT = N1.getValueType();
3637
3638   // x & x --> x
3639   if (N0 == N1)
3640     return N0;
3641
3642   // fold vector ops
3643   if (VT.isVector()) {
3644     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3645       return FoldedVOp;
3646
3647     // fold (and x, 0) -> 0, vector edition
3648     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3649       // do not return N0, because undef node may exist in N0
3650       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3651                              SDLoc(N), N0.getValueType());
3652     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3653       // do not return N1, because undef node may exist in N1
3654       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3655                              SDLoc(N), N1.getValueType());
3656
3657     // fold (and x, -1) -> x, vector edition
3658     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3659       return N1;
3660     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3661       return N0;
3662   }
3663
3664   // fold (and c1, c2) -> c1&c2
3665   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3666   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3667   if (N0C && N1C && !N1C->isOpaque())
3668     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3669   // canonicalize constant to RHS
3670   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3671      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3672     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3673   // fold (and x, -1) -> x
3674   if (isAllOnesConstant(N1))
3675     return N0;
3676   // if (and x, c) is known to be zero, return 0
3677   unsigned BitWidth = VT.getScalarSizeInBits();
3678   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3679                                    APInt::getAllOnesValue(BitWidth)))
3680     return DAG.getConstant(0, SDLoc(N), VT);
3681
3682   if (SDValue NewSel = foldBinOpIntoSelect(N))
3683     return NewSel;
3684
3685   // reassociate and
3686   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3687     return RAND;
3688   // fold (and (or x, C), D) -> D if (C & D) == D
3689   if (N1C && N0.getOpcode() == ISD::OR)
3690     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3691       if (N1C->getAPIntValue().isSubsetOf(ORI->getAPIntValue()))
3692         return N1;
3693   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3694   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3695     SDValue N0Op0 = N0.getOperand(0);
3696     APInt Mask = ~N1C->getAPIntValue();
3697     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3698     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3699       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3700                                  N0.getValueType(), N0Op0);
3701
3702       // Replace uses of the AND with uses of the Zero extend node.
3703       CombineTo(N, Zext);
3704
3705       // We actually want to replace all uses of the any_extend with the
3706       // zero_extend, to avoid duplicating things.  This will later cause this
3707       // AND to be folded.
3708       CombineTo(N0.getNode(), Zext);
3709       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3710     }
3711   }
3712   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3713   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3714   // already be zero by virtue of the width of the base type of the load.
3715   //
3716   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3717   // more cases.
3718   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3719        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3720        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3721        N0.getOperand(0).getResNo() == 0) ||
3722       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3723     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3724                                          N0 : N0.getOperand(0) );
3725
3726     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3727     // This can be a pure constant or a vector splat, in which case we treat the
3728     // vector as a scalar and use the splat value.
3729     APInt Constant = APInt::getNullValue(1);
3730     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3731       Constant = C->getAPIntValue();
3732     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3733       APInt SplatValue, SplatUndef;
3734       unsigned SplatBitSize;
3735       bool HasAnyUndefs;
3736       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3737                                              SplatBitSize, HasAnyUndefs);
3738       if (IsSplat) {
3739         // Undef bits can contribute to a possible optimisation if set, so
3740         // set them.
3741         SplatValue |= SplatUndef;
3742
3743         // The splat value may be something like "0x00FFFFFF", which means 0 for
3744         // the first vector value and FF for the rest, repeating. We need a mask
3745         // that will apply equally to all members of the vector, so AND all the
3746         // lanes of the constant together.
3747         EVT VT = Vector->getValueType(0);
3748         unsigned BitWidth = VT.getScalarSizeInBits();
3749
3750         // If the splat value has been compressed to a bitlength lower
3751         // than the size of the vector lane, we need to re-expand it to
3752         // the lane size.
3753         if (BitWidth > SplatBitSize)
3754           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3755                SplatBitSize < BitWidth;
3756                SplatBitSize = SplatBitSize * 2)
3757             SplatValue |= SplatValue.shl(SplatBitSize);
3758
3759         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3760         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3761         if (SplatBitSize % BitWidth == 0) {
3762           Constant = APInt::getAllOnesValue(BitWidth);
3763           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3764             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3765         }
3766       }
3767     }
3768
3769     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3770     // actually legal and isn't going to get expanded, else this is a false
3771     // optimisation.
3772     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3773                                                     Load->getValueType(0),
3774                                                     Load->getMemoryVT());
3775
3776     // Resize the constant to the same size as the original memory access before
3777     // extension. If it is still the AllOnesValue then this AND is completely
3778     // unneeded.
3779     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3780
3781     bool B;
3782     switch (Load->getExtensionType()) {
3783     default: B = false; break;
3784     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3785     case ISD::ZEXTLOAD:
3786     case ISD::NON_EXTLOAD: B = true; break;
3787     }
3788
3789     if (B && Constant.isAllOnesValue()) {
3790       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3791       // preserve semantics once we get rid of the AND.
3792       SDValue NewLoad(Load, 0);
3793
3794       // Fold the AND away. NewLoad may get replaced immediately.
3795       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3796
3797       if (Load->getExtensionType() == ISD::EXTLOAD) {
3798         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3799                               Load->getValueType(0), SDLoc(Load),
3800                               Load->getChain(), Load->getBasePtr(),
3801                               Load->getOffset(), Load->getMemoryVT(),
3802                               Load->getMemOperand());
3803         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3804         if (Load->getNumValues() == 3) {
3805           // PRE/POST_INC loads have 3 values.
3806           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3807                            NewLoad.getValue(2) };
3808           CombineTo(Load, To, 3, true);
3809         } else {
3810           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3811         }
3812       }
3813
3814       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3815     }
3816   }
3817
3818   // fold (and (load x), 255) -> (zextload x, i8)
3819   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3820   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3821   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3822                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3823                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3824     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3825     LoadSDNode *LN0 = HasAnyExt
3826       ? cast<LoadSDNode>(N0.getOperand(0))
3827       : cast<LoadSDNode>(N0);
3828     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3829         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3830       auto NarrowLoad = false;
3831       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3832       EVT ExtVT, LoadedVT;
3833       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3834                            NarrowLoad)) {
3835         if (!NarrowLoad) {
3836           SDValue NewLoad =
3837             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3838                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3839                            LN0->getMemOperand());
3840           AddToWorklist(N);
3841           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3842           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3843         } else {
3844           EVT PtrType = LN0->getOperand(1).getValueType();
3845
3846           unsigned Alignment = LN0->getAlignment();
3847           SDValue NewPtr = LN0->getBasePtr();
3848
3849           // For big endian targets, we need to add an offset to the pointer
3850           // to load the correct bytes.  For little endian systems, we merely
3851           // need to read fewer bytes from the same pointer.
3852           if (DAG.getDataLayout().isBigEndian()) {
3853             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3854             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3855             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3856             SDLoc DL(LN0);
3857             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3858                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3859             Alignment = MinAlign(Alignment, PtrOff);
3860           }
3861
3862           AddToWorklist(NewPtr.getNode());
3863
3864           SDValue Load = DAG.getExtLoad(
3865               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3866               LN0->getPointerInfo(), ExtVT, Alignment,
3867               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3868           AddToWorklist(N);
3869           CombineTo(LN0, Load, Load.getValue(1));
3870           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3871         }
3872       }
3873     }
3874   }
3875
3876   if (SDValue Combined = visitANDLike(N0, N1, N))
3877     return Combined;
3878
3879   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3880   if (N0.getOpcode() == N1.getOpcode())
3881     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3882       return Tmp;
3883
3884   // Masking the negated extension of a boolean is just the zero-extended
3885   // boolean:
3886   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3887   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3888   //
3889   // Note: the SimplifyDemandedBits fold below can make an information-losing
3890   // transform, and then we have no way to find this better fold.
3891   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3892     if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
3893       SDValue SubRHS = N0.getOperand(1);
3894       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3895           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3896         return SubRHS;
3897       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3898           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3899         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3900     }
3901   }
3902
3903   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3904   // fold (and (sra)) -> (and (srl)) when possible.
3905   if (SimplifyDemandedBits(SDValue(N, 0)))
3906     return SDValue(N, 0);
3907
3908   // fold (zext_inreg (extload x)) -> (zextload x)
3909   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3910     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3911     EVT MemVT = LN0->getMemoryVT();
3912     // If we zero all the possible extended bits, then we can turn this into
3913     // a zextload if we are running before legalize or the operation is legal.
3914     unsigned BitWidth = N1.getScalarValueSizeInBits();
3915     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3916                            BitWidth - MemVT.getScalarSizeInBits())) &&
3917         ((!LegalOperations && !LN0->isVolatile()) ||
3918          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3919       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3920                                        LN0->getChain(), LN0->getBasePtr(),
3921                                        MemVT, LN0->getMemOperand());
3922       AddToWorklist(N);
3923       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3924       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3925     }
3926   }
3927   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3928   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3929       N0.hasOneUse()) {
3930     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3931     EVT MemVT = LN0->getMemoryVT();
3932     // If we zero all the possible extended bits, then we can turn this into
3933     // a zextload if we are running before legalize or the operation is legal.
3934     unsigned BitWidth = N1.getScalarValueSizeInBits();
3935     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3936                            BitWidth - MemVT.getScalarSizeInBits())) &&
3937         ((!LegalOperations && !LN0->isVolatile()) ||
3938          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3939       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3940                                        LN0->getChain(), LN0->getBasePtr(),
3941                                        MemVT, LN0->getMemOperand());
3942       AddToWorklist(N);
3943       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3944       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3945     }
3946   }
3947   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3948   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3949     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3950                                            N0.getOperand(1), false))
3951       return BSwap;
3952   }
3953
3954   return SDValue();
3955 }
3956
3957 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3958 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3959                                         bool DemandHighBits) {
3960   if (!LegalOperations)
3961     return SDValue();
3962
3963   EVT VT = N->getValueType(0);
3964   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3965     return SDValue();
3966   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
3967     return SDValue();
3968
3969   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3970   bool LookPassAnd0 = false;
3971   bool LookPassAnd1 = false;
3972   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3973       std::swap(N0, N1);
3974   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3975       std::swap(N0, N1);
3976   if (N0.getOpcode() == ISD::AND) {
3977     if (!N0.getNode()->hasOneUse())
3978       return SDValue();
3979     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3980     if (!N01C || N01C->getZExtValue() != 0xFF00)
3981       return SDValue();
3982     N0 = N0.getOperand(0);
3983     LookPassAnd0 = true;
3984   }
3985
3986   if (N1.getOpcode() == ISD::AND) {
3987     if (!N1.getNode()->hasOneUse())
3988       return SDValue();
3989     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3990     if (!N11C || N11C->getZExtValue() != 0xFF)
3991       return SDValue();
3992     N1 = N1.getOperand(0);
3993     LookPassAnd1 = true;
3994   }
3995
3996   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3997     std::swap(N0, N1);
3998   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3999     return SDValue();
4000   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4001     return SDValue();
4002
4003   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4004   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4005   if (!N01C || !N11C)
4006     return SDValue();
4007   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4008     return SDValue();
4009
4010   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4011   SDValue N00 = N0->getOperand(0);
4012   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4013     if (!N00.getNode()->hasOneUse())
4014       return SDValue();
4015     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4016     if (!N001C || N001C->getZExtValue() != 0xFF)
4017       return SDValue();
4018     N00 = N00.getOperand(0);
4019     LookPassAnd0 = true;
4020   }
4021
4022   SDValue N10 = N1->getOperand(0);
4023   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4024     if (!N10.getNode()->hasOneUse())
4025       return SDValue();
4026     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4027     if (!N101C || N101C->getZExtValue() != 0xFF00)
4028       return SDValue();
4029     N10 = N10.getOperand(0);
4030     LookPassAnd1 = true;
4031   }
4032
4033   if (N00 != N10)
4034     return SDValue();
4035
4036   // Make sure everything beyond the low halfword gets set to zero since the SRL
4037   // 16 will clear the top bits.
4038   unsigned OpSizeInBits = VT.getSizeInBits();
4039   if (DemandHighBits && OpSizeInBits > 16) {
4040     // If the left-shift isn't masked out then the only way this is a bswap is
4041     // if all bits beyond the low 8 are 0. In that case the entire pattern
4042     // reduces to a left shift anyway: leave it for other parts of the combiner.
4043     if (!LookPassAnd0)
4044       return SDValue();
4045
4046     // However, if the right shift isn't masked out then it might be because
4047     // it's not needed. See if we can spot that too.
4048     if (!LookPassAnd1 &&
4049         !DAG.MaskedValueIsZero(
4050             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4051       return SDValue();
4052   }
4053
4054   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4055   if (OpSizeInBits > 16) {
4056     SDLoc DL(N);
4057     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4058                       DAG.getConstant(OpSizeInBits - 16, DL,
4059                                       getShiftAmountTy(VT)));
4060   }
4061   return Res;
4062 }
4063
4064 /// Return true if the specified node is an element that makes up a 32-bit
4065 /// packed halfword byteswap.
4066 /// ((x & 0x000000ff) << 8) |
4067 /// ((x & 0x0000ff00) >> 8) |
4068 /// ((x & 0x00ff0000) << 8) |
4069 /// ((x & 0xff000000) >> 8)
4070 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4071   if (!N.getNode()->hasOneUse())
4072     return false;
4073
4074   unsigned Opc = N.getOpcode();
4075   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4076     return false;
4077
4078   SDValue N0 = N.getOperand(0);
4079   unsigned Opc0 = N0.getOpcode();
4080   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4081     return false;
4082
4083   ConstantSDNode *N1C = nullptr;
4084   // SHL or SRL: look upstream for AND mask operand
4085   if (Opc == ISD::AND)
4086     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4087   else if (Opc0 == ISD::AND)
4088     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4089   if (!N1C)
4090     return false;
4091
4092   unsigned MaskByteOffset;
4093   switch (N1C->getZExtValue()) {
4094   default:
4095     return false;
4096   case 0xFF:       MaskByteOffset = 0; break;
4097   case 0xFF00:     MaskByteOffset = 1; break;
4098   case 0xFF0000:   MaskByteOffset = 2; break;
4099   case 0xFF000000: MaskByteOffset = 3; break;
4100   }
4101
4102   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4103   if (Opc == ISD::AND) {
4104     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4105       // (x >> 8) & 0xff
4106       // (x >> 8) & 0xff0000
4107       if (Opc0 != ISD::SRL)
4108         return false;
4109       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4110       if (!C || C->getZExtValue() != 8)
4111         return false;
4112     } else {
4113       // (x << 8) & 0xff00
4114       // (x << 8) & 0xff000000
4115       if (Opc0 != ISD::SHL)
4116         return false;
4117       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4118       if (!C || C->getZExtValue() != 8)
4119         return false;
4120     }
4121   } else if (Opc == ISD::SHL) {
4122     // (x & 0xff) << 8
4123     // (x & 0xff0000) << 8
4124     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4125       return false;
4126     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4127     if (!C || C->getZExtValue() != 8)
4128       return false;
4129   } else { // Opc == ISD::SRL
4130     // (x & 0xff00) >> 8
4131     // (x & 0xff000000) >> 8
4132     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4133       return false;
4134     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4135     if (!C || C->getZExtValue() != 8)
4136       return false;
4137   }
4138
4139   if (Parts[MaskByteOffset])
4140     return false;
4141
4142   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4143   return true;
4144 }
4145
4146 /// Match a 32-bit packed halfword bswap. That is
4147 /// ((x & 0x000000ff) << 8) |
4148 /// ((x & 0x0000ff00) >> 8) |
4149 /// ((x & 0x00ff0000) << 8) |
4150 /// ((x & 0xff000000) >> 8)
4151 /// => (rotl (bswap x), 16)
4152 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4153   if (!LegalOperations)
4154     return SDValue();
4155
4156   EVT VT = N->getValueType(0);
4157   if (VT != MVT::i32)
4158     return SDValue();
4159   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4160     return SDValue();
4161
4162   // Look for either
4163   // (or (or (and), (and)), (or (and), (and)))
4164   // (or (or (or (and), (and)), (and)), (and))
4165   if (N0.getOpcode() != ISD::OR)
4166     return SDValue();
4167   SDValue N00 = N0.getOperand(0);
4168   SDValue N01 = N0.getOperand(1);
4169   SDNode *Parts[4] = {};
4170
4171   if (N1.getOpcode() == ISD::OR &&
4172       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4173     // (or (or (and), (and)), (or (and), (and)))
4174     if (!isBSwapHWordElement(N00, Parts))
4175       return SDValue();
4176
4177     if (!isBSwapHWordElement(N01, Parts))
4178       return SDValue();
4179     SDValue N10 = N1.getOperand(0);
4180     if (!isBSwapHWordElement(N10, Parts))
4181       return SDValue();
4182     SDValue N11 = N1.getOperand(1);
4183     if (!isBSwapHWordElement(N11, Parts))
4184       return SDValue();
4185   } else {
4186     // (or (or (or (and), (and)), (and)), (and))
4187     if (!isBSwapHWordElement(N1, Parts))
4188       return SDValue();
4189     if (!isBSwapHWordElement(N01, Parts))
4190       return SDValue();
4191     if (N00.getOpcode() != ISD::OR)
4192       return SDValue();
4193     SDValue N000 = N00.getOperand(0);
4194     if (!isBSwapHWordElement(N000, Parts))
4195       return SDValue();
4196     SDValue N001 = N00.getOperand(1);
4197     if (!isBSwapHWordElement(N001, Parts))
4198       return SDValue();
4199   }
4200
4201   // Make sure the parts are all coming from the same node.
4202   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4203     return SDValue();
4204
4205   SDLoc DL(N);
4206   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4207                               SDValue(Parts[0], 0));
4208
4209   // Result of the bswap should be rotated by 16. If it's not legal, then
4210   // do  (x << 16) | (x >> 16).
4211   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4212   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4213     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4214   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4215     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4216   return DAG.getNode(ISD::OR, DL, VT,
4217                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4218                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4219 }
4220
4221 /// This contains all DAGCombine rules which reduce two values combined by
4222 /// an Or operation to a single value \see visitANDLike().
4223 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4224   EVT VT = N1.getValueType();
4225   SDLoc DL(N);
4226
4227   // fold (or x, undef) -> -1
4228   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4229     return DAG.getAllOnesConstant(DL, VT);
4230
4231   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4232     return V;
4233
4234   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4235   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4236       // Don't increase # computations.
4237       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4238     // We can only do this xform if we know that bits from X that are set in C2
4239     // but not in C1 are already zero.  Likewise for Y.
4240     if (const ConstantSDNode *N0O1C =
4241         getAsNonOpaqueConstant(N0.getOperand(1))) {
4242       if (const ConstantSDNode *N1O1C =
4243           getAsNonOpaqueConstant(N1.getOperand(1))) {
4244         // We can only do this xform if we know that bits from X that are set in
4245         // C2 but not in C1 are already zero.  Likewise for Y.
4246         const APInt &LHSMask = N0O1C->getAPIntValue();
4247         const APInt &RHSMask = N1O1C->getAPIntValue();
4248
4249         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4250             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4251           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4252                                   N0.getOperand(0), N1.getOperand(0));
4253           return DAG.getNode(ISD::AND, DL, VT, X,
4254                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4255         }
4256       }
4257     }
4258   }
4259
4260   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4261   if (N0.getOpcode() == ISD::AND &&
4262       N1.getOpcode() == ISD::AND &&
4263       N0.getOperand(0) == N1.getOperand(0) &&
4264       // Don't increase # computations.
4265       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4266     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4267                             N0.getOperand(1), N1.getOperand(1));
4268     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4269   }
4270
4271   return SDValue();
4272 }
4273
4274 SDValue DAGCombiner::visitOR(SDNode *N) {
4275   SDValue N0 = N->getOperand(0);
4276   SDValue N1 = N->getOperand(1);
4277   EVT VT = N1.getValueType();
4278
4279   // x | x --> x
4280   if (N0 == N1)
4281     return N0;
4282
4283   // fold vector ops
4284   if (VT.isVector()) {
4285     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4286       return FoldedVOp;
4287
4288     // fold (or x, 0) -> x, vector edition
4289     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4290       return N1;
4291     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4292       return N0;
4293
4294     // fold (or x, -1) -> -1, vector edition
4295     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4296       // do not return N0, because undef node may exist in N0
4297       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4298     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4299       // do not return N1, because undef node may exist in N1
4300       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4301
4302     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4303     // Do this only if the resulting shuffle is legal.
4304     if (isa<ShuffleVectorSDNode>(N0) &&
4305         isa<ShuffleVectorSDNode>(N1) &&
4306         // Avoid folding a node with illegal type.
4307         TLI.isTypeLegal(VT)) {
4308       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4309       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4310       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4311       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4312       // Ensure both shuffles have a zero input.
4313       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4314         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4315         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4316         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4317         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4318         bool CanFold = true;
4319         int NumElts = VT.getVectorNumElements();
4320         SmallVector<int, 4> Mask(NumElts);
4321
4322         for (int i = 0; i != NumElts; ++i) {
4323           int M0 = SV0->getMaskElt(i);
4324           int M1 = SV1->getMaskElt(i);
4325
4326           // Determine if either index is pointing to a zero vector.
4327           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4328           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4329
4330           // If one element is zero and the otherside is undef, keep undef.
4331           // This also handles the case that both are undef.
4332           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4333             Mask[i] = -1;
4334             continue;
4335           }
4336
4337           // Make sure only one of the elements is zero.
4338           if (M0Zero == M1Zero) {
4339             CanFold = false;
4340             break;
4341           }
4342
4343           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4344
4345           // We have a zero and non-zero element. If the non-zero came from
4346           // SV0 make the index a LHS index. If it came from SV1, make it
4347           // a RHS index. We need to mod by NumElts because we don't care
4348           // which operand it came from in the original shuffles.
4349           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4350         }
4351
4352         if (CanFold) {
4353           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4354           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4355
4356           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4357           if (!LegalMask) {
4358             std::swap(NewLHS, NewRHS);
4359             ShuffleVectorSDNode::commuteMask(Mask);
4360             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4361           }
4362
4363           if (LegalMask)
4364             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4365         }
4366       }
4367     }
4368   }
4369
4370   // fold (or c1, c2) -> c1|c2
4371   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4372   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4373   if (N0C && N1C && !N1C->isOpaque())
4374     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4375   // canonicalize constant to RHS
4376   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4377      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4378     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4379   // fold (or x, 0) -> x
4380   if (isNullConstant(N1))
4381     return N0;
4382   // fold (or x, -1) -> -1
4383   if (isAllOnesConstant(N1))
4384     return N1;
4385
4386   if (SDValue NewSel = foldBinOpIntoSelect(N))
4387     return NewSel;
4388
4389   // fold (or x, c) -> c iff (x & ~c) == 0
4390   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4391     return N1;
4392
4393   if (SDValue Combined = visitORLike(N0, N1, N))
4394     return Combined;
4395
4396   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4397   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4398     return BSwap;
4399   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4400     return BSwap;
4401
4402   // reassociate or
4403   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4404     return ROR;
4405
4406   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4407   // iff (c1 & c2) != 0.
4408   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4409     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4410       if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4411         if (SDValue COR =
4412                 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4413           return DAG.getNode(
4414               ISD::AND, SDLoc(N), VT,
4415               DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4416         return SDValue();
4417       }
4418     }
4419   }
4420
4421   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4422   if (N0.getOpcode() == N1.getOpcode())
4423     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4424       return Tmp;
4425
4426   // See if this is some rotate idiom.
4427   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4428     return SDValue(Rot, 0);
4429
4430   if (SDValue Load = MatchLoadCombine(N))
4431     return Load;
4432
4433   // Simplify the operands using demanded-bits information.
4434   if (SimplifyDemandedBits(SDValue(N, 0)))
4435     return SDValue(N, 0);
4436
4437   return SDValue();
4438 }
4439
4440 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4441 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4442   if (Op.getOpcode() == ISD::AND) {
4443     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4444       Mask = Op.getOperand(1);
4445       Op = Op.getOperand(0);
4446     } else {
4447       return false;
4448     }
4449   }
4450
4451   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4452     Shift = Op;
4453     return true;
4454   }
4455
4456   return false;
4457 }
4458
4459 // Return true if we can prove that, whenever Neg and Pos are both in the
4460 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4461 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4462 //
4463 //     (or (shift1 X, Neg), (shift2 X, Pos))
4464 //
4465 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4466 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4467 // to consider shift amounts with defined behavior.
4468 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4469   // If EltSize is a power of 2 then:
4470   //
4471   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4472   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4473   //
4474   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4475   // for the stronger condition:
4476   //
4477   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4478   //
4479   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4480   // we can just replace Neg with Neg' for the rest of the function.
4481   //
4482   // In other cases we check for the even stronger condition:
4483   //
4484   //     Neg == EltSize - Pos                                    [B]
4485   //
4486   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4487   // behavior if Pos == 0 (and consequently Neg == EltSize).
4488   //
4489   // We could actually use [A] whenever EltSize is a power of 2, but the
4490   // only extra cases that it would match are those uninteresting ones
4491   // where Neg and Pos are never in range at the same time.  E.g. for
4492   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4493   // as well as (sub 32, Pos), but:
4494   //
4495   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4496   //
4497   // always invokes undefined behavior for 32-bit X.
4498   //
4499   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4500   unsigned MaskLoBits = 0;
4501   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4502     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4503       if (NegC->getAPIntValue() == EltSize - 1) {
4504         Neg = Neg.getOperand(0);
4505         MaskLoBits = Log2_64(EltSize);
4506       }
4507     }
4508   }
4509
4510   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4511   if (Neg.getOpcode() != ISD::SUB)
4512     return false;
4513   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4514   if (!NegC)
4515     return false;
4516   SDValue NegOp1 = Neg.getOperand(1);
4517
4518   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4519   // Pos'.  The truncation is redundant for the purpose of the equality.
4520   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4521     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4522       if (PosC->getAPIntValue() == EltSize - 1)
4523         Pos = Pos.getOperand(0);
4524
4525   // The condition we need is now:
4526   //
4527   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4528   //
4529   // If NegOp1 == Pos then we need:
4530   //
4531   //              EltSize & Mask == NegC & Mask
4532   //
4533   // (because "x & Mask" is a truncation and distributes through subtraction).
4534   APInt Width;
4535   if (Pos == NegOp1)
4536     Width = NegC->getAPIntValue();
4537
4538   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4539   // Then the condition we want to prove becomes:
4540   //
4541   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4542   //
4543   // which, again because "x & Mask" is a truncation, becomes:
4544   //
4545   //                NegC & Mask == (EltSize - PosC) & Mask
4546   //             EltSize & Mask == (NegC + PosC) & Mask
4547   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4548     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4549       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4550     else
4551       return false;
4552   } else
4553     return false;
4554
4555   // Now we just need to check that EltSize & Mask == Width & Mask.
4556   if (MaskLoBits)
4557     // EltSize & Mask is 0 since Mask is EltSize - 1.
4558     return Width.getLoBits(MaskLoBits) == 0;
4559   return Width == EltSize;
4560 }
4561
4562 // A subroutine of MatchRotate used once we have found an OR of two opposite
4563 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4564 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4565 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4566 // Neg with outer conversions stripped away.
4567 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4568                                        SDValue Neg, SDValue InnerPos,
4569                                        SDValue InnerNeg, unsigned PosOpcode,
4570                                        unsigned NegOpcode, const SDLoc &DL) {
4571   // fold (or (shl x, (*ext y)),
4572   //          (srl x, (*ext (sub 32, y)))) ->
4573   //   (rotl x, y) or (rotr x, (sub 32, y))
4574   //
4575   // fold (or (shl x, (*ext (sub 32, y))),
4576   //          (srl x, (*ext y))) ->
4577   //   (rotr x, y) or (rotl x, (sub 32, y))
4578   EVT VT = Shifted.getValueType();
4579   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4580     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4581     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4582                        HasPos ? Pos : Neg).getNode();
4583   }
4584
4585   return nullptr;
4586 }
4587
4588 // if Left + Right == Sum (constant or constant splat vector)
4589 static bool sumMatchConstant(SDValue Left, SDValue Right, unsigned Sum,
4590                              SelectionDAG &DAG, const SDLoc &DL) {
4591   EVT ShiftVT = Left.getValueType();
4592   if (ShiftVT != Right.getValueType()) return false;
4593
4594   SDValue ShiftSum = DAG.FoldConstantArithmetic(ISD::ADD, DL, ShiftVT,
4595                          Left.getNode(), Right.getNode());
4596   if (!ShiftSum) return false;
4597
4598   ConstantSDNode *CSum = isConstOrConstSplat(ShiftSum);
4599   return CSum && CSum->getZExtValue() == Sum;
4600 }
4601
4602 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4603 // idioms for rotate, and if the target supports rotation instructions, generate
4604 // a rot[lr].
4605 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4606   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4607   EVT VT = LHS.getValueType();
4608   if (!TLI.isTypeLegal(VT)) return nullptr;
4609
4610   // The target must have at least one rotate flavor.
4611   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4612   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4613   if (!HasROTL && !HasROTR) return nullptr;
4614
4615   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4616   SDValue LHSShift;   // The shift.
4617   SDValue LHSMask;    // AND value if any.
4618   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4619     return nullptr; // Not part of a rotate.
4620
4621   SDValue RHSShift;   // The shift.
4622   SDValue RHSMask;    // AND value if any.
4623   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4624     return nullptr; // Not part of a rotate.
4625
4626   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4627     return nullptr;   // Not shifting the same value.
4628
4629   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4630     return nullptr;   // Shifts must disagree.
4631
4632   // Canonicalize shl to left side in a shl/srl pair.
4633   if (RHSShift.getOpcode() == ISD::SHL) {
4634     std::swap(LHS, RHS);
4635     std::swap(LHSShift, RHSShift);
4636     std::swap(LHSMask, RHSMask);
4637   }
4638
4639   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4640   SDValue LHSShiftArg = LHSShift.getOperand(0);
4641   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4642   SDValue RHSShiftArg = RHSShift.getOperand(0);
4643   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4644
4645   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4646   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4647   if (sumMatchConstant(LHSShiftAmt, RHSShiftAmt, EltSizeInBits, DAG, DL)) {
4648     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4649                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4650
4651     // If there is an AND of either shifted operand, apply it to the result.
4652     if (LHSMask.getNode() || RHSMask.getNode()) {
4653       SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
4654       SDValue Mask = AllOnes;
4655
4656       if (LHSMask.getNode()) {
4657         SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
4658         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4659                            DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
4660       }
4661       if (RHSMask.getNode()) {
4662         SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
4663         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4664                            DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
4665       }
4666
4667       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4668     }
4669
4670     return Rot.getNode();
4671   }
4672
4673   // If there is a mask here, and we have a variable shift, we can't be sure
4674   // that we're masking out the right stuff.
4675   if (LHSMask.getNode() || RHSMask.getNode())
4676     return nullptr;
4677
4678   // If the shift amount is sign/zext/any-extended just peel it off.
4679   SDValue LExtOp0 = LHSShiftAmt;
4680   SDValue RExtOp0 = RHSShiftAmt;
4681   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4682        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4683        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4684        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4685       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4686        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4687        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4688        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4689     LExtOp0 = LHSShiftAmt.getOperand(0);
4690     RExtOp0 = RHSShiftAmt.getOperand(0);
4691   }
4692
4693   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4694                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4695   if (TryL)
4696     return TryL;
4697
4698   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4699                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4700   if (TryR)
4701     return TryR;
4702
4703   return nullptr;
4704 }
4705
4706 namespace {
4707 /// Represents known origin of an individual byte in load combine pattern. The
4708 /// value of the byte is either constant zero or comes from memory.
4709 struct ByteProvider {
4710   // For constant zero providers Load is set to nullptr. For memory providers
4711   // Load represents the node which loads the byte from memory.
4712   // ByteOffset is the offset of the byte in the value produced by the load.
4713   LoadSDNode *Load;
4714   unsigned ByteOffset;
4715
4716   ByteProvider() : Load(nullptr), ByteOffset(0) {}
4717
4718   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4719     return ByteProvider(Load, ByteOffset);
4720   }
4721   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4722
4723   bool isConstantZero() const { return !Load; }
4724   bool isMemory() const { return Load; }
4725
4726   bool operator==(const ByteProvider &Other) const {
4727     return Other.Load == Load && Other.ByteOffset == ByteOffset;
4728   }
4729
4730 private:
4731   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4732       : Load(Load), ByteOffset(ByteOffset) {}
4733 };
4734
4735 /// Recursively traverses the expression calculating the origin of the requested
4736 /// byte of the given value. Returns None if the provider can't be calculated.
4737 ///
4738 /// For all the values except the root of the expression verifies that the value
4739 /// has exactly one use and if it's not true return None. This way if the origin
4740 /// of the byte is returned it's guaranteed that the values which contribute to
4741 /// the byte are not used outside of this expression.
4742 ///
4743 /// Because the parts of the expression are not allowed to have more than one
4744 /// use this function iterates over trees, not DAGs. So it never visits the same
4745 /// node more than once.
4746 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4747                                                    unsigned Depth,
4748                                                    bool Root = false) {
4749   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4750   if (Depth == 10)
4751     return None;
4752
4753   if (!Root && !Op.hasOneUse())
4754     return None;
4755
4756   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4757   unsigned BitWidth = Op.getValueSizeInBits();
4758   if (BitWidth % 8 != 0)
4759     return None;
4760   unsigned ByteWidth = BitWidth / 8;
4761   assert(Index < ByteWidth && "invalid index requested");
4762   (void) ByteWidth;
4763
4764   switch (Op.getOpcode()) {
4765   case ISD::OR: {
4766     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4767     if (!LHS)
4768       return None;
4769     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4770     if (!RHS)
4771       return None;
4772
4773     if (LHS->isConstantZero())
4774       return RHS;
4775     if (RHS->isConstantZero())
4776       return LHS;
4777     return None;
4778   }
4779   case ISD::SHL: {
4780     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4781     if (!ShiftOp)
4782       return None;
4783
4784     uint64_t BitShift = ShiftOp->getZExtValue();
4785     if (BitShift % 8 != 0)
4786       return None;
4787     uint64_t ByteShift = BitShift / 8;
4788
4789     return Index < ByteShift
4790                ? ByteProvider::getConstantZero()
4791                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4792                                        Depth + 1);
4793   }
4794   case ISD::ANY_EXTEND:
4795   case ISD::SIGN_EXTEND:
4796   case ISD::ZERO_EXTEND: {
4797     SDValue NarrowOp = Op->getOperand(0);
4798     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4799     if (NarrowBitWidth % 8 != 0)
4800       return None;
4801     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4802
4803     if (Index >= NarrowByteWidth)
4804       return Op.getOpcode() == ISD::ZERO_EXTEND
4805                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4806                  : None;
4807     return calculateByteProvider(NarrowOp, Index, Depth + 1);
4808   }
4809   case ISD::BSWAP:
4810     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4811                                  Depth + 1);
4812   case ISD::LOAD: {
4813     auto L = cast<LoadSDNode>(Op.getNode());
4814     if (L->isVolatile() || L->isIndexed())
4815       return None;
4816
4817     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4818     if (NarrowBitWidth % 8 != 0)
4819       return None;
4820     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4821
4822     if (Index >= NarrowByteWidth)
4823       return L->getExtensionType() == ISD::ZEXTLOAD
4824                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4825                  : None;
4826     return ByteProvider::getMemory(L, Index);
4827   }
4828   }
4829
4830   return None;
4831 }
4832 } // namespace
4833
4834 /// Match a pattern where a wide type scalar value is loaded by several narrow
4835 /// loads and combined by shifts and ors. Fold it into a single load or a load
4836 /// and a BSWAP if the targets supports it.
4837 ///
4838 /// Assuming little endian target:
4839 ///  i8 *a = ...
4840 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4841 /// =>
4842 ///  i32 val = *((i32)a)
4843 ///
4844 ///  i8 *a = ...
4845 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4846 /// =>
4847 ///  i32 val = BSWAP(*((i32)a))
4848 ///
4849 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4850 /// interact well with the worklist mechanism. When a part of the pattern is
4851 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4852 /// but the root node of the pattern which triggers the load combine is not
4853 /// necessarily a direct user of the changed node. For example, once the address
4854 /// of t28 load is reassociated load combine won't be triggered:
4855 ///             t25: i32 = add t4, Constant:i32<2>
4856 ///           t26: i64 = sign_extend t25
4857 ///        t27: i64 = add t2, t26
4858 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4859 ///     t29: i32 = zero_extend t28
4860 ///   t32: i32 = shl t29, Constant:i8<8>
4861 /// t33: i32 = or t23, t32
4862 /// As a possible fix visitLoad can check if the load can be a part of a load
4863 /// combine pattern and add corresponding OR roots to the worklist.
4864 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4865   assert(N->getOpcode() == ISD::OR &&
4866          "Can only match load combining against OR nodes");
4867
4868   // Handles simple types only
4869   EVT VT = N->getValueType(0);
4870   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4871     return SDValue();
4872   unsigned ByteWidth = VT.getSizeInBits() / 8;
4873
4874   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4875   // Before legalize we can introduce too wide illegal loads which will be later
4876   // split into legal sized loads. This enables us to combine i64 load by i8
4877   // patterns to a couple of i32 loads on 32 bit targets.
4878   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4879     return SDValue();
4880
4881   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4882     unsigned BW, unsigned i) { return i; };
4883   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4884     unsigned BW, unsigned i) { return BW - i - 1; };
4885
4886   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4887   auto MemoryByteOffset = [&] (ByteProvider P) {
4888     assert(P.isMemory() && "Must be a memory byte provider");
4889     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4890     assert(LoadBitWidth % 8 == 0 &&
4891            "can only analyze providers for individual bytes not bit");
4892     unsigned LoadByteWidth = LoadBitWidth / 8;
4893     return IsBigEndianTarget
4894             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4895             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4896   };
4897
4898   Optional<BaseIndexOffset> Base;
4899   SDValue Chain;
4900
4901   SmallSet<LoadSDNode *, 8> Loads;
4902   Optional<ByteProvider> FirstByteProvider;
4903   int64_t FirstOffset = INT64_MAX;
4904
4905   // Check if all the bytes of the OR we are looking at are loaded from the same
4906   // base address. Collect bytes offsets from Base address in ByteOffsets.
4907   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4908   for (unsigned i = 0; i < ByteWidth; i++) {
4909     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4910     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4911       return SDValue();
4912
4913     LoadSDNode *L = P->Load;
4914     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4915            "Must be enforced by calculateByteProvider");
4916     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4917
4918     // All loads must share the same chain
4919     SDValue LChain = L->getChain();
4920     if (!Chain)
4921       Chain = LChain;
4922     else if (Chain != LChain)
4923       return SDValue();
4924
4925     // Loads must share the same base address
4926     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4927     int64_t ByteOffsetFromBase = 0;
4928     if (!Base)
4929       Base = Ptr;
4930     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
4931       return SDValue();
4932
4933     // Calculate the offset of the current byte from the base address
4934     ByteOffsetFromBase += MemoryByteOffset(*P);
4935     ByteOffsets[i] = ByteOffsetFromBase;
4936
4937     // Remember the first byte load
4938     if (ByteOffsetFromBase < FirstOffset) {
4939       FirstByteProvider = P;
4940       FirstOffset = ByteOffsetFromBase;
4941     }
4942
4943     Loads.insert(L);
4944   }
4945   assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4946          "memory, so there must be at least one load which produces the value");
4947   assert(Base && "Base address of the accessed memory location must be set");
4948   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
4949
4950   // Check if the bytes of the OR we are looking at match with either big or
4951   // little endian value load
4952   bool BigEndian = true, LittleEndian = true;
4953   for (unsigned i = 0; i < ByteWidth; i++) {
4954     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
4955     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
4956     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
4957     if (!BigEndian && !LittleEndian)
4958       return SDValue();
4959   }
4960   assert((BigEndian != LittleEndian) && "should be either or");
4961   assert(FirstByteProvider && "must be set");
4962
4963   // Ensure that the first byte is loaded from zero offset of the first load.
4964   // So the combined value can be loaded from the first load address.
4965   if (MemoryByteOffset(*FirstByteProvider) != 0)
4966     return SDValue();
4967   LoadSDNode *FirstLoad = FirstByteProvider->Load;
4968
4969   // The node we are looking at matches with the pattern, check if we can
4970   // replace it with a single load and bswap if needed.
4971
4972   // If the load needs byte swap check if the target supports it
4973   bool NeedsBswap = IsBigEndianTarget != BigEndian;
4974
4975   // Before legalize we can introduce illegal bswaps which will be later
4976   // converted to an explicit bswap sequence. This way we end up with a single
4977   // load and byte shuffling instead of several loads and byte shuffling.
4978   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
4979     return SDValue();
4980
4981   // Check that a load of the wide type is both allowed and fast on the target
4982   bool Fast = false;
4983   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
4984                                         VT, FirstLoad->getAddressSpace(),
4985                                         FirstLoad->getAlignment(), &Fast);
4986   if (!Allowed || !Fast)
4987     return SDValue();
4988
4989   SDValue NewLoad =
4990       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
4991                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
4992
4993   // Transfer chain users from old loads to the new load.
4994   for (LoadSDNode *L : Loads)
4995     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
4996
4997   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
4998 }
4999
5000 SDValue DAGCombiner::visitXOR(SDNode *N) {
5001   SDValue N0 = N->getOperand(0);
5002   SDValue N1 = N->getOperand(1);
5003   EVT VT = N0.getValueType();
5004
5005   // fold vector ops
5006   if (VT.isVector()) {
5007     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5008       return FoldedVOp;
5009
5010     // fold (xor x, 0) -> x, vector edition
5011     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5012       return N1;
5013     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5014       return N0;
5015   }
5016
5017   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5018   if (N0.isUndef() && N1.isUndef())
5019     return DAG.getConstant(0, SDLoc(N), VT);
5020   // fold (xor x, undef) -> undef
5021   if (N0.isUndef())
5022     return N0;
5023   if (N1.isUndef())
5024     return N1;
5025   // fold (xor c1, c2) -> c1^c2
5026   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5027   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5028   if (N0C && N1C)
5029     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5030   // canonicalize constant to RHS
5031   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5032      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5033     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5034   // fold (xor x, 0) -> x
5035   if (isNullConstant(N1))
5036     return N0;
5037
5038   if (SDValue NewSel = foldBinOpIntoSelect(N))
5039     return NewSel;
5040
5041   // reassociate xor
5042   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5043     return RXOR;
5044
5045   // fold !(x cc y) -> (x !cc y)
5046   SDValue LHS, RHS, CC;
5047   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5048     bool isInt = LHS.getValueType().isInteger();
5049     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5050                                                isInt);
5051
5052     if (!LegalOperations ||
5053         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5054       switch (N0.getOpcode()) {
5055       default:
5056         llvm_unreachable("Unhandled SetCC Equivalent!");
5057       case ISD::SETCC:
5058         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5059       case ISD::SELECT_CC:
5060         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5061                                N0.getOperand(3), NotCC);
5062       }
5063     }
5064   }
5065
5066   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5067   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5068       N0.getNode()->hasOneUse() &&
5069       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5070     SDValue V = N0.getOperand(0);
5071     SDLoc DL(N0);
5072     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5073                     DAG.getConstant(1, DL, V.getValueType()));
5074     AddToWorklist(V.getNode());
5075     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5076   }
5077
5078   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5079   if (isOneConstant(N1) && VT == MVT::i1 &&
5080       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5081     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5082     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5083       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5084       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5085       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5086       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5087       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5088     }
5089   }
5090   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5091   if (isAllOnesConstant(N1) &&
5092       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5093     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5094     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5095       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5096       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5097       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5098       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5099       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5100     }
5101   }
5102   // fold (xor (and x, y), y) -> (and (not x), y)
5103   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5104       N0->getOperand(1) == N1) {
5105     SDValue X = N0->getOperand(0);
5106     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5107     AddToWorklist(NotX.getNode());
5108     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5109   }
5110   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5111   if (N1C && N0.getOpcode() == ISD::XOR) {
5112     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5113       SDLoc DL(N);
5114       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5115                          DAG.getConstant(N1C->getAPIntValue() ^
5116                                          N00C->getAPIntValue(), DL, VT));
5117     }
5118     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5119       SDLoc DL(N);
5120       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5121                          DAG.getConstant(N1C->getAPIntValue() ^
5122                                          N01C->getAPIntValue(), DL, VT));
5123     }
5124   }
5125
5126   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5127   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5128   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5129       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5130       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5131     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5132       if (C->getAPIntValue() == (OpSizeInBits - 1))
5133         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5134   }
5135
5136   // fold (xor x, x) -> 0
5137   if (N0 == N1)
5138     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5139
5140   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5141   // Here is a concrete example of this equivalence:
5142   // i16   x ==  14
5143   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5144   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5145   //
5146   // =>
5147   //
5148   // i16     ~1      == 0b1111111111111110
5149   // i16 rol(~1, 14) == 0b1011111111111111
5150   //
5151   // Some additional tips to help conceptualize this transform:
5152   // - Try to see the operation as placing a single zero in a value of all ones.
5153   // - There exists no value for x which would allow the result to contain zero.
5154   // - Values of x larger than the bitwidth are undefined and do not require a
5155   //   consistent result.
5156   // - Pushing the zero left requires shifting one bits in from the right.
5157   // A rotate left of ~1 is a nice way of achieving the desired result.
5158   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5159       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5160     SDLoc DL(N);
5161     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5162                        N0.getOperand(1));
5163   }
5164
5165   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5166   if (N0.getOpcode() == N1.getOpcode())
5167     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5168       return Tmp;
5169
5170   // Simplify the expression using non-local knowledge.
5171   if (SimplifyDemandedBits(SDValue(N, 0)))
5172     return SDValue(N, 0);
5173
5174   return SDValue();
5175 }
5176
5177 /// Handle transforms common to the three shifts, when the shift amount is a
5178 /// constant.
5179 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5180   SDNode *LHS = N->getOperand(0).getNode();
5181   if (!LHS->hasOneUse()) return SDValue();
5182
5183   // We want to pull some binops through shifts, so that we have (and (shift))
5184   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5185   // thing happens with address calculations, so it's important to canonicalize
5186   // it.
5187   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5188
5189   switch (LHS->getOpcode()) {
5190   default: return SDValue();
5191   case ISD::OR:
5192   case ISD::XOR:
5193     HighBitSet = false; // We can only transform sra if the high bit is clear.
5194     break;
5195   case ISD::AND:
5196     HighBitSet = true;  // We can only transform sra if the high bit is set.
5197     break;
5198   case ISD::ADD:
5199     if (N->getOpcode() != ISD::SHL)
5200       return SDValue(); // only shl(add) not sr[al](add).
5201     HighBitSet = false; // We can only transform sra if the high bit is clear.
5202     break;
5203   }
5204
5205   // We require the RHS of the binop to be a constant and not opaque as well.
5206   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5207   if (!BinOpCst) return SDValue();
5208
5209   // FIXME: disable this unless the input to the binop is a shift by a constant
5210   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5211   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5212   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5213                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5214                  BinOpLHSVal->getOpcode() == ISD::SRL;
5215   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5216                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5217
5218   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5219       !isCopyOrSelect)
5220     return SDValue();
5221
5222   if (isCopyOrSelect && N->hasOneUse())
5223     return SDValue();
5224
5225   EVT VT = N->getValueType(0);
5226
5227   // If this is a signed shift right, and the high bit is modified by the
5228   // logical operation, do not perform the transformation. The highBitSet
5229   // boolean indicates the value of the high bit of the constant which would
5230   // cause it to be modified for this operation.
5231   if (N->getOpcode() == ISD::SRA) {
5232     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5233     if (BinOpRHSSignSet != HighBitSet)
5234       return SDValue();
5235   }
5236
5237   if (!TLI.isDesirableToCommuteWithShift(LHS))
5238     return SDValue();
5239
5240   // Fold the constants, shifting the binop RHS by the shift amount.
5241   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5242                                N->getValueType(0),
5243                                LHS->getOperand(1), N->getOperand(1));
5244   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5245
5246   // Create the new shift.
5247   SDValue NewShift = DAG.getNode(N->getOpcode(),
5248                                  SDLoc(LHS->getOperand(0)),
5249                                  VT, LHS->getOperand(0), N->getOperand(1));
5250
5251   // Create the new binop.
5252   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5253 }
5254
5255 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5256   assert(N->getOpcode() == ISD::TRUNCATE);
5257   assert(N->getOperand(0).getOpcode() == ISD::AND);
5258
5259   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5260   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5261     SDValue N01 = N->getOperand(0).getOperand(1);
5262     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5263       SDLoc DL(N);
5264       EVT TruncVT = N->getValueType(0);
5265       SDValue N00 = N->getOperand(0).getOperand(0);
5266       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5267       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5268       AddToWorklist(Trunc00.getNode());
5269       AddToWorklist(Trunc01.getNode());
5270       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5271     }
5272   }
5273
5274   return SDValue();
5275 }
5276
5277 SDValue DAGCombiner::visitRotate(SDNode *N) {
5278   SDLoc dl(N);
5279   SDValue N0 = N->getOperand(0);
5280   SDValue N1 = N->getOperand(1);
5281   EVT VT = N->getValueType(0);
5282   unsigned Bitsize = VT.getScalarSizeInBits();
5283
5284   // fold (rot x, 0) -> x
5285   if (isNullConstantOrNullSplatConstant(N1))
5286     return N0;
5287
5288   // fold (rot x, c) -> (rot x, c % BitSize)
5289   if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
5290     if (Cst->getAPIntValue().uge(Bitsize)) {
5291       uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
5292       return DAG.getNode(N->getOpcode(), dl, VT, N0,
5293                          DAG.getConstant(RotAmt, dl, N1.getValueType()));
5294     }
5295   }
5296
5297   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5298   if (N1.getOpcode() == ISD::TRUNCATE &&
5299       N1.getOperand(0).getOpcode() == ISD::AND) {
5300     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5301       return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
5302   }
5303
5304   unsigned NextOp = N0.getOpcode();
5305   // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
5306   if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
5307     SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
5308     SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
5309     if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
5310       EVT ShiftVT = C1->getValueType(0);
5311       bool SameSide = (N->getOpcode() == NextOp);
5312       unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
5313       if (SDValue CombinedShift =
5314               DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
5315         SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
5316         SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
5317             ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
5318             BitsizeC.getNode());
5319         return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
5320                            CombinedShiftNorm);
5321       }
5322     }
5323   }
5324   return SDValue();
5325 }
5326
5327 SDValue DAGCombiner::visitSHL(SDNode *N) {
5328   SDValue N0 = N->getOperand(0);
5329   SDValue N1 = N->getOperand(1);
5330   EVT VT = N0.getValueType();
5331   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5332
5333   // fold vector ops
5334   if (VT.isVector()) {
5335     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5336       return FoldedVOp;
5337
5338     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5339     // If setcc produces all-one true value then:
5340     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5341     if (N1CV && N1CV->isConstant()) {
5342       if (N0.getOpcode() == ISD::AND) {
5343         SDValue N00 = N0->getOperand(0);
5344         SDValue N01 = N0->getOperand(1);
5345         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5346
5347         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5348             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5349                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5350           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5351                                                      N01CV, N1CV))
5352             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5353         }
5354       }
5355     }
5356   }
5357
5358   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5359
5360   // fold (shl c1, c2) -> c1<<c2
5361   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5362   if (N0C && N1C && !N1C->isOpaque())
5363     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5364   // fold (shl 0, x) -> 0
5365   if (isNullConstantOrNullSplatConstant(N0))
5366     return N0;
5367   // fold (shl x, c >= size(x)) -> undef
5368   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5369     return DAG.getUNDEF(VT);
5370   // fold (shl x, 0) -> x
5371   if (N1C && N1C->isNullValue())
5372     return N0;
5373   // fold (shl undef, x) -> 0
5374   if (N0.isUndef())
5375     return DAG.getConstant(0, SDLoc(N), VT);
5376
5377   if (SDValue NewSel = foldBinOpIntoSelect(N))
5378     return NewSel;
5379
5380   // if (shl x, c) is known to be zero, return 0
5381   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5382                             APInt::getAllOnesValue(OpSizeInBits)))
5383     return DAG.getConstant(0, SDLoc(N), VT);
5384   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5385   if (N1.getOpcode() == ISD::TRUNCATE &&
5386       N1.getOperand(0).getOpcode() == ISD::AND) {
5387     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5388       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5389   }
5390
5391   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5392     return SDValue(N, 0);
5393
5394   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5395   if (N1C && N0.getOpcode() == ISD::SHL) {
5396     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5397       SDLoc DL(N);
5398       APInt c1 = N0C1->getAPIntValue();
5399       APInt c2 = N1C->getAPIntValue();
5400       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5401
5402       APInt Sum = c1 + c2;
5403       if (Sum.uge(OpSizeInBits))
5404         return DAG.getConstant(0, DL, VT);
5405
5406       return DAG.getNode(
5407           ISD::SHL, DL, VT, N0.getOperand(0),
5408           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5409     }
5410   }
5411
5412   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5413   // For this to be valid, the second form must not preserve any of the bits
5414   // that are shifted out by the inner shift in the first form.  This means
5415   // the outer shift size must be >= the number of bits added by the ext.
5416   // As a corollary, we don't care what kind of ext it is.
5417   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5418               N0.getOpcode() == ISD::ANY_EXTEND ||
5419               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5420       N0.getOperand(0).getOpcode() == ISD::SHL) {
5421     SDValue N0Op0 = N0.getOperand(0);
5422     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5423       APInt c1 = N0Op0C1->getAPIntValue();
5424       APInt c2 = N1C->getAPIntValue();
5425       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5426
5427       EVT InnerShiftVT = N0Op0.getValueType();
5428       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5429       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5430         SDLoc DL(N0);
5431         APInt Sum = c1 + c2;
5432         if (Sum.uge(OpSizeInBits))
5433           return DAG.getConstant(0, DL, VT);
5434
5435         return DAG.getNode(
5436             ISD::SHL, DL, VT,
5437             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5438             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5439       }
5440     }
5441   }
5442
5443   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5444   // Only fold this if the inner zext has no other uses to avoid increasing
5445   // the total number of instructions.
5446   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5447       N0.getOperand(0).getOpcode() == ISD::SRL) {
5448     SDValue N0Op0 = N0.getOperand(0);
5449     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5450       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5451         uint64_t c1 = N0Op0C1->getZExtValue();
5452         uint64_t c2 = N1C->getZExtValue();
5453         if (c1 == c2) {
5454           SDValue NewOp0 = N0.getOperand(0);
5455           EVT CountVT = NewOp0.getOperand(1).getValueType();
5456           SDLoc DL(N);
5457           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5458                                        NewOp0,
5459                                        DAG.getConstant(c2, DL, CountVT));
5460           AddToWorklist(NewSHL.getNode());
5461           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5462         }
5463       }
5464     }
5465   }
5466
5467   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5468   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5469   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5470       N0->getFlags().hasExact()) {
5471     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5472       uint64_t C1 = N0C1->getZExtValue();
5473       uint64_t C2 = N1C->getZExtValue();
5474       SDLoc DL(N);
5475       if (C1 <= C2)
5476         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5477                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5478       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5479                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5480     }
5481   }
5482
5483   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5484   //                               (and (srl x, (sub c1, c2), MASK)
5485   // Only fold this if the inner shift has no other uses -- if it does, folding
5486   // this will increase the total number of instructions.
5487   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5488     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5489       uint64_t c1 = N0C1->getZExtValue();
5490       if (c1 < OpSizeInBits) {
5491         uint64_t c2 = N1C->getZExtValue();
5492         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5493         SDValue Shift;
5494         if (c2 > c1) {
5495           Mask <<= c2 - c1;
5496           SDLoc DL(N);
5497           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5498                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5499         } else {
5500           Mask.lshrInPlace(c1 - c2);
5501           SDLoc DL(N);
5502           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5503                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5504         }
5505         SDLoc DL(N0);
5506         return DAG.getNode(ISD::AND, DL, VT, Shift,
5507                            DAG.getConstant(Mask, DL, VT));
5508       }
5509     }
5510   }
5511
5512   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5513   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5514       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5515     SDLoc DL(N);
5516     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5517     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5518     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5519   }
5520
5521   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5522   // Variant of version done on multiply, except mul by a power of 2 is turned
5523   // into a shift.
5524   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5525       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5526       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5527     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5528     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5529     AddToWorklist(Shl0.getNode());
5530     AddToWorklist(Shl1.getNode());
5531     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5532   }
5533
5534   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5535   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5536       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5537       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5538     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5539     if (isConstantOrConstantVector(Shl))
5540       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5541   }
5542
5543   if (N1C && !N1C->isOpaque())
5544     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5545       return NewSHL;
5546
5547   return SDValue();
5548 }
5549
5550 SDValue DAGCombiner::visitSRA(SDNode *N) {
5551   SDValue N0 = N->getOperand(0);
5552   SDValue N1 = N->getOperand(1);
5553   EVT VT = N0.getValueType();
5554   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5555
5556   // Arithmetic shifting an all-sign-bit value is a no-op.
5557   // fold (sra 0, x) -> 0
5558   // fold (sra -1, x) -> -1
5559   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5560     return N0;
5561
5562   // fold vector ops
5563   if (VT.isVector())
5564     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5565       return FoldedVOp;
5566
5567   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5568
5569   // fold (sra c1, c2) -> (sra c1, c2)
5570   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5571   if (N0C && N1C && !N1C->isOpaque())
5572     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5573   // fold (sra x, c >= size(x)) -> undef
5574   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5575     return DAG.getUNDEF(VT);
5576   // fold (sra x, 0) -> x
5577   if (N1C && N1C->isNullValue())
5578     return N0;
5579
5580   if (SDValue NewSel = foldBinOpIntoSelect(N))
5581     return NewSel;
5582
5583   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5584   // sext_inreg.
5585   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5586     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5587     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5588     if (VT.isVector())
5589       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5590                                ExtVT, VT.getVectorNumElements());
5591     if ((!LegalOperations ||
5592          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5593       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5594                          N0.getOperand(0), DAG.getValueType(ExtVT));
5595   }
5596
5597   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5598   if (N1C && N0.getOpcode() == ISD::SRA) {
5599     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5600       SDLoc DL(N);
5601       APInt c1 = N0C1->getAPIntValue();
5602       APInt c2 = N1C->getAPIntValue();
5603       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5604
5605       APInt Sum = c1 + c2;
5606       if (Sum.uge(OpSizeInBits))
5607         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5608
5609       return DAG.getNode(
5610           ISD::SRA, DL, VT, N0.getOperand(0),
5611           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5612     }
5613   }
5614
5615   // fold (sra (shl X, m), (sub result_size, n))
5616   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5617   // result_size - n != m.
5618   // If truncate is free for the target sext(shl) is likely to result in better
5619   // code.
5620   if (N0.getOpcode() == ISD::SHL && N1C) {
5621     // Get the two constanst of the shifts, CN0 = m, CN = n.
5622     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5623     if (N01C) {
5624       LLVMContext &Ctx = *DAG.getContext();
5625       // Determine what the truncate's result bitsize and type would be.
5626       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5627
5628       if (VT.isVector())
5629         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5630
5631       // Determine the residual right-shift amount.
5632       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5633
5634       // If the shift is not a no-op (in which case this should be just a sign
5635       // extend already), the truncated to type is legal, sign_extend is legal
5636       // on that type, and the truncate to that type is both legal and free,
5637       // perform the transform.
5638       if ((ShiftAmt > 0) &&
5639           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5640           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5641           TLI.isTruncateFree(VT, TruncVT)) {
5642
5643         SDLoc DL(N);
5644         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5645             getShiftAmountTy(N0.getOperand(0).getValueType()));
5646         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5647                                     N0.getOperand(0), Amt);
5648         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5649                                     Shift);
5650         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5651                            N->getValueType(0), Trunc);
5652       }
5653     }
5654   }
5655
5656   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5657   if (N1.getOpcode() == ISD::TRUNCATE &&
5658       N1.getOperand(0).getOpcode() == ISD::AND) {
5659     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5660       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5661   }
5662
5663   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5664   //      if c1 is equal to the number of bits the trunc removes
5665   if (N0.getOpcode() == ISD::TRUNCATE &&
5666       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5667        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5668       N0.getOperand(0).hasOneUse() &&
5669       N0.getOperand(0).getOperand(1).hasOneUse() &&
5670       N1C) {
5671     SDValue N0Op0 = N0.getOperand(0);
5672     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5673       unsigned LargeShiftVal = LargeShift->getZExtValue();
5674       EVT LargeVT = N0Op0.getValueType();
5675
5676       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5677         SDLoc DL(N);
5678         SDValue Amt =
5679           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5680                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5681         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5682                                   N0Op0.getOperand(0), Amt);
5683         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5684       }
5685     }
5686   }
5687
5688   // Simplify, based on bits shifted out of the LHS.
5689   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5690     return SDValue(N, 0);
5691
5692
5693   // If the sign bit is known to be zero, switch this to a SRL.
5694   if (DAG.SignBitIsZero(N0))
5695     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5696
5697   if (N1C && !N1C->isOpaque())
5698     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5699       return NewSRA;
5700
5701   return SDValue();
5702 }
5703
5704 SDValue DAGCombiner::visitSRL(SDNode *N) {
5705   SDValue N0 = N->getOperand(0);
5706   SDValue N1 = N->getOperand(1);
5707   EVT VT = N0.getValueType();
5708   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5709
5710   // fold vector ops
5711   if (VT.isVector())
5712     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5713       return FoldedVOp;
5714
5715   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5716
5717   // fold (srl c1, c2) -> c1 >>u c2
5718   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5719   if (N0C && N1C && !N1C->isOpaque())
5720     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5721   // fold (srl 0, x) -> 0
5722   if (isNullConstantOrNullSplatConstant(N0))
5723     return N0;
5724   // fold (srl x, c >= size(x)) -> undef
5725   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5726     return DAG.getUNDEF(VT);
5727   // fold (srl x, 0) -> x
5728   if (N1C && N1C->isNullValue())
5729     return N0;
5730
5731   if (SDValue NewSel = foldBinOpIntoSelect(N))
5732     return NewSel;
5733
5734   // if (srl x, c) is known to be zero, return 0
5735   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5736                                    APInt::getAllOnesValue(OpSizeInBits)))
5737     return DAG.getConstant(0, SDLoc(N), VT);
5738
5739   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5740   if (N1C && N0.getOpcode() == ISD::SRL) {
5741     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5742       SDLoc DL(N);
5743       APInt c1 = N0C1->getAPIntValue();
5744       APInt c2 = N1C->getAPIntValue();
5745       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5746
5747       APInt Sum = c1 + c2;
5748       if (Sum.uge(OpSizeInBits))
5749         return DAG.getConstant(0, DL, VT);
5750
5751       return DAG.getNode(
5752           ISD::SRL, DL, VT, N0.getOperand(0),
5753           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5754     }
5755   }
5756
5757   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5758   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5759       N0.getOperand(0).getOpcode() == ISD::SRL) {
5760     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5761       uint64_t c1 = N001C->getZExtValue();
5762       uint64_t c2 = N1C->getZExtValue();
5763       EVT InnerShiftVT = N0.getOperand(0).getValueType();
5764       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5765       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5766       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5767       if (c1 + OpSizeInBits == InnerShiftSize) {
5768         SDLoc DL(N0);
5769         if (c1 + c2 >= InnerShiftSize)
5770           return DAG.getConstant(0, DL, VT);
5771         return DAG.getNode(ISD::TRUNCATE, DL, VT,
5772                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5773                                        N0.getOperand(0).getOperand(0),
5774                                        DAG.getConstant(c1 + c2, DL,
5775                                                        ShiftCountVT)));
5776       }
5777     }
5778   }
5779
5780   // fold (srl (shl x, c), c) -> (and x, cst2)
5781   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5782       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5783     SDLoc DL(N);
5784     SDValue Mask =
5785         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5786     AddToWorklist(Mask.getNode());
5787     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5788   }
5789
5790   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5791   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5792     // Shifting in all undef bits?
5793     EVT SmallVT = N0.getOperand(0).getValueType();
5794     unsigned BitSize = SmallVT.getScalarSizeInBits();
5795     if (N1C->getZExtValue() >= BitSize)
5796       return DAG.getUNDEF(VT);
5797
5798     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5799       uint64_t ShiftAmt = N1C->getZExtValue();
5800       SDLoc DL0(N0);
5801       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5802                                        N0.getOperand(0),
5803                           DAG.getConstant(ShiftAmt, DL0,
5804                                           getShiftAmountTy(SmallVT)));
5805       AddToWorklist(SmallShift.getNode());
5806       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5807       SDLoc DL(N);
5808       return DAG.getNode(ISD::AND, DL, VT,
5809                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5810                          DAG.getConstant(Mask, DL, VT));
5811     }
5812   }
5813
5814   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
5815   // bit, which is unmodified by sra.
5816   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5817     if (N0.getOpcode() == ISD::SRA)
5818       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5819   }
5820
5821   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5822   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5823       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5824     KnownBits Known;
5825     DAG.computeKnownBits(N0.getOperand(0), Known);
5826
5827     // If any of the input bits are KnownOne, then the input couldn't be all
5828     // zeros, thus the result of the srl will always be zero.
5829     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5830
5831     // If all of the bits input the to ctlz node are known to be zero, then
5832     // the result of the ctlz is "32" and the result of the shift is one.
5833     APInt UnknownBits = ~Known.Zero;
5834     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5835
5836     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5837     if (UnknownBits.isPowerOf2()) {
5838       // Okay, we know that only that the single bit specified by UnknownBits
5839       // could be set on input to the CTLZ node. If this bit is set, the SRL
5840       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5841       // to an SRL/XOR pair, which is likely to simplify more.
5842       unsigned ShAmt = UnknownBits.countTrailingZeros();
5843       SDValue Op = N0.getOperand(0);
5844
5845       if (ShAmt) {
5846         SDLoc DL(N0);
5847         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5848                   DAG.getConstant(ShAmt, DL,
5849                                   getShiftAmountTy(Op.getValueType())));
5850         AddToWorklist(Op.getNode());
5851       }
5852
5853       SDLoc DL(N);
5854       return DAG.getNode(ISD::XOR, DL, VT,
5855                          Op, DAG.getConstant(1, DL, VT));
5856     }
5857   }
5858
5859   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5860   if (N1.getOpcode() == ISD::TRUNCATE &&
5861       N1.getOperand(0).getOpcode() == ISD::AND) {
5862     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5863       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5864   }
5865
5866   // fold operands of srl based on knowledge that the low bits are not
5867   // demanded.
5868   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5869     return SDValue(N, 0);
5870
5871   if (N1C && !N1C->isOpaque())
5872     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5873       return NewSRL;
5874
5875   // Attempt to convert a srl of a load into a narrower zero-extending load.
5876   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5877     return NarrowLoad;
5878
5879   // Here is a common situation. We want to optimize:
5880   //
5881   //   %a = ...
5882   //   %b = and i32 %a, 2
5883   //   %c = srl i32 %b, 1
5884   //   brcond i32 %c ...
5885   //
5886   // into
5887   //
5888   //   %a = ...
5889   //   %b = and %a, 2
5890   //   %c = setcc eq %b, 0
5891   //   brcond %c ...
5892   //
5893   // However when after the source operand of SRL is optimized into AND, the SRL
5894   // itself may not be optimized further. Look for it and add the BRCOND into
5895   // the worklist.
5896   if (N->hasOneUse()) {
5897     SDNode *Use = *N->use_begin();
5898     if (Use->getOpcode() == ISD::BRCOND)
5899       AddToWorklist(Use);
5900     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5901       // Also look pass the truncate.
5902       Use = *Use->use_begin();
5903       if (Use->getOpcode() == ISD::BRCOND)
5904         AddToWorklist(Use);
5905     }
5906   }
5907
5908   return SDValue();
5909 }
5910
5911 SDValue DAGCombiner::visitABS(SDNode *N) {
5912   SDValue N0 = N->getOperand(0);
5913   EVT VT = N->getValueType(0);
5914
5915   // fold (abs c1) -> c2
5916   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5917     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
5918   // fold (abs (abs x)) -> (abs x)
5919   if (N0.getOpcode() == ISD::ABS)
5920     return N0;
5921   // fold (abs x) -> x iff not-negative
5922   if (DAG.SignBitIsZero(N0))
5923     return N0;
5924   return SDValue();
5925 }
5926
5927 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5928   SDValue N0 = N->getOperand(0);
5929   EVT VT = N->getValueType(0);
5930
5931   // fold (bswap c1) -> c2
5932   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5933     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5934   // fold (bswap (bswap x)) -> x
5935   if (N0.getOpcode() == ISD::BSWAP)
5936     return N0->getOperand(0);
5937   return SDValue();
5938 }
5939
5940 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5941   SDValue N0 = N->getOperand(0);
5942   EVT VT = N->getValueType(0);
5943
5944   // fold (bitreverse c1) -> c2
5945   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5946     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
5947   // fold (bitreverse (bitreverse x)) -> x
5948   if (N0.getOpcode() == ISD::BITREVERSE)
5949     return N0.getOperand(0);
5950   return SDValue();
5951 }
5952
5953 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5954   SDValue N0 = N->getOperand(0);
5955   EVT VT = N->getValueType(0);
5956
5957   // fold (ctlz c1) -> c2
5958   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5959     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5960   return SDValue();
5961 }
5962
5963 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5964   SDValue N0 = N->getOperand(0);
5965   EVT VT = N->getValueType(0);
5966
5967   // fold (ctlz_zero_undef c1) -> c2
5968   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5969     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5970   return SDValue();
5971 }
5972
5973 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5974   SDValue N0 = N->getOperand(0);
5975   EVT VT = N->getValueType(0);
5976
5977   // fold (cttz c1) -> c2
5978   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5979     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5980   return SDValue();
5981 }
5982
5983 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5984   SDValue N0 = N->getOperand(0);
5985   EVT VT = N->getValueType(0);
5986
5987   // fold (cttz_zero_undef c1) -> c2
5988   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5989     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5990   return SDValue();
5991 }
5992
5993 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5994   SDValue N0 = N->getOperand(0);
5995   EVT VT = N->getValueType(0);
5996
5997   // fold (ctpop c1) -> c2
5998   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5999     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6000   return SDValue();
6001 }
6002
6003
6004 /// \brief Generate Min/Max node
6005 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6006                                    SDValue RHS, SDValue True, SDValue False,
6007                                    ISD::CondCode CC, const TargetLowering &TLI,
6008                                    SelectionDAG &DAG) {
6009   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6010     return SDValue();
6011
6012   switch (CC) {
6013   case ISD::SETOLT:
6014   case ISD::SETOLE:
6015   case ISD::SETLT:
6016   case ISD::SETLE:
6017   case ISD::SETULT:
6018   case ISD::SETULE: {
6019     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6020     if (TLI.isOperationLegal(Opcode, VT))
6021       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6022     return SDValue();
6023   }
6024   case ISD::SETOGT:
6025   case ISD::SETOGE:
6026   case ISD::SETGT:
6027   case ISD::SETGE:
6028   case ISD::SETUGT:
6029   case ISD::SETUGE: {
6030     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6031     if (TLI.isOperationLegal(Opcode, VT))
6032       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6033     return SDValue();
6034   }
6035   default:
6036     return SDValue();
6037   }
6038 }
6039
6040 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6041   SDValue Cond = N->getOperand(0);
6042   SDValue N1 = N->getOperand(1);
6043   SDValue N2 = N->getOperand(2);
6044   EVT VT = N->getValueType(0);
6045   EVT CondVT = Cond.getValueType();
6046   SDLoc DL(N);
6047
6048   if (!VT.isInteger())
6049     return SDValue();
6050
6051   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6052   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6053   if (!C1 || !C2)
6054     return SDValue();
6055
6056   // Only do this before legalization to avoid conflicting with target-specific
6057   // transforms in the other direction (create a select from a zext/sext). There
6058   // is also a target-independent combine here in DAGCombiner in the other
6059   // direction for (select Cond, -1, 0) when the condition is not i1.
6060   if (CondVT == MVT::i1 && !LegalOperations) {
6061     if (C1->isNullValue() && C2->isOne()) {
6062       // select Cond, 0, 1 --> zext (!Cond)
6063       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6064       if (VT != MVT::i1)
6065         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6066       return NotCond;
6067     }
6068     if (C1->isNullValue() && C2->isAllOnesValue()) {
6069       // select Cond, 0, -1 --> sext (!Cond)
6070       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6071       if (VT != MVT::i1)
6072         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6073       return NotCond;
6074     }
6075     if (C1->isOne() && C2->isNullValue()) {
6076       // select Cond, 1, 0 --> zext (Cond)
6077       if (VT != MVT::i1)
6078         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6079       return Cond;
6080     }
6081     if (C1->isAllOnesValue() && C2->isNullValue()) {
6082       // select Cond, -1, 0 --> sext (Cond)
6083       if (VT != MVT::i1)
6084         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6085       return Cond;
6086     }
6087
6088     // For any constants that differ by 1, we can transform the select into an
6089     // extend and add. Use a target hook because some targets may prefer to
6090     // transform in the other direction.
6091     if (TLI.convertSelectOfConstantsToMath()) {
6092       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6093         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6094         if (VT != MVT::i1)
6095           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6096         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6097       }
6098       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6099         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6100         if (VT != MVT::i1)
6101           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6102         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6103       }
6104     }
6105
6106     return SDValue();
6107   }
6108
6109   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6110   // We can't do this reliably if integer based booleans have different contents
6111   // to floating point based booleans. This is because we can't tell whether we
6112   // have an integer-based boolean or a floating-point-based boolean unless we
6113   // can find the SETCC that produced it and inspect its operands. This is
6114   // fairly easy if C is the SETCC node, but it can potentially be
6115   // undiscoverable (or not reasonably discoverable). For example, it could be
6116   // in another basic block or it could require searching a complicated
6117   // expression.
6118   if (CondVT.isInteger() &&
6119       TLI.getBooleanContents(false, true) ==
6120           TargetLowering::ZeroOrOneBooleanContent &&
6121       TLI.getBooleanContents(false, false) ==
6122           TargetLowering::ZeroOrOneBooleanContent &&
6123       C1->isNullValue() && C2->isOne()) {
6124     SDValue NotCond =
6125         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6126     if (VT.bitsEq(CondVT))
6127       return NotCond;
6128     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6129   }
6130
6131   return SDValue();
6132 }
6133
6134 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6135   SDValue N0 = N->getOperand(0);
6136   SDValue N1 = N->getOperand(1);
6137   SDValue N2 = N->getOperand(2);
6138   EVT VT = N->getValueType(0);
6139   EVT VT0 = N0.getValueType();
6140   SDLoc DL(N);
6141
6142   // fold (select C, X, X) -> X
6143   if (N1 == N2)
6144     return N1;
6145
6146   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6147     // fold (select true, X, Y) -> X
6148     // fold (select false, X, Y) -> Y
6149     return !N0C->isNullValue() ? N1 : N2;
6150   }
6151
6152   // fold (select X, X, Y) -> (or X, Y)
6153   // fold (select X, 1, Y) -> (or C, Y)
6154   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6155     return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6156
6157   if (SDValue V = foldSelectOfConstants(N))
6158     return V;
6159
6160   // fold (select C, 0, X) -> (and (not C), X)
6161   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6162     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6163     AddToWorklist(NOTNode.getNode());
6164     return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6165   }
6166   // fold (select C, X, 1) -> (or (not C), X)
6167   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6168     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6169     AddToWorklist(NOTNode.getNode());
6170     return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6171   }
6172   // fold (select X, Y, X) -> (and X, Y)
6173   // fold (select X, Y, 0) -> (and X, Y)
6174   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6175     return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6176
6177   // If we can fold this based on the true/false value, do so.
6178   if (SimplifySelectOps(N, N1, N2))
6179     return SDValue(N, 0); // Don't revisit N.
6180
6181   if (VT0 == MVT::i1) {
6182     // The code in this block deals with the following 2 equivalences:
6183     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6184     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6185     // The target can specify its preferred form with the
6186     // shouldNormalizeToSelectSequence() callback. However we always transform
6187     // to the right anyway if we find the inner select exists in the DAG anyway
6188     // and we always transform to the left side if we know that we can further
6189     // optimize the combination of the conditions.
6190     bool normalizeToSequence =
6191         TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6192     // select (and Cond0, Cond1), X, Y
6193     //   -> select Cond0, (select Cond1, X, Y), Y
6194     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6195       SDValue Cond0 = N0->getOperand(0);
6196       SDValue Cond1 = N0->getOperand(1);
6197       SDValue InnerSelect =
6198           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6199       if (normalizeToSequence || !InnerSelect.use_empty())
6200         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6201                            InnerSelect, N2);
6202     }
6203     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6204     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6205       SDValue Cond0 = N0->getOperand(0);
6206       SDValue Cond1 = N0->getOperand(1);
6207       SDValue InnerSelect =
6208           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6209       if (normalizeToSequence || !InnerSelect.use_empty())
6210         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
6211                            InnerSelect);
6212     }
6213
6214     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6215     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6216       SDValue N1_0 = N1->getOperand(0);
6217       SDValue N1_1 = N1->getOperand(1);
6218       SDValue N1_2 = N1->getOperand(2);
6219       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6220         // Create the actual and node if we can generate good code for it.
6221         if (!normalizeToSequence) {
6222           SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
6223           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
6224         }
6225         // Otherwise see if we can optimize the "and" to a better pattern.
6226         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6227           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
6228                              N2);
6229       }
6230     }
6231     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6232     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6233       SDValue N2_0 = N2->getOperand(0);
6234       SDValue N2_1 = N2->getOperand(1);
6235       SDValue N2_2 = N2->getOperand(2);
6236       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6237         // Create the actual or node if we can generate good code for it.
6238         if (!normalizeToSequence) {
6239           SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
6240           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
6241         }
6242         // Otherwise see if we can optimize to a better pattern.
6243         if (SDValue Combined = visitORLike(N0, N2_0, N))
6244           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
6245                              N2_2);
6246       }
6247     }
6248   }
6249
6250   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6251   if (VT0 == MVT::i1) {
6252     if (N0->getOpcode() == ISD::XOR) {
6253       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6254         SDValue Cond0 = N0->getOperand(0);
6255         if (C->isOne())
6256           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1);
6257       }
6258     }
6259   }
6260
6261   // fold selects based on a setcc into other things, such as min/max/abs
6262   if (N0.getOpcode() == ISD::SETCC) {
6263     // select x, y (fcmp lt x, y) -> fminnum x, y
6264     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6265     //
6266     // This is OK if we don't care about what happens if either operand is a
6267     // NaN.
6268     //
6269
6270     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6271     // no signed zeros as well as no nans.
6272     const TargetOptions &Options = DAG.getTarget().Options;
6273     if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
6274         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6275       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6276
6277       if (SDValue FMinMax = combineMinNumMaxNum(
6278               DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
6279         return FMinMax;
6280     }
6281
6282     if ((!LegalOperations &&
6283          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6284         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6285       return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
6286                          N0.getOperand(1), N1, N2, N0.getOperand(2));
6287     return SimplifySelect(DL, N0, N1, N2);
6288   }
6289
6290   return SDValue();
6291 }
6292
6293 static
6294 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6295   SDLoc DL(N);
6296   EVT LoVT, HiVT;
6297   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6298
6299   // Split the inputs.
6300   SDValue Lo, Hi, LL, LH, RL, RH;
6301   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6302   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6303
6304   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6305   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6306
6307   return std::make_pair(Lo, Hi);
6308 }
6309
6310 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6311 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6312 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6313   SDLoc DL(N);
6314   SDValue Cond = N->getOperand(0);
6315   SDValue LHS = N->getOperand(1);
6316   SDValue RHS = N->getOperand(2);
6317   EVT VT = N->getValueType(0);
6318   int NumElems = VT.getVectorNumElements();
6319   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6320          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6321          Cond.getOpcode() == ISD::BUILD_VECTOR);
6322
6323   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6324   // binary ones here.
6325   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6326     return SDValue();
6327
6328   // We're sure we have an even number of elements due to the
6329   // concat_vectors we have as arguments to vselect.
6330   // Skip BV elements until we find one that's not an UNDEF
6331   // After we find an UNDEF element, keep looping until we get to half the
6332   // length of the BV and see if all the non-undef nodes are the same.
6333   ConstantSDNode *BottomHalf = nullptr;
6334   for (int i = 0; i < NumElems / 2; ++i) {
6335     if (Cond->getOperand(i)->isUndef())
6336       continue;
6337
6338     if (BottomHalf == nullptr)
6339       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6340     else if (Cond->getOperand(i).getNode() != BottomHalf)
6341       return SDValue();
6342   }
6343
6344   // Do the same for the second half of the BuildVector
6345   ConstantSDNode *TopHalf = nullptr;
6346   for (int i = NumElems / 2; i < NumElems; ++i) {
6347     if (Cond->getOperand(i)->isUndef())
6348       continue;
6349
6350     if (TopHalf == nullptr)
6351       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6352     else if (Cond->getOperand(i).getNode() != TopHalf)
6353       return SDValue();
6354   }
6355
6356   assert(TopHalf && BottomHalf &&
6357          "One half of the selector was all UNDEFs and the other was all the "
6358          "same value. This should have been addressed before this function.");
6359   return DAG.getNode(
6360       ISD::CONCAT_VECTORS, DL, VT,
6361       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6362       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6363 }
6364
6365 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6366
6367   if (Level >= AfterLegalizeTypes)
6368     return SDValue();
6369
6370   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6371   SDValue Mask = MSC->getMask();
6372   SDValue Data  = MSC->getValue();
6373   SDLoc DL(N);
6374
6375   // If the MSCATTER data type requires splitting and the mask is provided by a
6376   // SETCC, then split both nodes and its operands before legalization. This
6377   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6378   // and enables future optimizations (e.g. min/max pattern matching on X86).
6379   if (Mask.getOpcode() != ISD::SETCC)
6380     return SDValue();
6381
6382   // Check if any splitting is required.
6383   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6384       TargetLowering::TypeSplitVector)
6385     return SDValue();
6386   SDValue MaskLo, MaskHi, Lo, Hi;
6387   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6388
6389   EVT LoVT, HiVT;
6390   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6391
6392   SDValue Chain = MSC->getChain();
6393
6394   EVT MemoryVT = MSC->getMemoryVT();
6395   unsigned Alignment = MSC->getOriginalAlignment();
6396
6397   EVT LoMemVT, HiMemVT;
6398   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6399
6400   SDValue DataLo, DataHi;
6401   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6402
6403   SDValue BasePtr = MSC->getBasePtr();
6404   SDValue IndexLo, IndexHi;
6405   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6406
6407   MachineMemOperand *MMO = DAG.getMachineFunction().
6408     getMachineMemOperand(MSC->getPointerInfo(),
6409                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6410                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6411
6412   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6413   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6414                             DL, OpsLo, MMO);
6415
6416   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6417   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6418                             DL, OpsHi, MMO);
6419
6420   AddToWorklist(Lo.getNode());
6421   AddToWorklist(Hi.getNode());
6422
6423   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6424 }
6425
6426 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6427
6428   if (Level >= AfterLegalizeTypes)
6429     return SDValue();
6430
6431   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6432   SDValue Mask = MST->getMask();
6433   SDValue Data  = MST->getValue();
6434   EVT VT = Data.getValueType();
6435   SDLoc DL(N);
6436
6437   // If the MSTORE data type requires splitting and the mask is provided by a
6438   // SETCC, then split both nodes and its operands before legalization. This
6439   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6440   // and enables future optimizations (e.g. min/max pattern matching on X86).
6441   if (Mask.getOpcode() == ISD::SETCC) {
6442
6443     // Check if any splitting is required.
6444     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6445         TargetLowering::TypeSplitVector)
6446       return SDValue();
6447
6448     SDValue MaskLo, MaskHi, Lo, Hi;
6449     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6450
6451     SDValue Chain = MST->getChain();
6452     SDValue Ptr   = MST->getBasePtr();
6453
6454     EVT MemoryVT = MST->getMemoryVT();
6455     unsigned Alignment = MST->getOriginalAlignment();
6456
6457     // if Alignment is equal to the vector size,
6458     // take the half of it for the second part
6459     unsigned SecondHalfAlignment =
6460       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6461
6462     EVT LoMemVT, HiMemVT;
6463     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6464
6465     SDValue DataLo, DataHi;
6466     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6467
6468     MachineMemOperand *MMO = DAG.getMachineFunction().
6469       getMachineMemOperand(MST->getPointerInfo(),
6470                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6471                            Alignment, MST->getAAInfo(), MST->getRanges());
6472
6473     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6474                             MST->isTruncatingStore(),
6475                             MST->isCompressingStore());
6476
6477     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6478                                      MST->isCompressingStore());
6479
6480     MMO = DAG.getMachineFunction().
6481       getMachineMemOperand(MST->getPointerInfo(),
6482                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6483                            SecondHalfAlignment, MST->getAAInfo(),
6484                            MST->getRanges());
6485
6486     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6487                             MST->isTruncatingStore(),
6488                             MST->isCompressingStore());
6489
6490     AddToWorklist(Lo.getNode());
6491     AddToWorklist(Hi.getNode());
6492
6493     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6494   }
6495   return SDValue();
6496 }
6497
6498 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6499
6500   if (Level >= AfterLegalizeTypes)
6501     return SDValue();
6502
6503   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6504   SDValue Mask = MGT->getMask();
6505   SDLoc DL(N);
6506
6507   // If the MGATHER result requires splitting and the mask is provided by a
6508   // SETCC, then split both nodes and its operands before legalization. This
6509   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6510   // and enables future optimizations (e.g. min/max pattern matching on X86).
6511
6512   if (Mask.getOpcode() != ISD::SETCC)
6513     return SDValue();
6514
6515   EVT VT = N->getValueType(0);
6516
6517   // Check if any splitting is required.
6518   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6519       TargetLowering::TypeSplitVector)
6520     return SDValue();
6521
6522   SDValue MaskLo, MaskHi, Lo, Hi;
6523   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6524
6525   SDValue Src0 = MGT->getValue();
6526   SDValue Src0Lo, Src0Hi;
6527   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6528
6529   EVT LoVT, HiVT;
6530   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6531
6532   SDValue Chain = MGT->getChain();
6533   EVT MemoryVT = MGT->getMemoryVT();
6534   unsigned Alignment = MGT->getOriginalAlignment();
6535
6536   EVT LoMemVT, HiMemVT;
6537   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6538
6539   SDValue BasePtr = MGT->getBasePtr();
6540   SDValue Index = MGT->getIndex();
6541   SDValue IndexLo, IndexHi;
6542   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6543
6544   MachineMemOperand *MMO = DAG.getMachineFunction().
6545     getMachineMemOperand(MGT->getPointerInfo(),
6546                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6547                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6548
6549   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6550   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6551                             MMO);
6552
6553   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6554   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6555                             MMO);
6556
6557   AddToWorklist(Lo.getNode());
6558   AddToWorklist(Hi.getNode());
6559
6560   // Build a factor node to remember that this load is independent of the
6561   // other one.
6562   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6563                       Hi.getValue(1));
6564
6565   // Legalized the chain result - switch anything that used the old chain to
6566   // use the new one.
6567   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6568
6569   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6570
6571   SDValue RetOps[] = { GatherRes, Chain };
6572   return DAG.getMergeValues(RetOps, DL);
6573 }
6574
6575 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6576
6577   if (Level >= AfterLegalizeTypes)
6578     return SDValue();
6579
6580   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6581   SDValue Mask = MLD->getMask();
6582   SDLoc DL(N);
6583
6584   // If the MLOAD result requires splitting and the mask is provided by a
6585   // SETCC, then split both nodes and its operands before legalization. This
6586   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6587   // and enables future optimizations (e.g. min/max pattern matching on X86).
6588
6589   if (Mask.getOpcode() == ISD::SETCC) {
6590     EVT VT = N->getValueType(0);
6591
6592     // Check if any splitting is required.
6593     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6594         TargetLowering::TypeSplitVector)
6595       return SDValue();
6596
6597     SDValue MaskLo, MaskHi, Lo, Hi;
6598     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6599
6600     SDValue Src0 = MLD->getSrc0();
6601     SDValue Src0Lo, Src0Hi;
6602     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6603
6604     EVT LoVT, HiVT;
6605     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6606
6607     SDValue Chain = MLD->getChain();
6608     SDValue Ptr   = MLD->getBasePtr();
6609     EVT MemoryVT = MLD->getMemoryVT();
6610     unsigned Alignment = MLD->getOriginalAlignment();
6611
6612     // if Alignment is equal to the vector size,
6613     // take the half of it for the second part
6614     unsigned SecondHalfAlignment =
6615       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6616          Alignment/2 : Alignment;
6617
6618     EVT LoMemVT, HiMemVT;
6619     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6620
6621     MachineMemOperand *MMO = DAG.getMachineFunction().
6622     getMachineMemOperand(MLD->getPointerInfo(),
6623                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6624                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6625
6626     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6627                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6628
6629     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6630                                      MLD->isExpandingLoad());
6631
6632     MMO = DAG.getMachineFunction().
6633     getMachineMemOperand(MLD->getPointerInfo(),
6634                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6635                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6636
6637     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6638                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6639
6640     AddToWorklist(Lo.getNode());
6641     AddToWorklist(Hi.getNode());
6642
6643     // Build a factor node to remember that this load is independent of the
6644     // other one.
6645     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6646                         Hi.getValue(1));
6647
6648     // Legalized the chain result - switch anything that used the old chain to
6649     // use the new one.
6650     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6651
6652     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6653
6654     SDValue RetOps[] = { LoadRes, Chain };
6655     return DAG.getMergeValues(RetOps, DL);
6656   }
6657   return SDValue();
6658 }
6659
6660 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6661   SDValue N0 = N->getOperand(0);
6662   SDValue N1 = N->getOperand(1);
6663   SDValue N2 = N->getOperand(2);
6664   SDLoc DL(N);
6665
6666   // fold (vselect C, X, X) -> X
6667   if (N1 == N2)
6668     return N1;
6669
6670   // Canonicalize integer abs.
6671   // vselect (setg[te] X,  0),  X, -X ->
6672   // vselect (setgt    X, -1),  X, -X ->
6673   // vselect (setl[te] X,  0), -X,  X ->
6674   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6675   if (N0.getOpcode() == ISD::SETCC) {
6676     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6677     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6678     bool isAbs = false;
6679     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6680
6681     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6682          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6683         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6684       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6685     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6686              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6687       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6688
6689     if (isAbs) {
6690       EVT VT = LHS.getValueType();
6691       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
6692         return DAG.getNode(ISD::ABS, DL, VT, LHS);
6693
6694       SDValue Shift = DAG.getNode(
6695           ISD::SRA, DL, VT, LHS,
6696           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6697       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6698       AddToWorklist(Shift.getNode());
6699       AddToWorklist(Add.getNode());
6700       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6701     }
6702   }
6703
6704   if (SimplifySelectOps(N, N1, N2))
6705     return SDValue(N, 0);  // Don't revisit N.
6706
6707   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6708   if (ISD::isBuildVectorAllOnes(N0.getNode()))
6709     return N1;
6710   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6711   if (ISD::isBuildVectorAllZeros(N0.getNode()))
6712     return N2;
6713
6714   // The ConvertSelectToConcatVector function is assuming both the above
6715   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6716   // and addressed.
6717   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6718       N2.getOpcode() == ISD::CONCAT_VECTORS &&
6719       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6720     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6721       return CV;
6722   }
6723
6724   return SDValue();
6725 }
6726
6727 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6728   SDValue N0 = N->getOperand(0);
6729   SDValue N1 = N->getOperand(1);
6730   SDValue N2 = N->getOperand(2);
6731   SDValue N3 = N->getOperand(3);
6732   SDValue N4 = N->getOperand(4);
6733   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6734
6735   // fold select_cc lhs, rhs, x, x, cc -> x
6736   if (N2 == N3)
6737     return N2;
6738
6739   // Determine if the condition we're dealing with is constant
6740   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6741                                   CC, SDLoc(N), false)) {
6742     AddToWorklist(SCC.getNode());
6743
6744     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6745       if (!SCCC->isNullValue())
6746         return N2;    // cond always true -> true val
6747       else
6748         return N3;    // cond always false -> false val
6749     } else if (SCC->isUndef()) {
6750       // When the condition is UNDEF, just return the first operand. This is
6751       // coherent the DAG creation, no setcc node is created in this case
6752       return N2;
6753     } else if (SCC.getOpcode() == ISD::SETCC) {
6754       // Fold to a simpler select_cc
6755       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6756                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6757                          SCC.getOperand(2));
6758     }
6759   }
6760
6761   // If we can fold this based on the true/false value, do so.
6762   if (SimplifySelectOps(N, N2, N3))
6763     return SDValue(N, 0);  // Don't revisit N.
6764
6765   // fold select_cc into other things, such as min/max/abs
6766   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6767 }
6768
6769 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6770   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6771                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
6772                        SDLoc(N));
6773 }
6774
6775 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6776   SDValue LHS = N->getOperand(0);
6777   SDValue RHS = N->getOperand(1);
6778   SDValue Carry = N->getOperand(2);
6779   SDValue Cond = N->getOperand(3);
6780
6781   // If Carry is false, fold to a regular SETCC.
6782   if (Carry.getOpcode() == ISD::CARRY_FALSE)
6783     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6784
6785   return SDValue();
6786 }
6787
6788 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
6789   SDValue LHS = N->getOperand(0);
6790   SDValue RHS = N->getOperand(1);
6791   SDValue Carry = N->getOperand(2);
6792   SDValue Cond = N->getOperand(3);
6793
6794   // If Carry is false, fold to a regular SETCC.
6795   if (isNullConstant(Carry))
6796     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6797
6798   return SDValue();
6799 }
6800
6801 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6802 /// a build_vector of constants.
6803 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6804 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6805 /// Vector extends are not folded if operations are legal; this is to
6806 /// avoid introducing illegal build_vector dag nodes.
6807 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6808                                          SelectionDAG &DAG, bool LegalTypes,
6809                                          bool LegalOperations) {
6810   unsigned Opcode = N->getOpcode();
6811   SDValue N0 = N->getOperand(0);
6812   EVT VT = N->getValueType(0);
6813
6814   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6815          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6816          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6817          && "Expected EXTEND dag node in input!");
6818
6819   // fold (sext c1) -> c1
6820   // fold (zext c1) -> c1
6821   // fold (aext c1) -> c1
6822   if (isa<ConstantSDNode>(N0))
6823     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6824
6825   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6826   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6827   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6828   EVT SVT = VT.getScalarType();
6829   if (!(VT.isVector() &&
6830       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6831       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6832     return nullptr;
6833
6834   // We can fold this node into a build_vector.
6835   unsigned VTBits = SVT.getSizeInBits();
6836   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6837   SmallVector<SDValue, 8> Elts;
6838   unsigned NumElts = VT.getVectorNumElements();
6839   SDLoc DL(N);
6840
6841   for (unsigned i=0; i != NumElts; ++i) {
6842     SDValue Op = N0->getOperand(i);
6843     if (Op->isUndef()) {
6844       Elts.push_back(DAG.getUNDEF(SVT));
6845       continue;
6846     }
6847
6848     SDLoc DL(Op);
6849     // Get the constant value and if needed trunc it to the size of the type.
6850     // Nodes like build_vector might have constants wider than the scalar type.
6851     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6852     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6853       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6854     else
6855       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6856   }
6857
6858   return DAG.getBuildVector(VT, DL, Elts).getNode();
6859 }
6860
6861 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6862 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6863 // transformation. Returns true if extension are possible and the above
6864 // mentioned transformation is profitable.
6865 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6866                                     unsigned ExtOpc,
6867                                     SmallVectorImpl<SDNode *> &ExtendNodes,
6868                                     const TargetLowering &TLI) {
6869   bool HasCopyToRegUses = false;
6870   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6871   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6872                             UE = N0.getNode()->use_end();
6873        UI != UE; ++UI) {
6874     SDNode *User = *UI;
6875     if (User == N)
6876       continue;
6877     if (UI.getUse().getResNo() != N0.getResNo())
6878       continue;
6879     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6880     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6881       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6882       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6883         // Sign bits will be lost after a zext.
6884         return false;
6885       bool Add = false;
6886       for (unsigned i = 0; i != 2; ++i) {
6887         SDValue UseOp = User->getOperand(i);
6888         if (UseOp == N0)
6889           continue;
6890         if (!isa<ConstantSDNode>(UseOp))
6891           return false;
6892         Add = true;
6893       }
6894       if (Add)
6895         ExtendNodes.push_back(User);
6896       continue;
6897     }
6898     // If truncates aren't free and there are users we can't
6899     // extend, it isn't worthwhile.
6900     if (!isTruncFree)
6901       return false;
6902     // Remember if this value is live-out.
6903     if (User->getOpcode() == ISD::CopyToReg)
6904       HasCopyToRegUses = true;
6905   }
6906
6907   if (HasCopyToRegUses) {
6908     bool BothLiveOut = false;
6909     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6910          UI != UE; ++UI) {
6911       SDUse &Use = UI.getUse();
6912       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6913         BothLiveOut = true;
6914         break;
6915       }
6916     }
6917     if (BothLiveOut)
6918       // Both unextended and extended values are live out. There had better be
6919       // a good reason for the transformation.
6920       return ExtendNodes.size();
6921   }
6922   return true;
6923 }
6924
6925 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6926                                   SDValue Trunc, SDValue ExtLoad,
6927                                   const SDLoc &DL, ISD::NodeType ExtType) {
6928   // Extend SetCC uses if necessary.
6929   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6930     SDNode *SetCC = SetCCs[i];
6931     SmallVector<SDValue, 4> Ops;
6932
6933     for (unsigned j = 0; j != 2; ++j) {
6934       SDValue SOp = SetCC->getOperand(j);
6935       if (SOp == Trunc)
6936         Ops.push_back(ExtLoad);
6937       else
6938         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6939     }
6940
6941     Ops.push_back(SetCC->getOperand(2));
6942     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6943   }
6944 }
6945
6946 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6947 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6948   SDValue N0 = N->getOperand(0);
6949   EVT DstVT = N->getValueType(0);
6950   EVT SrcVT = N0.getValueType();
6951
6952   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6953           N->getOpcode() == ISD::ZERO_EXTEND) &&
6954          "Unexpected node type (not an extend)!");
6955
6956   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6957   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6958   //   (v8i32 (sext (v8i16 (load x))))
6959   // into:
6960   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6961   //                          (v4i32 (sextload (x + 16)))))
6962   // Where uses of the original load, i.e.:
6963   //   (v8i16 (load x))
6964   // are replaced with:
6965   //   (v8i16 (truncate
6966   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6967   //                            (v4i32 (sextload (x + 16)))))))
6968   //
6969   // This combine is only applicable to illegal, but splittable, vectors.
6970   // All legal types, and illegal non-vector types, are handled elsewhere.
6971   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6972   //
6973   if (N0->getOpcode() != ISD::LOAD)
6974     return SDValue();
6975
6976   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6977
6978   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6979       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6980       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6981     return SDValue();
6982
6983   SmallVector<SDNode *, 4> SetCCs;
6984   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6985     return SDValue();
6986
6987   ISD::LoadExtType ExtType =
6988       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6989
6990   // Try to split the vector types to get down to legal types.
6991   EVT SplitSrcVT = SrcVT;
6992   EVT SplitDstVT = DstVT;
6993   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6994          SplitSrcVT.getVectorNumElements() > 1) {
6995     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6996     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6997   }
6998
6999   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7000     return SDValue();
7001
7002   SDLoc DL(N);
7003   const unsigned NumSplits =
7004       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7005   const unsigned Stride = SplitSrcVT.getStoreSize();
7006   SmallVector<SDValue, 4> Loads;
7007   SmallVector<SDValue, 4> Chains;
7008
7009   SDValue BasePtr = LN0->getBasePtr();
7010   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7011     const unsigned Offset = Idx * Stride;
7012     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7013
7014     SDValue SplitLoad = DAG.getExtLoad(
7015         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7016         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7017         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7018
7019     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7020                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7021
7022     Loads.push_back(SplitLoad.getValue(0));
7023     Chains.push_back(SplitLoad.getValue(1));
7024   }
7025
7026   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7027   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7028
7029   // Simplify TF.
7030   AddToWorklist(NewChain.getNode());
7031
7032   CombineTo(N, NewValue);
7033
7034   // Replace uses of the original load (before extension)
7035   // with a truncate of the concatenated sextloaded vectors.
7036   SDValue Trunc =
7037       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7038   CombineTo(N0.getNode(), Trunc, NewChain);
7039   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
7040                   (ISD::NodeType)N->getOpcode());
7041   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7042 }
7043
7044 /// If we're narrowing or widening the result of a vector select and the final
7045 /// size is the same size as a setcc (compare) feeding the select, then try to
7046 /// apply the cast operation to the select's operands because matching vector
7047 /// sizes for a select condition and other operands should be more efficient.
7048 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7049   unsigned CastOpcode = Cast->getOpcode();
7050   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7051           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7052           CastOpcode == ISD::FP_ROUND) &&
7053          "Unexpected opcode for vector select narrowing/widening");
7054
7055   // We only do this transform before legal ops because the pattern may be
7056   // obfuscated by target-specific operations after legalization. Do not create
7057   // an illegal select op, however, because that may be difficult to lower.
7058   EVT VT = Cast->getValueType(0);
7059   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7060     return SDValue();
7061
7062   SDValue VSel = Cast->getOperand(0);
7063   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7064       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7065     return SDValue();
7066
7067   // Does the setcc have the same vector size as the casted select?
7068   SDValue SetCC = VSel.getOperand(0);
7069   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7070   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7071     return SDValue();
7072
7073   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7074   SDValue A = VSel.getOperand(1);
7075   SDValue B = VSel.getOperand(2);
7076   SDValue CastA, CastB;
7077   SDLoc DL(Cast);
7078   if (CastOpcode == ISD::FP_ROUND) {
7079     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7080     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7081     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7082   } else {
7083     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7084     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7085   }
7086   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7087 }
7088
7089 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7090   SDValue N0 = N->getOperand(0);
7091   EVT VT = N->getValueType(0);
7092   SDLoc DL(N);
7093
7094   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7095                                               LegalOperations))
7096     return SDValue(Res, 0);
7097
7098   // fold (sext (sext x)) -> (sext x)
7099   // fold (sext (aext x)) -> (sext x)
7100   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7101     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7102
7103   if (N0.getOpcode() == ISD::TRUNCATE) {
7104     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7105     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7106     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7107       SDNode *oye = N0.getOperand(0).getNode();
7108       if (NarrowLoad.getNode() != N0.getNode()) {
7109         CombineTo(N0.getNode(), NarrowLoad);
7110         // CombineTo deleted the truncate, if needed, but not what's under it.
7111         AddToWorklist(oye);
7112       }
7113       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7114     }
7115
7116     // See if the value being truncated is already sign extended.  If so, just
7117     // eliminate the trunc/sext pair.
7118     SDValue Op = N0.getOperand(0);
7119     unsigned OpBits   = Op.getScalarValueSizeInBits();
7120     unsigned MidBits  = N0.getScalarValueSizeInBits();
7121     unsigned DestBits = VT.getScalarSizeInBits();
7122     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7123
7124     if (OpBits == DestBits) {
7125       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7126       // bits, it is already ready.
7127       if (NumSignBits > DestBits-MidBits)
7128         return Op;
7129     } else if (OpBits < DestBits) {
7130       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7131       // bits, just sext from i32.
7132       if (NumSignBits > OpBits-MidBits)
7133         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7134     } else {
7135       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7136       // bits, just truncate to i32.
7137       if (NumSignBits > OpBits-MidBits)
7138         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7139     }
7140
7141     // fold (sext (truncate x)) -> (sextinreg x).
7142     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7143                                                  N0.getValueType())) {
7144       if (OpBits < DestBits)
7145         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7146       else if (OpBits > DestBits)
7147         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7148       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7149                          DAG.getValueType(N0.getValueType()));
7150     }
7151   }
7152
7153   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7154   // Only generate vector extloads when 1) they're legal, and 2) they are
7155   // deemed desirable by the target.
7156   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7157       ((!LegalOperations && !VT.isVector() &&
7158         !cast<LoadSDNode>(N0)->isVolatile()) ||
7159        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7160     bool DoXform = true;
7161     SmallVector<SDNode*, 4> SetCCs;
7162     if (!N0.hasOneUse())
7163       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7164     if (VT.isVector())
7165       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7166     if (DoXform) {
7167       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7168       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7169                                        LN0->getBasePtr(), N0.getValueType(),
7170                                        LN0->getMemOperand());
7171       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7172                                   N0.getValueType(), ExtLoad);
7173       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7174       // If the load value is used only by N, replace it via CombineTo N.
7175       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7176       CombineTo(N, ExtLoad);
7177       if (NoReplaceTrunc)
7178         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7179       else
7180         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7181       return SDValue(N, 0);
7182     }
7183   }
7184
7185   // fold (sext (load x)) to multiple smaller sextloads.
7186   // Only on illegal but splittable vectors.
7187   if (SDValue ExtLoad = CombineExtLoad(N))
7188     return ExtLoad;
7189
7190   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7191   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7192   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7193       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7194     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7195     EVT MemVT = LN0->getMemoryVT();
7196     if ((!LegalOperations && !LN0->isVolatile()) ||
7197         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7198       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7199                                        LN0->getBasePtr(), MemVT,
7200                                        LN0->getMemOperand());
7201       CombineTo(N, ExtLoad);
7202       CombineTo(N0.getNode(),
7203                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7204                             N0.getValueType(), ExtLoad),
7205                 ExtLoad.getValue(1));
7206       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7207     }
7208   }
7209
7210   // fold (sext (and/or/xor (load x), cst)) ->
7211   //      (and/or/xor (sextload x), (sext cst))
7212   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7213        N0.getOpcode() == ISD::XOR) &&
7214       isa<LoadSDNode>(N0.getOperand(0)) &&
7215       N0.getOperand(1).getOpcode() == ISD::Constant &&
7216       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7217       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7218     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7219     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7220       bool DoXform = true;
7221       SmallVector<SDNode*, 4> SetCCs;
7222       if (!N0.hasOneUse())
7223         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7224                                           SetCCs, TLI);
7225       if (DoXform) {
7226         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7227                                          LN0->getChain(), LN0->getBasePtr(),
7228                                          LN0->getMemoryVT(),
7229                                          LN0->getMemOperand());
7230         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7231         Mask = Mask.sext(VT.getSizeInBits());
7232         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7233                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7234         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7235                                     SDLoc(N0.getOperand(0)),
7236                                     N0.getOperand(0).getValueType(), ExtLoad);
7237         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7238         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7239         CombineTo(N, And);
7240         if (NoReplaceTrunc)
7241           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7242         else
7243           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7244         return SDValue(N,0); // Return N so it doesn't get rechecked!
7245       }
7246     }
7247   }
7248
7249   if (N0.getOpcode() == ISD::SETCC) {
7250     SDValue N00 = N0.getOperand(0);
7251     SDValue N01 = N0.getOperand(1);
7252     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7253     EVT N00VT = N0.getOperand(0).getValueType();
7254
7255     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7256     // Only do this before legalize for now.
7257     if (VT.isVector() && !LegalOperations &&
7258         TLI.getBooleanContents(N00VT) ==
7259             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7260       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7261       // of the same size as the compared operands. Only optimize sext(setcc())
7262       // if this is the case.
7263       EVT SVT = getSetCCResultType(N00VT);
7264
7265       // We know that the # elements of the results is the same as the
7266       // # elements of the compare (and the # elements of the compare result
7267       // for that matter).  Check to see that they are the same size.  If so,
7268       // we know that the element size of the sext'd result matches the
7269       // element size of the compare operands.
7270       if (VT.getSizeInBits() == SVT.getSizeInBits())
7271         return DAG.getSetCC(DL, VT, N00, N01, CC);
7272
7273       // If the desired elements are smaller or larger than the source
7274       // elements, we can use a matching integer vector type and then
7275       // truncate/sign extend.
7276       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7277       if (SVT == MatchingVecType) {
7278         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7279         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7280       }
7281     }
7282
7283     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7284     // Here, T can be 1 or -1, depending on the type of the setcc and
7285     // getBooleanContents().
7286     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7287
7288     // To determine the "true" side of the select, we need to know the high bit
7289     // of the value returned by the setcc if it evaluates to true.
7290     // If the type of the setcc is i1, then the true case of the select is just
7291     // sext(i1 1), that is, -1.
7292     // If the type of the setcc is larger (say, i8) then the value of the high
7293     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7294     // of the appropriate width.
7295     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7296                                            : TLI.getConstTrueVal(DAG, VT, DL);
7297     SDValue Zero = DAG.getConstant(0, DL, VT);
7298     if (SDValue SCC =
7299             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7300       return SCC;
7301
7302     if (!VT.isVector()) {
7303       EVT SetCCVT = getSetCCResultType(N00VT);
7304       // Don't do this transform for i1 because there's a select transform
7305       // that would reverse it.
7306       // TODO: We should not do this transform at all without a target hook
7307       // because a sext is likely cheaper than a select?
7308       if (SetCCVT.getScalarSizeInBits() != 1 &&
7309           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7310         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7311         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7312       }
7313     }
7314   }
7315
7316   // fold (sext x) -> (zext x) if the sign bit is known zero.
7317   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7318       DAG.SignBitIsZero(N0))
7319     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7320
7321   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7322     return NewVSel;
7323
7324   return SDValue();
7325 }
7326
7327 // isTruncateOf - If N is a truncate of some other value, return true, record
7328 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7329 // This function computes KnownBits to avoid a duplicated call to
7330 // computeKnownBits in the caller.
7331 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7332                          KnownBits &Known) {
7333   if (N->getOpcode() == ISD::TRUNCATE) {
7334     Op = N->getOperand(0);
7335     DAG.computeKnownBits(Op, Known);
7336     return true;
7337   }
7338
7339   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7340       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7341     return false;
7342
7343   SDValue Op0 = N->getOperand(0);
7344   SDValue Op1 = N->getOperand(1);
7345   assert(Op0.getValueType() == Op1.getValueType());
7346
7347   if (isNullConstant(Op0))
7348     Op = Op1;
7349   else if (isNullConstant(Op1))
7350     Op = Op0;
7351   else
7352     return false;
7353
7354   DAG.computeKnownBits(Op, Known);
7355
7356   if (!(Known.Zero | 1).isAllOnesValue())
7357     return false;
7358
7359   return true;
7360 }
7361
7362 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7363   SDValue N0 = N->getOperand(0);
7364   EVT VT = N->getValueType(0);
7365
7366   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7367                                               LegalOperations))
7368     return SDValue(Res, 0);
7369
7370   // fold (zext (zext x)) -> (zext x)
7371   // fold (zext (aext x)) -> (zext x)
7372   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7373     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7374                        N0.getOperand(0));
7375
7376   // fold (zext (truncate x)) -> (zext x) or
7377   //      (zext (truncate x)) -> (truncate x)
7378   // This is valid when the truncated bits of x are already zero.
7379   // FIXME: We should extend this to work for vectors too.
7380   SDValue Op;
7381   KnownBits Known;
7382   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7383     APInt TruncatedBits =
7384       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7385       APInt(Op.getValueSizeInBits(), 0) :
7386       APInt::getBitsSet(Op.getValueSizeInBits(),
7387                         N0.getValueSizeInBits(),
7388                         std::min(Op.getValueSizeInBits(),
7389                                  VT.getSizeInBits()));
7390     if (TruncatedBits.isSubsetOf(Known.Zero))
7391       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7392   }
7393
7394   // fold (zext (truncate (load x))) -> (zext (smaller load x))
7395   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7396   if (N0.getOpcode() == ISD::TRUNCATE) {
7397     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7398       SDNode *oye = N0.getOperand(0).getNode();
7399       if (NarrowLoad.getNode() != N0.getNode()) {
7400         CombineTo(N0.getNode(), NarrowLoad);
7401         // CombineTo deleted the truncate, if needed, but not what's under it.
7402         AddToWorklist(oye);
7403       }
7404       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7405     }
7406   }
7407
7408   // fold (zext (truncate x)) -> (and x, mask)
7409   if (N0.getOpcode() == ISD::TRUNCATE) {
7410     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7411     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7412     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7413       SDNode *oye = N0.getOperand(0).getNode();
7414       if (NarrowLoad.getNode() != N0.getNode()) {
7415         CombineTo(N0.getNode(), NarrowLoad);
7416         // CombineTo deleted the truncate, if needed, but not what's under it.
7417         AddToWorklist(oye);
7418       }
7419       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7420     }
7421
7422     EVT SrcVT = N0.getOperand(0).getValueType();
7423     EVT MinVT = N0.getValueType();
7424
7425     // Try to mask before the extension to avoid having to generate a larger mask,
7426     // possibly over several sub-vectors.
7427     if (SrcVT.bitsLT(VT)) {
7428       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7429                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7430         SDValue Op = N0.getOperand(0);
7431         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7432         AddToWorklist(Op.getNode());
7433         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7434       }
7435     }
7436
7437     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7438       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7439       AddToWorklist(Op.getNode());
7440       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7441     }
7442   }
7443
7444   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7445   // if either of the casts is not free.
7446   if (N0.getOpcode() == ISD::AND &&
7447       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7448       N0.getOperand(1).getOpcode() == ISD::Constant &&
7449       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7450                            N0.getValueType()) ||
7451        !TLI.isZExtFree(N0.getValueType(), VT))) {
7452     SDValue X = N0.getOperand(0).getOperand(0);
7453     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7454     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7455     Mask = Mask.zext(VT.getSizeInBits());
7456     SDLoc DL(N);
7457     return DAG.getNode(ISD::AND, DL, VT,
7458                        X, DAG.getConstant(Mask, DL, VT));
7459   }
7460
7461   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7462   // Only generate vector extloads when 1) they're legal, and 2) they are
7463   // deemed desirable by the target.
7464   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7465       ((!LegalOperations && !VT.isVector() &&
7466         !cast<LoadSDNode>(N0)->isVolatile()) ||
7467        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7468     bool DoXform = true;
7469     SmallVector<SDNode*, 4> SetCCs;
7470     if (!N0.hasOneUse())
7471       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7472     if (VT.isVector())
7473       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7474     if (DoXform) {
7475       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7476       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7477                                        LN0->getChain(),
7478                                        LN0->getBasePtr(), N0.getValueType(),
7479                                        LN0->getMemOperand());
7480
7481       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7482                                   N0.getValueType(), ExtLoad);
7483       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
7484       // If the load value is used only by N, replace it via CombineTo N.
7485       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7486       CombineTo(N, ExtLoad);
7487       if (NoReplaceTrunc)
7488         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7489       else
7490         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7491       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7492     }
7493   }
7494
7495   // fold (zext (load x)) to multiple smaller zextloads.
7496   // Only on illegal but splittable vectors.
7497   if (SDValue ExtLoad = CombineExtLoad(N))
7498     return ExtLoad;
7499
7500   // fold (zext (and/or/xor (load x), cst)) ->
7501   //      (and/or/xor (zextload x), (zext cst))
7502   // Unless (and (load x) cst) will match as a zextload already and has
7503   // additional users.
7504   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7505        N0.getOpcode() == ISD::XOR) &&
7506       isa<LoadSDNode>(N0.getOperand(0)) &&
7507       N0.getOperand(1).getOpcode() == ISD::Constant &&
7508       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7509       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7510     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7511     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7512       bool DoXform = true;
7513       SmallVector<SDNode*, 4> SetCCs;
7514       if (!N0.hasOneUse()) {
7515         if (N0.getOpcode() == ISD::AND) {
7516           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7517           auto NarrowLoad = false;
7518           EVT LoadResultTy = AndC->getValueType(0);
7519           EVT ExtVT, LoadedVT;
7520           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7521                                NarrowLoad))
7522             DoXform = false;
7523         }
7524         if (DoXform)
7525           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7526                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7527       }
7528       if (DoXform) {
7529         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7530                                          LN0->getChain(), LN0->getBasePtr(),
7531                                          LN0->getMemoryVT(),
7532                                          LN0->getMemOperand());
7533         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7534         Mask = Mask.zext(VT.getSizeInBits());
7535         SDLoc DL(N);
7536         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7537                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7538         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7539                                     SDLoc(N0.getOperand(0)),
7540                                     N0.getOperand(0).getValueType(), ExtLoad);
7541         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND);
7542         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7543         CombineTo(N, And);
7544         if (NoReplaceTrunc)
7545           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7546         else
7547           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7548         return SDValue(N,0); // Return N so it doesn't get rechecked!
7549       }
7550     }
7551   }
7552
7553   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7554   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7555   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7556       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7557     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7558     EVT MemVT = LN0->getMemoryVT();
7559     if ((!LegalOperations && !LN0->isVolatile()) ||
7560         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7561       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7562                                        LN0->getChain(),
7563                                        LN0->getBasePtr(), MemVT,
7564                                        LN0->getMemOperand());
7565       CombineTo(N, ExtLoad);
7566       CombineTo(N0.getNode(),
7567                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7568                             ExtLoad),
7569                 ExtLoad.getValue(1));
7570       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7571     }
7572   }
7573
7574   if (N0.getOpcode() == ISD::SETCC) {
7575     // Only do this before legalize for now.
7576     if (!LegalOperations && VT.isVector() &&
7577         N0.getValueType().getVectorElementType() == MVT::i1) {
7578       EVT N00VT = N0.getOperand(0).getValueType();
7579       if (getSetCCResultType(N00VT) == N0.getValueType())
7580         return SDValue();
7581
7582       // We know that the # elements of the results is the same as the #
7583       // elements of the compare (and the # elements of the compare result for
7584       // that matter). Check to see that they are the same size. If so, we know
7585       // that the element size of the sext'd result matches the element size of
7586       // the compare operands.
7587       SDLoc DL(N);
7588       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7589       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7590         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7591         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7592                                      N0.getOperand(1), N0.getOperand(2));
7593         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7594       }
7595
7596       // If the desired elements are smaller or larger than the source
7597       // elements we can use a matching integer vector type and then
7598       // truncate/sign extend.
7599       EVT MatchingElementType = EVT::getIntegerVT(
7600           *DAG.getContext(), N00VT.getScalarSizeInBits());
7601       EVT MatchingVectorType = EVT::getVectorVT(
7602           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7603       SDValue VsetCC =
7604           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7605                       N0.getOperand(1), N0.getOperand(2));
7606       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7607                          VecOnes);
7608     }
7609
7610     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7611     SDLoc DL(N);
7612     if (SDValue SCC = SimplifySelectCC(
7613             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7614             DAG.getConstant(0, DL, VT),
7615             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7616       return SCC;
7617   }
7618
7619   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7620   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7621       isa<ConstantSDNode>(N0.getOperand(1)) &&
7622       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7623       N0.hasOneUse()) {
7624     SDValue ShAmt = N0.getOperand(1);
7625     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7626     if (N0.getOpcode() == ISD::SHL) {
7627       SDValue InnerZExt = N0.getOperand(0);
7628       // If the original shl may be shifting out bits, do not perform this
7629       // transformation.
7630       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7631         InnerZExt.getOperand(0).getValueSizeInBits();
7632       if (ShAmtVal > KnownZeroBits)
7633         return SDValue();
7634     }
7635
7636     SDLoc DL(N);
7637
7638     // Ensure that the shift amount is wide enough for the shifted value.
7639     if (VT.getSizeInBits() >= 256)
7640       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7641
7642     return DAG.getNode(N0.getOpcode(), DL, VT,
7643                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7644                        ShAmt);
7645   }
7646
7647   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7648     return NewVSel;
7649
7650   return SDValue();
7651 }
7652
7653 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7654   SDValue N0 = N->getOperand(0);
7655   EVT VT = N->getValueType(0);
7656
7657   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7658                                               LegalOperations))
7659     return SDValue(Res, 0);
7660
7661   // fold (aext (aext x)) -> (aext x)
7662   // fold (aext (zext x)) -> (zext x)
7663   // fold (aext (sext x)) -> (sext x)
7664   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
7665       N0.getOpcode() == ISD::ZERO_EXTEND ||
7666       N0.getOpcode() == ISD::SIGN_EXTEND)
7667     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7668
7669   // fold (aext (truncate (load x))) -> (aext (smaller load x))
7670   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7671   if (N0.getOpcode() == ISD::TRUNCATE) {
7672     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7673       SDNode *oye = N0.getOperand(0).getNode();
7674       if (NarrowLoad.getNode() != N0.getNode()) {
7675         CombineTo(N0.getNode(), NarrowLoad);
7676         // CombineTo deleted the truncate, if needed, but not what's under it.
7677         AddToWorklist(oye);
7678       }
7679       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7680     }
7681   }
7682
7683   // fold (aext (truncate x))
7684   if (N0.getOpcode() == ISD::TRUNCATE)
7685     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7686
7687   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7688   // if the trunc is not free.
7689   if (N0.getOpcode() == ISD::AND &&
7690       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7691       N0.getOperand(1).getOpcode() == ISD::Constant &&
7692       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7693                           N0.getValueType())) {
7694     SDLoc DL(N);
7695     SDValue X = N0.getOperand(0).getOperand(0);
7696     X = DAG.getAnyExtOrTrunc(X, DL, VT);
7697     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7698     Mask = Mask.zext(VT.getSizeInBits());
7699     return DAG.getNode(ISD::AND, DL, VT,
7700                        X, DAG.getConstant(Mask, DL, VT));
7701   }
7702
7703   // fold (aext (load x)) -> (aext (truncate (extload x)))
7704   // None of the supported targets knows how to perform load and any_ext
7705   // on vectors in one instruction.  We only perform this transformation on
7706   // scalars.
7707   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7708       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7709       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7710     bool DoXform = true;
7711     SmallVector<SDNode*, 4> SetCCs;
7712     if (!N0.hasOneUse())
7713       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7714     if (DoXform) {
7715       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7716       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7717                                        LN0->getChain(),
7718                                        LN0->getBasePtr(), N0.getValueType(),
7719                                        LN0->getMemOperand());
7720       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7721                                   N0.getValueType(), ExtLoad);
7722       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7723                       ISD::ANY_EXTEND);
7724       // If the load value is used only by N, replace it via CombineTo N.
7725       bool NoReplaceTrunc = N0.hasOneUse();
7726       CombineTo(N, ExtLoad); 
7727       if (NoReplaceTrunc)
7728         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7729       else
7730         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7731       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7732     }
7733   }
7734
7735   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7736   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7737   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
7738   if (N0.getOpcode() == ISD::LOAD &&
7739       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7740       N0.hasOneUse()) {
7741     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7742     ISD::LoadExtType ExtType = LN0->getExtensionType();
7743     EVT MemVT = LN0->getMemoryVT();
7744     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7745       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7746                                        VT, LN0->getChain(), LN0->getBasePtr(),
7747                                        MemVT, LN0->getMemOperand());
7748       CombineTo(N, ExtLoad);
7749       CombineTo(N0.getNode(),
7750                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7751                             N0.getValueType(), ExtLoad),
7752                 ExtLoad.getValue(1));
7753       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7754     }
7755   }
7756
7757   if (N0.getOpcode() == ISD::SETCC) {
7758     // For vectors:
7759     // aext(setcc) -> vsetcc
7760     // aext(setcc) -> truncate(vsetcc)
7761     // aext(setcc) -> aext(vsetcc)
7762     // Only do this before legalize for now.
7763     if (VT.isVector() && !LegalOperations) {
7764       EVT N0VT = N0.getOperand(0).getValueType();
7765         // We know that the # elements of the results is the same as the
7766         // # elements of the compare (and the # elements of the compare result
7767         // for that matter).  Check to see that they are the same size.  If so,
7768         // we know that the element size of the sext'd result matches the
7769         // element size of the compare operands.
7770       if (VT.getSizeInBits() == N0VT.getSizeInBits())
7771         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7772                              N0.getOperand(1),
7773                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
7774       // If the desired elements are smaller or larger than the source
7775       // elements we can use a matching integer vector type and then
7776       // truncate/any extend
7777       else {
7778         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7779         SDValue VsetCC =
7780           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7781                         N0.getOperand(1),
7782                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
7783         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7784       }
7785     }
7786
7787     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7788     SDLoc DL(N);
7789     if (SDValue SCC = SimplifySelectCC(
7790             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7791             DAG.getConstant(0, DL, VT),
7792             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7793       return SCC;
7794   }
7795
7796   return SDValue();
7797 }
7798
7799 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7800   SDValue N0 = N->getOperand(0);
7801   SDValue N1 = N->getOperand(1);
7802   EVT EVT = cast<VTSDNode>(N1)->getVT();
7803
7804   // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7805   if (N0.getOpcode() == ISD::AssertZext &&
7806       EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7807     return N0;
7808
7809   return SDValue();
7810 }
7811
7812 /// See if the specified operand can be simplified with the knowledge that only
7813 /// the bits specified by Mask are used.  If so, return the simpler operand,
7814 /// otherwise return a null SDValue.
7815 ///
7816 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
7817 /// simplify nodes with multiple uses more aggressively.)
7818 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7819   switch (V.getOpcode()) {
7820   default: break;
7821   case ISD::Constant: {
7822     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7823     assert(CV && "Const value should be ConstSDNode.");
7824     const APInt &CVal = CV->getAPIntValue();
7825     APInt NewVal = CVal & Mask;
7826     if (NewVal != CVal)
7827       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7828     break;
7829   }
7830   case ISD::OR:
7831   case ISD::XOR:
7832     // If the LHS or RHS don't contribute bits to the or, drop them.
7833     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7834       return V.getOperand(1);
7835     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7836       return V.getOperand(0);
7837     break;
7838   case ISD::SRL:
7839     // Only look at single-use SRLs.
7840     if (!V.getNode()->hasOneUse())
7841       break;
7842     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7843       // See if we can recursively simplify the LHS.
7844       unsigned Amt = RHSC->getZExtValue();
7845
7846       // Watch out for shift count overflow though.
7847       if (Amt >= Mask.getBitWidth()) break;
7848       APInt NewMask = Mask << Amt;
7849       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7850         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7851                            SimplifyLHS, V.getOperand(1));
7852     }
7853     break;
7854   case ISD::AND: {
7855     // X & -1 -> X (ignoring bits which aren't demanded).
7856     ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
7857     if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
7858       return V.getOperand(0);
7859     break;
7860   }
7861   }
7862   return SDValue();
7863 }
7864
7865 /// If the result of a wider load is shifted to right of N  bits and then
7866 /// truncated to a narrower type and where N is a multiple of number of bits of
7867 /// the narrower type, transform it to a narrower load from address + N / num of
7868 /// bits of new type. If the result is to be extended, also fold the extension
7869 /// to form a extending load.
7870 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7871   unsigned Opc = N->getOpcode();
7872
7873   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7874   SDValue N0 = N->getOperand(0);
7875   EVT VT = N->getValueType(0);
7876   EVT ExtVT = VT;
7877
7878   // This transformation isn't valid for vector loads.
7879   if (VT.isVector())
7880     return SDValue();
7881
7882   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7883   // extended to VT.
7884   if (Opc == ISD::SIGN_EXTEND_INREG) {
7885     ExtType = ISD::SEXTLOAD;
7886     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7887   } else if (Opc == ISD::SRL) {
7888     // Another special-case: SRL is basically zero-extending a narrower value.
7889     ExtType = ISD::ZEXTLOAD;
7890     N0 = SDValue(N, 0);
7891     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7892     if (!N01) return SDValue();
7893     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7894                               VT.getSizeInBits() - N01->getZExtValue());
7895   }
7896   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7897     return SDValue();
7898
7899   unsigned EVTBits = ExtVT.getSizeInBits();
7900
7901   // Do not generate loads of non-round integer types since these can
7902   // be expensive (and would be wrong if the type is not byte sized).
7903   if (!ExtVT.isRound())
7904     return SDValue();
7905
7906   unsigned ShAmt = 0;
7907   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7908     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7909       ShAmt = N01->getZExtValue();
7910       // Is the shift amount a multiple of size of VT?
7911       if ((ShAmt & (EVTBits-1)) == 0) {
7912         N0 = N0.getOperand(0);
7913         // Is the load width a multiple of size of VT?
7914         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7915           return SDValue();
7916       }
7917
7918       // At this point, we must have a load or else we can't do the transform.
7919       if (!isa<LoadSDNode>(N0)) return SDValue();
7920
7921       // Because a SRL must be assumed to *need* to zero-extend the high bits
7922       // (as opposed to anyext the high bits), we can't combine the zextload
7923       // lowering of SRL and an sextload.
7924       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7925         return SDValue();
7926
7927       // If the shift amount is larger than the input type then we're not
7928       // accessing any of the loaded bytes.  If the load was a zextload/extload
7929       // then the result of the shift+trunc is zero/undef (handled elsewhere).
7930       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7931         return SDValue();
7932     }
7933   }
7934
7935   // If the load is shifted left (and the result isn't shifted back right),
7936   // we can fold the truncate through the shift.
7937   unsigned ShLeftAmt = 0;
7938   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7939       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7940     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7941       ShLeftAmt = N01->getZExtValue();
7942       N0 = N0.getOperand(0);
7943     }
7944   }
7945
7946   // If we haven't found a load, we can't narrow it.  Don't transform one with
7947   // multiple uses, this would require adding a new load.
7948   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7949     return SDValue();
7950
7951   // Don't change the width of a volatile load.
7952   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7953   if (LN0->isVolatile())
7954     return SDValue();
7955
7956   // Verify that we are actually reducing a load width here.
7957   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7958     return SDValue();
7959
7960   // For the transform to be legal, the load must produce only two values
7961   // (the value loaded and the chain).  Don't transform a pre-increment
7962   // load, for example, which produces an extra value.  Otherwise the
7963   // transformation is not equivalent, and the downstream logic to replace
7964   // uses gets things wrong.
7965   if (LN0->getNumValues() > 2)
7966     return SDValue();
7967
7968   // If the load that we're shrinking is an extload and we're not just
7969   // discarding the extension we can't simply shrink the load. Bail.
7970   // TODO: It would be possible to merge the extensions in some cases.
7971   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7972       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7973     return SDValue();
7974
7975   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7976     return SDValue();
7977
7978   EVT PtrType = N0.getOperand(1).getValueType();
7979
7980   if (PtrType == MVT::Untyped || PtrType.isExtended())
7981     // It's not possible to generate a constant of extended or untyped type.
7982     return SDValue();
7983
7984   // For big endian targets, we need to adjust the offset to the pointer to
7985   // load the correct bytes.
7986   if (DAG.getDataLayout().isBigEndian()) {
7987     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7988     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7989     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7990   }
7991
7992   uint64_t PtrOff = ShAmt / 8;
7993   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7994   SDLoc DL(LN0);
7995   // The original load itself didn't wrap, so an offset within it doesn't.
7996   SDNodeFlags Flags;
7997   Flags.setNoUnsignedWrap(true);
7998   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7999                                PtrType, LN0->getBasePtr(),
8000                                DAG.getConstant(PtrOff, DL, PtrType),
8001                                Flags);
8002   AddToWorklist(NewPtr.getNode());
8003
8004   SDValue Load;
8005   if (ExtType == ISD::NON_EXTLOAD)
8006     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8007                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8008                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8009   else
8010     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8011                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8012                           NewAlign, LN0->getMemOperand()->getFlags(),
8013                           LN0->getAAInfo());
8014
8015   // Replace the old load's chain with the new load's chain.
8016   WorklistRemover DeadNodes(*this);
8017   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8018
8019   // Shift the result left, if we've swallowed a left shift.
8020   SDValue Result = Load;
8021   if (ShLeftAmt != 0) {
8022     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8023     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8024       ShImmTy = VT;
8025     // If the shift amount is as large as the result size (but, presumably,
8026     // no larger than the source) then the useful bits of the result are
8027     // zero; we can't simply return the shortened shift, because the result
8028     // of that operation is undefined.
8029     SDLoc DL(N0);
8030     if (ShLeftAmt >= VT.getSizeInBits())
8031       Result = DAG.getConstant(0, DL, VT);
8032     else
8033       Result = DAG.getNode(ISD::SHL, DL, VT,
8034                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8035   }
8036
8037   // Return the new loaded value.
8038   return Result;
8039 }
8040
8041 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8042   SDValue N0 = N->getOperand(0);
8043   SDValue N1 = N->getOperand(1);
8044   EVT VT = N->getValueType(0);
8045   EVT EVT = cast<VTSDNode>(N1)->getVT();
8046   unsigned VTBits = VT.getScalarSizeInBits();
8047   unsigned EVTBits = EVT.getScalarSizeInBits();
8048
8049   if (N0.isUndef())
8050     return DAG.getUNDEF(VT);
8051
8052   // fold (sext_in_reg c1) -> c1
8053   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8054     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8055
8056   // If the input is already sign extended, just drop the extension.
8057   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8058     return N0;
8059
8060   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8061   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8062       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8063     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8064                        N0.getOperand(0), N1);
8065
8066   // fold (sext_in_reg (sext x)) -> (sext x)
8067   // fold (sext_in_reg (aext x)) -> (sext x)
8068   // if x is small enough.
8069   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8070     SDValue N00 = N0.getOperand(0);
8071     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8072         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8073       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8074   }
8075
8076   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8077   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8078        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8079        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8080       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8081     if (!LegalOperations ||
8082         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8083       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8084   }
8085
8086   // fold (sext_in_reg (zext x)) -> (sext x)
8087   // iff we are extending the source sign bit.
8088   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8089     SDValue N00 = N0.getOperand(0);
8090     if (N00.getScalarValueSizeInBits() == EVTBits &&
8091         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8092       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8093   }
8094
8095   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8096   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8097     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8098
8099   // fold operands of sext_in_reg based on knowledge that the top bits are not
8100   // demanded.
8101   if (SimplifyDemandedBits(SDValue(N, 0)))
8102     return SDValue(N, 0);
8103
8104   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8105   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8106   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8107     return NarrowLoad;
8108
8109   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8110   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8111   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8112   if (N0.getOpcode() == ISD::SRL) {
8113     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8114       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8115         // We can turn this into an SRA iff the input to the SRL is already sign
8116         // extended enough.
8117         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8118         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8119           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8120                              N0.getOperand(0), N0.getOperand(1));
8121       }
8122   }
8123
8124   // fold (sext_inreg (extload x)) -> (sextload x)
8125   if (ISD::isEXTLoad(N0.getNode()) &&
8126       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8127       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8128       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8129        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8130     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8131     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8132                                      LN0->getChain(),
8133                                      LN0->getBasePtr(), EVT,
8134                                      LN0->getMemOperand());
8135     CombineTo(N, ExtLoad);
8136     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8137     AddToWorklist(ExtLoad.getNode());
8138     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8139   }
8140   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8141   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8142       N0.hasOneUse() &&
8143       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8144       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8145        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8146     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8147     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8148                                      LN0->getChain(),
8149                                      LN0->getBasePtr(), EVT,
8150                                      LN0->getMemOperand());
8151     CombineTo(N, ExtLoad);
8152     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8153     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8154   }
8155
8156   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8157   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8158     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8159                                            N0.getOperand(1), false))
8160       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8161                          BSwap, N1);
8162   }
8163
8164   return SDValue();
8165 }
8166
8167 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8168   SDValue N0 = N->getOperand(0);
8169   EVT VT = N->getValueType(0);
8170
8171   if (N0.isUndef())
8172     return DAG.getUNDEF(VT);
8173
8174   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8175                                               LegalOperations))
8176     return SDValue(Res, 0);
8177
8178   return SDValue();
8179 }
8180
8181 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8182   SDValue N0 = N->getOperand(0);
8183   EVT VT = N->getValueType(0);
8184
8185   if (N0.isUndef())
8186     return DAG.getUNDEF(VT);
8187
8188   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8189                                               LegalOperations))
8190     return SDValue(Res, 0);
8191
8192   return SDValue();
8193 }
8194
8195 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8196   SDValue N0 = N->getOperand(0);
8197   EVT VT = N->getValueType(0);
8198   bool isLE = DAG.getDataLayout().isLittleEndian();
8199
8200   // noop truncate
8201   if (N0.getValueType() == N->getValueType(0))
8202     return N0;
8203   // fold (truncate c1) -> c1
8204   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8205     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8206   // fold (truncate (truncate x)) -> (truncate x)
8207   if (N0.getOpcode() == ISD::TRUNCATE)
8208     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8209   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8210   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8211       N0.getOpcode() == ISD::SIGN_EXTEND ||
8212       N0.getOpcode() == ISD::ANY_EXTEND) {
8213     // if the source is smaller than the dest, we still need an extend.
8214     if (N0.getOperand(0).getValueType().bitsLT(VT))
8215       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8216     // if the source is larger than the dest, than we just need the truncate.
8217     if (N0.getOperand(0).getValueType().bitsGT(VT))
8218       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8219     // if the source and dest are the same type, we can drop both the extend
8220     // and the truncate.
8221     return N0.getOperand(0);
8222   }
8223
8224   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8225   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8226     return SDValue();
8227
8228   // Fold extract-and-trunc into a narrow extract. For example:
8229   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8230   //   i32 y = TRUNCATE(i64 x)
8231   //        -- becomes --
8232   //   v16i8 b = BITCAST (v2i64 val)
8233   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8234   //
8235   // Note: We only run this optimization after type legalization (which often
8236   // creates this pattern) and before operation legalization after which
8237   // we need to be more careful about the vector instructions that we generate.
8238   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8239       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8240
8241     EVT VecTy = N0.getOperand(0).getValueType();
8242     EVT ExTy = N0.getValueType();
8243     EVT TrTy = N->getValueType(0);
8244
8245     unsigned NumElem = VecTy.getVectorNumElements();
8246     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8247
8248     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8249     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8250
8251     SDValue EltNo = N0->getOperand(1);
8252     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8253       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8254       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8255       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8256
8257       SDLoc DL(N);
8258       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8259                          DAG.getBitcast(NVT, N0.getOperand(0)),
8260                          DAG.getConstant(Index, DL, IndexTy));
8261     }
8262   }
8263
8264   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8265   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8266     EVT SrcVT = N0.getValueType();
8267     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8268         TLI.isTruncateFree(SrcVT, VT)) {
8269       SDLoc SL(N0);
8270       SDValue Cond = N0.getOperand(0);
8271       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8272       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8273       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8274     }
8275   }
8276
8277   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8278   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8279       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8280       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8281     SDValue Amt = N0.getOperand(1);
8282     KnownBits Known;
8283     DAG.computeKnownBits(Amt, Known);
8284     unsigned Size = VT.getScalarSizeInBits();
8285     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8286       SDLoc SL(N);
8287       EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8288
8289       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8290       if (AmtVT != Amt.getValueType()) {
8291         Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8292         AddToWorklist(Amt.getNode());
8293       }
8294       return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8295     }
8296   }
8297
8298   // Fold a series of buildvector, bitcast, and truncate if possible.
8299   // For example fold
8300   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8301   //   (2xi32 (buildvector x, y)).
8302   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8303       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8304       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8305       N0.getOperand(0).hasOneUse()) {
8306
8307     SDValue BuildVect = N0.getOperand(0);
8308     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8309     EVT TruncVecEltTy = VT.getVectorElementType();
8310
8311     // Check that the element types match.
8312     if (BuildVectEltTy == TruncVecEltTy) {
8313       // Now we only need to compute the offset of the truncated elements.
8314       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8315       unsigned TruncVecNumElts = VT.getVectorNumElements();
8316       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8317
8318       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8319              "Invalid number of elements");
8320
8321       SmallVector<SDValue, 8> Opnds;
8322       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8323         Opnds.push_back(BuildVect.getOperand(i));
8324
8325       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8326     }
8327   }
8328
8329   // See if we can simplify the input to this truncate through knowledge that
8330   // only the low bits are being used.
8331   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8332   // Currently we only perform this optimization on scalars because vectors
8333   // may have different active low bits.
8334   if (!VT.isVector()) {
8335     if (SDValue Shorter =
8336             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
8337                                                      VT.getSizeInBits())))
8338       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8339   }
8340
8341   // fold (truncate (load x)) -> (smaller load x)
8342   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8343   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8344     if (SDValue Reduced = ReduceLoadWidth(N))
8345       return Reduced;
8346
8347     // Handle the case where the load remains an extending load even
8348     // after truncation.
8349     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8350       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8351       if (!LN0->isVolatile() &&
8352           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8353         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8354                                          VT, LN0->getChain(), LN0->getBasePtr(),
8355                                          LN0->getMemoryVT(),
8356                                          LN0->getMemOperand());
8357         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8358         return NewLoad;
8359       }
8360     }
8361   }
8362
8363   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8364   // where ... are all 'undef'.
8365   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8366     SmallVector<EVT, 8> VTs;
8367     SDValue V;
8368     unsigned Idx = 0;
8369     unsigned NumDefs = 0;
8370
8371     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8372       SDValue X = N0.getOperand(i);
8373       if (!X.isUndef()) {
8374         V = X;
8375         Idx = i;
8376         NumDefs++;
8377       }
8378       // Stop if more than one members are non-undef.
8379       if (NumDefs > 1)
8380         break;
8381       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8382                                      VT.getVectorElementType(),
8383                                      X.getValueType().getVectorNumElements()));
8384     }
8385
8386     if (NumDefs == 0)
8387       return DAG.getUNDEF(VT);
8388
8389     if (NumDefs == 1) {
8390       assert(V.getNode() && "The single defined operand is empty!");
8391       SmallVector<SDValue, 8> Opnds;
8392       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8393         if (i != Idx) {
8394           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8395           continue;
8396         }
8397         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8398         AddToWorklist(NV.getNode());
8399         Opnds.push_back(NV);
8400       }
8401       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8402     }
8403   }
8404
8405   // Fold truncate of a bitcast of a vector to an extract of the low vector
8406   // element.
8407   //
8408   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
8409   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8410     SDValue VecSrc = N0.getOperand(0);
8411     EVT SrcVT = VecSrc.getValueType();
8412     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8413         (!LegalOperations ||
8414          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8415       SDLoc SL(N);
8416
8417       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8418       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8419                          VecSrc, DAG.getConstant(0, SL, IdxVT));
8420     }
8421   }
8422
8423   // Simplify the operands using demanded-bits information.
8424   if (!VT.isVector() &&
8425       SimplifyDemandedBits(SDValue(N, 0)))
8426     return SDValue(N, 0);
8427
8428   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8429   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8430   // When the adde's carry is not used.
8431   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8432       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8433       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8434     SDLoc SL(N);
8435     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8436     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8437     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8438     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8439   }
8440
8441   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8442     return NewVSel;
8443
8444   return SDValue();
8445 }
8446
8447 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8448   SDValue Elt = N->getOperand(i);
8449   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8450     return Elt.getNode();
8451   return Elt.getOperand(Elt.getResNo()).getNode();
8452 }
8453
8454 /// build_pair (load, load) -> load
8455 /// if load locations are consecutive.
8456 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8457   assert(N->getOpcode() == ISD::BUILD_PAIR);
8458
8459   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8460   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8461   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8462       LD1->getAddressSpace() != LD2->getAddressSpace())
8463     return SDValue();
8464   EVT LD1VT = LD1->getValueType(0);
8465   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8466   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8467       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8468     unsigned Align = LD1->getAlignment();
8469     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8470         VT.getTypeForEVT(*DAG.getContext()));
8471
8472     if (NewAlign <= Align &&
8473         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8474       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8475                          LD1->getPointerInfo(), Align);
8476   }
8477
8478   return SDValue();
8479 }
8480
8481 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8482   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8483   // and Lo parts; on big-endian machines it doesn't.
8484   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8485 }
8486
8487 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8488                                     const TargetLowering &TLI) {
8489   // If this is not a bitcast to an FP type or if the target doesn't have
8490   // IEEE754-compliant FP logic, we're done.
8491   EVT VT = N->getValueType(0);
8492   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8493     return SDValue();
8494
8495   // TODO: Use splat values for the constant-checking below and remove this
8496   // restriction.
8497   SDValue N0 = N->getOperand(0);
8498   EVT SourceVT = N0.getValueType();
8499   if (SourceVT.isVector())
8500     return SDValue();
8501
8502   unsigned FPOpcode;
8503   APInt SignMask;
8504   switch (N0.getOpcode()) {
8505   case ISD::AND:
8506     FPOpcode = ISD::FABS;
8507     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8508     break;
8509   case ISD::XOR:
8510     FPOpcode = ISD::FNEG;
8511     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8512     break;
8513   // TODO: ISD::OR --> ISD::FNABS?
8514   default:
8515     return SDValue();
8516   }
8517
8518   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8519   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8520   SDValue LogicOp0 = N0.getOperand(0);
8521   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8522   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8523       LogicOp0.getOpcode() == ISD::BITCAST &&
8524       LogicOp0->getOperand(0).getValueType() == VT)
8525     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8526
8527   return SDValue();
8528 }
8529
8530 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8531   SDValue N0 = N->getOperand(0);
8532   EVT VT = N->getValueType(0);
8533
8534   if (N0.isUndef())
8535     return DAG.getUNDEF(VT);
8536
8537   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8538   // Only do this before legalize, since afterward the target may be depending
8539   // on the bitconvert.
8540   // First check to see if this is all constant.
8541   if (!LegalTypes &&
8542       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8543       VT.isVector()) {
8544     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8545
8546     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8547     assert(!DestEltVT.isVector() &&
8548            "Element type of vector ValueType must not be vector!");
8549     if (isSimple)
8550       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8551   }
8552
8553   // If the input is a constant, let getNode fold it.
8554   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8555     // If we can't allow illegal operations, we need to check that this is just
8556     // a fp -> int or int -> conversion and that the resulting operation will
8557     // be legal.
8558     if (!LegalOperations ||
8559         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8560          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8561         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8562          TLI.isOperationLegal(ISD::Constant, VT)))
8563       return DAG.getBitcast(VT, N0);
8564   }
8565
8566   // (conv (conv x, t1), t2) -> (conv x, t2)
8567   if (N0.getOpcode() == ISD::BITCAST)
8568     return DAG.getBitcast(VT, N0.getOperand(0));
8569
8570   // fold (conv (load x)) -> (load (conv*)x)
8571   // If the resultant load doesn't need a higher alignment than the original!
8572   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8573       // Do not change the width of a volatile load.
8574       !cast<LoadSDNode>(N0)->isVolatile() &&
8575       // Do not remove the cast if the types differ in endian layout.
8576       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8577           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8578       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8579       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8580     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8581     unsigned OrigAlign = LN0->getAlignment();
8582
8583     bool Fast = false;
8584     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8585                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8586         Fast) {
8587       SDValue Load =
8588           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8589                       LN0->getPointerInfo(), OrigAlign,
8590                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8591       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8592       return Load;
8593     }
8594   }
8595
8596   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8597     return V;
8598
8599   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8600   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8601   //
8602   // For ppc_fp128:
8603   // fold (bitcast (fneg x)) ->
8604   //     flipbit = signbit
8605   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8606   //
8607   // fold (bitcast (fabs x)) ->
8608   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8609   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8610   // This often reduces constant pool loads.
8611   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8612        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8613       N0.getNode()->hasOneUse() && VT.isInteger() &&
8614       !VT.isVector() && !N0.getValueType().isVector()) {
8615     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8616     AddToWorklist(NewConv.getNode());
8617
8618     SDLoc DL(N);
8619     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8620       assert(VT.getSizeInBits() == 128);
8621       SDValue SignBit = DAG.getConstant(
8622           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8623       SDValue FlipBit;
8624       if (N0.getOpcode() == ISD::FNEG) {
8625         FlipBit = SignBit;
8626         AddToWorklist(FlipBit.getNode());
8627       } else {
8628         assert(N0.getOpcode() == ISD::FABS);
8629         SDValue Hi =
8630             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8631                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8632                                               SDLoc(NewConv)));
8633         AddToWorklist(Hi.getNode());
8634         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8635         AddToWorklist(FlipBit.getNode());
8636       }
8637       SDValue FlipBits =
8638           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8639       AddToWorklist(FlipBits.getNode());
8640       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8641     }
8642     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8643     if (N0.getOpcode() == ISD::FNEG)
8644       return DAG.getNode(ISD::XOR, DL, VT,
8645                          NewConv, DAG.getConstant(SignBit, DL, VT));
8646     assert(N0.getOpcode() == ISD::FABS);
8647     return DAG.getNode(ISD::AND, DL, VT,
8648                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8649   }
8650
8651   // fold (bitconvert (fcopysign cst, x)) ->
8652   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8653   // Note that we don't handle (copysign x, cst) because this can always be
8654   // folded to an fneg or fabs.
8655   //
8656   // For ppc_fp128:
8657   // fold (bitcast (fcopysign cst, x)) ->
8658   //     flipbit = (and (extract_element
8659   //                     (xor (bitcast cst), (bitcast x)), 0),
8660   //                    signbit)
8661   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8662   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8663       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8664       VT.isInteger() && !VT.isVector()) {
8665     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8666     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8667     if (isTypeLegal(IntXVT)) {
8668       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8669       AddToWorklist(X.getNode());
8670
8671       // If X has a different width than the result/lhs, sext it or truncate it.
8672       unsigned VTWidth = VT.getSizeInBits();
8673       if (OrigXWidth < VTWidth) {
8674         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8675         AddToWorklist(X.getNode());
8676       } else if (OrigXWidth > VTWidth) {
8677         // To get the sign bit in the right place, we have to shift it right
8678         // before truncating.
8679         SDLoc DL(X);
8680         X = DAG.getNode(ISD::SRL, DL,
8681                         X.getValueType(), X,
8682                         DAG.getConstant(OrigXWidth-VTWidth, DL,
8683                                         X.getValueType()));
8684         AddToWorklist(X.getNode());
8685         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8686         AddToWorklist(X.getNode());
8687       }
8688
8689       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8690         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8691         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8692         AddToWorklist(Cst.getNode());
8693         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8694         AddToWorklist(X.getNode());
8695         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8696         AddToWorklist(XorResult.getNode());
8697         SDValue XorResult64 = DAG.getNode(
8698             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8699             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8700                                   SDLoc(XorResult)));
8701         AddToWorklist(XorResult64.getNode());
8702         SDValue FlipBit =
8703             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8704                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8705         AddToWorklist(FlipBit.getNode());
8706         SDValue FlipBits =
8707             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8708         AddToWorklist(FlipBits.getNode());
8709         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8710       }
8711       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8712       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8713                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
8714       AddToWorklist(X.getNode());
8715
8716       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8717       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8718                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8719       AddToWorklist(Cst.getNode());
8720
8721       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8722     }
8723   }
8724
8725   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8726   if (N0.getOpcode() == ISD::BUILD_PAIR)
8727     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8728       return CombineLD;
8729
8730   // Remove double bitcasts from shuffles - this is often a legacy of
8731   // XformToShuffleWithZero being used to combine bitmaskings (of
8732   // float vectors bitcast to integer vectors) into shuffles.
8733   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8734   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8735       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8736       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8737       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8738     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8739
8740     // If operands are a bitcast, peek through if it casts the original VT.
8741     // If operands are a constant, just bitcast back to original VT.
8742     auto PeekThroughBitcast = [&](SDValue Op) {
8743       if (Op.getOpcode() == ISD::BITCAST &&
8744           Op.getOperand(0).getValueType() == VT)
8745         return SDValue(Op.getOperand(0));
8746       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8747           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8748         return DAG.getBitcast(VT, Op);
8749       return SDValue();
8750     };
8751
8752     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8753     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8754     if (!(SV0 && SV1))
8755       return SDValue();
8756
8757     int MaskScale =
8758         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8759     SmallVector<int, 8> NewMask;
8760     for (int M : SVN->getMask())
8761       for (int i = 0; i != MaskScale; ++i)
8762         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8763
8764     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8765     if (!LegalMask) {
8766       std::swap(SV0, SV1);
8767       ShuffleVectorSDNode::commuteMask(NewMask);
8768       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8769     }
8770
8771     if (LegalMask)
8772       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8773   }
8774
8775   return SDValue();
8776 }
8777
8778 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8779   EVT VT = N->getValueType(0);
8780   return CombineConsecutiveLoads(N, VT);
8781 }
8782
8783 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8784 /// operands. DstEltVT indicates the destination element value type.
8785 SDValue DAGCombiner::
8786 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8787   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8788
8789   // If this is already the right type, we're done.
8790   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8791
8792   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8793   unsigned DstBitSize = DstEltVT.getSizeInBits();
8794
8795   // If this is a conversion of N elements of one type to N elements of another
8796   // type, convert each element.  This handles FP<->INT cases.
8797   if (SrcBitSize == DstBitSize) {
8798     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8799                               BV->getValueType(0).getVectorNumElements());
8800
8801     // Due to the FP element handling below calling this routine recursively,
8802     // we can end up with a scalar-to-vector node here.
8803     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8804       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8805                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8806
8807     SmallVector<SDValue, 8> Ops;
8808     for (SDValue Op : BV->op_values()) {
8809       // If the vector element type is not legal, the BUILD_VECTOR operands
8810       // are promoted and implicitly truncated.  Make that explicit here.
8811       if (Op.getValueType() != SrcEltVT)
8812         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8813       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8814       AddToWorklist(Ops.back().getNode());
8815     }
8816     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8817   }
8818
8819   // Otherwise, we're growing or shrinking the elements.  To avoid having to
8820   // handle annoying details of growing/shrinking FP values, we convert them to
8821   // int first.
8822   if (SrcEltVT.isFloatingPoint()) {
8823     // Convert the input float vector to a int vector where the elements are the
8824     // same sizes.
8825     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8826     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8827     SrcEltVT = IntVT;
8828   }
8829
8830   // Now we know the input is an integer vector.  If the output is a FP type,
8831   // convert to integer first, then to FP of the right size.
8832   if (DstEltVT.isFloatingPoint()) {
8833     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8834     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8835
8836     // Next, convert to FP elements of the same size.
8837     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8838   }
8839
8840   SDLoc DL(BV);
8841
8842   // Okay, we know the src/dst types are both integers of differing types.
8843   // Handling growing first.
8844   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8845   if (SrcBitSize < DstBitSize) {
8846     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8847
8848     SmallVector<SDValue, 8> Ops;
8849     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8850          i += NumInputsPerOutput) {
8851       bool isLE = DAG.getDataLayout().isLittleEndian();
8852       APInt NewBits = APInt(DstBitSize, 0);
8853       bool EltIsUndef = true;
8854       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8855         // Shift the previously computed bits over.
8856         NewBits <<= SrcBitSize;
8857         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8858         if (Op.isUndef()) continue;
8859         EltIsUndef = false;
8860
8861         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8862                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
8863       }
8864
8865       if (EltIsUndef)
8866         Ops.push_back(DAG.getUNDEF(DstEltVT));
8867       else
8868         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8869     }
8870
8871     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8872     return DAG.getBuildVector(VT, DL, Ops);
8873   }
8874
8875   // Finally, this must be the case where we are shrinking elements: each input
8876   // turns into multiple outputs.
8877   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8878   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8879                             NumOutputsPerInput*BV->getNumOperands());
8880   SmallVector<SDValue, 8> Ops;
8881
8882   for (const SDValue &Op : BV->op_values()) {
8883     if (Op.isUndef()) {
8884       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8885       continue;
8886     }
8887
8888     APInt OpVal = cast<ConstantSDNode>(Op)->
8889                   getAPIntValue().zextOrTrunc(SrcBitSize);
8890
8891     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8892       APInt ThisVal = OpVal.trunc(DstBitSize);
8893       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8894       OpVal.lshrInPlace(DstBitSize);
8895     }
8896
8897     // For big endian targets, swap the order of the pieces of each element.
8898     if (DAG.getDataLayout().isBigEndian())
8899       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8900   }
8901
8902   return DAG.getBuildVector(VT, DL, Ops);
8903 }
8904
8905 static bool isContractable(SDNode *N) {
8906   SDNodeFlags F = N->getFlags();
8907   return F.hasAllowContract() || F.hasUnsafeAlgebra();
8908 }
8909
8910 /// Try to perform FMA combining on a given FADD node.
8911 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8912   SDValue N0 = N->getOperand(0);
8913   SDValue N1 = N->getOperand(1);
8914   EVT VT = N->getValueType(0);
8915   SDLoc SL(N);
8916
8917   const TargetOptions &Options = DAG.getTarget().Options;
8918
8919   // Floating-point multiply-add with intermediate rounding.
8920   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8921
8922   // Floating-point multiply-add without intermediate rounding.
8923   bool HasFMA =
8924       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8925       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8926
8927   // No valid opcode, do not combine.
8928   if (!HasFMAD && !HasFMA)
8929     return SDValue();
8930
8931   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8932                               Options.UnsafeFPMath || HasFMAD);
8933   // If the addition is not contractable, do not combine.
8934   if (!AllowFusionGlobally && !isContractable(N))
8935     return SDValue();
8936
8937   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8938   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8939     return SDValue();
8940
8941   // Always prefer FMAD to FMA for precision.
8942   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8943   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8944   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8945
8946   // Is the node an FMUL and contractable either due to global flags or
8947   // SDNodeFlags.
8948   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8949     if (N.getOpcode() != ISD::FMUL)
8950       return false;
8951     return AllowFusionGlobally || isContractable(N.getNode());
8952   };
8953   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8954   // prefer to fold the multiply with fewer uses.
8955   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
8956     if (N0.getNode()->use_size() > N1.getNode()->use_size())
8957       std::swap(N0, N1);
8958   }
8959
8960   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8961   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8962     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8963                        N0.getOperand(0), N0.getOperand(1), N1);
8964   }
8965
8966   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8967   // Note: Commutes FADD operands.
8968   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
8969     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8970                        N1.getOperand(0), N1.getOperand(1), N0);
8971   }
8972
8973   // Look through FP_EXTEND nodes to do more combining.
8974   if (LookThroughFPExt) {
8975     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8976     if (N0.getOpcode() == ISD::FP_EXTEND) {
8977       SDValue N00 = N0.getOperand(0);
8978       if (isContractableFMUL(N00))
8979         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8980                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8981                                        N00.getOperand(0)),
8982                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8983                                        N00.getOperand(1)), N1);
8984     }
8985
8986     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8987     // Note: Commutes FADD operands.
8988     if (N1.getOpcode() == ISD::FP_EXTEND) {
8989       SDValue N10 = N1.getOperand(0);
8990       if (isContractableFMUL(N10))
8991         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8992                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8993                                        N10.getOperand(0)),
8994                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8995                                        N10.getOperand(1)), N0);
8996     }
8997   }
8998
8999   // More folding opportunities when target permits.
9000   if (Aggressive) {
9001     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9002     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9003     // are currently only supported on binary nodes.
9004     if (Options.UnsafeFPMath &&
9005         N0.getOpcode() == PreferredFusedOpcode &&
9006         N0.getOperand(2).getOpcode() == ISD::FMUL &&
9007         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9008       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9009                          N0.getOperand(0), N0.getOperand(1),
9010                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9011                                      N0.getOperand(2).getOperand(0),
9012                                      N0.getOperand(2).getOperand(1),
9013                                      N1));
9014     }
9015
9016     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9017     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9018     // are currently only supported on binary nodes.
9019     if (Options.UnsafeFPMath &&
9020         N1->getOpcode() == PreferredFusedOpcode &&
9021         N1.getOperand(2).getOpcode() == ISD::FMUL &&
9022         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9023       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9024                          N1.getOperand(0), N1.getOperand(1),
9025                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9026                                      N1.getOperand(2).getOperand(0),
9027                                      N1.getOperand(2).getOperand(1),
9028                                      N0));
9029     }
9030
9031     if (LookThroughFPExt) {
9032       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9033       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
9034       auto FoldFAddFMAFPExtFMul = [&] (
9035           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9036         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9037                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9038                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9039                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9040                                        Z));
9041       };
9042       if (N0.getOpcode() == PreferredFusedOpcode) {
9043         SDValue N02 = N0.getOperand(2);
9044         if (N02.getOpcode() == ISD::FP_EXTEND) {
9045           SDValue N020 = N02.getOperand(0);
9046           if (isContractableFMUL(N020))
9047             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9048                                         N020.getOperand(0), N020.getOperand(1),
9049                                         N1);
9050         }
9051       }
9052
9053       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9054       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9055       // FIXME: This turns two single-precision and one double-precision
9056       // operation into two double-precision operations, which might not be
9057       // interesting for all targets, especially GPUs.
9058       auto FoldFAddFPExtFMAFMul = [&] (
9059           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9060         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9061                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9062                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9063                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9064                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9065                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9066                                        Z));
9067       };
9068       if (N0.getOpcode() == ISD::FP_EXTEND) {
9069         SDValue N00 = N0.getOperand(0);
9070         if (N00.getOpcode() == PreferredFusedOpcode) {
9071           SDValue N002 = N00.getOperand(2);
9072           if (isContractableFMUL(N002))
9073             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9074                                         N002.getOperand(0), N002.getOperand(1),
9075                                         N1);
9076         }
9077       }
9078
9079       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9080       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9081       if (N1.getOpcode() == PreferredFusedOpcode) {
9082         SDValue N12 = N1.getOperand(2);
9083         if (N12.getOpcode() == ISD::FP_EXTEND) {
9084           SDValue N120 = N12.getOperand(0);
9085           if (isContractableFMUL(N120))
9086             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9087                                         N120.getOperand(0), N120.getOperand(1),
9088                                         N0);
9089         }
9090       }
9091
9092       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9093       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9094       // FIXME: This turns two single-precision and one double-precision
9095       // operation into two double-precision operations, which might not be
9096       // interesting for all targets, especially GPUs.
9097       if (N1.getOpcode() == ISD::FP_EXTEND) {
9098         SDValue N10 = N1.getOperand(0);
9099         if (N10.getOpcode() == PreferredFusedOpcode) {
9100           SDValue N102 = N10.getOperand(2);
9101           if (isContractableFMUL(N102))
9102             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9103                                         N102.getOperand(0), N102.getOperand(1),
9104                                         N0);
9105         }
9106       }
9107     }
9108   }
9109
9110   return SDValue();
9111 }
9112
9113 /// Try to perform FMA combining on a given FSUB node.
9114 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9115   SDValue N0 = N->getOperand(0);
9116   SDValue N1 = N->getOperand(1);
9117   EVT VT = N->getValueType(0);
9118   SDLoc SL(N);
9119
9120   const TargetOptions &Options = DAG.getTarget().Options;
9121   // Floating-point multiply-add with intermediate rounding.
9122   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9123
9124   // Floating-point multiply-add without intermediate rounding.
9125   bool HasFMA =
9126       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9127       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9128
9129   // No valid opcode, do not combine.
9130   if (!HasFMAD && !HasFMA)
9131     return SDValue();
9132
9133   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9134                               Options.UnsafeFPMath || HasFMAD);
9135   // If the subtraction is not contractable, do not combine.
9136   if (!AllowFusionGlobally && !isContractable(N))
9137     return SDValue();
9138
9139   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9140   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9141     return SDValue();
9142
9143   // Always prefer FMAD to FMA for precision.
9144   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9145   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9146   bool LookThroughFPExt = TLI.isFPExtFree(VT);
9147
9148   // Is the node an FMUL and contractable either due to global flags or
9149   // SDNodeFlags.
9150   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9151     if (N.getOpcode() != ISD::FMUL)
9152       return false;
9153     return AllowFusionGlobally || isContractable(N.getNode());
9154   };
9155
9156   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9157   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9158     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9159                        N0.getOperand(0), N0.getOperand(1),
9160                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9161   }
9162
9163   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9164   // Note: Commutes FSUB operands.
9165   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9166     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9167                        DAG.getNode(ISD::FNEG, SL, VT,
9168                                    N1.getOperand(0)),
9169                        N1.getOperand(1), N0);
9170
9171   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9172   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9173       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9174     SDValue N00 = N0.getOperand(0).getOperand(0);
9175     SDValue N01 = N0.getOperand(0).getOperand(1);
9176     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9177                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9178                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9179   }
9180
9181   // Look through FP_EXTEND nodes to do more combining.
9182   if (LookThroughFPExt) {
9183     // fold (fsub (fpext (fmul x, y)), z)
9184     //   -> (fma (fpext x), (fpext y), (fneg z))
9185     if (N0.getOpcode() == ISD::FP_EXTEND) {
9186       SDValue N00 = N0.getOperand(0);
9187       if (isContractableFMUL(N00))
9188         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9189                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9190                                        N00.getOperand(0)),
9191                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9192                                        N00.getOperand(1)),
9193                            DAG.getNode(ISD::FNEG, SL, VT, N1));
9194     }
9195
9196     // fold (fsub x, (fpext (fmul y, z)))
9197     //   -> (fma (fneg (fpext y)), (fpext z), x)
9198     // Note: Commutes FSUB operands.
9199     if (N1.getOpcode() == ISD::FP_EXTEND) {
9200       SDValue N10 = N1.getOperand(0);
9201       if (isContractableFMUL(N10))
9202         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9203                            DAG.getNode(ISD::FNEG, SL, VT,
9204                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9205                                                    N10.getOperand(0))),
9206                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9207                                        N10.getOperand(1)),
9208                            N0);
9209     }
9210
9211     // fold (fsub (fpext (fneg (fmul, x, y))), z)
9212     //   -> (fneg (fma (fpext x), (fpext y), z))
9213     // Note: This could be removed with appropriate canonicalization of the
9214     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9215     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9216     // from implementing the canonicalization in visitFSUB.
9217     if (N0.getOpcode() == ISD::FP_EXTEND) {
9218       SDValue N00 = N0.getOperand(0);
9219       if (N00.getOpcode() == ISD::FNEG) {
9220         SDValue N000 = N00.getOperand(0);
9221         if (isContractableFMUL(N000)) {
9222           return DAG.getNode(ISD::FNEG, SL, VT,
9223                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9224                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9225                                                      N000.getOperand(0)),
9226                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9227                                                      N000.getOperand(1)),
9228                                          N1));
9229         }
9230       }
9231     }
9232
9233     // fold (fsub (fneg (fpext (fmul, x, y))), z)
9234     //   -> (fneg (fma (fpext x)), (fpext y), z)
9235     // Note: This could be removed with appropriate canonicalization of the
9236     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9237     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9238     // from implementing the canonicalization in visitFSUB.
9239     if (N0.getOpcode() == ISD::FNEG) {
9240       SDValue N00 = N0.getOperand(0);
9241       if (N00.getOpcode() == ISD::FP_EXTEND) {
9242         SDValue N000 = N00.getOperand(0);
9243         if (isContractableFMUL(N000)) {
9244           return DAG.getNode(ISD::FNEG, SL, VT,
9245                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9246                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9247                                                      N000.getOperand(0)),
9248                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9249                                                      N000.getOperand(1)),
9250                                          N1));
9251         }
9252       }
9253     }
9254
9255   }
9256
9257   // More folding opportunities when target permits.
9258   if (Aggressive) {
9259     // fold (fsub (fma x, y, (fmul u, v)), z)
9260     //   -> (fma x, y (fma u, v, (fneg z)))
9261     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9262     // are currently only supported on binary nodes.
9263     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9264         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9265         N0.getOperand(2)->hasOneUse()) {
9266       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9267                          N0.getOperand(0), N0.getOperand(1),
9268                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9269                                      N0.getOperand(2).getOperand(0),
9270                                      N0.getOperand(2).getOperand(1),
9271                                      DAG.getNode(ISD::FNEG, SL, VT,
9272                                                  N1)));
9273     }
9274
9275     // fold (fsub x, (fma y, z, (fmul u, v)))
9276     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9277     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9278     // are currently only supported on binary nodes.
9279     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9280         isContractableFMUL(N1.getOperand(2))) {
9281       SDValue N20 = N1.getOperand(2).getOperand(0);
9282       SDValue N21 = N1.getOperand(2).getOperand(1);
9283       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9284                          DAG.getNode(ISD::FNEG, SL, VT,
9285                                      N1.getOperand(0)),
9286                          N1.getOperand(1),
9287                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9288                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9289
9290                                      N21, N0));
9291     }
9292
9293     if (LookThroughFPExt) {
9294       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9295       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9296       if (N0.getOpcode() == PreferredFusedOpcode) {
9297         SDValue N02 = N0.getOperand(2);
9298         if (N02.getOpcode() == ISD::FP_EXTEND) {
9299           SDValue N020 = N02.getOperand(0);
9300           if (isContractableFMUL(N020))
9301             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9302                                N0.getOperand(0), N0.getOperand(1),
9303                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9304                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9305                                                        N020.getOperand(0)),
9306                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9307                                                        N020.getOperand(1)),
9308                                            DAG.getNode(ISD::FNEG, SL, VT,
9309                                                        N1)));
9310         }
9311       }
9312
9313       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9314       //   -> (fma (fpext x), (fpext y),
9315       //           (fma (fpext u), (fpext v), (fneg z)))
9316       // FIXME: This turns two single-precision and one double-precision
9317       // operation into two double-precision operations, which might not be
9318       // interesting for all targets, especially GPUs.
9319       if (N0.getOpcode() == ISD::FP_EXTEND) {
9320         SDValue N00 = N0.getOperand(0);
9321         if (N00.getOpcode() == PreferredFusedOpcode) {
9322           SDValue N002 = N00.getOperand(2);
9323           if (isContractableFMUL(N002))
9324             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9325                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9326                                            N00.getOperand(0)),
9327                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9328                                            N00.getOperand(1)),
9329                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9330                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9331                                                        N002.getOperand(0)),
9332                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9333                                                        N002.getOperand(1)),
9334                                            DAG.getNode(ISD::FNEG, SL, VT,
9335                                                        N1)));
9336         }
9337       }
9338
9339       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9340       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9341       if (N1.getOpcode() == PreferredFusedOpcode &&
9342         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9343         SDValue N120 = N1.getOperand(2).getOperand(0);
9344         if (isContractableFMUL(N120)) {
9345           SDValue N1200 = N120.getOperand(0);
9346           SDValue N1201 = N120.getOperand(1);
9347           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9348                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9349                              N1.getOperand(1),
9350                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9351                                          DAG.getNode(ISD::FNEG, SL, VT,
9352                                              DAG.getNode(ISD::FP_EXTEND, SL,
9353                                                          VT, N1200)),
9354                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9355                                                      N1201),
9356                                          N0));
9357         }
9358       }
9359
9360       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9361       //   -> (fma (fneg (fpext y)), (fpext z),
9362       //           (fma (fneg (fpext u)), (fpext v), x))
9363       // FIXME: This turns two single-precision and one double-precision
9364       // operation into two double-precision operations, which might not be
9365       // interesting for all targets, especially GPUs.
9366       if (N1.getOpcode() == ISD::FP_EXTEND &&
9367         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9368         SDValue N100 = N1.getOperand(0).getOperand(0);
9369         SDValue N101 = N1.getOperand(0).getOperand(1);
9370         SDValue N102 = N1.getOperand(0).getOperand(2);
9371         if (isContractableFMUL(N102)) {
9372           SDValue N1020 = N102.getOperand(0);
9373           SDValue N1021 = N102.getOperand(1);
9374           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9375                              DAG.getNode(ISD::FNEG, SL, VT,
9376                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9377                                                      N100)),
9378                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9379                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9380                                          DAG.getNode(ISD::FNEG, SL, VT,
9381                                              DAG.getNode(ISD::FP_EXTEND, SL,
9382                                                          VT, N1020)),
9383                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9384                                                      N1021),
9385                                          N0));
9386         }
9387       }
9388     }
9389   }
9390
9391   return SDValue();
9392 }
9393
9394 /// Try to perform FMA combining on a given FMUL node based on the distributive
9395 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9396 /// subtraction instead of addition).
9397 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9398   SDValue N0 = N->getOperand(0);
9399   SDValue N1 = N->getOperand(1);
9400   EVT VT = N->getValueType(0);
9401   SDLoc SL(N);
9402
9403   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9404
9405   const TargetOptions &Options = DAG.getTarget().Options;
9406
9407   // The transforms below are incorrect when x == 0 and y == inf, because the
9408   // intermediate multiplication produces a nan.
9409   if (!Options.NoInfsFPMath)
9410     return SDValue();
9411
9412   // Floating-point multiply-add without intermediate rounding.
9413   bool HasFMA =
9414       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9415       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9416       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9417
9418   // Floating-point multiply-add with intermediate rounding. This can result
9419   // in a less precise result due to the changed rounding order.
9420   bool HasFMAD = Options.UnsafeFPMath &&
9421                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9422
9423   // No valid opcode, do not combine.
9424   if (!HasFMAD && !HasFMA)
9425     return SDValue();
9426
9427   // Always prefer FMAD to FMA for precision.
9428   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9429   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9430
9431   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9432   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9433   auto FuseFADD = [&](SDValue X, SDValue Y) {
9434     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9435       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9436       if (XC1 && XC1->isExactlyValue(+1.0))
9437         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9438       if (XC1 && XC1->isExactlyValue(-1.0))
9439         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9440                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9441     }
9442     return SDValue();
9443   };
9444
9445   if (SDValue FMA = FuseFADD(N0, N1))
9446     return FMA;
9447   if (SDValue FMA = FuseFADD(N1, N0))
9448     return FMA;
9449
9450   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9451   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9452   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9453   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9454   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9455     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9456       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9457       if (XC0 && XC0->isExactlyValue(+1.0))
9458         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9459                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9460                            Y);
9461       if (XC0 && XC0->isExactlyValue(-1.0))
9462         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9463                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9464                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9465
9466       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9467       if (XC1 && XC1->isExactlyValue(+1.0))
9468         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9469                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9470       if (XC1 && XC1->isExactlyValue(-1.0))
9471         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9472     }
9473     return SDValue();
9474   };
9475
9476   if (SDValue FMA = FuseFSUB(N0, N1))
9477     return FMA;
9478   if (SDValue FMA = FuseFSUB(N1, N0))
9479     return FMA;
9480
9481   return SDValue();
9482 }
9483
9484 static bool isFMulNegTwo(SDValue &N) {
9485   if (N.getOpcode() != ISD::FMUL)
9486     return false;
9487   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9488     return CFP->isExactlyValue(-2.0);
9489   return false;
9490 }
9491
9492 SDValue DAGCombiner::visitFADD(SDNode *N) {
9493   SDValue N0 = N->getOperand(0);
9494   SDValue N1 = N->getOperand(1);
9495   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9496   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9497   EVT VT = N->getValueType(0);
9498   SDLoc DL(N);
9499   const TargetOptions &Options = DAG.getTarget().Options;
9500   const SDNodeFlags Flags = N->getFlags();
9501
9502   // fold vector ops
9503   if (VT.isVector())
9504     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9505       return FoldedVOp;
9506
9507   // fold (fadd c1, c2) -> c1 + c2
9508   if (N0CFP && N1CFP)
9509     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9510
9511   // canonicalize constant to RHS
9512   if (N0CFP && !N1CFP)
9513     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9514
9515   if (SDValue NewSel = foldBinOpIntoSelect(N))
9516     return NewSel;
9517
9518   // fold (fadd A, (fneg B)) -> (fsub A, B)
9519   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9520       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9521     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9522                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9523
9524   // fold (fadd (fneg A), B) -> (fsub B, A)
9525   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9526       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9527     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9528                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9529
9530   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9531   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9532   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9533       (isFMulNegTwo(N1) && N1.hasOneUse())) {
9534     bool N1IsFMul = isFMulNegTwo(N1);
9535     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9536     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9537     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9538   }
9539
9540   // FIXME: Auto-upgrade the target/function-level option.
9541   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9542     // fold (fadd A, 0) -> A
9543     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9544       if (N1C->isZero())
9545         return N0;
9546   }
9547
9548   // If 'unsafe math' is enabled, fold lots of things.
9549   if (Options.UnsafeFPMath) {
9550     // No FP constant should be created after legalization as Instruction
9551     // Selection pass has a hard time dealing with FP constants.
9552     bool AllowNewConst = (Level < AfterLegalizeDAG);
9553
9554     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9555     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9556         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9557       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9558                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9559                                      Flags),
9560                          Flags);
9561
9562     // If allowed, fold (fadd (fneg x), x) -> 0.0
9563     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9564       return DAG.getConstantFP(0.0, DL, VT);
9565
9566     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9567     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9568       return DAG.getConstantFP(0.0, DL, VT);
9569
9570     // We can fold chains of FADD's of the same value into multiplications.
9571     // This transform is not safe in general because we are reducing the number
9572     // of rounding steps.
9573     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9574       if (N0.getOpcode() == ISD::FMUL) {
9575         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9576         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9577
9578         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9579         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9580           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9581                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9582           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9583         }
9584
9585         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9586         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9587             N1.getOperand(0) == N1.getOperand(1) &&
9588             N0.getOperand(0) == N1.getOperand(0)) {
9589           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9590                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9591           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9592         }
9593       }
9594
9595       if (N1.getOpcode() == ISD::FMUL) {
9596         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9597         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9598
9599         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9600         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9601           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9602                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9603           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9604         }
9605
9606         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9607         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9608             N0.getOperand(0) == N0.getOperand(1) &&
9609             N1.getOperand(0) == N0.getOperand(0)) {
9610           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9611                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9612           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9613         }
9614       }
9615
9616       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9617         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9618         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9619         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9620             (N0.getOperand(0) == N1)) {
9621           return DAG.getNode(ISD::FMUL, DL, VT,
9622                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9623         }
9624       }
9625
9626       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9627         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9628         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9629         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9630             N1.getOperand(0) == N0) {
9631           return DAG.getNode(ISD::FMUL, DL, VT,
9632                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9633         }
9634       }
9635
9636       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9637       if (AllowNewConst &&
9638           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9639           N0.getOperand(0) == N0.getOperand(1) &&
9640           N1.getOperand(0) == N1.getOperand(1) &&
9641           N0.getOperand(0) == N1.getOperand(0)) {
9642         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9643                            DAG.getConstantFP(4.0, DL, VT), Flags);
9644       }
9645     }
9646   } // enable-unsafe-fp-math
9647
9648   // FADD -> FMA combines:
9649   if (SDValue Fused = visitFADDForFMACombine(N)) {
9650     AddToWorklist(Fused.getNode());
9651     return Fused;
9652   }
9653   return SDValue();
9654 }
9655
9656 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9657   SDValue N0 = N->getOperand(0);
9658   SDValue N1 = N->getOperand(1);
9659   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9660   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9661   EVT VT = N->getValueType(0);
9662   SDLoc DL(N);
9663   const TargetOptions &Options = DAG.getTarget().Options;
9664   const SDNodeFlags Flags = N->getFlags();
9665
9666   // fold vector ops
9667   if (VT.isVector())
9668     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9669       return FoldedVOp;
9670
9671   // fold (fsub c1, c2) -> c1-c2
9672   if (N0CFP && N1CFP)
9673     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9674
9675   if (SDValue NewSel = foldBinOpIntoSelect(N))
9676     return NewSel;
9677
9678   // fold (fsub A, (fneg B)) -> (fadd A, B)
9679   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9680     return DAG.getNode(ISD::FADD, DL, VT, N0,
9681                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9682
9683   // FIXME: Auto-upgrade the target/function-level option.
9684   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
9685     // (fsub 0, B) -> -B
9686     if (N0CFP && N0CFP->isZero()) {
9687       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9688         return GetNegatedExpression(N1, DAG, LegalOperations);
9689       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9690         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9691     }
9692   }
9693
9694   // If 'unsafe math' is enabled, fold lots of things.
9695   if (Options.UnsafeFPMath) {
9696     // (fsub A, 0) -> A
9697     if (N1CFP && N1CFP->isZero())
9698       return N0;
9699
9700     // (fsub x, x) -> 0.0
9701     if (N0 == N1)
9702       return DAG.getConstantFP(0.0f, DL, VT);
9703
9704     // (fsub x, (fadd x, y)) -> (fneg y)
9705     // (fsub x, (fadd y, x)) -> (fneg y)
9706     if (N1.getOpcode() == ISD::FADD) {
9707       SDValue N10 = N1->getOperand(0);
9708       SDValue N11 = N1->getOperand(1);
9709
9710       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9711         return GetNegatedExpression(N11, DAG, LegalOperations);
9712
9713       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9714         return GetNegatedExpression(N10, DAG, LegalOperations);
9715     }
9716   }
9717
9718   // FSUB -> FMA combines:
9719   if (SDValue Fused = visitFSUBForFMACombine(N)) {
9720     AddToWorklist(Fused.getNode());
9721     return Fused;
9722   }
9723
9724   return SDValue();
9725 }
9726
9727 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9728   SDValue N0 = N->getOperand(0);
9729   SDValue N1 = N->getOperand(1);
9730   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9731   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9732   EVT VT = N->getValueType(0);
9733   SDLoc DL(N);
9734   const TargetOptions &Options = DAG.getTarget().Options;
9735   const SDNodeFlags Flags = N->getFlags();
9736
9737   // fold vector ops
9738   if (VT.isVector()) {
9739     // This just handles C1 * C2 for vectors. Other vector folds are below.
9740     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9741       return FoldedVOp;
9742   }
9743
9744   // fold (fmul c1, c2) -> c1*c2
9745   if (N0CFP && N1CFP)
9746     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9747
9748   // canonicalize constant to RHS
9749   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9750      !isConstantFPBuildVectorOrConstantFP(N1))
9751     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9752
9753   // fold (fmul A, 1.0) -> A
9754   if (N1CFP && N1CFP->isExactlyValue(1.0))
9755     return N0;
9756
9757   if (SDValue NewSel = foldBinOpIntoSelect(N))
9758     return NewSel;
9759
9760   if (Options.UnsafeFPMath) {
9761     // fold (fmul A, 0) -> 0
9762     if (N1CFP && N1CFP->isZero())
9763       return N1;
9764
9765     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9766     if (N0.getOpcode() == ISD::FMUL) {
9767       // Fold scalars or any vector constants (not just splats).
9768       // This fold is done in general by InstCombine, but extra fmul insts
9769       // may have been generated during lowering.
9770       SDValue N00 = N0.getOperand(0);
9771       SDValue N01 = N0.getOperand(1);
9772       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9773       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9774       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9775
9776       // Check 1: Make sure that the first operand of the inner multiply is NOT
9777       // a constant. Otherwise, we may induce infinite looping.
9778       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9779         // Check 2: Make sure that the second operand of the inner multiply and
9780         // the second operand of the outer multiply are constants.
9781         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9782             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9783           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9784           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9785         }
9786       }
9787     }
9788
9789     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9790     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9791     // during an early run of DAGCombiner can prevent folding with fmuls
9792     // inserted during lowering.
9793     if (N0.getOpcode() == ISD::FADD &&
9794         (N0.getOperand(0) == N0.getOperand(1)) &&
9795         N0.hasOneUse()) {
9796       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9797       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9798       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9799     }
9800   }
9801
9802   // fold (fmul X, 2.0) -> (fadd X, X)
9803   if (N1CFP && N1CFP->isExactlyValue(+2.0))
9804     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9805
9806   // fold (fmul X, -1.0) -> (fneg X)
9807   if (N1CFP && N1CFP->isExactlyValue(-1.0))
9808     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9809       return DAG.getNode(ISD::FNEG, DL, VT, N0);
9810
9811   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9812   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9813     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9814       // Both can be negated for free, check to see if at least one is cheaper
9815       // negated.
9816       if (LHSNeg == 2 || RHSNeg == 2)
9817         return DAG.getNode(ISD::FMUL, DL, VT,
9818                            GetNegatedExpression(N0, DAG, LegalOperations),
9819                            GetNegatedExpression(N1, DAG, LegalOperations),
9820                            Flags);
9821     }
9822   }
9823
9824   // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
9825   // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
9826   if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
9827       (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
9828       TLI.isOperationLegal(ISD::FABS, VT)) {
9829     SDValue Select = N0, X = N1;
9830     if (Select.getOpcode() != ISD::SELECT)
9831       std::swap(Select, X);
9832
9833     SDValue Cond = Select.getOperand(0);
9834     auto TrueOpnd  = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
9835     auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
9836
9837     if (TrueOpnd && FalseOpnd &&
9838         Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
9839         isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
9840         cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
9841       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9842       switch (CC) {
9843       default: break;
9844       case ISD::SETOLT:
9845       case ISD::SETULT:
9846       case ISD::SETOLE:
9847       case ISD::SETULE:
9848       case ISD::SETLT:
9849       case ISD::SETLE:
9850         std::swap(TrueOpnd, FalseOpnd);
9851         // Fall through
9852       case ISD::SETOGT:
9853       case ISD::SETUGT:
9854       case ISD::SETOGE:
9855       case ISD::SETUGE:
9856       case ISD::SETGT:
9857       case ISD::SETGE:
9858         if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
9859             TLI.isOperationLegal(ISD::FNEG, VT))
9860           return DAG.getNode(ISD::FNEG, DL, VT,
9861                    DAG.getNode(ISD::FABS, DL, VT, X));
9862         if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
9863           return DAG.getNode(ISD::FABS, DL, VT, X);
9864
9865         break;
9866       }
9867     }
9868   }
9869
9870   // FMUL -> FMA combines:
9871   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9872     AddToWorklist(Fused.getNode());
9873     return Fused;
9874   }
9875
9876   return SDValue();
9877 }
9878
9879 SDValue DAGCombiner::visitFMA(SDNode *N) {
9880   SDValue N0 = N->getOperand(0);
9881   SDValue N1 = N->getOperand(1);
9882   SDValue N2 = N->getOperand(2);
9883   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9884   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9885   EVT VT = N->getValueType(0);
9886   SDLoc DL(N);
9887   const TargetOptions &Options = DAG.getTarget().Options;
9888
9889   // Constant fold FMA.
9890   if (isa<ConstantFPSDNode>(N0) &&
9891       isa<ConstantFPSDNode>(N1) &&
9892       isa<ConstantFPSDNode>(N2)) {
9893     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9894   }
9895
9896   if (Options.UnsafeFPMath) {
9897     if (N0CFP && N0CFP->isZero())
9898       return N2;
9899     if (N1CFP && N1CFP->isZero())
9900       return N2;
9901   }
9902   // TODO: The FMA node should have flags that propagate to these nodes.
9903   if (N0CFP && N0CFP->isExactlyValue(1.0))
9904     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9905   if (N1CFP && N1CFP->isExactlyValue(1.0))
9906     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9907
9908   // Canonicalize (fma c, x, y) -> (fma x, c, y)
9909   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9910      !isConstantFPBuildVectorOrConstantFP(N1))
9911     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9912
9913   // TODO: FMA nodes should have flags that propagate to the created nodes.
9914   // For now, create a Flags object for use with all unsafe math transforms.
9915   SDNodeFlags Flags;
9916   Flags.setUnsafeAlgebra(true);
9917
9918   if (Options.UnsafeFPMath) {
9919     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9920     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9921         isConstantFPBuildVectorOrConstantFP(N1) &&
9922         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9923       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9924                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9925                                      Flags), Flags);
9926     }
9927
9928     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9929     if (N0.getOpcode() == ISD::FMUL &&
9930         isConstantFPBuildVectorOrConstantFP(N1) &&
9931         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9932       return DAG.getNode(ISD::FMA, DL, VT,
9933                          N0.getOperand(0),
9934                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9935                                      Flags),
9936                          N2);
9937     }
9938   }
9939
9940   // (fma x, 1, y) -> (fadd x, y)
9941   // (fma x, -1, y) -> (fadd (fneg x), y)
9942   if (N1CFP) {
9943     if (N1CFP->isExactlyValue(1.0))
9944       // TODO: The FMA node should have flags that propagate to this node.
9945       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9946
9947     if (N1CFP->isExactlyValue(-1.0) &&
9948         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9949       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9950       AddToWorklist(RHSNeg.getNode());
9951       // TODO: The FMA node should have flags that propagate to this node.
9952       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9953     }
9954   }
9955
9956   if (Options.UnsafeFPMath) {
9957     // (fma x, c, x) -> (fmul x, (c+1))
9958     if (N1CFP && N0 == N2) {
9959       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9960                          DAG.getNode(ISD::FADD, DL, VT, N1,
9961                                      DAG.getConstantFP(1.0, DL, VT), Flags),
9962                          Flags);
9963     }
9964
9965     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9966     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
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
9974   return SDValue();
9975 }
9976
9977 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9978 // reciprocal.
9979 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9980 // Notice that this is not always beneficial. One reason is different targets
9981 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9982 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9983 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9984 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9985   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9986   const SDNodeFlags Flags = N->getFlags();
9987   if (!UnsafeMath && !Flags.hasAllowReciprocal())
9988     return SDValue();
9989
9990   // Skip if current node is a reciprocal.
9991   SDValue N0 = N->getOperand(0);
9992   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9993   if (N0CFP && N0CFP->isExactlyValue(1.0))
9994     return SDValue();
9995
9996   // Exit early if the target does not want this transform or if there can't
9997   // possibly be enough uses of the divisor to make the transform worthwhile.
9998   SDValue N1 = N->getOperand(1);
9999   unsigned MinUses = TLI.combineRepeatedFPDivisors();
10000   if (!MinUses || N1->use_size() < MinUses)
10001     return SDValue();
10002
10003   // Find all FDIV users of the same divisor.
10004   // Use a set because duplicates may be present in the user list.
10005   SetVector<SDNode *> Users;
10006   for (auto *U : N1->uses()) {
10007     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
10008       // This division is eligible for optimization only if global unsafe math
10009       // is enabled or if this division allows reciprocal formation.
10010       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
10011         Users.insert(U);
10012     }
10013   }
10014
10015   // Now that we have the actual number of divisor uses, make sure it meets
10016   // the minimum threshold specified by the target.
10017   if (Users.size() < MinUses)
10018     return SDValue();
10019
10020   EVT VT = N->getValueType(0);
10021   SDLoc DL(N);
10022   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10023   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10024
10025   // Dividend / Divisor -> Dividend * Reciprocal
10026   for (auto *U : Users) {
10027     SDValue Dividend = U->getOperand(0);
10028     if (Dividend != FPOne) {
10029       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10030                                     Reciprocal, Flags);
10031       CombineTo(U, NewNode);
10032     } else if (U != Reciprocal.getNode()) {
10033       // In the absence of fast-math-flags, this user node is always the
10034       // same node as Reciprocal, but with FMF they may be different nodes.
10035       CombineTo(U, Reciprocal);
10036     }
10037   }
10038   return SDValue(N, 0);  // N was replaced.
10039 }
10040
10041 SDValue DAGCombiner::visitFDIV(SDNode *N) {
10042   SDValue N0 = N->getOperand(0);
10043   SDValue N1 = N->getOperand(1);
10044   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10045   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10046   EVT VT = N->getValueType(0);
10047   SDLoc DL(N);
10048   const TargetOptions &Options = DAG.getTarget().Options;
10049   SDNodeFlags Flags = N->getFlags();
10050
10051   // fold vector ops
10052   if (VT.isVector())
10053     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10054       return FoldedVOp;
10055
10056   // fold (fdiv c1, c2) -> c1/c2
10057   if (N0CFP && N1CFP)
10058     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10059
10060   if (SDValue NewSel = foldBinOpIntoSelect(N))
10061     return NewSel;
10062
10063   if (Options.UnsafeFPMath) {
10064     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10065     if (N1CFP) {
10066       // Compute the reciprocal 1.0 / c2.
10067       const APFloat &N1APF = N1CFP->getValueAPF();
10068       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10069       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10070       // Only do the transform if the reciprocal is a legal fp immediate that
10071       // isn't too nasty (eg NaN, denormal, ...).
10072       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10073           (!LegalOperations ||
10074            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10075            // backend)... we should handle this gracefully after Legalize.
10076            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
10077            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
10078            TLI.isFPImmLegal(Recip, VT)))
10079         return DAG.getNode(ISD::FMUL, DL, VT, N0,
10080                            DAG.getConstantFP(Recip, DL, VT), Flags);
10081     }
10082
10083     // If this FDIV is part of a reciprocal square root, it may be folded
10084     // into a target-specific square root estimate instruction.
10085     if (N1.getOpcode() == ISD::FSQRT) {
10086       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10087         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10088       }
10089     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10090                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10091       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10092                                           Flags)) {
10093         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10094         AddToWorklist(RV.getNode());
10095         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10096       }
10097     } else if (N1.getOpcode() == ISD::FP_ROUND &&
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_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10102         AddToWorklist(RV.getNode());
10103         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10104       }
10105     } else if (N1.getOpcode() == ISD::FMUL) {
10106       // Look through an FMUL. Even though this won't remove the FDIV directly,
10107       // it's still worthwhile to get rid of the FSQRT if possible.
10108       SDValue SqrtOp;
10109       SDValue OtherOp;
10110       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10111         SqrtOp = N1.getOperand(0);
10112         OtherOp = N1.getOperand(1);
10113       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10114         SqrtOp = N1.getOperand(1);
10115         OtherOp = N1.getOperand(0);
10116       }
10117       if (SqrtOp.getNode()) {
10118         // We found a FSQRT, so try to make this fold:
10119         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10120         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10121           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10122           AddToWorklist(RV.getNode());
10123           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10124         }
10125       }
10126     }
10127
10128     // Fold into a reciprocal estimate and multiply instead of a real divide.
10129     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10130       AddToWorklist(RV.getNode());
10131       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10132     }
10133   }
10134
10135   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10136   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10137     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10138       // Both can be negated for free, check to see if at least one is cheaper
10139       // negated.
10140       if (LHSNeg == 2 || RHSNeg == 2)
10141         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10142                            GetNegatedExpression(N0, DAG, LegalOperations),
10143                            GetNegatedExpression(N1, DAG, LegalOperations),
10144                            Flags);
10145     }
10146   }
10147
10148   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10149     return CombineRepeatedDivisors;
10150
10151   return SDValue();
10152 }
10153
10154 SDValue DAGCombiner::visitFREM(SDNode *N) {
10155   SDValue N0 = N->getOperand(0);
10156   SDValue N1 = N->getOperand(1);
10157   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10158   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10159   EVT VT = N->getValueType(0);
10160
10161   // fold (frem c1, c2) -> fmod(c1,c2)
10162   if (N0CFP && N1CFP)
10163     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10164
10165   if (SDValue NewSel = foldBinOpIntoSelect(N))
10166     return NewSel;
10167
10168   return SDValue();
10169 }
10170
10171 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10172   if (!DAG.getTarget().Options.UnsafeFPMath)
10173     return SDValue();
10174
10175   SDValue N0 = N->getOperand(0);
10176   if (TLI.isFsqrtCheap(N0, DAG))
10177     return SDValue();
10178
10179   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10180   // For now, create a Flags object for use with all unsafe math transforms.
10181   SDNodeFlags Flags;
10182   Flags.setUnsafeAlgebra(true);
10183   return buildSqrtEstimate(N0, Flags);
10184 }
10185
10186 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10187 /// copysign(x, fp_round(y)) -> copysign(x, y)
10188 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10189   SDValue N1 = N->getOperand(1);
10190   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10191        N1.getOpcode() == ISD::FP_ROUND)) {
10192     // Do not optimize out type conversion of f128 type yet.
10193     // For some targets like x86_64, configuration is changed to keep one f128
10194     // value in one SSE register, but instruction selection cannot handle
10195     // FCOPYSIGN on SSE registers yet.
10196     EVT N1VT = N1->getValueType(0);
10197     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10198     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10199   }
10200   return false;
10201 }
10202
10203 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10204   SDValue N0 = N->getOperand(0);
10205   SDValue N1 = N->getOperand(1);
10206   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10207   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10208   EVT VT = N->getValueType(0);
10209
10210   if (N0CFP && N1CFP) // Constant fold
10211     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10212
10213   if (N1CFP) {
10214     const APFloat &V = N1CFP->getValueAPF();
10215     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10216     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10217     if (!V.isNegative()) {
10218       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10219         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10220     } else {
10221       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10222         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10223                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10224     }
10225   }
10226
10227   // copysign(fabs(x), y) -> copysign(x, y)
10228   // copysign(fneg(x), y) -> copysign(x, y)
10229   // copysign(copysign(x,z), y) -> copysign(x, y)
10230   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10231       N0.getOpcode() == ISD::FCOPYSIGN)
10232     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10233
10234   // copysign(x, abs(y)) -> abs(x)
10235   if (N1.getOpcode() == ISD::FABS)
10236     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10237
10238   // copysign(x, copysign(y,z)) -> copysign(x, z)
10239   if (N1.getOpcode() == ISD::FCOPYSIGN)
10240     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10241
10242   // copysign(x, fp_extend(y)) -> copysign(x, y)
10243   // copysign(x, fp_round(y)) -> copysign(x, y)
10244   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10245     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10246
10247   return SDValue();
10248 }
10249
10250 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10251   SDValue N0 = N->getOperand(0);
10252   EVT VT = N->getValueType(0);
10253   EVT OpVT = N0.getValueType();
10254
10255   // fold (sint_to_fp c1) -> c1fp
10256   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10257       // ...but only if the target supports immediate floating-point values
10258       (!LegalOperations ||
10259        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10260     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10261
10262   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10263   // but UINT_TO_FP is legal on this target, try to convert.
10264   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10265       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10266     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10267     if (DAG.SignBitIsZero(N0))
10268       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10269   }
10270
10271   // The next optimizations are desirable only if SELECT_CC can be lowered.
10272   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10273     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10274     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10275         !VT.isVector() &&
10276         (!LegalOperations ||
10277          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10278       SDLoc DL(N);
10279       SDValue Ops[] =
10280         { N0.getOperand(0), N0.getOperand(1),
10281           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10282           N0.getOperand(2) };
10283       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10284     }
10285
10286     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10287     //      (select_cc x, y, 1.0, 0.0,, cc)
10288     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10289         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10290         (!LegalOperations ||
10291          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10292       SDLoc DL(N);
10293       SDValue Ops[] =
10294         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10295           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10296           N0.getOperand(0).getOperand(2) };
10297       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10298     }
10299   }
10300
10301   return SDValue();
10302 }
10303
10304 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10305   SDValue N0 = N->getOperand(0);
10306   EVT VT = N->getValueType(0);
10307   EVT OpVT = N0.getValueType();
10308
10309   // fold (uint_to_fp c1) -> c1fp
10310   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10311       // ...but only if the target supports immediate floating-point values
10312       (!LegalOperations ||
10313        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10314     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10315
10316   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10317   // but SINT_TO_FP is legal on this target, try to convert.
10318   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10319       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10320     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10321     if (DAG.SignBitIsZero(N0))
10322       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10323   }
10324
10325   // The next optimizations are desirable only if SELECT_CC can be lowered.
10326   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10327     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10328
10329     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10330         (!LegalOperations ||
10331          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10332       SDLoc DL(N);
10333       SDValue Ops[] =
10334         { N0.getOperand(0), N0.getOperand(1),
10335           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10336           N0.getOperand(2) };
10337       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10338     }
10339   }
10340
10341   return SDValue();
10342 }
10343
10344 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10345 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10346   SDValue N0 = N->getOperand(0);
10347   EVT VT = N->getValueType(0);
10348
10349   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10350     return SDValue();
10351
10352   SDValue Src = N0.getOperand(0);
10353   EVT SrcVT = Src.getValueType();
10354   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10355   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10356
10357   // We can safely assume the conversion won't overflow the output range,
10358   // because (for example) (uint8_t)18293.f is undefined behavior.
10359
10360   // Since we can assume the conversion won't overflow, our decision as to
10361   // whether the input will fit in the float should depend on the minimum
10362   // of the input range and output range.
10363
10364   // This means this is also safe for a signed input and unsigned output, since
10365   // a negative input would lead to undefined behavior.
10366   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10367   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10368   unsigned ActualSize = std::min(InputSize, OutputSize);
10369   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10370
10371   // We can only fold away the float conversion if the input range can be
10372   // represented exactly in the float range.
10373   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10374     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10375       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10376                                                        : ISD::ZERO_EXTEND;
10377       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10378     }
10379     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10380       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10381     return DAG.getBitcast(VT, Src);
10382   }
10383   return SDValue();
10384 }
10385
10386 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10387   SDValue N0 = N->getOperand(0);
10388   EVT VT = N->getValueType(0);
10389
10390   // fold (fp_to_sint c1fp) -> c1
10391   if (isConstantFPBuildVectorOrConstantFP(N0))
10392     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10393
10394   return FoldIntToFPToInt(N, DAG);
10395 }
10396
10397 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10398   SDValue N0 = N->getOperand(0);
10399   EVT VT = N->getValueType(0);
10400
10401   // fold (fp_to_uint c1fp) -> c1
10402   if (isConstantFPBuildVectorOrConstantFP(N0))
10403     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10404
10405   return FoldIntToFPToInt(N, DAG);
10406 }
10407
10408 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10409   SDValue N0 = N->getOperand(0);
10410   SDValue N1 = N->getOperand(1);
10411   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10412   EVT VT = N->getValueType(0);
10413
10414   // fold (fp_round c1fp) -> c1fp
10415   if (N0CFP)
10416     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10417
10418   // fold (fp_round (fp_extend x)) -> x
10419   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10420     return N0.getOperand(0);
10421
10422   // fold (fp_round (fp_round x)) -> (fp_round x)
10423   if (N0.getOpcode() == ISD::FP_ROUND) {
10424     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10425     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10426
10427     // Skip this folding if it results in an fp_round from f80 to f16.
10428     //
10429     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10430     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10431     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10432     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10433     // x86.
10434     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10435       return SDValue();
10436
10437     // If the first fp_round isn't a value preserving truncation, it might
10438     // introduce a tie in the second fp_round, that wouldn't occur in the
10439     // single-step fp_round we want to fold to.
10440     // In other words, double rounding isn't the same as rounding.
10441     // Also, this is a value preserving truncation iff both fp_round's are.
10442     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10443       SDLoc DL(N);
10444       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10445                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10446     }
10447   }
10448
10449   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10450   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10451     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10452                               N0.getOperand(0), N1);
10453     AddToWorklist(Tmp.getNode());
10454     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10455                        Tmp, N0.getOperand(1));
10456   }
10457
10458   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10459     return NewVSel;
10460
10461   return SDValue();
10462 }
10463
10464 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10465   SDValue N0 = N->getOperand(0);
10466   EVT VT = N->getValueType(0);
10467   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10468   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10469
10470   // fold (fp_round_inreg c1fp) -> c1fp
10471   if (N0CFP && isTypeLegal(EVT)) {
10472     SDLoc DL(N);
10473     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10474     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10475   }
10476
10477   return SDValue();
10478 }
10479
10480 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10481   SDValue N0 = N->getOperand(0);
10482   EVT VT = N->getValueType(0);
10483
10484   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10485   if (N->hasOneUse() &&
10486       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10487     return SDValue();
10488
10489   // fold (fp_extend c1fp) -> c1fp
10490   if (isConstantFPBuildVectorOrConstantFP(N0))
10491     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10492
10493   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10494   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10495       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10496     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10497
10498   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10499   // value of X.
10500   if (N0.getOpcode() == ISD::FP_ROUND
10501       && N0.getConstantOperandVal(1) == 1) {
10502     SDValue In = N0.getOperand(0);
10503     if (In.getValueType() == VT) return In;
10504     if (VT.bitsLT(In.getValueType()))
10505       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10506                          In, N0.getOperand(1));
10507     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10508   }
10509
10510   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10511   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10512        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10513     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10514     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10515                                      LN0->getChain(),
10516                                      LN0->getBasePtr(), N0.getValueType(),
10517                                      LN0->getMemOperand());
10518     CombineTo(N, ExtLoad);
10519     CombineTo(N0.getNode(),
10520               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10521                           N0.getValueType(), ExtLoad,
10522                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10523               ExtLoad.getValue(1));
10524     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10525   }
10526
10527   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10528     return NewVSel;
10529
10530   return SDValue();
10531 }
10532
10533 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10534   SDValue N0 = N->getOperand(0);
10535   EVT VT = N->getValueType(0);
10536
10537   // fold (fceil c1) -> fceil(c1)
10538   if (isConstantFPBuildVectorOrConstantFP(N0))
10539     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10540
10541   return SDValue();
10542 }
10543
10544 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10545   SDValue N0 = N->getOperand(0);
10546   EVT VT = N->getValueType(0);
10547
10548   // fold (ftrunc c1) -> ftrunc(c1)
10549   if (isConstantFPBuildVectorOrConstantFP(N0))
10550     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10551
10552   return SDValue();
10553 }
10554
10555 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10556   SDValue N0 = N->getOperand(0);
10557   EVT VT = N->getValueType(0);
10558
10559   // fold (ffloor c1) -> ffloor(c1)
10560   if (isConstantFPBuildVectorOrConstantFP(N0))
10561     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10562
10563   return SDValue();
10564 }
10565
10566 // FIXME: FNEG and FABS have a lot in common; refactor.
10567 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10568   SDValue N0 = N->getOperand(0);
10569   EVT VT = N->getValueType(0);
10570
10571   // Constant fold FNEG.
10572   if (isConstantFPBuildVectorOrConstantFP(N0))
10573     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10574
10575   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10576                          &DAG.getTarget().Options))
10577     return GetNegatedExpression(N0, DAG, LegalOperations);
10578
10579   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10580   // constant pool values.
10581   if (!TLI.isFNegFree(VT) &&
10582       N0.getOpcode() == ISD::BITCAST &&
10583       N0.getNode()->hasOneUse()) {
10584     SDValue Int = N0.getOperand(0);
10585     EVT IntVT = Int.getValueType();
10586     if (IntVT.isInteger() && !IntVT.isVector()) {
10587       APInt SignMask;
10588       if (N0.getValueType().isVector()) {
10589         // For a vector, get a mask such as 0x80... per scalar element
10590         // and splat it.
10591         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10592         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10593       } else {
10594         // For a scalar, just generate 0x80...
10595         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10596       }
10597       SDLoc DL0(N0);
10598       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10599                         DAG.getConstant(SignMask, DL0, IntVT));
10600       AddToWorklist(Int.getNode());
10601       return DAG.getBitcast(VT, Int);
10602     }
10603   }
10604
10605   // (fneg (fmul c, x)) -> (fmul -c, x)
10606   if (N0.getOpcode() == ISD::FMUL &&
10607       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10608     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10609     if (CFP1) {
10610       APFloat CVal = CFP1->getValueAPF();
10611       CVal.changeSign();
10612       if (Level >= AfterLegalizeDAG &&
10613           (TLI.isFPImmLegal(CVal, VT) ||
10614            TLI.isOperationLegal(ISD::ConstantFP, VT)))
10615         return DAG.getNode(
10616             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10617             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10618             N0->getFlags());
10619     }
10620   }
10621
10622   return SDValue();
10623 }
10624
10625 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10626   SDValue N0 = N->getOperand(0);
10627   SDValue N1 = N->getOperand(1);
10628   EVT VT = N->getValueType(0);
10629   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10630   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10631
10632   if (N0CFP && N1CFP) {
10633     const APFloat &C0 = N0CFP->getValueAPF();
10634     const APFloat &C1 = N1CFP->getValueAPF();
10635     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10636   }
10637
10638   // Canonicalize to constant on RHS.
10639   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10640      !isConstantFPBuildVectorOrConstantFP(N1))
10641     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10642
10643   return SDValue();
10644 }
10645
10646 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10647   SDValue N0 = N->getOperand(0);
10648   SDValue N1 = N->getOperand(1);
10649   EVT VT = N->getValueType(0);
10650   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10651   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10652
10653   if (N0CFP && N1CFP) {
10654     const APFloat &C0 = N0CFP->getValueAPF();
10655     const APFloat &C1 = N1CFP->getValueAPF();
10656     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10657   }
10658
10659   // Canonicalize to constant on RHS.
10660   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10661      !isConstantFPBuildVectorOrConstantFP(N1))
10662     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10663
10664   return SDValue();
10665 }
10666
10667 SDValue DAGCombiner::visitFABS(SDNode *N) {
10668   SDValue N0 = N->getOperand(0);
10669   EVT VT = N->getValueType(0);
10670
10671   // fold (fabs c1) -> fabs(c1)
10672   if (isConstantFPBuildVectorOrConstantFP(N0))
10673     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10674
10675   // fold (fabs (fabs x)) -> (fabs x)
10676   if (N0.getOpcode() == ISD::FABS)
10677     return N->getOperand(0);
10678
10679   // fold (fabs (fneg x)) -> (fabs x)
10680   // fold (fabs (fcopysign x, y)) -> (fabs x)
10681   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10682     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10683
10684   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10685   // constant pool values.
10686   if (!TLI.isFAbsFree(VT) &&
10687       N0.getOpcode() == ISD::BITCAST &&
10688       N0.getNode()->hasOneUse()) {
10689     SDValue Int = N0.getOperand(0);
10690     EVT IntVT = Int.getValueType();
10691     if (IntVT.isInteger() && !IntVT.isVector()) {
10692       APInt SignMask;
10693       if (N0.getValueType().isVector()) {
10694         // For a vector, get a mask such as 0x7f... per scalar element
10695         // and splat it.
10696         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10697         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10698       } else {
10699         // For a scalar, just generate 0x7f...
10700         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10701       }
10702       SDLoc DL(N0);
10703       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10704                         DAG.getConstant(SignMask, DL, IntVT));
10705       AddToWorklist(Int.getNode());
10706       return DAG.getBitcast(N->getValueType(0), Int);
10707     }
10708   }
10709
10710   return SDValue();
10711 }
10712
10713 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10714   SDValue Chain = N->getOperand(0);
10715   SDValue N1 = N->getOperand(1);
10716   SDValue N2 = N->getOperand(2);
10717
10718   // If N is a constant we could fold this into a fallthrough or unconditional
10719   // branch. However that doesn't happen very often in normal code, because
10720   // Instcombine/SimplifyCFG should have handled the available opportunities.
10721   // If we did this folding here, it would be necessary to update the
10722   // MachineBasicBlock CFG, which is awkward.
10723
10724   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10725   // on the target.
10726   if (N1.getOpcode() == ISD::SETCC &&
10727       TLI.isOperationLegalOrCustom(ISD::BR_CC,
10728                                    N1.getOperand(0).getValueType())) {
10729     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10730                        Chain, N1.getOperand(2),
10731                        N1.getOperand(0), N1.getOperand(1), N2);
10732   }
10733
10734   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10735       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10736        (N1.getOperand(0).hasOneUse() &&
10737         N1.getOperand(0).getOpcode() == ISD::SRL))) {
10738     SDNode *Trunc = nullptr;
10739     if (N1.getOpcode() == ISD::TRUNCATE) {
10740       // Look pass the truncate.
10741       Trunc = N1.getNode();
10742       N1 = N1.getOperand(0);
10743     }
10744
10745     // Match this pattern so that we can generate simpler code:
10746     //
10747     //   %a = ...
10748     //   %b = and i32 %a, 2
10749     //   %c = srl i32 %b, 1
10750     //   brcond i32 %c ...
10751     //
10752     // into
10753     //
10754     //   %a = ...
10755     //   %b = and i32 %a, 2
10756     //   %c = setcc eq %b, 0
10757     //   brcond %c ...
10758     //
10759     // This applies only when the AND constant value has one bit set and the
10760     // SRL constant is equal to the log2 of the AND constant. The back-end is
10761     // smart enough to convert the result into a TEST/JMP sequence.
10762     SDValue Op0 = N1.getOperand(0);
10763     SDValue Op1 = N1.getOperand(1);
10764
10765     if (Op0.getOpcode() == ISD::AND &&
10766         Op1.getOpcode() == ISD::Constant) {
10767       SDValue AndOp1 = Op0.getOperand(1);
10768
10769       if (AndOp1.getOpcode() == ISD::Constant) {
10770         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10771
10772         if (AndConst.isPowerOf2() &&
10773             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10774           SDLoc DL(N);
10775           SDValue SetCC =
10776             DAG.getSetCC(DL,
10777                          getSetCCResultType(Op0.getValueType()),
10778                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10779                          ISD::SETNE);
10780
10781           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10782                                           MVT::Other, Chain, SetCC, N2);
10783           // Don't add the new BRCond into the worklist or else SimplifySelectCC
10784           // will convert it back to (X & C1) >> C2.
10785           CombineTo(N, NewBRCond, false);
10786           // Truncate is dead.
10787           if (Trunc)
10788             deleteAndRecombine(Trunc);
10789           // Replace the uses of SRL with SETCC
10790           WorklistRemover DeadNodes(*this);
10791           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10792           deleteAndRecombine(N1.getNode());
10793           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10794         }
10795       }
10796     }
10797
10798     if (Trunc)
10799       // Restore N1 if the above transformation doesn't match.
10800       N1 = N->getOperand(1);
10801   }
10802
10803   // Transform br(xor(x, y)) -> br(x != y)
10804   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10805   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10806     SDNode *TheXor = N1.getNode();
10807     SDValue Op0 = TheXor->getOperand(0);
10808     SDValue Op1 = TheXor->getOperand(1);
10809     if (Op0.getOpcode() == Op1.getOpcode()) {
10810       // Avoid missing important xor optimizations.
10811       if (SDValue Tmp = visitXOR(TheXor)) {
10812         if (Tmp.getNode() != TheXor) {
10813           DEBUG(dbgs() << "\nReplacing.8 ";
10814                 TheXor->dump(&DAG);
10815                 dbgs() << "\nWith: ";
10816                 Tmp.getNode()->dump(&DAG);
10817                 dbgs() << '\n');
10818           WorklistRemover DeadNodes(*this);
10819           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10820           deleteAndRecombine(TheXor);
10821           return DAG.getNode(ISD::BRCOND, SDLoc(N),
10822                              MVT::Other, Chain, Tmp, N2);
10823         }
10824
10825         // visitXOR has changed XOR's operands or replaced the XOR completely,
10826         // bail out.
10827         return SDValue(N, 0);
10828       }
10829     }
10830
10831     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10832       bool Equal = false;
10833       if (isOneConstant(Op0) && Op0.hasOneUse() &&
10834           Op0.getOpcode() == ISD::XOR) {
10835         TheXor = Op0.getNode();
10836         Equal = true;
10837       }
10838
10839       EVT SetCCVT = N1.getValueType();
10840       if (LegalTypes)
10841         SetCCVT = getSetCCResultType(SetCCVT);
10842       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10843                                    SetCCVT,
10844                                    Op0, Op1,
10845                                    Equal ? ISD::SETEQ : ISD::SETNE);
10846       // Replace the uses of XOR with SETCC
10847       WorklistRemover DeadNodes(*this);
10848       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10849       deleteAndRecombine(N1.getNode());
10850       return DAG.getNode(ISD::BRCOND, SDLoc(N),
10851                          MVT::Other, Chain, SetCC, N2);
10852     }
10853   }
10854
10855   return SDValue();
10856 }
10857
10858 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10859 //
10860 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10861   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10862   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10863
10864   // If N is a constant we could fold this into a fallthrough or unconditional
10865   // branch. However that doesn't happen very often in normal code, because
10866   // Instcombine/SimplifyCFG should have handled the available opportunities.
10867   // If we did this folding here, it would be necessary to update the
10868   // MachineBasicBlock CFG, which is awkward.
10869
10870   // Use SimplifySetCC to simplify SETCC's.
10871   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10872                                CondLHS, CondRHS, CC->get(), SDLoc(N),
10873                                false);
10874   if (Simp.getNode()) AddToWorklist(Simp.getNode());
10875
10876   // fold to a simpler setcc
10877   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10878     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10879                        N->getOperand(0), Simp.getOperand(2),
10880                        Simp.getOperand(0), Simp.getOperand(1),
10881                        N->getOperand(4));
10882
10883   return SDValue();
10884 }
10885
10886 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10887 /// and that N may be folded in the load / store addressing mode.
10888 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10889                                     SelectionDAG &DAG,
10890                                     const TargetLowering &TLI) {
10891   EVT VT;
10892   unsigned AS;
10893
10894   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
10895     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10896       return false;
10897     VT = LD->getMemoryVT();
10898     AS = LD->getAddressSpace();
10899   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
10900     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10901       return false;
10902     VT = ST->getMemoryVT();
10903     AS = ST->getAddressSpace();
10904   } else
10905     return false;
10906
10907   TargetLowering::AddrMode AM;
10908   if (N->getOpcode() == ISD::ADD) {
10909     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10910     if (Offset)
10911       // [reg +/- imm]
10912       AM.BaseOffs = Offset->getSExtValue();
10913     else
10914       // [reg +/- reg]
10915       AM.Scale = 1;
10916   } else if (N->getOpcode() == ISD::SUB) {
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
10925     return false;
10926
10927   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10928                                    VT.getTypeForEVT(*DAG.getContext()), AS);
10929 }
10930
10931 /// Try turning a load/store into a pre-indexed load/store when the base
10932 /// pointer is an add or subtract and it has other uses besides the load/store.
10933 /// After the transformation, the new indexed load/store has effectively folded
10934 /// the add/subtract in and all of its other uses are redirected to the
10935 /// new load/store.
10936 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10937   if (Level < AfterLegalizeDAG)
10938     return false;
10939
10940   bool isLoad = true;
10941   SDValue Ptr;
10942   EVT VT;
10943   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10944     if (LD->isIndexed())
10945       return false;
10946     VT = LD->getMemoryVT();
10947     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10948         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10949       return false;
10950     Ptr = LD->getBasePtr();
10951   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10952     if (ST->isIndexed())
10953       return false;
10954     VT = ST->getMemoryVT();
10955     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10956         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10957       return false;
10958     Ptr = ST->getBasePtr();
10959     isLoad = false;
10960   } else {
10961     return false;
10962   }
10963
10964   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10965   // out.  There is no reason to make this a preinc/predec.
10966   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10967       Ptr.getNode()->hasOneUse())
10968     return false;
10969
10970   // Ask the target to do addressing mode selection.
10971   SDValue BasePtr;
10972   SDValue Offset;
10973   ISD::MemIndexedMode AM = ISD::UNINDEXED;
10974   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10975     return false;
10976
10977   // Backends without true r+i pre-indexed forms may need to pass a
10978   // constant base with a variable offset so that constant coercion
10979   // will work with the patterns in canonical form.
10980   bool Swapped = false;
10981   if (isa<ConstantSDNode>(BasePtr)) {
10982     std::swap(BasePtr, Offset);
10983     Swapped = true;
10984   }
10985
10986   // Don't create a indexed load / store with zero offset.
10987   if (isNullConstant(Offset))
10988     return false;
10989
10990   // Try turning it into a pre-indexed load / store except when:
10991   // 1) The new base ptr is a frame index.
10992   // 2) If N is a store and the new base ptr is either the same as or is a
10993   //    predecessor of the value being stored.
10994   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10995   //    that would create a cycle.
10996   // 4) All uses are load / store ops that use it as old base ptr.
10997
10998   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
10999   // (plus the implicit offset) to a register to preinc anyway.
11000   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11001     return false;
11002
11003   // Check #2.
11004   if (!isLoad) {
11005     SDValue Val = cast<StoreSDNode>(N)->getValue();
11006     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
11007       return false;
11008   }
11009
11010   // Caches for hasPredecessorHelper.
11011   SmallPtrSet<const SDNode *, 32> Visited;
11012   SmallVector<const SDNode *, 16> Worklist;
11013   Worklist.push_back(N);
11014
11015   // If the offset is a constant, there may be other adds of constants that
11016   // can be folded with this one. We should do this to avoid having to keep
11017   // a copy of the original base pointer.
11018   SmallVector<SDNode *, 16> OtherUses;
11019   if (isa<ConstantSDNode>(Offset))
11020     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11021                               UE = BasePtr.getNode()->use_end();
11022          UI != UE; ++UI) {
11023       SDUse &Use = UI.getUse();
11024       // Skip the use that is Ptr and uses of other results from BasePtr's
11025       // node (important for nodes that return multiple results).
11026       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11027         continue;
11028
11029       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11030         continue;
11031
11032       if (Use.getUser()->getOpcode() != ISD::ADD &&
11033           Use.getUser()->getOpcode() != ISD::SUB) {
11034         OtherUses.clear();
11035         break;
11036       }
11037
11038       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11039       if (!isa<ConstantSDNode>(Op1)) {
11040         OtherUses.clear();
11041         break;
11042       }
11043
11044       // FIXME: In some cases, we can be smarter about this.
11045       if (Op1.getValueType() != Offset.getValueType()) {
11046         OtherUses.clear();
11047         break;
11048       }
11049
11050       OtherUses.push_back(Use.getUser());
11051     }
11052
11053   if (Swapped)
11054     std::swap(BasePtr, Offset);
11055
11056   // Now check for #3 and #4.
11057   bool RealUse = false;
11058
11059   for (SDNode *Use : Ptr.getNode()->uses()) {
11060     if (Use == N)
11061       continue;
11062     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11063       return false;
11064
11065     // If Ptr may be folded in addressing mode of other use, then it's
11066     // not profitable to do this transformation.
11067     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11068       RealUse = true;
11069   }
11070
11071   if (!RealUse)
11072     return false;
11073
11074   SDValue Result;
11075   if (isLoad)
11076     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11077                                 BasePtr, Offset, AM);
11078   else
11079     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11080                                  BasePtr, Offset, AM);
11081   ++PreIndexedNodes;
11082   ++NodesCombined;
11083   DEBUG(dbgs() << "\nReplacing.4 ";
11084         N->dump(&DAG);
11085         dbgs() << "\nWith: ";
11086         Result.getNode()->dump(&DAG);
11087         dbgs() << '\n');
11088   WorklistRemover DeadNodes(*this);
11089   if (isLoad) {
11090     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11091     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11092   } else {
11093     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11094   }
11095
11096   // Finally, since the node is now dead, remove it from the graph.
11097   deleteAndRecombine(N);
11098
11099   if (Swapped)
11100     std::swap(BasePtr, Offset);
11101
11102   // Replace other uses of BasePtr that can be updated to use Ptr
11103   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11104     unsigned OffsetIdx = 1;
11105     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11106       OffsetIdx = 0;
11107     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11108            BasePtr.getNode() && "Expected BasePtr operand");
11109
11110     // We need to replace ptr0 in the following expression:
11111     //   x0 * offset0 + y0 * ptr0 = t0
11112     // knowing that
11113     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11114     //
11115     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11116     // indexed load/store and the expression that needs to be re-written.
11117     //
11118     // Therefore, we have:
11119     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11120
11121     ConstantSDNode *CN =
11122       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11123     int X0, X1, Y0, Y1;
11124     const APInt &Offset0 = CN->getAPIntValue();
11125     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11126
11127     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11128     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11129     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11130     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11131
11132     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11133
11134     APInt CNV = Offset0;
11135     if (X0 < 0) CNV = -CNV;
11136     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11137     else CNV = CNV - Offset1;
11138
11139     SDLoc DL(OtherUses[i]);
11140
11141     // We can now generate the new expression.
11142     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11143     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11144
11145     SDValue NewUse = DAG.getNode(Opcode,
11146                                  DL,
11147                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11148     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11149     deleteAndRecombine(OtherUses[i]);
11150   }
11151
11152   // Replace the uses of Ptr with uses of the updated base value.
11153   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11154   deleteAndRecombine(Ptr.getNode());
11155
11156   return true;
11157 }
11158
11159 /// Try to combine a load/store with a add/sub of the base pointer node into a
11160 /// post-indexed load/store. The transformation folded the add/subtract into the
11161 /// new indexed load/store effectively and all of its uses are redirected to the
11162 /// new load/store.
11163 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11164   if (Level < AfterLegalizeDAG)
11165     return false;
11166
11167   bool isLoad = true;
11168   SDValue Ptr;
11169   EVT VT;
11170   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11171     if (LD->isIndexed())
11172       return false;
11173     VT = LD->getMemoryVT();
11174     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11175         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11176       return false;
11177     Ptr = LD->getBasePtr();
11178   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11179     if (ST->isIndexed())
11180       return false;
11181     VT = ST->getMemoryVT();
11182     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11183         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11184       return false;
11185     Ptr = ST->getBasePtr();
11186     isLoad = false;
11187   } else {
11188     return false;
11189   }
11190
11191   if (Ptr.getNode()->hasOneUse())
11192     return false;
11193
11194   for (SDNode *Op : Ptr.getNode()->uses()) {
11195     if (Op == N ||
11196         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11197       continue;
11198
11199     SDValue BasePtr;
11200     SDValue Offset;
11201     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11202     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11203       // Don't create a indexed load / store with zero offset.
11204       if (isNullConstant(Offset))
11205         continue;
11206
11207       // Try turning it into a post-indexed load / store except when
11208       // 1) All uses are load / store ops that use it as base ptr (and
11209       //    it may be folded as addressing mmode).
11210       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11211       //    nor a successor of N. Otherwise, if Op is folded that would
11212       //    create a cycle.
11213
11214       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11215         continue;
11216
11217       // Check for #1.
11218       bool TryNext = false;
11219       for (SDNode *Use : BasePtr.getNode()->uses()) {
11220         if (Use == Ptr.getNode())
11221           continue;
11222
11223         // If all the uses are load / store addresses, then don't do the
11224         // transformation.
11225         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11226           bool RealUse = false;
11227           for (SDNode *UseUse : Use->uses()) {
11228             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11229               RealUse = true;
11230           }
11231
11232           if (!RealUse) {
11233             TryNext = true;
11234             break;
11235           }
11236         }
11237       }
11238
11239       if (TryNext)
11240         continue;
11241
11242       // Check for #2
11243       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11244         SDValue Result = isLoad
11245           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11246                                BasePtr, Offset, AM)
11247           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11248                                 BasePtr, Offset, AM);
11249         ++PostIndexedNodes;
11250         ++NodesCombined;
11251         DEBUG(dbgs() << "\nReplacing.5 ";
11252               N->dump(&DAG);
11253               dbgs() << "\nWith: ";
11254               Result.getNode()->dump(&DAG);
11255               dbgs() << '\n');
11256         WorklistRemover DeadNodes(*this);
11257         if (isLoad) {
11258           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11259           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11260         } else {
11261           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11262         }
11263
11264         // Finally, since the node is now dead, remove it from the graph.
11265         deleteAndRecombine(N);
11266
11267         // Replace the uses of Use with uses of the updated base value.
11268         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11269                                       Result.getValue(isLoad ? 1 : 0));
11270         deleteAndRecombine(Op);
11271         return true;
11272       }
11273     }
11274   }
11275
11276   return false;
11277 }
11278
11279 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11280 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11281   ISD::MemIndexedMode AM = LD->getAddressingMode();
11282   assert(AM != ISD::UNINDEXED);
11283   SDValue BP = LD->getOperand(1);
11284   SDValue Inc = LD->getOperand(2);
11285
11286   // Some backends use TargetConstants for load offsets, but don't expect
11287   // TargetConstants in general ADD nodes. We can convert these constants into
11288   // regular Constants (if the constant is not opaque).
11289   assert((Inc.getOpcode() != ISD::TargetConstant ||
11290           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11291          "Cannot split out indexing using opaque target constants");
11292   if (Inc.getOpcode() == ISD::TargetConstant) {
11293     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11294     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11295                           ConstInc->getValueType(0));
11296   }
11297
11298   unsigned Opc =
11299       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11300   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11301 }
11302
11303 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11304   LoadSDNode *LD  = cast<LoadSDNode>(N);
11305   SDValue Chain = LD->getChain();
11306   SDValue Ptr   = LD->getBasePtr();
11307
11308   // If load is not volatile and there are no uses of the loaded value (and
11309   // the updated indexed value in case of indexed loads), change uses of the
11310   // chain value into uses of the chain input (i.e. delete the dead load).
11311   if (!LD->isVolatile()) {
11312     if (N->getValueType(1) == MVT::Other) {
11313       // Unindexed loads.
11314       if (!N->hasAnyUseOfValue(0)) {
11315         // It's not safe to use the two value CombineTo variant here. e.g.
11316         // v1, chain2 = load chain1, loc
11317         // v2, chain3 = load chain2, loc
11318         // v3         = add v2, c
11319         // Now we replace use of chain2 with chain1.  This makes the second load
11320         // isomorphic to the one we are deleting, and thus makes this load live.
11321         DEBUG(dbgs() << "\nReplacing.6 ";
11322               N->dump(&DAG);
11323               dbgs() << "\nWith chain: ";
11324               Chain.getNode()->dump(&DAG);
11325               dbgs() << "\n");
11326         WorklistRemover DeadNodes(*this);
11327         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11328         AddUsersToWorklist(Chain.getNode());
11329         if (N->use_empty())
11330           deleteAndRecombine(N);
11331
11332         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11333       }
11334     } else {
11335       // Indexed loads.
11336       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11337
11338       // If this load has an opaque TargetConstant offset, then we cannot split
11339       // the indexing into an add/sub directly (that TargetConstant may not be
11340       // valid for a different type of node, and we cannot convert an opaque
11341       // target constant into a regular constant).
11342       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11343                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11344
11345       if (!N->hasAnyUseOfValue(0) &&
11346           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11347         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11348         SDValue Index;
11349         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11350           Index = SplitIndexingFromLoad(LD);
11351           // Try to fold the base pointer arithmetic into subsequent loads and
11352           // stores.
11353           AddUsersToWorklist(N);
11354         } else
11355           Index = DAG.getUNDEF(N->getValueType(1));
11356         DEBUG(dbgs() << "\nReplacing.7 ";
11357               N->dump(&DAG);
11358               dbgs() << "\nWith: ";
11359               Undef.getNode()->dump(&DAG);
11360               dbgs() << " and 2 other values\n");
11361         WorklistRemover DeadNodes(*this);
11362         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11363         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11364         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11365         deleteAndRecombine(N);
11366         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11367       }
11368     }
11369   }
11370
11371   // If this load is directly stored, replace the load value with the stored
11372   // value.
11373   // TODO: Handle store large -> read small portion.
11374   // TODO: Handle TRUNCSTORE/LOADEXT
11375   if (OptLevel != CodeGenOpt::None &&
11376       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11377     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11378       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11379       if (PrevST->getBasePtr() == Ptr &&
11380           PrevST->getValue().getValueType() == N->getValueType(0))
11381         return CombineTo(N, PrevST->getOperand(1), Chain);
11382     }
11383   }
11384
11385   // Try to infer better alignment information than the load already has.
11386   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11387     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11388       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11389         SDValue NewLoad = DAG.getExtLoad(
11390             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11391             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11392             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11393         if (NewLoad.getNode() != N)
11394           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11395       }
11396     }
11397   }
11398
11399   if (LD->isUnindexed()) {
11400     // Walk up chain skipping non-aliasing memory nodes.
11401     SDValue BetterChain = FindBetterChain(N, Chain);
11402
11403     // If there is a better chain.
11404     if (Chain != BetterChain) {
11405       SDValue ReplLoad;
11406
11407       // Replace the chain to void dependency.
11408       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11409         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11410                                BetterChain, Ptr, LD->getMemOperand());
11411       } else {
11412         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11413                                   LD->getValueType(0),
11414                                   BetterChain, Ptr, LD->getMemoryVT(),
11415                                   LD->getMemOperand());
11416       }
11417
11418       // Create token factor to keep old chain connected.
11419       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11420                                   MVT::Other, Chain, ReplLoad.getValue(1));
11421
11422       // Replace uses with load result and token factor
11423       return CombineTo(N, ReplLoad.getValue(0), Token);
11424     }
11425   }
11426
11427   // Try transforming N to an indexed load.
11428   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11429     return SDValue(N, 0);
11430
11431   // Try to slice up N to more direct loads if the slices are mapped to
11432   // different register banks or pairing can take place.
11433   if (SliceUpLoad(N))
11434     return SDValue(N, 0);
11435
11436   return SDValue();
11437 }
11438
11439 namespace {
11440 /// \brief Helper structure used to slice a load in smaller loads.
11441 /// Basically a slice is obtained from the following sequence:
11442 /// Origin = load Ty1, Base
11443 /// Shift = srl Ty1 Origin, CstTy Amount
11444 /// Inst = trunc Shift to Ty2
11445 ///
11446 /// Then, it will be rewritten into:
11447 /// Slice = load SliceTy, Base + SliceOffset
11448 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11449 ///
11450 /// SliceTy is deduced from the number of bits that are actually used to
11451 /// build Inst.
11452 struct LoadedSlice {
11453   /// \brief Helper structure used to compute the cost of a slice.
11454   struct Cost {
11455     /// Are we optimizing for code size.
11456     bool ForCodeSize;
11457     /// Various cost.
11458     unsigned Loads;
11459     unsigned Truncates;
11460     unsigned CrossRegisterBanksCopies;
11461     unsigned ZExts;
11462     unsigned Shift;
11463
11464     Cost(bool ForCodeSize = false)
11465         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11466           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11467
11468     /// \brief Get the cost of one isolated slice.
11469     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11470         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11471           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11472       EVT TruncType = LS.Inst->getValueType(0);
11473       EVT LoadedType = LS.getLoadedType();
11474       if (TruncType != LoadedType &&
11475           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11476         ZExts = 1;
11477     }
11478
11479     /// \brief Account for slicing gain in the current cost.
11480     /// Slicing provide a few gains like removing a shift or a
11481     /// truncate. This method allows to grow the cost of the original
11482     /// load with the gain from this slice.
11483     void addSliceGain(const LoadedSlice &LS) {
11484       // Each slice saves a truncate.
11485       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11486       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11487                               LS.Inst->getValueType(0)))
11488         ++Truncates;
11489       // If there is a shift amount, this slice gets rid of it.
11490       if (LS.Shift)
11491         ++Shift;
11492       // If this slice can merge a cross register bank copy, account for it.
11493       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11494         ++CrossRegisterBanksCopies;
11495     }
11496
11497     Cost &operator+=(const Cost &RHS) {
11498       Loads += RHS.Loads;
11499       Truncates += RHS.Truncates;
11500       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11501       ZExts += RHS.ZExts;
11502       Shift += RHS.Shift;
11503       return *this;
11504     }
11505
11506     bool operator==(const Cost &RHS) const {
11507       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11508              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11509              ZExts == RHS.ZExts && Shift == RHS.Shift;
11510     }
11511
11512     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11513
11514     bool operator<(const Cost &RHS) const {
11515       // Assume cross register banks copies are as expensive as loads.
11516       // FIXME: Do we want some more target hooks?
11517       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11518       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11519       // Unless we are optimizing for code size, consider the
11520       // expensive operation first.
11521       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11522         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11523       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11524              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11525     }
11526
11527     bool operator>(const Cost &RHS) const { return RHS < *this; }
11528
11529     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11530
11531     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11532   };
11533   // The last instruction that represent the slice. This should be a
11534   // truncate instruction.
11535   SDNode *Inst;
11536   // The original load instruction.
11537   LoadSDNode *Origin;
11538   // The right shift amount in bits from the original load.
11539   unsigned Shift;
11540   // The DAG from which Origin came from.
11541   // This is used to get some contextual information about legal types, etc.
11542   SelectionDAG *DAG;
11543
11544   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11545               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11546       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11547
11548   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11549   /// \return Result is \p BitWidth and has used bits set to 1 and
11550   ///         not used bits set to 0.
11551   APInt getUsedBits() const {
11552     // Reproduce the trunc(lshr) sequence:
11553     // - Start from the truncated value.
11554     // - Zero extend to the desired bit width.
11555     // - Shift left.
11556     assert(Origin && "No original load to compare against.");
11557     unsigned BitWidth = Origin->getValueSizeInBits(0);
11558     assert(Inst && "This slice is not bound to an instruction");
11559     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11560            "Extracted slice is bigger than the whole type!");
11561     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11562     UsedBits.setAllBits();
11563     UsedBits = UsedBits.zext(BitWidth);
11564     UsedBits <<= Shift;
11565     return UsedBits;
11566   }
11567
11568   /// \brief Get the size of the slice to be loaded in bytes.
11569   unsigned getLoadedSize() const {
11570     unsigned SliceSize = getUsedBits().countPopulation();
11571     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11572     return SliceSize / 8;
11573   }
11574
11575   /// \brief Get the type that will be loaded for this slice.
11576   /// Note: This may not be the final type for the slice.
11577   EVT getLoadedType() const {
11578     assert(DAG && "Missing context");
11579     LLVMContext &Ctxt = *DAG->getContext();
11580     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11581   }
11582
11583   /// \brief Get the alignment of the load used for this slice.
11584   unsigned getAlignment() const {
11585     unsigned Alignment = Origin->getAlignment();
11586     unsigned Offset = getOffsetFromBase();
11587     if (Offset != 0)
11588       Alignment = MinAlign(Alignment, Alignment + Offset);
11589     return Alignment;
11590   }
11591
11592   /// \brief Check if this slice can be rewritten with legal operations.
11593   bool isLegal() const {
11594     // An invalid slice is not legal.
11595     if (!Origin || !Inst || !DAG)
11596       return false;
11597
11598     // Offsets are for indexed load only, we do not handle that.
11599     if (!Origin->getOffset().isUndef())
11600       return false;
11601
11602     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11603
11604     // Check that the type is legal.
11605     EVT SliceType = getLoadedType();
11606     if (!TLI.isTypeLegal(SliceType))
11607       return false;
11608
11609     // Check that the load is legal for this type.
11610     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11611       return false;
11612
11613     // Check that the offset can be computed.
11614     // 1. Check its type.
11615     EVT PtrType = Origin->getBasePtr().getValueType();
11616     if (PtrType == MVT::Untyped || PtrType.isExtended())
11617       return false;
11618
11619     // 2. Check that it fits in the immediate.
11620     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11621       return false;
11622
11623     // 3. Check that the computation is legal.
11624     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11625       return false;
11626
11627     // Check that the zext is legal if it needs one.
11628     EVT TruncateType = Inst->getValueType(0);
11629     if (TruncateType != SliceType &&
11630         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11631       return false;
11632
11633     return true;
11634   }
11635
11636   /// \brief Get the offset in bytes of this slice in the original chunk of
11637   /// bits.
11638   /// \pre DAG != nullptr.
11639   uint64_t getOffsetFromBase() const {
11640     assert(DAG && "Missing context.");
11641     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11642     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11643     uint64_t Offset = Shift / 8;
11644     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11645     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11646            "The size of the original loaded type is not a multiple of a"
11647            " byte.");
11648     // If Offset is bigger than TySizeInBytes, it means we are loading all
11649     // zeros. This should have been optimized before in the process.
11650     assert(TySizeInBytes > Offset &&
11651            "Invalid shift amount for given loaded size");
11652     if (IsBigEndian)
11653       Offset = TySizeInBytes - Offset - getLoadedSize();
11654     return Offset;
11655   }
11656
11657   /// \brief Generate the sequence of instructions to load the slice
11658   /// represented by this object and redirect the uses of this slice to
11659   /// this new sequence of instructions.
11660   /// \pre this->Inst && this->Origin are valid Instructions and this
11661   /// object passed the legal check: LoadedSlice::isLegal returned true.
11662   /// \return The last instruction of the sequence used to load the slice.
11663   SDValue loadSlice() const {
11664     assert(Inst && Origin && "Unable to replace a non-existing slice.");
11665     const SDValue &OldBaseAddr = Origin->getBasePtr();
11666     SDValue BaseAddr = OldBaseAddr;
11667     // Get the offset in that chunk of bytes w.r.t. the endianness.
11668     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11669     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11670     if (Offset) {
11671       // BaseAddr = BaseAddr + Offset.
11672       EVT ArithType = BaseAddr.getValueType();
11673       SDLoc DL(Origin);
11674       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11675                               DAG->getConstant(Offset, DL, ArithType));
11676     }
11677
11678     // Create the type of the loaded slice according to its size.
11679     EVT SliceType = getLoadedType();
11680
11681     // Create the load for the slice.
11682     SDValue LastInst =
11683         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11684                      Origin->getPointerInfo().getWithOffset(Offset),
11685                      getAlignment(), Origin->getMemOperand()->getFlags());
11686     // If the final type is not the same as the loaded type, this means that
11687     // we have to pad with zero. Create a zero extend for that.
11688     EVT FinalType = Inst->getValueType(0);
11689     if (SliceType != FinalType)
11690       LastInst =
11691           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11692     return LastInst;
11693   }
11694
11695   /// \brief Check if this slice can be merged with an expensive cross register
11696   /// bank copy. E.g.,
11697   /// i = load i32
11698   /// f = bitcast i32 i to float
11699   bool canMergeExpensiveCrossRegisterBankCopy() const {
11700     if (!Inst || !Inst->hasOneUse())
11701       return false;
11702     SDNode *Use = *Inst->use_begin();
11703     if (Use->getOpcode() != ISD::BITCAST)
11704       return false;
11705     assert(DAG && "Missing context");
11706     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11707     EVT ResVT = Use->getValueType(0);
11708     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11709     const TargetRegisterClass *ArgRC =
11710         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11711     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11712       return false;
11713
11714     // At this point, we know that we perform a cross-register-bank copy.
11715     // Check if it is expensive.
11716     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11717     // Assume bitcasts are cheap, unless both register classes do not
11718     // explicitly share a common sub class.
11719     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11720       return false;
11721
11722     // Check if it will be merged with the load.
11723     // 1. Check the alignment constraint.
11724     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11725         ResVT.getTypeForEVT(*DAG->getContext()));
11726
11727     if (RequiredAlignment > getAlignment())
11728       return false;
11729
11730     // 2. Check that the load is a legal operation for that type.
11731     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11732       return false;
11733
11734     // 3. Check that we do not have a zext in the way.
11735     if (Inst->getValueType(0) != getLoadedType())
11736       return false;
11737
11738     return true;
11739   }
11740 };
11741 }
11742
11743 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11744 /// \p UsedBits looks like 0..0 1..1 0..0.
11745 static bool areUsedBitsDense(const APInt &UsedBits) {
11746   // If all the bits are one, this is dense!
11747   if (UsedBits.isAllOnesValue())
11748     return true;
11749
11750   // Get rid of the unused bits on the right.
11751   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11752   // Get rid of the unused bits on the left.
11753   if (NarrowedUsedBits.countLeadingZeros())
11754     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11755   // Check that the chunk of bits is completely used.
11756   return NarrowedUsedBits.isAllOnesValue();
11757 }
11758
11759 /// \brief Check whether or not \p First and \p Second are next to each other
11760 /// in memory. This means that there is no hole between the bits loaded
11761 /// by \p First and the bits loaded by \p Second.
11762 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11763                                      const LoadedSlice &Second) {
11764   assert(First.Origin == Second.Origin && First.Origin &&
11765          "Unable to match different memory origins.");
11766   APInt UsedBits = First.getUsedBits();
11767   assert((UsedBits & Second.getUsedBits()) == 0 &&
11768          "Slices are not supposed to overlap.");
11769   UsedBits |= Second.getUsedBits();
11770   return areUsedBitsDense(UsedBits);
11771 }
11772
11773 /// \brief Adjust the \p GlobalLSCost according to the target
11774 /// paring capabilities and the layout of the slices.
11775 /// \pre \p GlobalLSCost should account for at least as many loads as
11776 /// there is in the slices in \p LoadedSlices.
11777 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11778                                  LoadedSlice::Cost &GlobalLSCost) {
11779   unsigned NumberOfSlices = LoadedSlices.size();
11780   // If there is less than 2 elements, no pairing is possible.
11781   if (NumberOfSlices < 2)
11782     return;
11783
11784   // Sort the slices so that elements that are likely to be next to each
11785   // other in memory are next to each other in the list.
11786   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11787             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11788     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11789     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11790   });
11791   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11792   // First (resp. Second) is the first (resp. Second) potentially candidate
11793   // to be placed in a paired load.
11794   const LoadedSlice *First = nullptr;
11795   const LoadedSlice *Second = nullptr;
11796   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11797                 // Set the beginning of the pair.
11798                                                            First = Second) {
11799
11800     Second = &LoadedSlices[CurrSlice];
11801
11802     // If First is NULL, it means we start a new pair.
11803     // Get to the next slice.
11804     if (!First)
11805       continue;
11806
11807     EVT LoadedType = First->getLoadedType();
11808
11809     // If the types of the slices are different, we cannot pair them.
11810     if (LoadedType != Second->getLoadedType())
11811       continue;
11812
11813     // Check if the target supplies paired loads for this type.
11814     unsigned RequiredAlignment = 0;
11815     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11816       // move to the next pair, this type is hopeless.
11817       Second = nullptr;
11818       continue;
11819     }
11820     // Check if we meet the alignment requirement.
11821     if (RequiredAlignment > First->getAlignment())
11822       continue;
11823
11824     // Check that both loads are next to each other in memory.
11825     if (!areSlicesNextToEachOther(*First, *Second))
11826       continue;
11827
11828     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11829     --GlobalLSCost.Loads;
11830     // Move to the next pair.
11831     Second = nullptr;
11832   }
11833 }
11834
11835 /// \brief Check the profitability of all involved LoadedSlice.
11836 /// Currently, it is considered profitable if there is exactly two
11837 /// involved slices (1) which are (2) next to each other in memory, and
11838 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11839 ///
11840 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11841 /// the elements themselves.
11842 ///
11843 /// FIXME: When the cost model will be mature enough, we can relax
11844 /// constraints (1) and (2).
11845 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11846                                 const APInt &UsedBits, bool ForCodeSize) {
11847   unsigned NumberOfSlices = LoadedSlices.size();
11848   if (StressLoadSlicing)
11849     return NumberOfSlices > 1;
11850
11851   // Check (1).
11852   if (NumberOfSlices != 2)
11853     return false;
11854
11855   // Check (2).
11856   if (!areUsedBitsDense(UsedBits))
11857     return false;
11858
11859   // Check (3).
11860   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11861   // The original code has one big load.
11862   OrigCost.Loads = 1;
11863   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11864     const LoadedSlice &LS = LoadedSlices[CurrSlice];
11865     // Accumulate the cost of all the slices.
11866     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11867     GlobalSlicingCost += SliceCost;
11868
11869     // Account as cost in the original configuration the gain obtained
11870     // with the current slices.
11871     OrigCost.addSliceGain(LS);
11872   }
11873
11874   // If the target supports paired load, adjust the cost accordingly.
11875   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11876   return OrigCost > GlobalSlicingCost;
11877 }
11878
11879 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11880 /// operations, split it in the various pieces being extracted.
11881 ///
11882 /// This sort of thing is introduced by SROA.
11883 /// This slicing takes care not to insert overlapping loads.
11884 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11885 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11886   if (Level < AfterLegalizeDAG)
11887     return false;
11888
11889   LoadSDNode *LD = cast<LoadSDNode>(N);
11890   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11891       !LD->getValueType(0).isInteger())
11892     return false;
11893
11894   // Keep track of already used bits to detect overlapping values.
11895   // In that case, we will just abort the transformation.
11896   APInt UsedBits(LD->getValueSizeInBits(0), 0);
11897
11898   SmallVector<LoadedSlice, 4> LoadedSlices;
11899
11900   // Check if this load is used as several smaller chunks of bits.
11901   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11902   // of computation for each trunc.
11903   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11904        UI != UIEnd; ++UI) {
11905     // Skip the uses of the chain.
11906     if (UI.getUse().getResNo() != 0)
11907       continue;
11908
11909     SDNode *User = *UI;
11910     unsigned Shift = 0;
11911
11912     // Check if this is a trunc(lshr).
11913     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11914         isa<ConstantSDNode>(User->getOperand(1))) {
11915       Shift = User->getConstantOperandVal(1);
11916       User = *User->use_begin();
11917     }
11918
11919     // At this point, User is a Truncate, iff we encountered, trunc or
11920     // trunc(lshr).
11921     if (User->getOpcode() != ISD::TRUNCATE)
11922       return false;
11923
11924     // The width of the type must be a power of 2 and greater than 8-bits.
11925     // Otherwise the load cannot be represented in LLVM IR.
11926     // Moreover, if we shifted with a non-8-bits multiple, the slice
11927     // will be across several bytes. We do not support that.
11928     unsigned Width = User->getValueSizeInBits(0);
11929     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11930       return 0;
11931
11932     // Build the slice for this chain of computations.
11933     LoadedSlice LS(User, LD, Shift, &DAG);
11934     APInt CurrentUsedBits = LS.getUsedBits();
11935
11936     // Check if this slice overlaps with another.
11937     if ((CurrentUsedBits & UsedBits) != 0)
11938       return false;
11939     // Update the bits used globally.
11940     UsedBits |= CurrentUsedBits;
11941
11942     // Check if the new slice would be legal.
11943     if (!LS.isLegal())
11944       return false;
11945
11946     // Record the slice.
11947     LoadedSlices.push_back(LS);
11948   }
11949
11950   // Abort slicing if it does not seem to be profitable.
11951   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11952     return false;
11953
11954   ++SlicedLoads;
11955
11956   // Rewrite each chain to use an independent load.
11957   // By construction, each chain can be represented by a unique load.
11958
11959   // Prepare the argument for the new token factor for all the slices.
11960   SmallVector<SDValue, 8> ArgChains;
11961   for (SmallVectorImpl<LoadedSlice>::const_iterator
11962            LSIt = LoadedSlices.begin(),
11963            LSItEnd = LoadedSlices.end();
11964        LSIt != LSItEnd; ++LSIt) {
11965     SDValue SliceInst = LSIt->loadSlice();
11966     CombineTo(LSIt->Inst, SliceInst, true);
11967     if (SliceInst.getOpcode() != ISD::LOAD)
11968       SliceInst = SliceInst.getOperand(0);
11969     assert(SliceInst->getOpcode() == ISD::LOAD &&
11970            "It takes more than a zext to get to the loaded slice!!");
11971     ArgChains.push_back(SliceInst.getValue(1));
11972   }
11973
11974   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11975                               ArgChains);
11976   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11977   AddToWorklist(Chain.getNode());
11978   return true;
11979 }
11980
11981 /// Check to see if V is (and load (ptr), imm), where the load is having
11982 /// specific bytes cleared out.  If so, return the byte size being masked out
11983 /// and the shift amount.
11984 static std::pair<unsigned, unsigned>
11985 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11986   std::pair<unsigned, unsigned> Result(0, 0);
11987
11988   // Check for the structure we're looking for.
11989   if (V->getOpcode() != ISD::AND ||
11990       !isa<ConstantSDNode>(V->getOperand(1)) ||
11991       !ISD::isNormalLoad(V->getOperand(0).getNode()))
11992     return Result;
11993
11994   // Check the chain and pointer.
11995   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11996   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
11997
11998   // The store should be chained directly to the load or be an operand of a
11999   // tokenfactor.
12000   if (LD == Chain.getNode())
12001     ; // ok.
12002   else if (Chain->getOpcode() != ISD::TokenFactor)
12003     return Result; // Fail.
12004   else {
12005     bool isOk = false;
12006     for (const SDValue &ChainOp : Chain->op_values())
12007       if (ChainOp.getNode() == LD) {
12008         isOk = true;
12009         break;
12010       }
12011     if (!isOk) return Result;
12012   }
12013
12014   // This only handles simple types.
12015   if (V.getValueType() != MVT::i16 &&
12016       V.getValueType() != MVT::i32 &&
12017       V.getValueType() != MVT::i64)
12018     return Result;
12019
12020   // Check the constant mask.  Invert it so that the bits being masked out are
12021   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
12022   // follow the sign bit for uniformity.
12023   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12024   unsigned NotMaskLZ = countLeadingZeros(NotMask);
12025   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
12026   unsigned NotMaskTZ = countTrailingZeros(NotMask);
12027   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
12028   if (NotMaskLZ == 64) return Result;  // All zero mask.
12029
12030   // See if we have a continuous run of bits.  If so, we have 0*1+0*
12031   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12032     return Result;
12033
12034   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12035   if (V.getValueType() != MVT::i64 && NotMaskLZ)
12036     NotMaskLZ -= 64-V.getValueSizeInBits();
12037
12038   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12039   switch (MaskedBytes) {
12040   case 1:
12041   case 2:
12042   case 4: break;
12043   default: return Result; // All one mask, or 5-byte mask.
12044   }
12045
12046   // Verify that the first bit starts at a multiple of mask so that the access
12047   // is aligned the same as the access width.
12048   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12049
12050   Result.first = MaskedBytes;
12051   Result.second = NotMaskTZ/8;
12052   return Result;
12053 }
12054
12055
12056 /// Check to see if IVal is something that provides a value as specified by
12057 /// MaskInfo. If so, replace the specified store with a narrower store of
12058 /// truncated IVal.
12059 static SDNode *
12060 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12061                                 SDValue IVal, StoreSDNode *St,
12062                                 DAGCombiner *DC) {
12063   unsigned NumBytes = MaskInfo.first;
12064   unsigned ByteShift = MaskInfo.second;
12065   SelectionDAG &DAG = DC->getDAG();
12066
12067   // Check to see if IVal is all zeros in the part being masked in by the 'or'
12068   // that uses this.  If not, this is not a replacement.
12069   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12070                                   ByteShift*8, (ByteShift+NumBytes)*8);
12071   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12072
12073   // Check that it is legal on the target to do this.  It is legal if the new
12074   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12075   // legalization.
12076   MVT VT = MVT::getIntegerVT(NumBytes*8);
12077   if (!DC->isTypeLegal(VT))
12078     return nullptr;
12079
12080   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
12081   // shifted by ByteShift and truncated down to NumBytes.
12082   if (ByteShift) {
12083     SDLoc DL(IVal);
12084     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12085                        DAG.getConstant(ByteShift*8, DL,
12086                                     DC->getShiftAmountTy(IVal.getValueType())));
12087   }
12088
12089   // Figure out the offset for the store and the alignment of the access.
12090   unsigned StOffset;
12091   unsigned NewAlign = St->getAlignment();
12092
12093   if (DAG.getDataLayout().isLittleEndian())
12094     StOffset = ByteShift;
12095   else
12096     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12097
12098   SDValue Ptr = St->getBasePtr();
12099   if (StOffset) {
12100     SDLoc DL(IVal);
12101     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12102                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12103     NewAlign = MinAlign(NewAlign, StOffset);
12104   }
12105
12106   // Truncate down to the new size.
12107   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12108
12109   ++OpsNarrowed;
12110   return DAG
12111       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12112                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12113       .getNode();
12114 }
12115
12116
12117 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12118 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12119 /// narrowing the load and store if it would end up being a win for performance
12120 /// or code size.
12121 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12122   StoreSDNode *ST  = cast<StoreSDNode>(N);
12123   if (ST->isVolatile())
12124     return SDValue();
12125
12126   SDValue Chain = ST->getChain();
12127   SDValue Value = ST->getValue();
12128   SDValue Ptr   = ST->getBasePtr();
12129   EVT VT = Value.getValueType();
12130
12131   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12132     return SDValue();
12133
12134   unsigned Opc = Value.getOpcode();
12135
12136   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12137   // is a byte mask indicating a consecutive number of bytes, check to see if
12138   // Y is known to provide just those bytes.  If so, we try to replace the
12139   // load + replace + store sequence with a single (narrower) store, which makes
12140   // the load dead.
12141   if (Opc == ISD::OR) {
12142     std::pair<unsigned, unsigned> MaskedLoad;
12143     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12144     if (MaskedLoad.first)
12145       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12146                                                   Value.getOperand(1), ST,this))
12147         return SDValue(NewST, 0);
12148
12149     // Or is commutative, so try swapping X and Y.
12150     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12151     if (MaskedLoad.first)
12152       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12153                                                   Value.getOperand(0), ST,this))
12154         return SDValue(NewST, 0);
12155   }
12156
12157   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12158       Value.getOperand(1).getOpcode() != ISD::Constant)
12159     return SDValue();
12160
12161   SDValue N0 = Value.getOperand(0);
12162   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12163       Chain == SDValue(N0.getNode(), 1)) {
12164     LoadSDNode *LD = cast<LoadSDNode>(N0);
12165     if (LD->getBasePtr() != Ptr ||
12166         LD->getPointerInfo().getAddrSpace() !=
12167         ST->getPointerInfo().getAddrSpace())
12168       return SDValue();
12169
12170     // Find the type to narrow it the load / op / store to.
12171     SDValue N1 = Value.getOperand(1);
12172     unsigned BitWidth = N1.getValueSizeInBits();
12173     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12174     if (Opc == ISD::AND)
12175       Imm ^= APInt::getAllOnesValue(BitWidth);
12176     if (Imm == 0 || Imm.isAllOnesValue())
12177       return SDValue();
12178     unsigned ShAmt = Imm.countTrailingZeros();
12179     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12180     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12181     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12182     // The narrowing should be profitable, the load/store operation should be
12183     // legal (or custom) and the store size should be equal to the NewVT width.
12184     while (NewBW < BitWidth &&
12185            (NewVT.getStoreSizeInBits() != NewBW ||
12186             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12187             !TLI.isNarrowingProfitable(VT, NewVT))) {
12188       NewBW = NextPowerOf2(NewBW);
12189       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12190     }
12191     if (NewBW >= BitWidth)
12192       return SDValue();
12193
12194     // If the lsb changed does not start at the type bitwidth boundary,
12195     // start at the previous one.
12196     if (ShAmt % NewBW)
12197       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12198     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12199                                    std::min(BitWidth, ShAmt + NewBW));
12200     if ((Imm & Mask) == Imm) {
12201       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12202       if (Opc == ISD::AND)
12203         NewImm ^= APInt::getAllOnesValue(NewBW);
12204       uint64_t PtrOff = ShAmt / 8;
12205       // For big endian targets, we need to adjust the offset to the pointer to
12206       // load the correct bytes.
12207       if (DAG.getDataLayout().isBigEndian())
12208         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12209
12210       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12211       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12212       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12213         return SDValue();
12214
12215       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12216                                    Ptr.getValueType(), Ptr,
12217                                    DAG.getConstant(PtrOff, SDLoc(LD),
12218                                                    Ptr.getValueType()));
12219       SDValue NewLD =
12220           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12221                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12222                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12223       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12224                                    DAG.getConstant(NewImm, SDLoc(Value),
12225                                                    NewVT));
12226       SDValue NewST =
12227           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12228                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12229
12230       AddToWorklist(NewPtr.getNode());
12231       AddToWorklist(NewLD.getNode());
12232       AddToWorklist(NewVal.getNode());
12233       WorklistRemover DeadNodes(*this);
12234       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12235       ++OpsNarrowed;
12236       return NewST;
12237     }
12238   }
12239
12240   return SDValue();
12241 }
12242
12243 /// For a given floating point load / store pair, if the load value isn't used
12244 /// by any other operations, then consider transforming the pair to integer
12245 /// load / store operations if the target deems the transformation profitable.
12246 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12247   StoreSDNode *ST  = cast<StoreSDNode>(N);
12248   SDValue Chain = ST->getChain();
12249   SDValue Value = ST->getValue();
12250   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12251       Value.hasOneUse() &&
12252       Chain == SDValue(Value.getNode(), 1)) {
12253     LoadSDNode *LD = cast<LoadSDNode>(Value);
12254     EVT VT = LD->getMemoryVT();
12255     if (!VT.isFloatingPoint() ||
12256         VT != ST->getMemoryVT() ||
12257         LD->isNonTemporal() ||
12258         ST->isNonTemporal() ||
12259         LD->getPointerInfo().getAddrSpace() != 0 ||
12260         ST->getPointerInfo().getAddrSpace() != 0)
12261       return SDValue();
12262
12263     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12264     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12265         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12266         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12267         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12268       return SDValue();
12269
12270     unsigned LDAlign = LD->getAlignment();
12271     unsigned STAlign = ST->getAlignment();
12272     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12273     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12274     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12275       return SDValue();
12276
12277     SDValue NewLD =
12278         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12279                     LD->getPointerInfo(), LDAlign);
12280
12281     SDValue NewST =
12282         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12283                      ST->getPointerInfo(), STAlign);
12284
12285     AddToWorklist(NewLD.getNode());
12286     AddToWorklist(NewST.getNode());
12287     WorklistRemover DeadNodes(*this);
12288     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12289     ++LdStFP2Int;
12290     return NewST;
12291   }
12292
12293   return SDValue();
12294 }
12295
12296 // This is a helper function for visitMUL to check the profitability
12297 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12298 // MulNode is the original multiply, AddNode is (add x, c1),
12299 // and ConstNode is c2.
12300 //
12301 // If the (add x, c1) has multiple uses, we could increase
12302 // the number of adds if we make this transformation.
12303 // It would only be worth doing this if we can remove a
12304 // multiply in the process. Check for that here.
12305 // To illustrate:
12306 //     (A + c1) * c3
12307 //     (A + c2) * c3
12308 // We're checking for cases where we have common "c3 * A" expressions.
12309 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12310                                               SDValue &AddNode,
12311                                               SDValue &ConstNode) {
12312   APInt Val;
12313
12314   // If the add only has one use, this would be OK to do.
12315   if (AddNode.getNode()->hasOneUse())
12316     return true;
12317
12318   // Walk all the users of the constant with which we're multiplying.
12319   for (SDNode *Use : ConstNode->uses()) {
12320
12321     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12322       continue;
12323
12324     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12325       SDNode *OtherOp;
12326       SDNode *MulVar = AddNode.getOperand(0).getNode();
12327
12328       // OtherOp is what we're multiplying against the constant.
12329       if (Use->getOperand(0) == ConstNode)
12330         OtherOp = Use->getOperand(1).getNode();
12331       else
12332         OtherOp = Use->getOperand(0).getNode();
12333
12334       // Check to see if multiply is with the same operand of our "add".
12335       //
12336       //     ConstNode  = CONST
12337       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12338       //     ...
12339       //     AddNode  = (A + c1)  <-- MulVar is A.
12340       //         = AddNode * ConstNode   <-- current visiting instruction.
12341       //
12342       // If we make this transformation, we will have a common
12343       // multiply (ConstNode * A) that we can save.
12344       if (OtherOp == MulVar)
12345         return true;
12346
12347       // Now check to see if a future expansion will give us a common
12348       // multiply.
12349       //
12350       //     ConstNode  = CONST
12351       //     AddNode    = (A + c1)
12352       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12353       //     ...
12354       //     OtherOp = (A + c2)
12355       //     Use     = OtherOp * ConstNode <-- visiting Use.
12356       //
12357       // If we make this transformation, we will have a common
12358       // multiply (CONST * A) after we also do the same transformation
12359       // to the "t2" instruction.
12360       if (OtherOp->getOpcode() == ISD::ADD &&
12361           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12362           OtherOp->getOperand(0).getNode() == MulVar)
12363         return true;
12364     }
12365   }
12366
12367   // Didn't find a case where this would be profitable.
12368   return false;
12369 }
12370
12371 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12372                                          unsigned NumStores) {
12373   SmallVector<SDValue, 8> Chains;
12374   SmallPtrSet<const SDNode *, 8> Visited;
12375   SDLoc StoreDL(StoreNodes[0].MemNode);
12376
12377   for (unsigned i = 0; i < NumStores; ++i) {
12378     Visited.insert(StoreNodes[i].MemNode);
12379   }
12380
12381   // don't include nodes that are children
12382   for (unsigned i = 0; i < NumStores; ++i) {
12383     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12384       Chains.push_back(StoreNodes[i].MemNode->getChain());
12385   }
12386
12387   assert(Chains.size() > 0 && "Chain should have generated a chain");
12388   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12389 }
12390
12391 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12392     SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
12393     bool IsConstantSrc, bool UseVector, bool UseTrunc) {
12394   // Make sure we have something to merge.
12395   if (NumStores < 2)
12396     return false;
12397
12398   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12399
12400   // The latest Node in the DAG.
12401   SDLoc DL(StoreNodes[0].MemNode);
12402
12403   SDValue StoredVal;
12404   if (UseVector) {
12405     bool IsVec = MemVT.isVector();
12406     unsigned Elts = NumStores;
12407     if (IsVec) {
12408       // When merging vector stores, get the total number of elements.
12409       Elts *= MemVT.getVectorNumElements();
12410     }
12411     // Get the type for the merged vector store.
12412     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12413     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
12414
12415     if (IsConstantSrc) {
12416       SmallVector<SDValue, 8> BuildVector;
12417       for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
12418         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12419         SDValue Val = St->getValue();
12420         if (MemVT.getScalarType().isInteger())
12421           if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
12422             Val = DAG.getConstant(
12423                 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
12424                 SDLoc(CFP), MemVT);
12425         BuildVector.push_back(Val);
12426       }
12427       StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
12428     } else {
12429       SmallVector<SDValue, 8> Ops;
12430       for (unsigned i = 0; i < NumStores; ++i) {
12431         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12432         SDValue Val = St->getValue();
12433         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
12434         if (Val.getValueType() != MemVT)
12435           return false;
12436         Ops.push_back(Val);
12437       }
12438
12439       // Build the extracted vector elements back into a vector.
12440       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
12441                               DL, Ty, Ops);    }
12442   } else {
12443     // We should always use a vector store when merging extracted vector
12444     // elements, so this path implies a store of constants.
12445     assert(IsConstantSrc && "Merged vector elements should use vector store");
12446
12447     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12448     APInt StoreInt(SizeInBits, 0);
12449
12450     // Construct a single integer constant which is made of the smaller
12451     // constant inputs.
12452     bool IsLE = DAG.getDataLayout().isLittleEndian();
12453     for (unsigned i = 0; i < NumStores; ++i) {
12454       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12455       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12456
12457       SDValue Val = St->getValue();
12458       StoreInt <<= ElementSizeBytes * 8;
12459       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12460         StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits);
12461       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12462         StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits);
12463       } else {
12464         llvm_unreachable("Invalid constant element type");
12465       }
12466     }
12467
12468     // Create the new Load and Store operations.
12469     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12470     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12471   }
12472
12473   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12474   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12475
12476   // make sure we use trunc store if it's necessary to be legal.
12477   SDValue NewStore;
12478   if (UseVector || !UseTrunc) {
12479     NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
12480                             FirstInChain->getPointerInfo(),
12481                             FirstInChain->getAlignment());
12482   } else { // Must be realized as a trunc store
12483     EVT LegalizedStoredValueTy =
12484         TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
12485     unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
12486     ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
12487     SDValue ExtendedStoreVal =
12488         DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
12489                         LegalizedStoredValueTy);
12490     NewStore = DAG.getTruncStore(
12491         NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
12492         FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
12493         FirstInChain->getAlignment(),
12494         FirstInChain->getMemOperand()->getFlags());
12495   }
12496
12497   // Replace all merged stores with the new store.
12498   for (unsigned i = 0; i < NumStores; ++i)
12499     CombineTo(StoreNodes[i].MemNode, NewStore);
12500
12501   AddToWorklist(NewChain.getNode());
12502   return true;
12503 }
12504
12505 void DAGCombiner::getStoreMergeCandidates(
12506     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12507   // This holds the base pointer, index, and the offset in bytes from the base
12508   // pointer.
12509   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12510   EVT MemVT = St->getMemoryVT();
12511
12512   // We must have a base and an offset.
12513   if (!BasePtr.getBase().getNode())
12514     return;
12515
12516   // Do not handle stores to undef base pointers.
12517   if (BasePtr.getBase().isUndef())
12518     return;
12519
12520   bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
12521                        isa<ConstantFPSDNode>(St->getValue());
12522   bool IsExtractVecSrc =
12523       (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12524        St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
12525   bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
12526   BaseIndexOffset LBasePtr;
12527   // Match on loadbaseptr if relevant.
12528   if (IsLoadSrc)
12529     LBasePtr = BaseIndexOffset::match(
12530         cast<LoadSDNode>(St->getValue())->getBasePtr(), DAG);
12531
12532   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
12533                             int64_t &Offset) -> bool {
12534     if (Other->isVolatile() || Other->isIndexed())
12535       return false;
12536     // We can merge constant floats to equivalent integers
12537     if (Other->getMemoryVT() != MemVT)
12538       if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) &&
12539             isa<ConstantFPSDNode>(Other->getValue())))
12540         return false;
12541     if (IsLoadSrc) {
12542       // The Load's Base Ptr must also match
12543       if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Other->getValue())) {
12544         auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG);
12545         if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
12546           return false;
12547       } else
12548         return false;
12549     }
12550     if (IsConstantSrc)
12551       if (!(isa<ConstantSDNode>(Other->getValue()) ||
12552             isa<ConstantFPSDNode>(Other->getValue())))
12553         return false;
12554     if (IsExtractVecSrc)
12555       if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12556             Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR))
12557         return false;
12558     Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12559     return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
12560   };
12561   // We looking for a root node which is an ancestor to all mergable
12562   // stores. We search up through a load, to our root and then down
12563   // through all children. For instance we will find Store{1,2,3} if
12564   // St is Store1, Store2. or Store3 where the root is not a load
12565   // which always true for nonvolatile ops. TODO: Expand
12566   // the search to find all valid candidates through multiple layers of loads.
12567   //
12568   // Root
12569   // |-------|-------|
12570   // Load    Load    Store3
12571   // |       |
12572   // Store1   Store2
12573   //
12574   // FIXME: We should be able to climb and
12575   // descend TokenFactors to find candidates as well.
12576
12577   SDNode *RootNode = (St->getChain()).getNode();
12578
12579   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12580     RootNode = Ldn->getChain().getNode();
12581     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12582       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12583         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12584           if (I2.getOperandNo() == 0)
12585             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12586               BaseIndexOffset Ptr;
12587               int64_t PtrDiff;
12588               if (CandidateMatch(OtherST, Ptr, PtrDiff))
12589                 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12590             }
12591   } else
12592     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12593       if (I.getOperandNo() == 0)
12594         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12595           BaseIndexOffset Ptr;
12596           int64_t PtrDiff;
12597           if (CandidateMatch(OtherST, Ptr, PtrDiff))
12598             StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12599         }
12600 }
12601
12602 // We need to check that merging these stores does not cause a loop
12603 // in the DAG. Any store candidate may depend on another candidate
12604 // indirectly through its operand (we already consider dependencies
12605 // through the chain). Check in parallel by searching up from
12606 // non-chain operands of candidates.
12607 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12608     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12609   SmallPtrSet<const SDNode *, 16> Visited;
12610   SmallVector<const SDNode *, 8> Worklist;
12611   // search ops of store candidates
12612   for (unsigned i = 0; i < NumStores; ++i) {
12613     SDNode *n = StoreNodes[i].MemNode;
12614     // Potential loops may happen only through non-chain operands
12615     for (unsigned j = 1; j < n->getNumOperands(); ++j)
12616       Worklist.push_back(n->getOperand(j).getNode());
12617   }
12618   // search through DAG. We can stop early if we find a storenode
12619   for (unsigned i = 0; i < NumStores; ++i) {
12620     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12621       return false;
12622   }
12623   return true;
12624 }
12625
12626 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12627   if (OptLevel == CodeGenOpt::None)
12628     return false;
12629
12630   EVT MemVT = St->getMemoryVT();
12631   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12632
12633   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12634     return false;
12635
12636   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12637       Attribute::NoImplicitFloat);
12638
12639   // This function cannot currently deal with non-byte-sized memory sizes.
12640   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12641     return false;
12642
12643   if (!MemVT.isSimple())
12644     return false;
12645
12646   // Perform an early exit check. Do not bother looking at stored values that
12647   // are not constants, loads, or extracted vector elements.
12648   SDValue StoredVal = St->getValue();
12649   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12650   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12651                        isa<ConstantFPSDNode>(StoredVal);
12652   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12653                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12654
12655   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12656     return false;
12657
12658   // Don't merge vectors into wider vectors if the source data comes from loads.
12659   // TODO: This restriction can be lifted by using logic similar to the
12660   // ExtractVecSrc case.
12661   if (MemVT.isVector() && IsLoadSrc)
12662     return false;
12663
12664   SmallVector<MemOpLink, 8> StoreNodes;
12665   // Find potential store merge candidates by searching through chain sub-DAG
12666   getStoreMergeCandidates(St, StoreNodes);
12667
12668   // Check if there is anything to merge.
12669   if (StoreNodes.size() < 2)
12670     return false;
12671
12672   // Sort the memory operands according to their distance from the
12673   // base pointer.
12674   std::sort(StoreNodes.begin(), StoreNodes.end(),
12675             [](MemOpLink LHS, MemOpLink RHS) {
12676               return LHS.OffsetFromBase < RHS.OffsetFromBase;
12677             });
12678
12679   // Store Merge attempts to merge the lowest stores. This generally
12680   // works out as if successful, as the remaining stores are checked
12681   // after the first collection of stores is merged. However, in the
12682   // case that a non-mergeable store is found first, e.g., {p[-2],
12683   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12684   // mergeable cases. To prevent this, we prune such stores from the
12685   // front of StoreNodes here.
12686
12687   bool RV = false;
12688   while (StoreNodes.size() > 1) {
12689     unsigned StartIdx = 0;
12690     while ((StartIdx + 1 < StoreNodes.size()) &&
12691            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12692                StoreNodes[StartIdx + 1].OffsetFromBase)
12693       ++StartIdx;
12694
12695     // Bail if we don't have enough candidates to merge.
12696     if (StartIdx + 1 >= StoreNodes.size())
12697       return RV;
12698
12699     if (StartIdx)
12700       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12701
12702     // Scan the memory operations on the chain and find the first
12703     // non-consecutive store memory address.
12704     unsigned NumConsecutiveStores = 1;
12705     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12706     // Check that the addresses are consecutive starting from the second
12707     // element in the list of stores.
12708     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12709       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12710       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12711         break;
12712       NumConsecutiveStores = i + 1;
12713     }
12714
12715     if (NumConsecutiveStores < 2) {
12716       StoreNodes.erase(StoreNodes.begin(),
12717                        StoreNodes.begin() + NumConsecutiveStores);
12718       continue;
12719     }
12720
12721     // Check that we can merge these candidates without causing a cycle
12722     if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
12723                                                   NumConsecutiveStores)) {
12724       StoreNodes.erase(StoreNodes.begin(),
12725                        StoreNodes.begin() + NumConsecutiveStores);
12726       continue;
12727     }
12728
12729     // The node with the lowest store address.
12730     LLVMContext &Context = *DAG.getContext();
12731     const DataLayout &DL = DAG.getDataLayout();
12732
12733     // Store the constants into memory as one consecutive store.
12734     if (IsConstantSrc) {
12735       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12736       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12737       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12738       unsigned LastLegalType = 1;
12739       unsigned LastLegalVectorType = 1;
12740       bool LastIntegerTrunc = false;
12741       bool NonZero = false;
12742       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12743         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12744         SDValue StoredVal = ST->getValue();
12745
12746         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12747           NonZero |= !C->isNullValue();
12748         } else if (ConstantFPSDNode *C =
12749                        dyn_cast<ConstantFPSDNode>(StoredVal)) {
12750           NonZero |= !C->getConstantFPValue()->isNullValue();
12751         } else {
12752           // Non-constant.
12753           break;
12754         }
12755
12756         // Find a legal type for the constant store.
12757         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12758         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12759         bool IsFast = false;
12760         if (TLI.isTypeLegal(StoreTy) &&
12761             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
12762             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12763                                    FirstStoreAlign, &IsFast) &&
12764             IsFast) {
12765           LastIntegerTrunc = false;
12766           LastLegalType = i + 1;
12767           // Or check whether a truncstore is legal.
12768         } else if (TLI.getTypeAction(Context, StoreTy) ==
12769                    TargetLowering::TypePromoteInteger) {
12770           EVT LegalizedStoredValueTy =
12771               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12772           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12773               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
12774               TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12775                                      FirstStoreAS, FirstStoreAlign, &IsFast) &&
12776               IsFast) {
12777             LastIntegerTrunc = true;
12778             LastLegalType = i + 1;
12779           }
12780         }
12781
12782         // We only use vectors if the constant is known to be zero or the target
12783         // allows it and the function is not marked with the noimplicitfloat
12784         // attribute.
12785         if ((!NonZero ||
12786              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12787             !NoVectors) {
12788           // Find a legal type for the vector store.
12789           unsigned Elts = i + 1;
12790           if (MemVT.isVector()) {
12791             // When merging vector stores, get the total number of elements.
12792             Elts *= MemVT.getVectorNumElements();
12793           }
12794           EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
12795           if (TLI.isTypeLegal(Ty) &&
12796               TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
12797               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12798                                      FirstStoreAlign, &IsFast) &&
12799               IsFast)
12800             LastLegalVectorType = i + 1;
12801         }
12802       }
12803
12804       // Check if we found a legal integer type that creates a meaningful merge.
12805       if (LastLegalType < 2 && LastLegalVectorType < 2) {
12806         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12807         continue;
12808       }
12809
12810       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12811       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12812
12813       bool Merged = MergeStoresOfConstantsOrVecElts(
12814           StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
12815       if (!Merged) {
12816         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12817         continue;
12818       }
12819       // Remove merged stores for next iteration.
12820       RV = true;
12821       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12822       continue;
12823     }
12824
12825     // When extracting multiple vector elements, try to store them
12826     // in one vector store rather than a sequence of scalar stores.
12827     if (IsExtractVecSrc) {
12828       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12829       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12830       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12831       unsigned NumStoresToMerge = 1;
12832       bool IsVec = MemVT.isVector();
12833       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12834         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12835         unsigned StoreValOpcode = St->getValue().getOpcode();
12836         // This restriction could be loosened.
12837         // Bail out if any stored values are not elements extracted from a
12838         // vector. It should be possible to handle mixed sources, but load
12839         // sources need more careful handling (see the block of code below that
12840         // handles consecutive loads).
12841         if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12842             StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12843           return RV;
12844
12845         // Find a legal type for the vector store.
12846         unsigned Elts = i + 1;
12847         if (IsVec) {
12848           // When merging vector stores, get the total number of elements.
12849           Elts *= MemVT.getVectorNumElements();
12850         }
12851         EVT Ty =
12852             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12853         bool IsFast;
12854         if (TLI.isTypeLegal(Ty) &&
12855             TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
12856             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12857                                    FirstStoreAlign, &IsFast) &&
12858             IsFast)
12859           NumStoresToMerge = i + 1;
12860       }
12861
12862       bool Merged = MergeStoresOfConstantsOrVecElts(
12863           StoreNodes, MemVT, NumStoresToMerge, false, true, false);
12864       if (!Merged) {
12865         StoreNodes.erase(StoreNodes.begin(),
12866                          StoreNodes.begin() + NumStoresToMerge);
12867         continue;
12868       }
12869       // Remove merged stores for next iteration.
12870       StoreNodes.erase(StoreNodes.begin(),
12871                        StoreNodes.begin() + NumStoresToMerge);
12872       RV = true;
12873       continue;
12874     }
12875
12876     // Below we handle the case of multiple consecutive stores that
12877     // come from multiple consecutive loads. We merge them into a single
12878     // wide load and a single wide store.
12879
12880     // Look for load nodes which are used by the stored values.
12881     SmallVector<MemOpLink, 8> LoadNodes;
12882
12883     // Find acceptable loads. Loads need to have the same chain (token factor),
12884     // must not be zext, volatile, indexed, and they must be consecutive.
12885     BaseIndexOffset LdBasePtr;
12886     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12887       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12888       LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12889       if (!Ld)
12890         break;
12891
12892       // Loads must only have one use.
12893       if (!Ld->hasNUsesOfValue(1, 0))
12894         break;
12895
12896       // The memory operands must not be volatile.
12897       if (Ld->isVolatile() || Ld->isIndexed())
12898         break;
12899
12900       // We do not accept ext loads.
12901       if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12902         break;
12903
12904       // The stored memory type must be the same.
12905       if (Ld->getMemoryVT() != MemVT)
12906         break;
12907
12908       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12909       // If this is not the first ptr that we check.
12910       int64_t LdOffset = 0;
12911       if (LdBasePtr.getBase().getNode()) {
12912         // The base ptr must be the same.
12913         if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
12914           break;
12915       } else {
12916         // Check that all other base pointers are the same as this one.
12917         LdBasePtr = LdPtr;
12918       }
12919
12920       // We found a potential memory operand to merge.
12921       LoadNodes.push_back(MemOpLink(Ld, LdOffset));
12922     }
12923
12924     if (LoadNodes.size() < 2) {
12925       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12926       continue;
12927     }
12928
12929     // If we have load/store pair instructions and we only have two values,
12930     // don't bother merging.
12931     unsigned RequiredAlignment;
12932     if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12933         StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
12934       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
12935       continue;
12936     }
12937     LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12938     unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12939     unsigned FirstStoreAlign = FirstInChain->getAlignment();
12940     LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12941     unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12942     unsigned FirstLoadAlign = FirstLoad->getAlignment();
12943
12944     // Scan the memory operations on the chain and find the first
12945     // non-consecutive load memory address. These variables hold the index in
12946     // the store node array.
12947     unsigned LastConsecutiveLoad = 1;
12948     // This variable refers to the size and not index in the array.
12949     unsigned LastLegalVectorType = 1;
12950     unsigned LastLegalIntegerType = 1;
12951     bool isDereferenceable = true;
12952     bool DoIntegerTruncate = false;
12953     StartAddress = LoadNodes[0].OffsetFromBase;
12954     SDValue FirstChain = FirstLoad->getChain();
12955     for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12956       // All loads must share the same chain.
12957       if (LoadNodes[i].MemNode->getChain() != FirstChain)
12958         break;
12959
12960       int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12961       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12962         break;
12963       LastConsecutiveLoad = i;
12964
12965       if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
12966         isDereferenceable = false;
12967
12968       // Find a legal type for the vector store.
12969       EVT StoreTy = EVT::getVectorVT(Context, MemVT, i + 1);
12970       bool IsFastSt, IsFastLd;
12971       if (TLI.isTypeLegal(StoreTy) &&
12972           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
12973           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12974                                  FirstStoreAlign, &IsFastSt) &&
12975           IsFastSt &&
12976           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12977                                  FirstLoadAlign, &IsFastLd) &&
12978           IsFastLd) {
12979         LastLegalVectorType = i + 1;
12980       }
12981
12982       // Find a legal type for the integer store.
12983       unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12984       StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12985       if (TLI.isTypeLegal(StoreTy) &&
12986           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
12987           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12988                                  FirstStoreAlign, &IsFastSt) &&
12989           IsFastSt &&
12990           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12991                                  FirstLoadAlign, &IsFastLd) &&
12992           IsFastLd) {
12993         LastLegalIntegerType = i + 1;
12994         DoIntegerTruncate = false;
12995         // Or check whether a truncstore and extload is legal.
12996       } else if (TLI.getTypeAction(Context, StoreTy) ==
12997                  TargetLowering::TypePromoteInteger) {
12998         EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
12999         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13000             TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13001             TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
13002                                StoreTy) &&
13003             TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
13004                                StoreTy) &&
13005             TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
13006             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
13007                                    FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
13008             IsFastSt &&
13009             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13010                                    FirstLoadAlign, &IsFastLd) &&
13011             IsFastLd) {
13012           LastLegalIntegerType = i + 1;
13013           DoIntegerTruncate = true;
13014         }
13015       }
13016     }
13017
13018     // Only use vector types if the vector type is larger than the integer type.
13019     // If they are the same, use integers.
13020     bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
13021     unsigned LastLegalType =
13022         std::max(LastLegalVectorType, LastLegalIntegerType);
13023
13024     // We add +1 here because the LastXXX variables refer to location while
13025     // the NumElem refers to array/index size.
13026     unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
13027     NumElem = std::min(LastLegalType, NumElem);
13028
13029     if (NumElem < 2) {
13030       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
13031       continue;
13032     }
13033
13034     // Find if it is better to use vectors or integers to load and store
13035     // to memory.
13036     EVT JointMemOpVT;
13037     if (UseVectorTy) {
13038       JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
13039     } else {
13040       unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
13041       JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
13042     }
13043
13044     SDLoc LoadDL(LoadNodes[0].MemNode);
13045     SDLoc StoreDL(StoreNodes[0].MemNode);
13046
13047     // The merged loads are required to have the same incoming chain, so
13048     // using the first's chain is acceptable.
13049
13050     SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
13051     AddToWorklist(NewStoreChain.getNode());
13052
13053     MachineMemOperand::Flags MMOFlags = isDereferenceable ?
13054                                           MachineMemOperand::MODereferenceable:
13055                                           MachineMemOperand::MONone;
13056
13057     SDValue NewLoad, NewStore;
13058     if (UseVectorTy || !DoIntegerTruncate) {
13059       NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
13060                             FirstLoad->getBasePtr(),
13061                             FirstLoad->getPointerInfo(), FirstLoadAlign,
13062                             MMOFlags);
13063       NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
13064                               FirstInChain->getBasePtr(),
13065                               FirstInChain->getPointerInfo(), FirstStoreAlign);
13066     } else { // This must be the truncstore/extload case
13067       EVT ExtendedTy =
13068           TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
13069       NewLoad =
13070           DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13071                          FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13072                          JointMemOpVT, FirstLoadAlign, MMOFlags);
13073       NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13074                                    FirstInChain->getBasePtr(),
13075                                    FirstInChain->getPointerInfo(), JointMemOpVT,
13076                                    FirstInChain->getAlignment(),
13077                                    FirstInChain->getMemOperand()->getFlags());
13078     }
13079
13080     // Transfer chain users from old loads to the new load.
13081     for (unsigned i = 0; i < NumElem; ++i) {
13082       LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13083       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13084                                     SDValue(NewLoad.getNode(), 1));
13085     }
13086
13087     // Replace the all stores with the new store.
13088     for (unsigned i = 0; i < NumElem; ++i)
13089       CombineTo(StoreNodes[i].MemNode, NewStore);
13090     RV = true;
13091     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13092     continue;
13093   }
13094   return RV;
13095 }
13096
13097 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13098   SDLoc SL(ST);
13099   SDValue ReplStore;
13100
13101   // Replace the chain to avoid dependency.
13102   if (ST->isTruncatingStore()) {
13103     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13104                                   ST->getBasePtr(), ST->getMemoryVT(),
13105                                   ST->getMemOperand());
13106   } else {
13107     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13108                              ST->getMemOperand());
13109   }
13110
13111   // Create token to keep both nodes around.
13112   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13113                               MVT::Other, ST->getChain(), ReplStore);
13114
13115   // Make sure the new and old chains are cleaned up.
13116   AddToWorklist(Token.getNode());
13117
13118   // Don't add users to work list.
13119   return CombineTo(ST, Token, false);
13120 }
13121
13122 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13123   SDValue Value = ST->getValue();
13124   if (Value.getOpcode() == ISD::TargetConstantFP)
13125     return SDValue();
13126
13127   SDLoc DL(ST);
13128
13129   SDValue Chain = ST->getChain();
13130   SDValue Ptr = ST->getBasePtr();
13131
13132   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13133
13134   // NOTE: If the original store is volatile, this transform must not increase
13135   // the number of stores.  For example, on x86-32 an f64 can be stored in one
13136   // processor operation but an i64 (which is not legal) requires two.  So the
13137   // transform should not be done in this case.
13138
13139   SDValue Tmp;
13140   switch (CFP->getSimpleValueType(0).SimpleTy) {
13141   default:
13142     llvm_unreachable("Unknown FP type");
13143   case MVT::f16:    // We don't do this for these yet.
13144   case MVT::f80:
13145   case MVT::f128:
13146   case MVT::ppcf128:
13147     return SDValue();
13148   case MVT::f32:
13149     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13150         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13151       ;
13152       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13153                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13154                             MVT::i32);
13155       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13156     }
13157
13158     return SDValue();
13159   case MVT::f64:
13160     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13161          !ST->isVolatile()) ||
13162         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13163       ;
13164       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13165                             getZExtValue(), SDLoc(CFP), MVT::i64);
13166       return DAG.getStore(Chain, DL, Tmp,
13167                           Ptr, ST->getMemOperand());
13168     }
13169
13170     if (!ST->isVolatile() &&
13171         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13172       // Many FP stores are not made apparent until after legalize, e.g. for
13173       // argument passing.  Since this is so common, custom legalize the
13174       // 64-bit integer store into two 32-bit stores.
13175       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13176       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13177       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13178       if (DAG.getDataLayout().isBigEndian())
13179         std::swap(Lo, Hi);
13180
13181       unsigned Alignment = ST->getAlignment();
13182       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13183       AAMDNodes AAInfo = ST->getAAInfo();
13184
13185       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13186                                  ST->getAlignment(), MMOFlags, AAInfo);
13187       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13188                         DAG.getConstant(4, DL, Ptr.getValueType()));
13189       Alignment = MinAlign(Alignment, 4U);
13190       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13191                                  ST->getPointerInfo().getWithOffset(4),
13192                                  Alignment, MMOFlags, AAInfo);
13193       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13194                          St0, St1);
13195     }
13196
13197     return SDValue();
13198   }
13199 }
13200
13201 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13202   StoreSDNode *ST  = cast<StoreSDNode>(N);
13203   SDValue Chain = ST->getChain();
13204   SDValue Value = ST->getValue();
13205   SDValue Ptr   = ST->getBasePtr();
13206
13207   // If this is a store of a bit convert, store the input value if the
13208   // resultant store does not need a higher alignment than the original.
13209   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13210       ST->isUnindexed()) {
13211     EVT SVT = Value.getOperand(0).getValueType();
13212     if (((!LegalOperations && !ST->isVolatile()) ||
13213          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13214         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13215       unsigned OrigAlign = ST->getAlignment();
13216       bool Fast = false;
13217       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13218                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13219           Fast) {
13220         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13221                             ST->getPointerInfo(), OrigAlign,
13222                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13223       }
13224     }
13225   }
13226
13227   // Turn 'store undef, Ptr' -> nothing.
13228   if (Value.isUndef() && ST->isUnindexed())
13229     return Chain;
13230
13231   // Try to infer better alignment information than the store already has.
13232   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13233     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13234       if (Align > ST->getAlignment()) {
13235         SDValue NewStore =
13236             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13237                               ST->getMemoryVT(), Align,
13238                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13239         if (NewStore.getNode() != N)
13240           return CombineTo(ST, NewStore, true);
13241       }
13242     }
13243   }
13244
13245   // Try transforming a pair floating point load / store ops to integer
13246   // load / store ops.
13247   if (SDValue NewST = TransformFPLoadStorePair(N))
13248     return NewST;
13249
13250   if (ST->isUnindexed()) {
13251     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13252     // adjacent stores.
13253     if (findBetterNeighborChains(ST)) {
13254       // replaceStoreChain uses CombineTo, which handled all of the worklist
13255       // manipulation. Return the original node to not do anything else.
13256       return SDValue(ST, 0);
13257     }
13258     Chain = ST->getChain();
13259   }
13260
13261   // FIXME: is there such a thing as a truncating indexed store?
13262   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13263       Value.getValueType().isInteger()) {
13264     // See if we can simplify the input to this truncstore with knowledge that
13265     // only the low bits are being used.  For example:
13266     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13267     SDValue Shorter = GetDemandedBits(
13268         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13269                                     ST->getMemoryVT().getScalarSizeInBits()));
13270     AddToWorklist(Value.getNode());
13271     if (Shorter.getNode())
13272       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13273                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13274
13275     // Otherwise, see if we can simplify the operation with
13276     // SimplifyDemandedBits, which only works if the value has a single use.
13277     if (SimplifyDemandedBits(
13278             Value,
13279             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13280                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13281       // Re-visit the store if anything changed and the store hasn't been merged
13282       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13283       // node back to the worklist if necessary, but we also need to re-visit
13284       // the Store node itself.
13285       if (N->getOpcode() != ISD::DELETED_NODE)
13286         AddToWorklist(N);
13287       return SDValue(N, 0);
13288     }
13289   }
13290
13291   // If this is a load followed by a store to the same location, then the store
13292   // is dead/noop.
13293   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13294     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13295         ST->isUnindexed() && !ST->isVolatile() &&
13296         // There can't be any side effects between the load and store, such as
13297         // a call or store.
13298         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13299       // The store is dead, remove it.
13300       return Chain;
13301     }
13302   }
13303
13304   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13305     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13306         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13307         ST->getMemoryVT() == ST1->getMemoryVT()) {
13308       // If this is a store followed by a store with the same value to the same
13309       // location, then the store is dead/noop.
13310       if (ST1->getValue() == Value) {
13311         // The store is dead, remove it.
13312         return Chain;
13313       }
13314
13315       // If this is a store who's preceeding store to the same location
13316       // and no one other node is chained to that store we can effectively
13317       // drop the store. Do not remove stores to undef as they may be used as
13318       // data sinks.
13319       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13320           !ST1->getBasePtr().isUndef()) {
13321         // ST1 is fully overwritten and can be elided. Combine with it's chain
13322         // value.
13323         CombineTo(ST1, ST1->getChain());
13324         return SDValue();
13325       }
13326     }
13327   }
13328
13329   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13330   // truncating store.  We can do this even if this is already a truncstore.
13331   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13332       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13333       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13334                             ST->getMemoryVT())) {
13335     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13336                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
13337   }
13338
13339   // Only perform this optimization before the types are legal, because we
13340   // don't want to perform this optimization on every DAGCombine invocation.
13341   if ((TLI.mergeStoresAfterLegalization()) ? Level == AfterLegalizeDAG
13342                                            : !LegalTypes) {
13343     for (;;) {
13344       // There can be multiple store sequences on the same chain.
13345       // Keep trying to merge store sequences until we are unable to do so
13346       // or until we merge the last store on the chain.
13347       bool Changed = MergeConsecutiveStores(ST);
13348       if (!Changed) break;
13349       // Return N as merge only uses CombineTo and no worklist clean
13350       // up is necessary.
13351       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13352         return SDValue(N, 0);
13353     }
13354   }
13355
13356   // Try transforming N to an indexed store.
13357   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13358     return SDValue(N, 0);
13359
13360   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13361   //
13362   // Make sure to do this only after attempting to merge stores in order to
13363   //  avoid changing the types of some subset of stores due to visit order,
13364   //  preventing their merging.
13365   if (isa<ConstantFPSDNode>(ST->getValue())) {
13366     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13367       return NewSt;
13368   }
13369
13370   if (SDValue NewSt = splitMergedValStore(ST))
13371     return NewSt;
13372
13373   return ReduceLoadOpStoreWidth(N);
13374 }
13375
13376 /// For the instruction sequence of store below, F and I values
13377 /// are bundled together as an i64 value before being stored into memory.
13378 /// Sometimes it is more efficent to generate separate stores for F and I,
13379 /// which can remove the bitwise instructions or sink them to colder places.
13380 ///
13381 ///   (store (or (zext (bitcast F to i32) to i64),
13382 ///              (shl (zext I to i64), 32)), addr)  -->
13383 ///   (store F, addr) and (store I, addr+4)
13384 ///
13385 /// Similarly, splitting for other merged store can also be beneficial, like:
13386 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13387 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13388 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13389 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13390 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13391 ///
13392 /// We allow each target to determine specifically which kind of splitting is
13393 /// supported.
13394 ///
13395 /// The store patterns are commonly seen from the simple code snippet below
13396 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13397 ///   void goo(const std::pair<int, float> &);
13398 ///   hoo() {
13399 ///     ...
13400 ///     goo(std::make_pair(tmp, ftmp));
13401 ///     ...
13402 ///   }
13403 ///
13404 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13405   if (OptLevel == CodeGenOpt::None)
13406     return SDValue();
13407
13408   SDValue Val = ST->getValue();
13409   SDLoc DL(ST);
13410
13411   // Match OR operand.
13412   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13413     return SDValue();
13414
13415   // Match SHL operand and get Lower and Higher parts of Val.
13416   SDValue Op1 = Val.getOperand(0);
13417   SDValue Op2 = Val.getOperand(1);
13418   SDValue Lo, Hi;
13419   if (Op1.getOpcode() != ISD::SHL) {
13420     std::swap(Op1, Op2);
13421     if (Op1.getOpcode() != ISD::SHL)
13422       return SDValue();
13423   }
13424   Lo = Op2;
13425   Hi = Op1.getOperand(0);
13426   if (!Op1.hasOneUse())
13427     return SDValue();
13428
13429   // Match shift amount to HalfValBitSize.
13430   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13431   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13432   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13433     return SDValue();
13434
13435   // Lo and Hi are zero-extended from int with size less equal than 32
13436   // to i64.
13437   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13438       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13439       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13440       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13441       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13442       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13443     return SDValue();
13444
13445   // Use the EVT of low and high parts before bitcast as the input
13446   // of target query.
13447   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13448                   ? Lo.getOperand(0).getValueType()
13449                   : Lo.getValueType();
13450   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13451                    ? Hi.getOperand(0).getValueType()
13452                    : Hi.getValueType();
13453   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13454     return SDValue();
13455
13456   // Start to split store.
13457   unsigned Alignment = ST->getAlignment();
13458   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13459   AAMDNodes AAInfo = ST->getAAInfo();
13460
13461   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13462   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13463   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13464   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13465
13466   SDValue Chain = ST->getChain();
13467   SDValue Ptr = ST->getBasePtr();
13468   // Lower value store.
13469   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13470                              ST->getAlignment(), MMOFlags, AAInfo);
13471   Ptr =
13472       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13473                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13474   // Higher value store.
13475   SDValue St1 =
13476       DAG.getStore(St0, DL, Hi, Ptr,
13477                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13478                    Alignment / 2, MMOFlags, AAInfo);
13479   return St1;
13480 }
13481
13482 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13483   SDValue InVec = N->getOperand(0);
13484   SDValue InVal = N->getOperand(1);
13485   SDValue EltNo = N->getOperand(2);
13486   SDLoc DL(N);
13487
13488   // If the inserted element is an UNDEF, just use the input vector.
13489   if (InVal.isUndef())
13490     return InVec;
13491
13492   EVT VT = InVec.getValueType();
13493
13494   // Check that we know which element is being inserted
13495   if (!isa<ConstantSDNode>(EltNo))
13496     return SDValue();
13497   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13498
13499   // Canonicalize insert_vector_elt dag nodes.
13500   // Example:
13501   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13502   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13503   //
13504   // Do this only if the child insert_vector node has one use; also
13505   // do this only if indices are both constants and Idx1 < Idx0.
13506   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13507       && isa<ConstantSDNode>(InVec.getOperand(2))) {
13508     unsigned OtherElt = InVec.getConstantOperandVal(2);
13509     if (Elt < OtherElt) {
13510       // Swap nodes.
13511       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13512                                   InVec.getOperand(0), InVal, EltNo);
13513       AddToWorklist(NewOp.getNode());
13514       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13515                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13516     }
13517   }
13518
13519   // If we can't generate a legal BUILD_VECTOR, exit
13520   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13521     return SDValue();
13522
13523   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13524   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
13525   // vector elements.
13526   SmallVector<SDValue, 8> Ops;
13527   // Do not combine these two vectors if the output vector will not replace
13528   // the input vector.
13529   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13530     Ops.append(InVec.getNode()->op_begin(),
13531                InVec.getNode()->op_end());
13532   } else if (InVec.isUndef()) {
13533     unsigned NElts = VT.getVectorNumElements();
13534     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13535   } else {
13536     return SDValue();
13537   }
13538
13539   // Insert the element
13540   if (Elt < Ops.size()) {
13541     // All the operands of BUILD_VECTOR must have the same type;
13542     // we enforce that here.
13543     EVT OpVT = Ops[0].getValueType();
13544     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13545   }
13546
13547   // Return the new vector
13548   return DAG.getBuildVector(VT, DL, Ops);
13549 }
13550
13551 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13552     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13553   assert(!OriginalLoad->isVolatile());
13554
13555   EVT ResultVT = EVE->getValueType(0);
13556   EVT VecEltVT = InVecVT.getVectorElementType();
13557   unsigned Align = OriginalLoad->getAlignment();
13558   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13559       VecEltVT.getTypeForEVT(*DAG.getContext()));
13560
13561   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13562     return SDValue();
13563
13564   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13565     ISD::NON_EXTLOAD : ISD::EXTLOAD;
13566   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13567     return SDValue();
13568
13569   Align = NewAlign;
13570
13571   SDValue NewPtr = OriginalLoad->getBasePtr();
13572   SDValue Offset;
13573   EVT PtrType = NewPtr.getValueType();
13574   MachinePointerInfo MPI;
13575   SDLoc DL(EVE);
13576   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13577     int Elt = ConstEltNo->getZExtValue();
13578     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13579     Offset = DAG.getConstant(PtrOff, DL, PtrType);
13580     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13581   } else {
13582     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13583     Offset = DAG.getNode(
13584         ISD::MUL, DL, PtrType, Offset,
13585         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13586     MPI = OriginalLoad->getPointerInfo();
13587   }
13588   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13589
13590   // The replacement we need to do here is a little tricky: we need to
13591   // replace an extractelement of a load with a load.
13592   // Use ReplaceAllUsesOfValuesWith to do the replacement.
13593   // Note that this replacement assumes that the extractvalue is the only
13594   // use of the load; that's okay because we don't want to perform this
13595   // transformation in other cases anyway.
13596   SDValue Load;
13597   SDValue Chain;
13598   if (ResultVT.bitsGT(VecEltVT)) {
13599     // If the result type of vextract is wider than the load, then issue an
13600     // extending load instead.
13601     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13602                                                   VecEltVT)
13603                                    ? ISD::ZEXTLOAD
13604                                    : ISD::EXTLOAD;
13605     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13606                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13607                           Align, OriginalLoad->getMemOperand()->getFlags(),
13608                           OriginalLoad->getAAInfo());
13609     Chain = Load.getValue(1);
13610   } else {
13611     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13612                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13613                        OriginalLoad->getAAInfo());
13614     Chain = Load.getValue(1);
13615     if (ResultVT.bitsLT(VecEltVT))
13616       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13617     else
13618       Load = DAG.getBitcast(ResultVT, Load);
13619   }
13620   WorklistRemover DeadNodes(*this);
13621   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13622   SDValue To[] = { Load, Chain };
13623   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13624   // Since we're explicitly calling ReplaceAllUses, add the new node to the
13625   // worklist explicitly as well.
13626   AddToWorklist(Load.getNode());
13627   AddUsersToWorklist(Load.getNode()); // Add users too
13628   // Make sure to revisit this node to clean it up; it will usually be dead.
13629   AddToWorklist(EVE);
13630   ++OpsNarrowed;
13631   return SDValue(EVE, 0);
13632 }
13633
13634 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13635   // (vextract (scalar_to_vector val, 0) -> val
13636   SDValue InVec = N->getOperand(0);
13637   EVT VT = InVec.getValueType();
13638   EVT NVT = N->getValueType(0);
13639
13640   if (InVec.isUndef())
13641     return DAG.getUNDEF(NVT);
13642
13643   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13644     // Check if the result type doesn't match the inserted element type. A
13645     // SCALAR_TO_VECTOR may truncate the inserted element and the
13646     // EXTRACT_VECTOR_ELT may widen the extracted vector.
13647     SDValue InOp = InVec.getOperand(0);
13648     if (InOp.getValueType() != NVT) {
13649       assert(InOp.getValueType().isInteger() && NVT.isInteger());
13650       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13651     }
13652     return InOp;
13653   }
13654
13655   SDValue EltNo = N->getOperand(1);
13656   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13657
13658   // extract_vector_elt (build_vector x, y), 1 -> y
13659   if (ConstEltNo &&
13660       InVec.getOpcode() == ISD::BUILD_VECTOR &&
13661       TLI.isTypeLegal(VT) &&
13662       (InVec.hasOneUse() ||
13663        TLI.aggressivelyPreferBuildVectorSources(VT))) {
13664     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13665     EVT InEltVT = Elt.getValueType();
13666
13667     // Sometimes build_vector's scalar input types do not match result type.
13668     if (NVT == InEltVT)
13669       return Elt;
13670
13671     // TODO: It may be useful to truncate if free if the build_vector implicitly
13672     // converts.
13673   }
13674
13675   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
13676   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13677       ConstEltNo->isNullValue() && VT.isInteger()) {
13678     SDValue BCSrc = InVec.getOperand(0);
13679     if (BCSrc.getValueType().isScalarInteger())
13680       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13681   }
13682
13683   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13684   //
13685   // This only really matters if the index is non-constant since other combines
13686   // on the constant elements already work.
13687   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13688       EltNo == InVec.getOperand(2)) {
13689     SDValue Elt = InVec.getOperand(1);
13690     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13691   }
13692
13693   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13694   // We only perform this optimization before the op legalization phase because
13695   // we may introduce new vector instructions which are not backed by TD
13696   // patterns. For example on AVX, extracting elements from a wide vector
13697   // without using extract_subvector. However, if we can find an underlying
13698   // scalar value, then we can always use that.
13699   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13700     int NumElem = VT.getVectorNumElements();
13701     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13702     // Find the new index to extract from.
13703     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13704
13705     // Extracting an undef index is undef.
13706     if (OrigElt == -1)
13707       return DAG.getUNDEF(NVT);
13708
13709     // Select the right vector half to extract from.
13710     SDValue SVInVec;
13711     if (OrigElt < NumElem) {
13712       SVInVec = InVec->getOperand(0);
13713     } else {
13714       SVInVec = InVec->getOperand(1);
13715       OrigElt -= NumElem;
13716     }
13717
13718     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13719       SDValue InOp = SVInVec.getOperand(OrigElt);
13720       if (InOp.getValueType() != NVT) {
13721         assert(InOp.getValueType().isInteger() && NVT.isInteger());
13722         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13723       }
13724
13725       return InOp;
13726     }
13727
13728     // FIXME: We should handle recursing on other vector shuffles and
13729     // scalar_to_vector here as well.
13730
13731     if (!LegalOperations) {
13732       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13733       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13734                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13735     }
13736   }
13737
13738   bool BCNumEltsChanged = false;
13739   EVT ExtVT = VT.getVectorElementType();
13740   EVT LVT = ExtVT;
13741
13742   // If the result of load has to be truncated, then it's not necessarily
13743   // profitable.
13744   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13745     return SDValue();
13746
13747   if (InVec.getOpcode() == ISD::BITCAST) {
13748     // Don't duplicate a load with other uses.
13749     if (!InVec.hasOneUse())
13750       return SDValue();
13751
13752     EVT BCVT = InVec.getOperand(0).getValueType();
13753     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13754       return SDValue();
13755     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13756       BCNumEltsChanged = true;
13757     InVec = InVec.getOperand(0);
13758     ExtVT = BCVT.getVectorElementType();
13759   }
13760
13761   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13762   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13763       ISD::isNormalLoad(InVec.getNode()) &&
13764       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13765     SDValue Index = N->getOperand(1);
13766     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13767       if (!OrigLoad->isVolatile()) {
13768         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13769                                                              OrigLoad);
13770       }
13771     }
13772   }
13773
13774   // Perform only after legalization to ensure build_vector / vector_shuffle
13775   // optimizations have already been done.
13776   if (!LegalOperations) return SDValue();
13777
13778   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13779   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13780   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13781
13782   if (ConstEltNo) {
13783     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13784
13785     LoadSDNode *LN0 = nullptr;
13786     const ShuffleVectorSDNode *SVN = nullptr;
13787     if (ISD::isNormalLoad(InVec.getNode())) {
13788       LN0 = cast<LoadSDNode>(InVec);
13789     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13790                InVec.getOperand(0).getValueType() == ExtVT &&
13791                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13792       // Don't duplicate a load with other uses.
13793       if (!InVec.hasOneUse())
13794         return SDValue();
13795
13796       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13797     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13798       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13799       // =>
13800       // (load $addr+1*size)
13801
13802       // Don't duplicate a load with other uses.
13803       if (!InVec.hasOneUse())
13804         return SDValue();
13805
13806       // If the bit convert changed the number of elements, it is unsafe
13807       // to examine the mask.
13808       if (BCNumEltsChanged)
13809         return SDValue();
13810
13811       // Select the input vector, guarding against out of range extract vector.
13812       unsigned NumElems = VT.getVectorNumElements();
13813       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13814       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13815
13816       if (InVec.getOpcode() == ISD::BITCAST) {
13817         // Don't duplicate a load with other uses.
13818         if (!InVec.hasOneUse())
13819           return SDValue();
13820
13821         InVec = InVec.getOperand(0);
13822       }
13823       if (ISD::isNormalLoad(InVec.getNode())) {
13824         LN0 = cast<LoadSDNode>(InVec);
13825         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13826         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13827       }
13828     }
13829
13830     // Make sure we found a non-volatile load and the extractelement is
13831     // the only use.
13832     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13833       return SDValue();
13834
13835     // If Idx was -1 above, Elt is going to be -1, so just return undef.
13836     if (Elt == -1)
13837       return DAG.getUNDEF(LVT);
13838
13839     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13840   }
13841
13842   return SDValue();
13843 }
13844
13845 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13846 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13847   // We perform this optimization post type-legalization because
13848   // the type-legalizer often scalarizes integer-promoted vectors.
13849   // Performing this optimization before may create bit-casts which
13850   // will be type-legalized to complex code sequences.
13851   // We perform this optimization only before the operation legalizer because we
13852   // may introduce illegal operations.
13853   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13854     return SDValue();
13855
13856   unsigned NumInScalars = N->getNumOperands();
13857   SDLoc DL(N);
13858   EVT VT = N->getValueType(0);
13859
13860   // Check to see if this is a BUILD_VECTOR of a bunch of values
13861   // which come from any_extend or zero_extend nodes. If so, we can create
13862   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13863   // optimizations. We do not handle sign-extend because we can't fill the sign
13864   // using shuffles.
13865   EVT SourceType = MVT::Other;
13866   bool AllAnyExt = true;
13867
13868   for (unsigned i = 0; i != NumInScalars; ++i) {
13869     SDValue In = N->getOperand(i);
13870     // Ignore undef inputs.
13871     if (In.isUndef()) continue;
13872
13873     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
13874     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13875
13876     // Abort if the element is not an extension.
13877     if (!ZeroExt && !AnyExt) {
13878       SourceType = MVT::Other;
13879       break;
13880     }
13881
13882     // The input is a ZeroExt or AnyExt. Check the original type.
13883     EVT InTy = In.getOperand(0).getValueType();
13884
13885     // Check that all of the widened source types are the same.
13886     if (SourceType == MVT::Other)
13887       // First time.
13888       SourceType = InTy;
13889     else if (InTy != SourceType) {
13890       // Multiple income types. Abort.
13891       SourceType = MVT::Other;
13892       break;
13893     }
13894
13895     // Check if all of the extends are ANY_EXTENDs.
13896     AllAnyExt &= AnyExt;
13897   }
13898
13899   // In order to have valid types, all of the inputs must be extended from the
13900   // same source type and all of the inputs must be any or zero extend.
13901   // Scalar sizes must be a power of two.
13902   EVT OutScalarTy = VT.getScalarType();
13903   bool ValidTypes = SourceType != MVT::Other &&
13904                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13905                  isPowerOf2_32(SourceType.getSizeInBits());
13906
13907   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13908   // turn into a single shuffle instruction.
13909   if (!ValidTypes)
13910     return SDValue();
13911
13912   bool isLE = DAG.getDataLayout().isLittleEndian();
13913   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13914   assert(ElemRatio > 1 && "Invalid element size ratio");
13915   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13916                                DAG.getConstant(0, DL, SourceType);
13917
13918   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13919   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13920
13921   // Populate the new build_vector
13922   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13923     SDValue Cast = N->getOperand(i);
13924     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13925             Cast.getOpcode() == ISD::ZERO_EXTEND ||
13926             Cast.isUndef()) && "Invalid cast opcode");
13927     SDValue In;
13928     if (Cast.isUndef())
13929       In = DAG.getUNDEF(SourceType);
13930     else
13931       In = Cast->getOperand(0);
13932     unsigned Index = isLE ? (i * ElemRatio) :
13933                             (i * ElemRatio + (ElemRatio - 1));
13934
13935     assert(Index < Ops.size() && "Invalid index");
13936     Ops[Index] = In;
13937   }
13938
13939   // The type of the new BUILD_VECTOR node.
13940   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13941   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13942          "Invalid vector size");
13943   // Check if the new vector type is legal.
13944   if (!isTypeLegal(VecVT)) return SDValue();
13945
13946   // Make the new BUILD_VECTOR.
13947   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13948
13949   // The new BUILD_VECTOR node has the potential to be further optimized.
13950   AddToWorklist(BV.getNode());
13951   // Bitcast to the desired type.
13952   return DAG.getBitcast(VT, BV);
13953 }
13954
13955 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13956   EVT VT = N->getValueType(0);
13957
13958   unsigned NumInScalars = N->getNumOperands();
13959   SDLoc DL(N);
13960
13961   EVT SrcVT = MVT::Other;
13962   unsigned Opcode = ISD::DELETED_NODE;
13963   unsigned NumDefs = 0;
13964
13965   for (unsigned i = 0; i != NumInScalars; ++i) {
13966     SDValue In = N->getOperand(i);
13967     unsigned Opc = In.getOpcode();
13968
13969     if (Opc == ISD::UNDEF)
13970       continue;
13971
13972     // If all scalar values are floats and converted from integers.
13973     if (Opcode == ISD::DELETED_NODE &&
13974         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13975       Opcode = Opc;
13976     }
13977
13978     if (Opc != Opcode)
13979       return SDValue();
13980
13981     EVT InVT = In.getOperand(0).getValueType();
13982
13983     // If all scalar values are typed differently, bail out. It's chosen to
13984     // simplify BUILD_VECTOR of integer types.
13985     if (SrcVT == MVT::Other)
13986       SrcVT = InVT;
13987     if (SrcVT != InVT)
13988       return SDValue();
13989     NumDefs++;
13990   }
13991
13992   // If the vector has just one element defined, it's not worth to fold it into
13993   // a vectorized one.
13994   if (NumDefs < 2)
13995     return SDValue();
13996
13997   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
13998          && "Should only handle conversion from integer to float.");
13999   assert(SrcVT != MVT::Other && "Cannot determine source type!");
14000
14001   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
14002
14003   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
14004     return SDValue();
14005
14006   // Just because the floating-point vector type is legal does not necessarily
14007   // mean that the corresponding integer vector type is.
14008   if (!isTypeLegal(NVT))
14009     return SDValue();
14010
14011   SmallVector<SDValue, 8> Opnds;
14012   for (unsigned i = 0; i != NumInScalars; ++i) {
14013     SDValue In = N->getOperand(i);
14014
14015     if (In.isUndef())
14016       Opnds.push_back(DAG.getUNDEF(SrcVT));
14017     else
14018       Opnds.push_back(In.getOperand(0));
14019   }
14020   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
14021   AddToWorklist(BV.getNode());
14022
14023   return DAG.getNode(Opcode, DL, VT, BV);
14024 }
14025
14026 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
14027                                            ArrayRef<int> VectorMask,
14028                                            SDValue VecIn1, SDValue VecIn2,
14029                                            unsigned LeftIdx) {
14030   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14031   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
14032
14033   EVT VT = N->getValueType(0);
14034   EVT InVT1 = VecIn1.getValueType();
14035   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
14036
14037   unsigned Vec2Offset = InVT1.getVectorNumElements();
14038   unsigned NumElems = VT.getVectorNumElements();
14039   unsigned ShuffleNumElems = NumElems;
14040
14041   // We can't generate a shuffle node with mismatched input and output types.
14042   // Try to make the types match the type of the output.
14043   if (InVT1 != VT || InVT2 != VT) {
14044     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
14045       // If the output vector length is a multiple of both input lengths,
14046       // we can concatenate them and pad the rest with undefs.
14047       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
14048       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
14049       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
14050       ConcatOps[0] = VecIn1;
14051       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
14052       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14053       VecIn2 = SDValue();
14054     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
14055       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
14056         return SDValue();
14057
14058       if (!VecIn2.getNode()) {
14059         // If we only have one input vector, and it's twice the size of the
14060         // output, split it in two.
14061         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
14062                              DAG.getConstant(NumElems, DL, IdxTy));
14063         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
14064         // Since we now have shorter input vectors, adjust the offset of the
14065         // second vector's start.
14066         Vec2Offset = NumElems;
14067       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
14068         // VecIn1 is wider than the output, and we have another, possibly
14069         // smaller input. Pad the smaller input with undefs, shuffle at the
14070         // input vector width, and extract the output.
14071         // The shuffle type is different than VT, so check legality again.
14072         if (LegalOperations &&
14073             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14074           return SDValue();
14075
14076         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14077         // lower it back into a BUILD_VECTOR. So if the inserted type is
14078         // illegal, don't even try.
14079         if (InVT1 != InVT2) {
14080           if (!TLI.isTypeLegal(InVT2))
14081             return SDValue();
14082           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14083                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14084         }
14085         ShuffleNumElems = NumElems * 2;
14086       } else {
14087         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14088         // than VecIn1. We can't handle this for now - this case will disappear
14089         // when we start sorting the vectors by type.
14090         return SDValue();
14091       }
14092     } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
14093                InVT1.getSizeInBits() == VT.getSizeInBits()) {
14094       SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
14095       ConcatOps[0] = VecIn2;
14096       VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14097     } else {
14098       // TODO: Support cases where the length mismatch isn't exactly by a
14099       // factor of 2.
14100       // TODO: Move this check upwards, so that if we have bad type
14101       // mismatches, we don't create any DAG nodes.
14102       return SDValue();
14103     }
14104   }
14105
14106   // Initialize mask to undef.
14107   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14108
14109   // Only need to run up to the number of elements actually used, not the
14110   // total number of elements in the shuffle - if we are shuffling a wider
14111   // vector, the high lanes should be set to undef.
14112   for (unsigned i = 0; i != NumElems; ++i) {
14113     if (VectorMask[i] <= 0)
14114       continue;
14115
14116     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14117     if (VectorMask[i] == (int)LeftIdx) {
14118       Mask[i] = ExtIndex;
14119     } else if (VectorMask[i] == (int)LeftIdx + 1) {
14120       Mask[i] = Vec2Offset + ExtIndex;
14121     }
14122   }
14123
14124   // The type the input vectors may have changed above.
14125   InVT1 = VecIn1.getValueType();
14126
14127   // If we already have a VecIn2, it should have the same type as VecIn1.
14128   // If we don't, get an undef/zero vector of the appropriate type.
14129   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14130   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
14131
14132   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14133   if (ShuffleNumElems > NumElems)
14134     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14135
14136   return Shuffle;
14137 }
14138
14139 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14140 // operations. If the types of the vectors we're extracting from allow it,
14141 // turn this into a vector_shuffle node.
14142 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14143   SDLoc DL(N);
14144   EVT VT = N->getValueType(0);
14145
14146   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14147   if (!isTypeLegal(VT))
14148     return SDValue();
14149
14150   // May only combine to shuffle after legalize if shuffle is legal.
14151   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14152     return SDValue();
14153
14154   bool UsesZeroVector = false;
14155   unsigned NumElems = N->getNumOperands();
14156
14157   // Record, for each element of the newly built vector, which input vector
14158   // that element comes from. -1 stands for undef, 0 for the zero vector,
14159   // and positive values for the input vectors.
14160   // VectorMask maps each element to its vector number, and VecIn maps vector
14161   // numbers to their initial SDValues.
14162
14163   SmallVector<int, 8> VectorMask(NumElems, -1);
14164   SmallVector<SDValue, 8> VecIn;
14165   VecIn.push_back(SDValue());
14166
14167   for (unsigned i = 0; i != NumElems; ++i) {
14168     SDValue Op = N->getOperand(i);
14169
14170     if (Op.isUndef())
14171       continue;
14172
14173     // See if we can use a blend with a zero vector.
14174     // TODO: Should we generalize this to a blend with an arbitrary constant
14175     // vector?
14176     if (isNullConstant(Op) || isNullFPConstant(Op)) {
14177       UsesZeroVector = true;
14178       VectorMask[i] = 0;
14179       continue;
14180     }
14181
14182     // Not an undef or zero. If the input is something other than an
14183     // EXTRACT_VECTOR_ELT with a constant index, bail out.
14184     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14185         !isa<ConstantSDNode>(Op.getOperand(1)))
14186       return SDValue();
14187
14188     SDValue ExtractedFromVec = Op.getOperand(0);
14189
14190     // All inputs must have the same element type as the output.
14191     if (VT.getVectorElementType() !=
14192         ExtractedFromVec.getValueType().getVectorElementType())
14193       return SDValue();
14194
14195     // Have we seen this input vector before?
14196     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14197     // a map back from SDValues to numbers isn't worth it.
14198     unsigned Idx = std::distance(
14199         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14200     if (Idx == VecIn.size())
14201       VecIn.push_back(ExtractedFromVec);
14202
14203     VectorMask[i] = Idx;
14204   }
14205
14206   // If we didn't find at least one input vector, bail out.
14207   if (VecIn.size() < 2)
14208     return SDValue();
14209
14210   // TODO: We want to sort the vectors by descending length, so that adjacent
14211   // pairs have similar length, and the longer vector is always first in the
14212   // pair.
14213
14214   // TODO: Should this fire if some of the input vectors has illegal type (like
14215   // it does now), or should we let legalization run its course first?
14216
14217   // Shuffle phase:
14218   // Take pairs of vectors, and shuffle them so that the result has elements
14219   // from these vectors in the correct places.
14220   // For example, given:
14221   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14222   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14223   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14224   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14225   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14226   // We will generate:
14227   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14228   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14229   SmallVector<SDValue, 4> Shuffles;
14230   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14231     unsigned LeftIdx = 2 * In + 1;
14232     SDValue VecLeft = VecIn[LeftIdx];
14233     SDValue VecRight =
14234         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14235
14236     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14237                                                 VecRight, LeftIdx))
14238       Shuffles.push_back(Shuffle);
14239     else
14240       return SDValue();
14241   }
14242
14243   // If we need the zero vector as an "ingredient" in the blend tree, add it
14244   // to the list of shuffles.
14245   if (UsesZeroVector)
14246     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14247                                       : DAG.getConstantFP(0.0, DL, VT));
14248
14249   // If we only have one shuffle, we're done.
14250   if (Shuffles.size() == 1)
14251     return Shuffles[0];
14252
14253   // Update the vector mask to point to the post-shuffle vectors.
14254   for (int &Vec : VectorMask)
14255     if (Vec == 0)
14256       Vec = Shuffles.size() - 1;
14257     else
14258       Vec = (Vec - 1) / 2;
14259
14260   // More than one shuffle. Generate a binary tree of blends, e.g. if from
14261   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14262   // generate:
14263   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14264   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14265   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14266   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14267   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14268   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14269   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14270
14271   // Make sure the initial size of the shuffle list is even.
14272   if (Shuffles.size() % 2)
14273     Shuffles.push_back(DAG.getUNDEF(VT));
14274
14275   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14276     if (CurSize % 2) {
14277       Shuffles[CurSize] = DAG.getUNDEF(VT);
14278       CurSize++;
14279     }
14280     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14281       int Left = 2 * In;
14282       int Right = 2 * In + 1;
14283       SmallVector<int, 8> Mask(NumElems, -1);
14284       for (unsigned i = 0; i != NumElems; ++i) {
14285         if (VectorMask[i] == Left) {
14286           Mask[i] = i;
14287           VectorMask[i] = In;
14288         } else if (VectorMask[i] == Right) {
14289           Mask[i] = i + NumElems;
14290           VectorMask[i] = In;
14291         }
14292       }
14293
14294       Shuffles[In] =
14295           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14296     }
14297   }
14298
14299   return Shuffles[0];
14300 }
14301
14302 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14303 // operations which can be matched to a truncate.
14304 SDValue DAGCombiner::reduceBuildVecToTrunc(SDNode *N) {
14305   // TODO: Add support for big-endian.
14306   if (DAG.getDataLayout().isBigEndian())
14307     return SDValue();
14308   if (N->getNumOperands() < 2)
14309     return SDValue();
14310   SDLoc DL(N);
14311   EVT VT = N->getValueType(0);
14312   unsigned NumElems = N->getNumOperands();
14313
14314   if (!isTypeLegal(VT))
14315     return SDValue();
14316
14317   // If the input is something other than an EXTRACT_VECTOR_ELT with a constant
14318   // index, bail out.
14319   // TODO: Allow undef elements in some cases?
14320   if (any_of(N->ops(), [VT](SDValue Op) {
14321         return Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14322                !isa<ConstantSDNode>(Op.getOperand(1)) ||
14323                Op.getValueType() != VT.getVectorElementType();
14324       }))
14325     return SDValue();
14326
14327   // Helper for obtaining an EXTRACT_VECTOR_ELT's constant index
14328   auto GetExtractIdx = [](SDValue Extract) {
14329     return cast<ConstantSDNode>(Extract.getOperand(1))->getSExtValue();
14330   };
14331
14332   // The first BUILD_VECTOR operand must be an an extract from index zero
14333   // (assuming no undef and little-endian).
14334   if (GetExtractIdx(N->getOperand(0)) != 0)
14335     return SDValue();
14336
14337   // Compute the stride from the first index.
14338   int Stride = GetExtractIdx(N->getOperand(1));
14339   SDValue ExtractedFromVec = N->getOperand(0).getOperand(0);
14340
14341   // Proceed only if the stride and the types can be matched to a truncate.
14342   if ((Stride == 1 || !isPowerOf2_32(Stride)) ||
14343       (ExtractedFromVec.getValueType().getVectorNumElements() !=
14344        Stride * NumElems) ||
14345       (VT.getScalarSizeInBits() * Stride > 64))
14346     return SDValue();
14347
14348   // Check remaining operands are consistent with the computed stride.
14349   for (unsigned i = 1; i != NumElems; ++i) {
14350     SDValue Op = N->getOperand(i);
14351
14352     if ((Op.getOperand(0) != ExtractedFromVec) ||
14353         (GetExtractIdx(Op) != Stride * i))
14354       return SDValue();
14355   }
14356
14357   // All checks were ok, construct the truncate.
14358   LLVMContext &Ctx = *DAG.getContext();
14359   EVT NewVT = VT.getVectorVT(
14360       Ctx, EVT::getIntegerVT(Ctx, VT.getScalarSizeInBits() * Stride), NumElems);
14361   EVT TruncVT =
14362       VT.isFloatingPoint() ? VT.changeVectorElementTypeToInteger() : VT;
14363
14364   SDValue Res = DAG.getBitcast(NewVT, ExtractedFromVec);
14365   Res = DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, Res);
14366   return DAG.getBitcast(VT, Res);
14367 }
14368
14369 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14370   EVT VT = N->getValueType(0);
14371
14372   // A vector built entirely of undefs is undef.
14373   if (ISD::allOperandsUndef(N))
14374     return DAG.getUNDEF(VT);
14375
14376   // Check if we can express BUILD VECTOR via subvector extract.
14377   if (!LegalTypes && (N->getNumOperands() > 1)) {
14378     SDValue Op0 = N->getOperand(0);
14379     auto checkElem = [&](SDValue Op) -> uint64_t {
14380       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14381           (Op0.getOperand(0) == Op.getOperand(0)))
14382         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14383           return CNode->getZExtValue();
14384       return -1;
14385     };
14386
14387     int Offset = checkElem(Op0);
14388     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14389       if (Offset + i != checkElem(N->getOperand(i))) {
14390         Offset = -1;
14391         break;
14392       }
14393     }
14394
14395     if ((Offset == 0) &&
14396         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14397       return Op0.getOperand(0);
14398     if ((Offset != -1) &&
14399         ((Offset % N->getValueType(0).getVectorNumElements()) ==
14400          0)) // IDX must be multiple of output size.
14401       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14402                          Op0.getOperand(0), Op0.getOperand(1));
14403   }
14404
14405   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14406     return V;
14407
14408   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14409     return V;
14410
14411   if (TLI.isDesirableToCombineBuildVectorToTruncate())
14412     if (SDValue V = reduceBuildVecToTrunc(N))
14413       return V;
14414
14415   if (SDValue V = reduceBuildVecToShuffle(N))
14416     return V;
14417
14418   return SDValue();
14419 }
14420
14421 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14422   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14423   EVT OpVT = N->getOperand(0).getValueType();
14424
14425   // If the operands are legal vectors, leave them alone.
14426   if (TLI.isTypeLegal(OpVT))
14427     return SDValue();
14428
14429   SDLoc DL(N);
14430   EVT VT = N->getValueType(0);
14431   SmallVector<SDValue, 8> Ops;
14432
14433   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14434   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14435
14436   // Keep track of what we encounter.
14437   bool AnyInteger = false;
14438   bool AnyFP = false;
14439   for (const SDValue &Op : N->ops()) {
14440     if (ISD::BITCAST == Op.getOpcode() &&
14441         !Op.getOperand(0).getValueType().isVector())
14442       Ops.push_back(Op.getOperand(0));
14443     else if (ISD::UNDEF == Op.getOpcode())
14444       Ops.push_back(ScalarUndef);
14445     else
14446       return SDValue();
14447
14448     // Note whether we encounter an integer or floating point scalar.
14449     // If it's neither, bail out, it could be something weird like x86mmx.
14450     EVT LastOpVT = Ops.back().getValueType();
14451     if (LastOpVT.isFloatingPoint())
14452       AnyFP = true;
14453     else if (LastOpVT.isInteger())
14454       AnyInteger = true;
14455     else
14456       return SDValue();
14457   }
14458
14459   // If any of the operands is a floating point scalar bitcast to a vector,
14460   // use floating point types throughout, and bitcast everything.
14461   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14462   if (AnyFP) {
14463     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14464     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14465     if (AnyInteger) {
14466       for (SDValue &Op : Ops) {
14467         if (Op.getValueType() == SVT)
14468           continue;
14469         if (Op.isUndef())
14470           Op = ScalarUndef;
14471         else
14472           Op = DAG.getBitcast(SVT, Op);
14473       }
14474     }
14475   }
14476
14477   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14478                                VT.getSizeInBits() / SVT.getSizeInBits());
14479   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14480 }
14481
14482 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14483 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14484 // most two distinct vectors the same size as the result, attempt to turn this
14485 // into a legal shuffle.
14486 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14487   EVT VT = N->getValueType(0);
14488   EVT OpVT = N->getOperand(0).getValueType();
14489   int NumElts = VT.getVectorNumElements();
14490   int NumOpElts = OpVT.getVectorNumElements();
14491
14492   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14493   SmallVector<int, 8> Mask;
14494
14495   for (SDValue Op : N->ops()) {
14496     // Peek through any bitcast.
14497     while (Op.getOpcode() == ISD::BITCAST)
14498       Op = Op.getOperand(0);
14499
14500     // UNDEF nodes convert to UNDEF shuffle mask values.
14501     if (Op.isUndef()) {
14502       Mask.append((unsigned)NumOpElts, -1);
14503       continue;
14504     }
14505
14506     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14507       return SDValue();
14508
14509     // What vector are we extracting the subvector from and at what index?
14510     SDValue ExtVec = Op.getOperand(0);
14511
14512     // We want the EVT of the original extraction to correctly scale the
14513     // extraction index.
14514     EVT ExtVT = ExtVec.getValueType();
14515
14516     // Peek through any bitcast.
14517     while (ExtVec.getOpcode() == ISD::BITCAST)
14518       ExtVec = ExtVec.getOperand(0);
14519
14520     // UNDEF nodes convert to UNDEF shuffle mask values.
14521     if (ExtVec.isUndef()) {
14522       Mask.append((unsigned)NumOpElts, -1);
14523       continue;
14524     }
14525
14526     if (!isa<ConstantSDNode>(Op.getOperand(1)))
14527       return SDValue();
14528     int ExtIdx = Op.getConstantOperandVal(1);
14529
14530     // Ensure that we are extracting a subvector from a vector the same
14531     // size as the result.
14532     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14533       return SDValue();
14534
14535     // Scale the subvector index to account for any bitcast.
14536     int NumExtElts = ExtVT.getVectorNumElements();
14537     if (0 == (NumExtElts % NumElts))
14538       ExtIdx /= (NumExtElts / NumElts);
14539     else if (0 == (NumElts % NumExtElts))
14540       ExtIdx *= (NumElts / NumExtElts);
14541     else
14542       return SDValue();
14543
14544     // At most we can reference 2 inputs in the final shuffle.
14545     if (SV0.isUndef() || SV0 == ExtVec) {
14546       SV0 = ExtVec;
14547       for (int i = 0; i != NumOpElts; ++i)
14548         Mask.push_back(i + ExtIdx);
14549     } else if (SV1.isUndef() || SV1 == ExtVec) {
14550       SV1 = ExtVec;
14551       for (int i = 0; i != NumOpElts; ++i)
14552         Mask.push_back(i + ExtIdx + NumElts);
14553     } else {
14554       return SDValue();
14555     }
14556   }
14557
14558   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14559     return SDValue();
14560
14561   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14562                               DAG.getBitcast(VT, SV1), Mask);
14563 }
14564
14565 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14566   // If we only have one input vector, we don't need to do any concatenation.
14567   if (N->getNumOperands() == 1)
14568     return N->getOperand(0);
14569
14570   // Check if all of the operands are undefs.
14571   EVT VT = N->getValueType(0);
14572   if (ISD::allOperandsUndef(N))
14573     return DAG.getUNDEF(VT);
14574
14575   // Optimize concat_vectors where all but the first of the vectors are undef.
14576   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14577         return Op.isUndef();
14578       })) {
14579     SDValue In = N->getOperand(0);
14580     assert(In.getValueType().isVector() && "Must concat vectors");
14581
14582     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14583     if (In->getOpcode() == ISD::BITCAST &&
14584         !In->getOperand(0)->getValueType(0).isVector()) {
14585       SDValue Scalar = In->getOperand(0);
14586
14587       // If the bitcast type isn't legal, it might be a trunc of a legal type;
14588       // look through the trunc so we can still do the transform:
14589       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14590       if (Scalar->getOpcode() == ISD::TRUNCATE &&
14591           !TLI.isTypeLegal(Scalar.getValueType()) &&
14592           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14593         Scalar = Scalar->getOperand(0);
14594
14595       EVT SclTy = Scalar->getValueType(0);
14596
14597       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14598         return SDValue();
14599
14600       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14601       if (VNTNumElms < 2)
14602         return SDValue();
14603
14604       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14605       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14606         return SDValue();
14607
14608       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14609       return DAG.getBitcast(VT, Res);
14610     }
14611   }
14612
14613   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14614   // We have already tested above for an UNDEF only concatenation.
14615   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14616   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14617   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14618     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14619   };
14620   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14621     SmallVector<SDValue, 8> Opnds;
14622     EVT SVT = VT.getScalarType();
14623
14624     EVT MinVT = SVT;
14625     if (!SVT.isFloatingPoint()) {
14626       // If BUILD_VECTOR are from built from integer, they may have different
14627       // operand types. Get the smallest type and truncate all operands to it.
14628       bool FoundMinVT = false;
14629       for (const SDValue &Op : N->ops())
14630         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14631           EVT OpSVT = Op.getOperand(0)->getValueType(0);
14632           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14633           FoundMinVT = true;
14634         }
14635       assert(FoundMinVT && "Concat vector type mismatch");
14636     }
14637
14638     for (const SDValue &Op : N->ops()) {
14639       EVT OpVT = Op.getValueType();
14640       unsigned NumElts = OpVT.getVectorNumElements();
14641
14642       if (ISD::UNDEF == Op.getOpcode())
14643         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14644
14645       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14646         if (SVT.isFloatingPoint()) {
14647           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14648           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14649         } else {
14650           for (unsigned i = 0; i != NumElts; ++i)
14651             Opnds.push_back(
14652                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14653         }
14654       }
14655     }
14656
14657     assert(VT.getVectorNumElements() == Opnds.size() &&
14658            "Concat vector type mismatch");
14659     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14660   }
14661
14662   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14663   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14664     return V;
14665
14666   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14667   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14668     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14669       return V;
14670
14671   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14672   // nodes often generate nop CONCAT_VECTOR nodes.
14673   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14674   // place the incoming vectors at the exact same location.
14675   SDValue SingleSource = SDValue();
14676   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14677
14678   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14679     SDValue Op = N->getOperand(i);
14680
14681     if (Op.isUndef())
14682       continue;
14683
14684     // Check if this is the identity extract:
14685     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14686       return SDValue();
14687
14688     // Find the single incoming vector for the extract_subvector.
14689     if (SingleSource.getNode()) {
14690       if (Op.getOperand(0) != SingleSource)
14691         return SDValue();
14692     } else {
14693       SingleSource = Op.getOperand(0);
14694
14695       // Check the source type is the same as the type of the result.
14696       // If not, this concat may extend the vector, so we can not
14697       // optimize it away.
14698       if (SingleSource.getValueType() != N->getValueType(0))
14699         return SDValue();
14700     }
14701
14702     unsigned IdentityIndex = i * PartNumElem;
14703     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14704     // The extract index must be constant.
14705     if (!CS)
14706       return SDValue();
14707
14708     // Check that we are reading from the identity index.
14709     if (CS->getZExtValue() != IdentityIndex)
14710       return SDValue();
14711   }
14712
14713   if (SingleSource.getNode())
14714     return SingleSource;
14715
14716   return SDValue();
14717 }
14718
14719 /// If we are extracting a subvector produced by a wide binary operator with at
14720 /// at least one operand that was the result of a vector concatenation, then try
14721 /// to use the narrow vector operands directly to avoid the concatenation and
14722 /// extraction.
14723 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
14724   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
14725   // some of these bailouts with other transforms.
14726
14727   // The extract index must be a constant, so we can map it to a concat operand.
14728   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14729   if (!ExtractIndex)
14730     return SDValue();
14731
14732   // Only handle the case where we are doubling and then halving. A larger ratio
14733   // may require more than two narrow binops to replace the wide binop.
14734   EVT VT = Extract->getValueType(0);
14735   unsigned NumElems = VT.getVectorNumElements();
14736   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
14737          "Extract index is not a multiple of the vector length.");
14738   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
14739     return SDValue();
14740
14741   // We are looking for an optionally bitcasted wide vector binary operator
14742   // feeding an extract subvector.
14743   SDValue BinOp = Extract->getOperand(0);
14744   if (BinOp.getOpcode() == ISD::BITCAST)
14745     BinOp = BinOp.getOperand(0);
14746
14747   // TODO: The motivating case for this transform is an x86 AVX1 target. That
14748   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
14749   // flavors, but no other 256-bit integer support. This could be extended to
14750   // handle any binop, but that may require fixing/adding other folds to avoid
14751   // codegen regressions.
14752   unsigned BOpcode = BinOp.getOpcode();
14753   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
14754     return SDValue();
14755
14756   // The binop must be a vector type, so we can chop it in half.
14757   EVT WideBVT = BinOp.getValueType();
14758   if (!WideBVT.isVector())
14759     return SDValue();
14760
14761   // Bail out if the target does not support a narrower version of the binop.
14762   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
14763                                    WideBVT.getVectorNumElements() / 2);
14764   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14765   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
14766     return SDValue();
14767
14768   // Peek through bitcasts of the binary operator operands if needed.
14769   SDValue LHS = BinOp.getOperand(0);
14770   if (LHS.getOpcode() == ISD::BITCAST)
14771     LHS = LHS.getOperand(0);
14772
14773   SDValue RHS = BinOp.getOperand(1);
14774   if (RHS.getOpcode() == ISD::BITCAST)
14775     RHS = RHS.getOperand(0);
14776
14777   // We need at least one concatenation operation of a binop operand to make
14778   // this transform worthwhile. The concat must double the input vector sizes.
14779   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
14780   bool ConcatL =
14781       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
14782   bool ConcatR =
14783       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
14784   if (!ConcatL && !ConcatR)
14785     return SDValue();
14786
14787   // If one of the binop operands was not the result of a concat, we must
14788   // extract a half-sized operand for our new narrow binop. We can't just reuse
14789   // the original extract index operand because we may have bitcasted.
14790   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
14791   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
14792   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
14793   SDLoc DL(Extract);
14794
14795   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
14796   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
14797   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
14798   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
14799                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14800                                     BinOp.getOperand(0),
14801                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14802
14803   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
14804                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14805                                     BinOp.getOperand(1),
14806                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14807
14808   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
14809   return DAG.getBitcast(VT, NarrowBinOp);
14810 }
14811
14812 /// If we are extracting a subvector from a wide vector load, convert to a
14813 /// narrow load to eliminate the extraction:
14814 /// (extract_subvector (load wide vector)) --> (load narrow vector)
14815 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
14816   // TODO: Add support for big-endian. The offset calculation must be adjusted.
14817   if (DAG.getDataLayout().isBigEndian())
14818     return SDValue();
14819
14820   // TODO: The one-use check is overly conservative. Check the cost of the
14821   // extract instead or remove that condition entirely.
14822   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
14823   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14824   if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
14825       !ExtIdx)
14826     return SDValue();
14827
14828   // The narrow load will be offset from the base address of the old load if
14829   // we are extracting from something besides index 0 (little-endian).
14830   EVT VT = Extract->getValueType(0);
14831   SDLoc DL(Extract);
14832   SDValue BaseAddr = Ld->getOperand(1);
14833   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
14834
14835   // TODO: Use "BaseIndexOffset" to make this more effective.
14836   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
14837   MachineFunction &MF = DAG.getMachineFunction();
14838   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
14839                                                    VT.getStoreSize());
14840   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
14841   DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
14842   return NewLd;
14843 }
14844
14845 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
14846   EVT NVT = N->getValueType(0);
14847   SDValue V = N->getOperand(0);
14848
14849   // Extract from UNDEF is UNDEF.
14850   if (V.isUndef())
14851     return DAG.getUNDEF(NVT);
14852
14853   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
14854     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
14855       return NarrowLoad;
14856
14857   // Combine:
14858   //    (extract_subvec (concat V1, V2, ...), i)
14859   // Into:
14860   //    Vi if possible
14861   // Only operand 0 is checked as 'concat' assumes all inputs of the same
14862   // type.
14863   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
14864       isa<ConstantSDNode>(N->getOperand(1)) &&
14865       V->getOperand(0).getValueType() == NVT) {
14866     unsigned Idx = N->getConstantOperandVal(1);
14867     unsigned NumElems = NVT.getVectorNumElements();
14868     assert((Idx % NumElems) == 0 &&
14869            "IDX in concat is not a multiple of the result vector length.");
14870     return V->getOperand(Idx / NumElems);
14871   }
14872
14873   // Skip bitcasting
14874   if (V->getOpcode() == ISD::BITCAST)
14875     V = V.getOperand(0);
14876
14877   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
14878     // Handle only simple case where vector being inserted and vector
14879     // being extracted are of same size.
14880     EVT SmallVT = V->getOperand(1).getValueType();
14881     if (!NVT.bitsEq(SmallVT))
14882       return SDValue();
14883
14884     // Only handle cases where both indexes are constants.
14885     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
14886     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
14887
14888     if (InsIdx && ExtIdx) {
14889       // Combine:
14890       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
14891       // Into:
14892       //    indices are equal or bit offsets are equal => V1
14893       //    otherwise => (extract_subvec V1, ExtIdx)
14894       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
14895           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
14896         return DAG.getBitcast(NVT, V->getOperand(1));
14897       return DAG.getNode(
14898           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
14899           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
14900           N->getOperand(1));
14901     }
14902   }
14903
14904   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
14905     return NarrowBOp;
14906
14907   return SDValue();
14908 }
14909
14910 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
14911                                                  SDValue V, SelectionDAG &DAG) {
14912   SDLoc DL(V);
14913   EVT VT = V.getValueType();
14914
14915   switch (V.getOpcode()) {
14916   default:
14917     return V;
14918
14919   case ISD::CONCAT_VECTORS: {
14920     EVT OpVT = V->getOperand(0).getValueType();
14921     int OpSize = OpVT.getVectorNumElements();
14922     SmallBitVector OpUsedElements(OpSize, false);
14923     bool FoundSimplification = false;
14924     SmallVector<SDValue, 4> NewOps;
14925     NewOps.reserve(V->getNumOperands());
14926     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
14927       SDValue Op = V->getOperand(i);
14928       bool OpUsed = false;
14929       for (int j = 0; j < OpSize; ++j)
14930         if (UsedElements[i * OpSize + j]) {
14931           OpUsedElements[j] = true;
14932           OpUsed = true;
14933         }
14934       NewOps.push_back(
14935           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
14936                  : DAG.getUNDEF(OpVT));
14937       FoundSimplification |= Op == NewOps.back();
14938       OpUsedElements.reset();
14939     }
14940     if (FoundSimplification)
14941       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
14942     return V;
14943   }
14944
14945   case ISD::INSERT_SUBVECTOR: {
14946     SDValue BaseV = V->getOperand(0);
14947     SDValue SubV = V->getOperand(1);
14948     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
14949     if (!IdxN)
14950       return V;
14951
14952     int SubSize = SubV.getValueType().getVectorNumElements();
14953     int Idx = IdxN->getZExtValue();
14954     bool SubVectorUsed = false;
14955     SmallBitVector SubUsedElements(SubSize, false);
14956     for (int i = 0; i < SubSize; ++i)
14957       if (UsedElements[i + Idx]) {
14958         SubVectorUsed = true;
14959         SubUsedElements[i] = true;
14960         UsedElements[i + Idx] = false;
14961       }
14962
14963     // Now recurse on both the base and sub vectors.
14964     SDValue SimplifiedSubV =
14965         SubVectorUsed
14966             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14967             : DAG.getUNDEF(SubV.getValueType());
14968     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14969     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14970       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14971                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14972     return V;
14973   }
14974   }
14975 }
14976
14977 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14978                                        SDValue N1, SelectionDAG &DAG) {
14979   EVT VT = SVN->getValueType(0);
14980   int NumElts = VT.getVectorNumElements();
14981   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
14982   for (int M : SVN->getMask())
14983     if (M >= 0 && M < NumElts)
14984       N0UsedElements[M] = true;
14985     else if (M >= NumElts)
14986       N1UsedElements[M - NumElts] = true;
14987
14988   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
14989   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
14990   if (S0 == N0 && S1 == N1)
14991     return SDValue();
14992
14993   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
14994 }
14995
14996 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
14997 // or turn a shuffle of a single concat into simpler shuffle then concat.
14998 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
14999   EVT VT = N->getValueType(0);
15000   unsigned NumElts = VT.getVectorNumElements();
15001
15002   SDValue N0 = N->getOperand(0);
15003   SDValue N1 = N->getOperand(1);
15004   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15005
15006   SmallVector<SDValue, 4> Ops;
15007   EVT ConcatVT = N0.getOperand(0).getValueType();
15008   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
15009   unsigned NumConcats = NumElts / NumElemsPerConcat;
15010
15011   // Special case: shuffle(concat(A,B)) can be more efficiently represented
15012   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
15013   // half vector elements.
15014   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
15015       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
15016                   SVN->getMask().end(), [](int i) { return i == -1; })) {
15017     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
15018                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
15019     N1 = DAG.getUNDEF(ConcatVT);
15020     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
15021   }
15022
15023   // Look at every vector that's inserted. We're looking for exact
15024   // subvector-sized copies from a concatenated vector
15025   for (unsigned I = 0; I != NumConcats; ++I) {
15026     // Make sure we're dealing with a copy.
15027     unsigned Begin = I * NumElemsPerConcat;
15028     bool AllUndef = true, NoUndef = true;
15029     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
15030       if (SVN->getMaskElt(J) >= 0)
15031         AllUndef = false;
15032       else
15033         NoUndef = false;
15034     }
15035
15036     if (NoUndef) {
15037       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
15038         return SDValue();
15039
15040       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
15041         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
15042           return SDValue();
15043
15044       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
15045       if (FirstElt < N0.getNumOperands())
15046         Ops.push_back(N0.getOperand(FirstElt));
15047       else
15048         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
15049
15050     } else if (AllUndef) {
15051       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
15052     } else { // Mixed with general masks and undefs, can't do optimization.
15053       return SDValue();
15054     }
15055   }
15056
15057   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15058 }
15059
15060 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15061 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15062 //
15063 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
15064 // a simplification in some sense, but it isn't appropriate in general: some
15065 // BUILD_VECTORs are substantially cheaper than others. The general case
15066 // of a BUILD_VECTOR requires inserting each element individually (or
15067 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
15068 // all constants is a single constant pool load.  A BUILD_VECTOR where each
15069 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
15070 // are undef lowers to a small number of element insertions.
15071 //
15072 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
15073 // We don't fold shuffles where one side is a non-zero constant, and we don't
15074 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
15075 // non-constant operands. This seems to work out reasonably well in practice.
15076 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
15077                                        SelectionDAG &DAG,
15078                                        const TargetLowering &TLI) {
15079   EVT VT = SVN->getValueType(0);
15080   unsigned NumElts = VT.getVectorNumElements();
15081   SDValue N0 = SVN->getOperand(0);
15082   SDValue N1 = SVN->getOperand(1);
15083
15084   if (!N0->hasOneUse() || !N1->hasOneUse())
15085     return SDValue();
15086   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
15087   // discussed above.
15088   if (!N1.isUndef()) {
15089     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
15090     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
15091     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
15092       return SDValue();
15093     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
15094       return SDValue();
15095   }
15096
15097   SmallVector<SDValue, 8> Ops;
15098   SmallSet<SDValue, 16> DuplicateOps;
15099   for (int M : SVN->getMask()) {
15100     SDValue Op = DAG.getUNDEF(VT.getScalarType());
15101     if (M >= 0) {
15102       int Idx = M < (int)NumElts ? M : M - NumElts;
15103       SDValue &S = (M < (int)NumElts ? N0 : N1);
15104       if (S.getOpcode() == ISD::BUILD_VECTOR) {
15105         Op = S.getOperand(Idx);
15106       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
15107         if (Idx == 0)
15108           Op = S.getOperand(0);
15109       } else {
15110         // Operand can't be combined - bail out.
15111         return SDValue();
15112       }
15113     }
15114
15115     // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
15116     // fine, but it's likely to generate low-quality code if the target can't
15117     // reconstruct an appropriate shuffle.
15118     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
15119       if (!DuplicateOps.insert(Op).second)
15120         return SDValue();
15121
15122     Ops.push_back(Op);
15123   }
15124   // BUILD_VECTOR requires all inputs to be of the same type, find the
15125   // maximum type and extend them all.
15126   EVT SVT = VT.getScalarType();
15127   if (SVT.isInteger())
15128     for (SDValue &Op : Ops)
15129       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
15130   if (SVT != VT.getScalarType())
15131     for (SDValue &Op : Ops)
15132       Op = TLI.isZExtFree(Op.getValueType(), SVT)
15133                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
15134                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
15135   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
15136 }
15137
15138 // Match shuffles that can be converted to any_vector_extend_in_reg.
15139 // This is often generated during legalization.
15140 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
15141 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
15142 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
15143                                             SelectionDAG &DAG,
15144                                             const TargetLowering &TLI,
15145                                             bool LegalOperations) {
15146   EVT VT = SVN->getValueType(0);
15147   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15148
15149   // TODO Add support for big-endian when we have a test case.
15150   if (!VT.isInteger() || IsBigEndian)
15151     return SDValue();
15152
15153   unsigned NumElts = VT.getVectorNumElements();
15154   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15155   ArrayRef<int> Mask = SVN->getMask();
15156   SDValue N0 = SVN->getOperand(0);
15157
15158   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15159   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15160     for (unsigned i = 0; i != NumElts; ++i) {
15161       if (Mask[i] < 0)
15162         continue;
15163       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15164         continue;
15165       return false;
15166     }
15167     return true;
15168   };
15169
15170   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15171   // power-of-2 extensions as they are the most likely.
15172   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15173     if (!isAnyExtend(Scale))
15174       continue;
15175
15176     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15177     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15178     if (!LegalOperations ||
15179         TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15180       return DAG.getBitcast(VT,
15181                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15182   }
15183
15184   return SDValue();
15185 }
15186
15187 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15188 // each source element of a large type into the lowest elements of a smaller
15189 // destination type. This is often generated during legalization.
15190 // If the source node itself was a '*_extend_vector_inreg' node then we should
15191 // then be able to remove it.
15192 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15193                                         SelectionDAG &DAG) {
15194   EVT VT = SVN->getValueType(0);
15195   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15196
15197   // TODO Add support for big-endian when we have a test case.
15198   if (!VT.isInteger() || IsBigEndian)
15199     return SDValue();
15200
15201   SDValue N0 = SVN->getOperand(0);
15202   while (N0.getOpcode() == ISD::BITCAST)
15203     N0 = N0.getOperand(0);
15204
15205   unsigned Opcode = N0.getOpcode();
15206   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15207       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15208       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15209     return SDValue();
15210
15211   SDValue N00 = N0.getOperand(0);
15212   ArrayRef<int> Mask = SVN->getMask();
15213   unsigned NumElts = VT.getVectorNumElements();
15214   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15215   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15216   unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
15217
15218   if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
15219     return SDValue();
15220   unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
15221
15222   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15223   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15224   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15225   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15226     for (unsigned i = 0; i != NumElts; ++i) {
15227       if (Mask[i] < 0)
15228         continue;
15229       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15230         continue;
15231       return false;
15232     }
15233     return true;
15234   };
15235
15236   // At the moment we just handle the case where we've truncated back to the
15237   // same size as before the extension.
15238   // TODO: handle more extension/truncation cases as cases arise.
15239   if (EltSizeInBits != ExtSrcSizeInBits)
15240     return SDValue();
15241
15242   // We can remove *extend_vector_inreg only if the truncation happens at
15243   // the same scale as the extension.
15244   if (isTruncate(ExtScale))
15245     return DAG.getBitcast(VT, N00);
15246
15247   return SDValue();
15248 }
15249
15250 // Combine shuffles of splat-shuffles of the form:
15251 // shuffle (shuffle V, undef, splat-mask), undef, M
15252 // If splat-mask contains undef elements, we need to be careful about
15253 // introducing undef's in the folded mask which are not the result of composing
15254 // the masks of the shuffles.
15255 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15256                                      ShuffleVectorSDNode *Splat,
15257                                      SelectionDAG &DAG) {
15258   ArrayRef<int> SplatMask = Splat->getMask();
15259   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
15260
15261   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15262   // every undef mask element in the splat-shuffle has a corresponding undef
15263   // element in the user-shuffle's mask or if the composition of mask elements
15264   // would result in undef.
15265   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15266   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15267   //   In this case it is not legal to simplify to the splat-shuffle because we
15268   //   may be exposing the users of the shuffle an undef element at index 1
15269   //   which was not there before the combine.
15270   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15271   //   In this case the composition of masks yields SplatMask, so it's ok to
15272   //   simplify to the splat-shuffle.
15273   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15274   //   In this case the composed mask includes all undef elements of SplatMask
15275   //   and in addition sets element zero to undef. It is safe to simplify to
15276   //   the splat-shuffle.
15277   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15278                                        ArrayRef<int> SplatMask) {
15279     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15280       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15281           SplatMask[UserMask[i]] != -1)
15282         return false;
15283     return true;
15284   };
15285   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15286     return SDValue(Splat, 0);
15287
15288   // Create a new shuffle with a mask that is composed of the two shuffles'
15289   // masks.
15290   SmallVector<int, 32> NewMask;
15291   for (int Idx : UserMask)
15292     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15293
15294   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15295                               Splat->getOperand(0), Splat->getOperand(1),
15296                               NewMask);
15297 }
15298
15299 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
15300   EVT VT = N->getValueType(0);
15301   unsigned NumElts = VT.getVectorNumElements();
15302
15303   SDValue N0 = N->getOperand(0);
15304   SDValue N1 = N->getOperand(1);
15305
15306   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
15307
15308   // Canonicalize shuffle undef, undef -> undef
15309   if (N0.isUndef() && N1.isUndef())
15310     return DAG.getUNDEF(VT);
15311
15312   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15313
15314   // Canonicalize shuffle v, v -> v, undef
15315   if (N0 == N1) {
15316     SmallVector<int, 8> NewMask;
15317     for (unsigned i = 0; i != NumElts; ++i) {
15318       int Idx = SVN->getMaskElt(i);
15319       if (Idx >= (int)NumElts) Idx -= NumElts;
15320       NewMask.push_back(Idx);
15321     }
15322     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
15323   }
15324
15325   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
15326   if (N0.isUndef())
15327     return DAG.getCommutedVectorShuffle(*SVN);
15328
15329   // Remove references to rhs if it is undef
15330   if (N1.isUndef()) {
15331     bool Changed = false;
15332     SmallVector<int, 8> NewMask;
15333     for (unsigned i = 0; i != NumElts; ++i) {
15334       int Idx = SVN->getMaskElt(i);
15335       if (Idx >= (int)NumElts) {
15336         Idx = -1;
15337         Changed = true;
15338       }
15339       NewMask.push_back(Idx);
15340     }
15341     if (Changed)
15342       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
15343   }
15344
15345   // A shuffle of a single vector that is a splat can always be folded.
15346   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
15347     if (N1->isUndef() && N0Shuf->isSplat())
15348       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
15349
15350   // If it is a splat, check if the argument vector is another splat or a
15351   // build_vector.
15352   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
15353     SDNode *V = N0.getNode();
15354
15355     // If this is a bit convert that changes the element type of the vector but
15356     // not the number of vector elements, look through it.  Be careful not to
15357     // look though conversions that change things like v4f32 to v2f64.
15358     if (V->getOpcode() == ISD::BITCAST) {
15359       SDValue ConvInput = V->getOperand(0);
15360       if (ConvInput.getValueType().isVector() &&
15361           ConvInput.getValueType().getVectorNumElements() == NumElts)
15362         V = ConvInput.getNode();
15363     }
15364
15365     if (V->getOpcode() == ISD::BUILD_VECTOR) {
15366       assert(V->getNumOperands() == NumElts &&
15367              "BUILD_VECTOR has wrong number of operands");
15368       SDValue Base;
15369       bool AllSame = true;
15370       for (unsigned i = 0; i != NumElts; ++i) {
15371         if (!V->getOperand(i).isUndef()) {
15372           Base = V->getOperand(i);
15373           break;
15374         }
15375       }
15376       // Splat of <u, u, u, u>, return <u, u, u, u>
15377       if (!Base.getNode())
15378         return N0;
15379       for (unsigned i = 0; i != NumElts; ++i) {
15380         if (V->getOperand(i) != Base) {
15381           AllSame = false;
15382           break;
15383         }
15384       }
15385       // Splat of <x, x, x, x>, return <x, x, x, x>
15386       if (AllSame)
15387         return N0;
15388
15389       // Canonicalize any other splat as a build_vector.
15390       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
15391       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
15392       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
15393
15394       // We may have jumped through bitcasts, so the type of the
15395       // BUILD_VECTOR may not match the type of the shuffle.
15396       if (V->getValueType(0) != VT)
15397         NewBV = DAG.getBitcast(VT, NewBV);
15398       return NewBV;
15399     }
15400   }
15401
15402   // There are various patterns used to build up a vector from smaller vectors,
15403   // subvectors, or elements. Scan chains of these and replace unused insertions
15404   // or components with undef.
15405   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
15406     return S;
15407
15408   // Match shuffles that can be converted to any_vector_extend_in_reg.
15409   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
15410     return V;
15411
15412   // Combine "truncate_vector_in_reg" style shuffles.
15413   if (SDValue V = combineTruncationShuffle(SVN, DAG))
15414     return V;
15415
15416   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
15417       Level < AfterLegalizeVectorOps &&
15418       (N1.isUndef() ||
15419       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
15420        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
15421     if (SDValue V = partitionShuffleOfConcats(N, DAG))
15422       return V;
15423   }
15424
15425   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15426   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15427   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15428     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
15429       return Res;
15430
15431   // If this shuffle only has a single input that is a bitcasted shuffle,
15432   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
15433   // back to their original types.
15434   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
15435       N1.isUndef() && Level < AfterLegalizeVectorOps &&
15436       TLI.isTypeLegal(VT)) {
15437
15438     // Peek through the bitcast only if there is one user.
15439     SDValue BC0 = N0;
15440     while (BC0.getOpcode() == ISD::BITCAST) {
15441       if (!BC0.hasOneUse())
15442         break;
15443       BC0 = BC0.getOperand(0);
15444     }
15445
15446     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
15447       if (Scale == 1)
15448         return SmallVector<int, 8>(Mask.begin(), Mask.end());
15449
15450       SmallVector<int, 8> NewMask;
15451       for (int M : Mask)
15452         for (int s = 0; s != Scale; ++s)
15453           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
15454       return NewMask;
15455     };
15456
15457     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
15458       EVT SVT = VT.getScalarType();
15459       EVT InnerVT = BC0->getValueType(0);
15460       EVT InnerSVT = InnerVT.getScalarType();
15461
15462       // Determine which shuffle works with the smaller scalar type.
15463       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
15464       EVT ScaleSVT = ScaleVT.getScalarType();
15465
15466       if (TLI.isTypeLegal(ScaleVT) &&
15467           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
15468           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
15469
15470         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15471         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15472
15473         // Scale the shuffle masks to the smaller scalar type.
15474         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
15475         SmallVector<int, 8> InnerMask =
15476             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
15477         SmallVector<int, 8> OuterMask =
15478             ScaleShuffleMask(SVN->getMask(), OuterScale);
15479
15480         // Merge the shuffle masks.
15481         SmallVector<int, 8> NewMask;
15482         for (int M : OuterMask)
15483           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
15484
15485         // Test for shuffle mask legality over both commutations.
15486         SDValue SV0 = BC0->getOperand(0);
15487         SDValue SV1 = BC0->getOperand(1);
15488         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15489         if (!LegalMask) {
15490           std::swap(SV0, SV1);
15491           ShuffleVectorSDNode::commuteMask(NewMask);
15492           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15493         }
15494
15495         if (LegalMask) {
15496           SV0 = DAG.getBitcast(ScaleVT, SV0);
15497           SV1 = DAG.getBitcast(ScaleVT, SV1);
15498           return DAG.getBitcast(
15499               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
15500         }
15501       }
15502     }
15503   }
15504
15505   // Canonicalize shuffles according to rules:
15506   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
15507   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
15508   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
15509   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
15510       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
15511       TLI.isTypeLegal(VT)) {
15512     // The incoming shuffle must be of the same type as the result of the
15513     // current shuffle.
15514     assert(N1->getOperand(0).getValueType() == VT &&
15515            "Shuffle types don't match");
15516
15517     SDValue SV0 = N1->getOperand(0);
15518     SDValue SV1 = N1->getOperand(1);
15519     bool HasSameOp0 = N0 == SV0;
15520     bool IsSV1Undef = SV1.isUndef();
15521     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
15522       // Commute the operands of this shuffle so that next rule
15523       // will trigger.
15524       return DAG.getCommutedVectorShuffle(*SVN);
15525   }
15526
15527   // Try to fold according to rules:
15528   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15529   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15530   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15531   // Don't try to fold shuffles with illegal type.
15532   // Only fold if this shuffle is the only user of the other shuffle.
15533   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
15534       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
15535     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
15536
15537     // Don't try to fold splats; they're likely to simplify somehow, or they
15538     // might be free.
15539     if (OtherSV->isSplat())
15540       return SDValue();
15541
15542     // The incoming shuffle must be of the same type as the result of the
15543     // current shuffle.
15544     assert(OtherSV->getOperand(0).getValueType() == VT &&
15545            "Shuffle types don't match");
15546
15547     SDValue SV0, SV1;
15548     SmallVector<int, 4> Mask;
15549     // Compute the combined shuffle mask for a shuffle with SV0 as the first
15550     // operand, and SV1 as the second operand.
15551     for (unsigned i = 0; i != NumElts; ++i) {
15552       int Idx = SVN->getMaskElt(i);
15553       if (Idx < 0) {
15554         // Propagate Undef.
15555         Mask.push_back(Idx);
15556         continue;
15557       }
15558
15559       SDValue CurrentVec;
15560       if (Idx < (int)NumElts) {
15561         // This shuffle index refers to the inner shuffle N0. Lookup the inner
15562         // shuffle mask to identify which vector is actually referenced.
15563         Idx = OtherSV->getMaskElt(Idx);
15564         if (Idx < 0) {
15565           // Propagate Undef.
15566           Mask.push_back(Idx);
15567           continue;
15568         }
15569
15570         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
15571                                            : OtherSV->getOperand(1);
15572       } else {
15573         // This shuffle index references an element within N1.
15574         CurrentVec = N1;
15575       }
15576
15577       // Simple case where 'CurrentVec' is UNDEF.
15578       if (CurrentVec.isUndef()) {
15579         Mask.push_back(-1);
15580         continue;
15581       }
15582
15583       // Canonicalize the shuffle index. We don't know yet if CurrentVec
15584       // will be the first or second operand of the combined shuffle.
15585       Idx = Idx % NumElts;
15586       if (!SV0.getNode() || SV0 == CurrentVec) {
15587         // Ok. CurrentVec is the left hand side.
15588         // Update the mask accordingly.
15589         SV0 = CurrentVec;
15590         Mask.push_back(Idx);
15591         continue;
15592       }
15593
15594       // Bail out if we cannot convert the shuffle pair into a single shuffle.
15595       if (SV1.getNode() && SV1 != CurrentVec)
15596         return SDValue();
15597
15598       // Ok. CurrentVec is the right hand side.
15599       // Update the mask accordingly.
15600       SV1 = CurrentVec;
15601       Mask.push_back(Idx + NumElts);
15602     }
15603
15604     // Check if all indices in Mask are Undef. In case, propagate Undef.
15605     bool isUndefMask = true;
15606     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
15607       isUndefMask &= Mask[i] < 0;
15608
15609     if (isUndefMask)
15610       return DAG.getUNDEF(VT);
15611
15612     if (!SV0.getNode())
15613       SV0 = DAG.getUNDEF(VT);
15614     if (!SV1.getNode())
15615       SV1 = DAG.getUNDEF(VT);
15616
15617     // Avoid introducing shuffles with illegal mask.
15618     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
15619       ShuffleVectorSDNode::commuteMask(Mask);
15620
15621       if (!TLI.isShuffleMaskLegal(Mask, VT))
15622         return SDValue();
15623
15624       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
15625       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
15626       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
15627       std::swap(SV0, SV1);
15628     }
15629
15630     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15631     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15632     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15633     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
15634   }
15635
15636   return SDValue();
15637 }
15638
15639 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
15640   SDValue InVal = N->getOperand(0);
15641   EVT VT = N->getValueType(0);
15642
15643   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
15644   // with a VECTOR_SHUFFLE.
15645   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15646     SDValue InVec = InVal->getOperand(0);
15647     SDValue EltNo = InVal->getOperand(1);
15648
15649     // FIXME: We could support implicit truncation if the shuffle can be
15650     // scaled to a smaller vector scalar type.
15651     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
15652     if (C0 && VT == InVec.getValueType() &&
15653         VT.getScalarType() == InVal.getValueType()) {
15654       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
15655       int Elt = C0->getZExtValue();
15656       NewMask[0] = Elt;
15657
15658       if (TLI.isShuffleMaskLegal(NewMask, VT))
15659         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
15660                                     NewMask);
15661     }
15662   }
15663
15664   return SDValue();
15665 }
15666
15667 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15668   EVT VT = N->getValueType(0);
15669   SDValue N0 = N->getOperand(0);
15670   SDValue N1 = N->getOperand(1);
15671   SDValue N2 = N->getOperand(2);
15672
15673   // If inserting an UNDEF, just return the original vector.
15674   if (N1.isUndef())
15675     return N0;
15676
15677   // If this is an insert of an extracted vector into an undef vector, we can
15678   // just use the input to the extract.
15679   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15680       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15681     return N1.getOperand(0);
15682
15683   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15684   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15685   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15686   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15687       N0.getOperand(1).getValueType() == N1.getValueType() &&
15688       N0.getOperand(2) == N2)
15689     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15690                        N1, N2);
15691
15692   if (!isa<ConstantSDNode>(N2))
15693     return SDValue();
15694
15695   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15696
15697   // Canonicalize insert_subvector dag nodes.
15698   // Example:
15699   // (insert_subvector (insert_subvector A, Idx0), Idx1)
15700   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15701   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15702       N1.getValueType() == N0.getOperand(1).getValueType() &&
15703       isa<ConstantSDNode>(N0.getOperand(2))) {
15704     unsigned OtherIdx = N0.getConstantOperandVal(2);
15705     if (InsIdx < OtherIdx) {
15706       // Swap nodes.
15707       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15708                                   N0.getOperand(0), N1, N2);
15709       AddToWorklist(NewOp.getNode());
15710       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15711                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15712     }
15713   }
15714
15715   // If the input vector is a concatenation, and the insert replaces
15716   // one of the pieces, we can optimize into a single concat_vectors.
15717   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15718       N0.getOperand(0).getValueType() == N1.getValueType()) {
15719     unsigned Factor = N1.getValueType().getVectorNumElements();
15720
15721     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15722     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15723
15724     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15725   }
15726
15727   return SDValue();
15728 }
15729
15730 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15731   SDValue N0 = N->getOperand(0);
15732
15733   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15734   if (N0->getOpcode() == ISD::FP16_TO_FP)
15735     return N0->getOperand(0);
15736
15737   return SDValue();
15738 }
15739
15740 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15741   SDValue N0 = N->getOperand(0);
15742
15743   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15744   if (N0->getOpcode() == ISD::AND) {
15745     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15746     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15747       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15748                          N0.getOperand(0));
15749     }
15750   }
15751
15752   return SDValue();
15753 }
15754
15755 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
15756 /// with the destination vector and a zero vector.
15757 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
15758 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
15759 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
15760   EVT VT = N->getValueType(0);
15761   SDValue LHS = N->getOperand(0);
15762   SDValue RHS = N->getOperand(1);
15763   SDLoc DL(N);
15764
15765   // Make sure we're not running after operation legalization where it
15766   // may have custom lowered the vector shuffles.
15767   if (LegalOperations)
15768     return SDValue();
15769
15770   if (N->getOpcode() != ISD::AND)
15771     return SDValue();
15772
15773   if (RHS.getOpcode() == ISD::BITCAST)
15774     RHS = RHS.getOperand(0);
15775
15776   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
15777     return SDValue();
15778
15779   EVT RVT = RHS.getValueType();
15780   unsigned NumElts = RHS.getNumOperands();
15781
15782   // Attempt to create a valid clear mask, splitting the mask into
15783   // sub elements and checking to see if each is
15784   // all zeros or all ones - suitable for shuffle masking.
15785   auto BuildClearMask = [&](int Split) {
15786     int NumSubElts = NumElts * Split;
15787     int NumSubBits = RVT.getScalarSizeInBits() / Split;
15788
15789     SmallVector<int, 8> Indices;
15790     for (int i = 0; i != NumSubElts; ++i) {
15791       int EltIdx = i / Split;
15792       int SubIdx = i % Split;
15793       SDValue Elt = RHS.getOperand(EltIdx);
15794       if (Elt.isUndef()) {
15795         Indices.push_back(-1);
15796         continue;
15797       }
15798
15799       APInt Bits;
15800       if (isa<ConstantSDNode>(Elt))
15801         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
15802       else if (isa<ConstantFPSDNode>(Elt))
15803         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
15804       else
15805         return SDValue();
15806
15807       // Extract the sub element from the constant bit mask.
15808       if (DAG.getDataLayout().isBigEndian()) {
15809         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
15810       } else {
15811         Bits.lshrInPlace(SubIdx * NumSubBits);
15812       }
15813
15814       if (Split > 1)
15815         Bits = Bits.trunc(NumSubBits);
15816
15817       if (Bits.isAllOnesValue())
15818         Indices.push_back(i);
15819       else if (Bits == 0)
15820         Indices.push_back(i + NumSubElts);
15821       else
15822         return SDValue();
15823     }
15824
15825     // Let's see if the target supports this vector_shuffle.
15826     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
15827     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
15828     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
15829       return SDValue();
15830
15831     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
15832     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
15833                                                    DAG.getBitcast(ClearVT, LHS),
15834                                                    Zero, Indices));
15835   };
15836
15837   // Determine maximum split level (byte level masking).
15838   int MaxSplit = 1;
15839   if (RVT.getScalarSizeInBits() % 8 == 0)
15840     MaxSplit = RVT.getScalarSizeInBits() / 8;
15841
15842   for (int Split = 1; Split <= MaxSplit; ++Split)
15843     if (RVT.getScalarSizeInBits() % Split == 0)
15844       if (SDValue S = BuildClearMask(Split))
15845         return S;
15846
15847   return SDValue();
15848 }
15849
15850 /// Visit a binary vector operation, like ADD.
15851 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
15852   assert(N->getValueType(0).isVector() &&
15853          "SimplifyVBinOp only works on vectors!");
15854
15855   SDValue LHS = N->getOperand(0);
15856   SDValue RHS = N->getOperand(1);
15857   SDValue Ops[] = {LHS, RHS};
15858
15859   // See if we can constant fold the vector operation.
15860   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
15861           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
15862     return Fold;
15863
15864   // Try to convert a constant mask AND into a shuffle clear mask.
15865   if (SDValue Shuffle = XformToShuffleWithZero(N))
15866     return Shuffle;
15867
15868   // Type legalization might introduce new shuffles in the DAG.
15869   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
15870   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
15871   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
15872       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
15873       LHS.getOperand(1).isUndef() &&
15874       RHS.getOperand(1).isUndef()) {
15875     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
15876     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
15877
15878     if (SVN0->getMask().equals(SVN1->getMask())) {
15879       EVT VT = N->getValueType(0);
15880       SDValue UndefVector = LHS.getOperand(1);
15881       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
15882                                      LHS.getOperand(0), RHS.getOperand(0),
15883                                      N->getFlags());
15884       AddUsersToWorklist(N);
15885       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
15886                                   SVN0->getMask());
15887     }
15888   }
15889
15890   return SDValue();
15891 }
15892
15893 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
15894                                     SDValue N2) {
15895   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
15896
15897   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
15898                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
15899
15900   // If we got a simplified select_cc node back from SimplifySelectCC, then
15901   // break it down into a new SETCC node, and a new SELECT node, and then return
15902   // the SELECT node, since we were called with a SELECT node.
15903   if (SCC.getNode()) {
15904     // Check to see if we got a select_cc back (to turn into setcc/select).
15905     // Otherwise, just return whatever node we got back, like fabs.
15906     if (SCC.getOpcode() == ISD::SELECT_CC) {
15907       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
15908                                   N0.getValueType(),
15909                                   SCC.getOperand(0), SCC.getOperand(1),
15910                                   SCC.getOperand(4));
15911       AddToWorklist(SETCC.getNode());
15912       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
15913                            SCC.getOperand(2), SCC.getOperand(3));
15914     }
15915
15916     return SCC;
15917   }
15918   return SDValue();
15919 }
15920
15921 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
15922 /// being selected between, see if we can simplify the select.  Callers of this
15923 /// should assume that TheSelect is deleted if this returns true.  As such, they
15924 /// should return the appropriate thing (e.g. the node) back to the top-level of
15925 /// the DAG combiner loop to avoid it being looked at.
15926 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
15927                                     SDValue RHS) {
15928
15929   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15930   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
15931   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
15932     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
15933       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
15934       SDValue Sqrt = RHS;
15935       ISD::CondCode CC;
15936       SDValue CmpLHS;
15937       const ConstantFPSDNode *Zero = nullptr;
15938
15939       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
15940         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
15941         CmpLHS = TheSelect->getOperand(0);
15942         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
15943       } else {
15944         // SELECT or VSELECT
15945         SDValue Cmp = TheSelect->getOperand(0);
15946         if (Cmp.getOpcode() == ISD::SETCC) {
15947           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
15948           CmpLHS = Cmp.getOperand(0);
15949           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
15950         }
15951       }
15952       if (Zero && Zero->isZero() &&
15953           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
15954           CC == ISD::SETULT || CC == ISD::SETLT)) {
15955         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15956         CombineTo(TheSelect, Sqrt);
15957         return true;
15958       }
15959     }
15960   }
15961   // Cannot simplify select with vector condition
15962   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
15963
15964   // If this is a select from two identical things, try to pull the operation
15965   // through the select.
15966   if (LHS.getOpcode() != RHS.getOpcode() ||
15967       !LHS.hasOneUse() || !RHS.hasOneUse())
15968     return false;
15969
15970   // If this is a load and the token chain is identical, replace the select
15971   // of two loads with a load through a select of the address to load from.
15972   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
15973   // constants have been dropped into the constant pool.
15974   if (LHS.getOpcode() == ISD::LOAD) {
15975     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
15976     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
15977
15978     // Token chains must be identical.
15979     if (LHS.getOperand(0) != RHS.getOperand(0) ||
15980         // Do not let this transformation reduce the number of volatile loads.
15981         LLD->isVolatile() || RLD->isVolatile() ||
15982         // FIXME: If either is a pre/post inc/dec load,
15983         // we'd need to split out the address adjustment.
15984         LLD->isIndexed() || RLD->isIndexed() ||
15985         // If this is an EXTLOAD, the VT's must match.
15986         LLD->getMemoryVT() != RLD->getMemoryVT() ||
15987         // If this is an EXTLOAD, the kind of extension must match.
15988         (LLD->getExtensionType() != RLD->getExtensionType() &&
15989          // The only exception is if one of the extensions is anyext.
15990          LLD->getExtensionType() != ISD::EXTLOAD &&
15991          RLD->getExtensionType() != ISD::EXTLOAD) ||
15992         // FIXME: this discards src value information.  This is
15993         // over-conservative. It would be beneficial to be able to remember
15994         // both potential memory locations.  Since we are discarding
15995         // src value info, don't do the transformation if the memory
15996         // locations are not in the default address space.
15997         LLD->getPointerInfo().getAddrSpace() != 0 ||
15998         RLD->getPointerInfo().getAddrSpace() != 0 ||
15999         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
16000                                       LLD->getBasePtr().getValueType()))
16001       return false;
16002
16003     // Check that the select condition doesn't reach either load.  If so,
16004     // folding this will induce a cycle into the DAG.  If not, this is safe to
16005     // xform, so create a select of the addresses.
16006     SDValue Addr;
16007     if (TheSelect->getOpcode() == ISD::SELECT) {
16008       SDNode *CondNode = TheSelect->getOperand(0).getNode();
16009       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
16010           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
16011         return false;
16012       // The loads must not depend on one another.
16013       if (LLD->isPredecessorOf(RLD) ||
16014           RLD->isPredecessorOf(LLD))
16015         return false;
16016       Addr = DAG.getSelect(SDLoc(TheSelect),
16017                            LLD->getBasePtr().getValueType(),
16018                            TheSelect->getOperand(0), LLD->getBasePtr(),
16019                            RLD->getBasePtr());
16020     } else {  // Otherwise SELECT_CC
16021       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
16022       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
16023
16024       if ((LLD->hasAnyUseOfValue(1) &&
16025            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
16026           (RLD->hasAnyUseOfValue(1) &&
16027            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
16028         return false;
16029
16030       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
16031                          LLD->getBasePtr().getValueType(),
16032                          TheSelect->getOperand(0),
16033                          TheSelect->getOperand(1),
16034                          LLD->getBasePtr(), RLD->getBasePtr(),
16035                          TheSelect->getOperand(4));
16036     }
16037
16038     SDValue Load;
16039     // It is safe to replace the two loads if they have different alignments,
16040     // but the new load must be the minimum (most restrictive) alignment of the
16041     // inputs.
16042     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
16043     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
16044     if (!RLD->isInvariant())
16045       MMOFlags &= ~MachineMemOperand::MOInvariant;
16046     if (!RLD->isDereferenceable())
16047       MMOFlags &= ~MachineMemOperand::MODereferenceable;
16048     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
16049       // FIXME: Discards pointer and AA info.
16050       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
16051                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
16052                          MMOFlags);
16053     } else {
16054       // FIXME: Discards pointer and AA info.
16055       Load = DAG.getExtLoad(
16056           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
16057                                                   : LLD->getExtensionType(),
16058           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
16059           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
16060     }
16061
16062     // Users of the select now use the result of the load.
16063     CombineTo(TheSelect, Load);
16064
16065     // Users of the old loads now use the new load's chain.  We know the
16066     // old-load value is dead now.
16067     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
16068     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
16069     return true;
16070   }
16071
16072   return false;
16073 }
16074
16075 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
16076 /// bitwise 'and'.
16077 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
16078                                             SDValue N1, SDValue N2, SDValue N3,
16079                                             ISD::CondCode CC) {
16080   // If this is a select where the false operand is zero and the compare is a
16081   // check of the sign bit, see if we can perform the "gzip trick":
16082   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
16083   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
16084   EVT XType = N0.getValueType();
16085   EVT AType = N2.getValueType();
16086   if (!isNullConstant(N3) || !XType.bitsGE(AType))
16087     return SDValue();
16088
16089   // If the comparison is testing for a positive value, we have to invert
16090   // the sign bit mask, so only do that transform if the target has a bitwise
16091   // 'and not' instruction (the invert is free).
16092   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
16093     // (X > -1) ? A : 0
16094     // (X >  0) ? X : 0 <-- This is canonical signed max.
16095     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
16096       return SDValue();
16097   } else if (CC == ISD::SETLT) {
16098     // (X <  0) ? A : 0
16099     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
16100     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
16101       return SDValue();
16102   } else {
16103     return SDValue();
16104   }
16105
16106   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
16107   // constant.
16108   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
16109   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16110   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
16111     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
16112     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
16113     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
16114     AddToWorklist(Shift.getNode());
16115
16116     if (XType.bitsGT(AType)) {
16117       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16118       AddToWorklist(Shift.getNode());
16119     }
16120
16121     if (CC == ISD::SETGT)
16122       Shift = DAG.getNOT(DL, Shift, AType);
16123
16124     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16125   }
16126
16127   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
16128   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
16129   AddToWorklist(Shift.getNode());
16130
16131   if (XType.bitsGT(AType)) {
16132     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16133     AddToWorklist(Shift.getNode());
16134   }
16135
16136   if (CC == ISD::SETGT)
16137     Shift = DAG.getNOT(DL, Shift, AType);
16138
16139   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16140 }
16141
16142 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
16143 /// where 'cond' is the comparison specified by CC.
16144 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
16145                                       SDValue N2, SDValue N3, ISD::CondCode CC,
16146                                       bool NotExtCompare) {
16147   // (x ? y : y) -> y.
16148   if (N2 == N3) return N2;
16149
16150   EVT VT = N2.getValueType();
16151   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
16152   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16153
16154   // Determine if the condition we're dealing with is constant
16155   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
16156                               N0, N1, CC, DL, false);
16157   if (SCC.getNode()) AddToWorklist(SCC.getNode());
16158
16159   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
16160     // fold select_cc true, x, y -> x
16161     // fold select_cc false, x, y -> y
16162     return !SCCC->isNullValue() ? N2 : N3;
16163   }
16164
16165   // Check to see if we can simplify the select into an fabs node
16166   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
16167     // Allow either -0.0 or 0.0
16168     if (CFP->isZero()) {
16169       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
16170       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
16171           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
16172           N2 == N3.getOperand(0))
16173         return DAG.getNode(ISD::FABS, DL, VT, N0);
16174
16175       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
16176       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
16177           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
16178           N2.getOperand(0) == N3)
16179         return DAG.getNode(ISD::FABS, DL, VT, N3);
16180     }
16181   }
16182
16183   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
16184   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
16185   // in it.  This is a win when the constant is not otherwise available because
16186   // it replaces two constant pool loads with one.  We only do this if the FP
16187   // type is known to be legal, because if it isn't, then we are before legalize
16188   // types an we want the other legalization to happen first (e.g. to avoid
16189   // messing with soft float) and if the ConstantFP is not legal, because if
16190   // it is legal, we may not need to store the FP constant in a constant pool.
16191   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
16192     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
16193       if (TLI.isTypeLegal(N2.getValueType()) &&
16194           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
16195                TargetLowering::Legal &&
16196            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
16197            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
16198           // If both constants have multiple uses, then we won't need to do an
16199           // extra load, they are likely around in registers for other users.
16200           (TV->hasOneUse() || FV->hasOneUse())) {
16201         Constant *Elts[] = {
16202           const_cast<ConstantFP*>(FV->getConstantFPValue()),
16203           const_cast<ConstantFP*>(TV->getConstantFPValue())
16204         };
16205         Type *FPTy = Elts[0]->getType();
16206         const DataLayout &TD = DAG.getDataLayout();
16207
16208         // Create a ConstantArray of the two constants.
16209         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
16210         SDValue CPIdx =
16211             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
16212                                 TD.getPrefTypeAlignment(FPTy));
16213         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
16214
16215         // Get the offsets to the 0 and 1 element of the array so that we can
16216         // select between them.
16217         SDValue Zero = DAG.getIntPtrConstant(0, DL);
16218         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
16219         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
16220
16221         SDValue Cond = DAG.getSetCC(DL,
16222                                     getSetCCResultType(N0.getValueType()),
16223                                     N0, N1, CC);
16224         AddToWorklist(Cond.getNode());
16225         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
16226                                           Cond, One, Zero);
16227         AddToWorklist(CstOffset.getNode());
16228         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
16229                             CstOffset);
16230         AddToWorklist(CPIdx.getNode());
16231         return DAG.getLoad(
16232             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
16233             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
16234             Alignment);
16235       }
16236     }
16237
16238   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
16239     return V;
16240
16241   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
16242   // where y is has a single bit set.
16243   // A plaintext description would be, we can turn the SELECT_CC into an AND
16244   // when the condition can be materialized as an all-ones register.  Any
16245   // single bit-test can be materialized as an all-ones register with
16246   // shift-left and shift-right-arith.
16247   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
16248       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
16249     SDValue AndLHS = N0->getOperand(0);
16250     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
16251     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
16252       // Shift the tested bit over the sign bit.
16253       const APInt &AndMask = ConstAndRHS->getAPIntValue();
16254       SDValue ShlAmt =
16255         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
16256                         getShiftAmountTy(AndLHS.getValueType()));
16257       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
16258
16259       // Now arithmetic right shift it all the way over, so the result is either
16260       // all-ones, or zero.
16261       SDValue ShrAmt =
16262         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
16263                         getShiftAmountTy(Shl.getValueType()));
16264       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
16265
16266       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
16267     }
16268   }
16269
16270   // fold select C, 16, 0 -> shl C, 4
16271   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
16272       TLI.getBooleanContents(N0.getValueType()) ==
16273           TargetLowering::ZeroOrOneBooleanContent) {
16274
16275     // If the caller doesn't want us to simplify this into a zext of a compare,
16276     // don't do it.
16277     if (NotExtCompare && N2C->isOne())
16278       return SDValue();
16279
16280     // Get a SetCC of the condition
16281     // NOTE: Don't create a SETCC if it's not legal on this target.
16282     if (!LegalOperations ||
16283         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
16284       SDValue Temp, SCC;
16285       // cast from setcc result type to select result type
16286       if (LegalTypes) {
16287         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
16288                             N0, N1, CC);
16289         if (N2.getValueType().bitsLT(SCC.getValueType()))
16290           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
16291                                         N2.getValueType());
16292         else
16293           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16294                              N2.getValueType(), SCC);
16295       } else {
16296         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
16297         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16298                            N2.getValueType(), SCC);
16299       }
16300
16301       AddToWorklist(SCC.getNode());
16302       AddToWorklist(Temp.getNode());
16303
16304       if (N2C->isOne())
16305         return Temp;
16306
16307       // shl setcc result by log2 n2c
16308       return DAG.getNode(
16309           ISD::SHL, DL, N2.getValueType(), Temp,
16310           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
16311                           getShiftAmountTy(Temp.getValueType())));
16312     }
16313   }
16314
16315   // Check to see if this is an integer abs.
16316   // select_cc setg[te] X,  0,  X, -X ->
16317   // select_cc setgt    X, -1,  X, -X ->
16318   // select_cc setl[te] X,  0, -X,  X ->
16319   // select_cc setlt    X,  1, -X,  X ->
16320   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
16321   if (N1C) {
16322     ConstantSDNode *SubC = nullptr;
16323     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
16324          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
16325         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
16326       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
16327     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
16328               (N1C->isOne() && CC == ISD::SETLT)) &&
16329              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
16330       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
16331
16332     EVT XType = N0.getValueType();
16333     if (SubC && SubC->isNullValue() && XType.isInteger()) {
16334       SDLoc DL(N0);
16335       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
16336                                   N0,
16337                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
16338                                          getShiftAmountTy(N0.getValueType())));
16339       SDValue Add = DAG.getNode(ISD::ADD, DL,
16340                                 XType, N0, Shift);
16341       AddToWorklist(Shift.getNode());
16342       AddToWorklist(Add.getNode());
16343       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
16344     }
16345   }
16346
16347   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
16348   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
16349   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
16350   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
16351   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
16352   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
16353   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
16354   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
16355   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
16356     SDValue ValueOnZero = N2;
16357     SDValue Count = N3;
16358     // If the condition is NE instead of E, swap the operands.
16359     if (CC == ISD::SETNE)
16360       std::swap(ValueOnZero, Count);
16361     // Check if the value on zero is a constant equal to the bits in the type.
16362     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
16363       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
16364         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
16365         // legal, combine to just cttz.
16366         if ((Count.getOpcode() == ISD::CTTZ ||
16367              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
16368             N0 == Count.getOperand(0) &&
16369             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
16370           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
16371         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
16372         // legal, combine to just ctlz.
16373         if ((Count.getOpcode() == ISD::CTLZ ||
16374              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
16375             N0 == Count.getOperand(0) &&
16376             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
16377           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
16378       }
16379     }
16380   }
16381
16382   return SDValue();
16383 }
16384
16385 /// This is a stub for TargetLowering::SimplifySetCC.
16386 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
16387                                    ISD::CondCode Cond, const SDLoc &DL,
16388                                    bool foldBooleans) {
16389   TargetLowering::DAGCombinerInfo
16390     DagCombineInfo(DAG, Level, false, this);
16391   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
16392 }
16393
16394 /// Given an ISD::SDIV node expressing a divide by constant, return
16395 /// a DAG expression to select that will generate the same value by multiplying
16396 /// by a magic number.
16397 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16398 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
16399   // when optimising for minimum size, we don't want to expand a div to a mul
16400   // and a shift.
16401   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16402     return SDValue();
16403
16404   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16405   if (!C)
16406     return SDValue();
16407
16408   // Avoid division by zero.
16409   if (C->isNullValue())
16410     return SDValue();
16411
16412   std::vector<SDNode*> Built;
16413   SDValue S =
16414       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16415
16416   for (SDNode *N : Built)
16417     AddToWorklist(N);
16418   return S;
16419 }
16420
16421 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
16422 /// DAG expression that will generate the same value by right shifting.
16423 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
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 = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
16434
16435   for (SDNode *N : Built)
16436     AddToWorklist(N);
16437   return S;
16438 }
16439
16440 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
16441 /// expression that will generate the same value by multiplying by a magic
16442 /// number.
16443 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16444 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
16445   // when optimising for minimum size, we don't want to expand a div to a mul
16446   // and a shift.
16447   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16448     return SDValue();
16449
16450   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16451   if (!C)
16452     return SDValue();
16453
16454   // Avoid division by zero.
16455   if (C->isNullValue())
16456     return SDValue();
16457
16458   std::vector<SDNode*> Built;
16459   SDValue S =
16460       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16461
16462   for (SDNode *N : Built)
16463     AddToWorklist(N);
16464   return S;
16465 }
16466
16467 /// Determines the LogBase2 value for a non-null input value using the
16468 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
16469 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
16470   EVT VT = V.getValueType();
16471   unsigned EltBits = VT.getScalarSizeInBits();
16472   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
16473   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
16474   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
16475   return LogBase2;
16476 }
16477
16478 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16479 /// For the reciprocal, we need to find the zero of the function:
16480 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
16481 ///     =>
16482 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
16483 ///     does not require additional intermediate precision]
16484 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
16485   if (Level >= AfterLegalizeDAG)
16486     return SDValue();
16487
16488   // TODO: Handle half and/or extended types?
16489   EVT VT = Op.getValueType();
16490   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16491     return SDValue();
16492
16493   // If estimates are explicitly disabled for this function, we're done.
16494   MachineFunction &MF = DAG.getMachineFunction();
16495   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
16496   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16497     return SDValue();
16498
16499   // Estimates may be explicitly enabled for this type with a custom number of
16500   // refinement steps.
16501   int Iterations = TLI.getDivRefinementSteps(VT, MF);
16502   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
16503     AddToWorklist(Est.getNode());
16504
16505     if (Iterations) {
16506       EVT VT = Op.getValueType();
16507       SDLoc DL(Op);
16508       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
16509
16510       // Newton iterations: Est = Est + Est (1 - Arg * Est)
16511       for (int i = 0; i < Iterations; ++i) {
16512         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
16513         AddToWorklist(NewEst.getNode());
16514
16515         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
16516         AddToWorklist(NewEst.getNode());
16517
16518         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16519         AddToWorklist(NewEst.getNode());
16520
16521         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
16522         AddToWorklist(Est.getNode());
16523       }
16524     }
16525     return Est;
16526   }
16527
16528   return SDValue();
16529 }
16530
16531 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16532 /// For the reciprocal sqrt, we need to find the zero of the function:
16533 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16534 ///     =>
16535 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
16536 /// As a result, we precompute A/2 prior to the iteration loop.
16537 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
16538                                          unsigned Iterations,
16539                                          SDNodeFlags Flags, bool Reciprocal) {
16540   EVT VT = Arg.getValueType();
16541   SDLoc DL(Arg);
16542   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
16543
16544   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
16545   // this entire sequence requires only one FP constant.
16546   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
16547   AddToWorklist(HalfArg.getNode());
16548
16549   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
16550   AddToWorklist(HalfArg.getNode());
16551
16552   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
16553   for (unsigned i = 0; i < Iterations; ++i) {
16554     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
16555     AddToWorklist(NewEst.getNode());
16556
16557     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
16558     AddToWorklist(NewEst.getNode());
16559
16560     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
16561     AddToWorklist(NewEst.getNode());
16562
16563     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16564     AddToWorklist(Est.getNode());
16565   }
16566
16567   // If non-reciprocal square root is requested, multiply the result by Arg.
16568   if (!Reciprocal) {
16569     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
16570     AddToWorklist(Est.getNode());
16571   }
16572
16573   return Est;
16574 }
16575
16576 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16577 /// For the reciprocal sqrt, we need to find the zero of the function:
16578 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16579 ///     =>
16580 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
16581 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
16582                                          unsigned Iterations,
16583                                          SDNodeFlags Flags, bool Reciprocal) {
16584   EVT VT = Arg.getValueType();
16585   SDLoc DL(Arg);
16586   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
16587   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
16588
16589   // This routine must enter the loop below to work correctly
16590   // when (Reciprocal == false).
16591   assert(Iterations > 0);
16592
16593   // Newton iterations for reciprocal square root:
16594   // E = (E * -0.5) * ((A * E) * E + -3.0)
16595   for (unsigned i = 0; i < Iterations; ++i) {
16596     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
16597     AddToWorklist(AE.getNode());
16598
16599     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
16600     AddToWorklist(AEE.getNode());
16601
16602     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
16603     AddToWorklist(RHS.getNode());
16604
16605     // When calculating a square root at the last iteration build:
16606     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
16607     // (notice a common subexpression)
16608     SDValue LHS;
16609     if (Reciprocal || (i + 1) < Iterations) {
16610       // RSQRT: LHS = (E * -0.5)
16611       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
16612     } else {
16613       // SQRT: LHS = (A * E) * -0.5
16614       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
16615     }
16616     AddToWorklist(LHS.getNode());
16617
16618     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
16619     AddToWorklist(Est.getNode());
16620   }
16621
16622   return Est;
16623 }
16624
16625 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
16626 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
16627 /// Op can be zero.
16628 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
16629                                            bool Reciprocal) {
16630   if (Level >= AfterLegalizeDAG)
16631     return SDValue();
16632
16633   // TODO: Handle half and/or extended types?
16634   EVT VT = Op.getValueType();
16635   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16636     return SDValue();
16637
16638   // If estimates are explicitly disabled for this function, we're done.
16639   MachineFunction &MF = DAG.getMachineFunction();
16640   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
16641   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16642     return SDValue();
16643
16644   // Estimates may be explicitly enabled for this type with a custom number of
16645   // refinement steps.
16646   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
16647
16648   bool UseOneConstNR = false;
16649   if (SDValue Est =
16650       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
16651                           Reciprocal)) {
16652     AddToWorklist(Est.getNode());
16653
16654     if (Iterations) {
16655       Est = UseOneConstNR
16656             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16657             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16658
16659       if (!Reciprocal) {
16660         // Unfortunately, Est is now NaN if the input was exactly 0.0.
16661         // Select out this case and force the answer to 0.0.
16662         EVT VT = Op.getValueType();
16663         SDLoc DL(Op);
16664
16665         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16666         EVT CCVT = getSetCCResultType(VT);
16667         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16668         AddToWorklist(ZeroCmp.getNode());
16669
16670         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16671                           ZeroCmp, FPZero, Est);
16672         AddToWorklist(Est.getNode());
16673       }
16674     }
16675     return Est;
16676   }
16677
16678   return SDValue();
16679 }
16680
16681 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16682   return buildSqrtEstimateImpl(Op, Flags, true);
16683 }
16684
16685 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16686   return buildSqrtEstimateImpl(Op, Flags, false);
16687 }
16688
16689 /// Return true if base is a frame index, which is known not to alias with
16690 /// anything but itself.  Provides base object and offset as results.
16691 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16692                            const GlobalValue *&GV, const void *&CV) {
16693   // Assume it is a primitive operation.
16694   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16695
16696   // If it's an adding a simple constant then integrate the offset.
16697   if (Base.getOpcode() == ISD::ADD) {
16698     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16699       Base = Base.getOperand(0);
16700       Offset += C->getSExtValue();
16701     }
16702   }
16703
16704   // Return the underlying GlobalValue, and update the Offset.  Return false
16705   // for GlobalAddressSDNode since the same GlobalAddress may be represented
16706   // by multiple nodes with different offsets.
16707   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16708     GV = G->getGlobal();
16709     Offset += G->getOffset();
16710     return false;
16711   }
16712
16713   // Return the underlying Constant value, and update the Offset.  Return false
16714   // for ConstantSDNodes since the same constant pool entry may be represented
16715   // by multiple nodes with different offsets.
16716   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16717     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16718                                          : (const void *)C->getConstVal();
16719     Offset += C->getOffset();
16720     return false;
16721   }
16722   // If it's any of the following then it can't alias with anything but itself.
16723   return isa<FrameIndexSDNode>(Base);
16724 }
16725
16726 /// Return true if there is any possibility that the two addresses overlap.
16727 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16728   // If they are the same then they must be aliases.
16729   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16730
16731   // If they are both volatile then they cannot be reordered.
16732   if (Op0->isVolatile() && Op1->isVolatile()) return true;
16733
16734   // If one operation reads from invariant memory, and the other may store, they
16735   // cannot alias. These should really be checking the equivalent of mayWrite,
16736   // but it only matters for memory nodes other than load /store.
16737   if (Op0->isInvariant() && Op1->writeMem())
16738     return false;
16739
16740   if (Op1->isInvariant() && Op0->writeMem())
16741     return false;
16742
16743   unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16744   unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16745
16746   // Check for BaseIndexOffset matching.
16747   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
16748   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
16749   int64_t PtrDiff;
16750   if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
16751     return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
16752
16753   // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
16754   // able to calculate their relative offset if at least one arises
16755   // from an alloca. However, these allocas cannot overlap and we
16756   // can infer there is no alias.
16757   if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
16758     if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
16759       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16760       // If the base are the same frame index but the we couldn't find a
16761       // constant offset, (indices are different) be conservative.
16762       if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
16763                      !MFI.isFixedObjectIndex(B->getIndex())))
16764         return false;
16765     }
16766
16767   // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
16768   // modified to use BaseIndexOffset.
16769
16770   // Gather base node and offset information.
16771   SDValue Base0, Base1;
16772   int64_t Offset0, Offset1;
16773   const GlobalValue *GV0, *GV1;
16774   const void *CV0, *CV1;
16775   bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
16776                                       Base0, Offset0, GV0, CV0);
16777   bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
16778                                       Base1, Offset1, GV1, CV1);
16779
16780   // If they have the same base address, then check to see if they overlap.
16781   if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
16782     return !((Offset0 + NumBytes0) <= Offset1 ||
16783              (Offset1 + NumBytes1) <= Offset0);
16784
16785   // It is possible for different frame indices to alias each other, mostly
16786   // when tail call optimization reuses return address slots for arguments.
16787   // To catch this case, look up the actual index of frame indices to compute
16788   // the real alias relationship.
16789   if (IsFrameIndex0 && IsFrameIndex1) {
16790     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16791     Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
16792     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
16793     return !((Offset0 + NumBytes0) <= Offset1 ||
16794              (Offset1 + NumBytes1) <= Offset0);
16795   }
16796
16797   // Otherwise, if we know what the bases are, and they aren't identical, then
16798   // we know they cannot alias.
16799   if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
16800     return false;
16801
16802   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
16803   // compared to the size and offset of the access, we may be able to prove they
16804   // do not alias. This check is conservative for now to catch cases created by
16805   // splitting vector types.
16806   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
16807   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
16808   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
16809   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
16810   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
16811       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
16812     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
16813     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
16814
16815     // There is no overlap between these relatively aligned accesses of similar
16816     // size. Return no alias.
16817     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
16818         (OffAlign1 + NumBytes1) <= OffAlign0)
16819       return false;
16820   }
16821
16822   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
16823                    ? CombinerGlobalAA
16824                    : DAG.getSubtarget().useAA();
16825 #ifndef NDEBUG
16826   if (CombinerAAOnlyFunc.getNumOccurrences() &&
16827       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
16828     UseAA = false;
16829 #endif
16830
16831   if (UseAA && AA &&
16832       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
16833     // Use alias analysis information.
16834     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
16835     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
16836     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
16837     AliasResult AAResult =
16838         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
16839                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
16840                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
16841                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
16842     if (AAResult == NoAlias)
16843       return false;
16844   }
16845
16846   // Otherwise we have to assume they alias.
16847   return true;
16848 }
16849
16850 /// Walk up chain skipping non-aliasing memory nodes,
16851 /// looking for aliasing nodes and adding them to the Aliases vector.
16852 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
16853                                    SmallVectorImpl<SDValue> &Aliases) {
16854   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
16855   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
16856
16857   // Get alias information for node.
16858   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
16859
16860   // Starting off.
16861   Chains.push_back(OriginalChain);
16862   unsigned Depth = 0;
16863
16864   // Look at each chain and determine if it is an alias.  If so, add it to the
16865   // aliases list.  If not, then continue up the chain looking for the next
16866   // candidate.
16867   while (!Chains.empty()) {
16868     SDValue Chain = Chains.pop_back_val();
16869
16870     // For TokenFactor nodes, look at each operand and only continue up the
16871     // chain until we reach the depth limit.
16872     //
16873     // FIXME: The depth check could be made to return the last non-aliasing
16874     // chain we found before we hit a tokenfactor rather than the original
16875     // chain.
16876     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
16877       Aliases.clear();
16878       Aliases.push_back(OriginalChain);
16879       return;
16880     }
16881
16882     // Don't bother if we've been before.
16883     if (!Visited.insert(Chain.getNode()).second)
16884       continue;
16885
16886     switch (Chain.getOpcode()) {
16887     case ISD::EntryToken:
16888       // Entry token is ideal chain operand, but handled in FindBetterChain.
16889       break;
16890
16891     case ISD::LOAD:
16892     case ISD::STORE: {
16893       // Get alias information for Chain.
16894       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
16895           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
16896
16897       // If chain is alias then stop here.
16898       if (!(IsLoad && IsOpLoad) &&
16899           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
16900         Aliases.push_back(Chain);
16901       } else {
16902         // Look further up the chain.
16903         Chains.push_back(Chain.getOperand(0));
16904         ++Depth;
16905       }
16906       break;
16907     }
16908
16909     case ISD::TokenFactor:
16910       // We have to check each of the operands of the token factor for "small"
16911       // token factors, so we queue them up.  Adding the operands to the queue
16912       // (stack) in reverse order maintains the original order and increases the
16913       // likelihood that getNode will find a matching token factor (CSE.)
16914       if (Chain.getNumOperands() > 16) {
16915         Aliases.push_back(Chain);
16916         break;
16917       }
16918       for (unsigned n = Chain.getNumOperands(); n;)
16919         Chains.push_back(Chain.getOperand(--n));
16920       ++Depth;
16921       break;
16922
16923     case ISD::CopyFromReg:
16924       // Forward past CopyFromReg.
16925       Chains.push_back(Chain.getOperand(0));
16926       ++Depth;
16927       break;
16928
16929     default:
16930       // For all other instructions we will just have to take what we can get.
16931       Aliases.push_back(Chain);
16932       break;
16933     }
16934   }
16935 }
16936
16937 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
16938 /// (aliasing node.)
16939 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
16940   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
16941
16942   // Accumulate all the aliases to this node.
16943   GatherAllAliases(N, OldChain, Aliases);
16944
16945   // If no operands then chain to entry token.
16946   if (Aliases.size() == 0)
16947     return DAG.getEntryNode();
16948
16949   // If a single operand then chain to it.  We don't need to revisit it.
16950   if (Aliases.size() == 1)
16951     return Aliases[0];
16952
16953   // Construct a custom tailored token factor.
16954   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
16955 }
16956
16957 // This function tries to collect a bunch of potentially interesting
16958 // nodes to improve the chains of, all at once. This might seem
16959 // redundant, as this function gets called when visiting every store
16960 // node, so why not let the work be done on each store as it's visited?
16961 //
16962 // I believe this is mainly important because MergeConsecutiveStores
16963 // is unable to deal with merging stores of different sizes, so unless
16964 // we improve the chains of all the potential candidates up-front
16965 // before running MergeConsecutiveStores, it might only see some of
16966 // the nodes that will eventually be candidates, and then not be able
16967 // to go from a partially-merged state to the desired final
16968 // fully-merged state.
16969 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
16970   // This holds the base pointer, index, and the offset in bytes from the base
16971   // pointer.
16972   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
16973
16974   // We must have a base and an offset.
16975   if (!BasePtr.getBase().getNode())
16976     return false;
16977
16978   // Do not handle stores to undef base pointers.
16979   if (BasePtr.getBase().isUndef())
16980     return false;
16981
16982   SmallVector<StoreSDNode *, 8> ChainedStores;
16983   ChainedStores.push_back(St);
16984
16985   // Walk up the chain and look for nodes with offsets from the same
16986   // base pointer. Stop when reaching an instruction with a different kind
16987   // or instruction which has a different base pointer.
16988   StoreSDNode *Index = St;
16989   while (Index) {
16990     // If the chain has more than one use, then we can't reorder the mem ops.
16991     if (Index != St && !SDValue(Index, 0)->hasOneUse())
16992       break;
16993
16994     if (Index->isVolatile() || Index->isIndexed())
16995       break;
16996
16997     // Find the base pointer and offset for this memory node.
16998     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
16999
17000     // Check that the base pointer is the same as the original one.
17001     if (!BasePtr.equalBaseIndex(Ptr, DAG))
17002       break;
17003
17004     // Walk up the chain to find the next store node, ignoring any
17005     // intermediate loads. Any other kind of node will halt the loop.
17006     SDNode *NextInChain = Index->getChain().getNode();
17007     while (true) {
17008       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
17009         // We found a store node. Use it for the next iteration.
17010         if (STn->isVolatile() || STn->isIndexed()) {
17011           Index = nullptr;
17012           break;
17013         }
17014         ChainedStores.push_back(STn);
17015         Index = STn;
17016         break;
17017       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
17018         NextInChain = Ldn->getChain().getNode();
17019         continue;
17020       } else {
17021         Index = nullptr;
17022         break;
17023       }
17024     } // end while
17025   }
17026
17027   // At this point, ChainedStores lists all of the Store nodes
17028   // reachable by iterating up through chain nodes matching the above
17029   // conditions.  For each such store identified, try to find an
17030   // earlier chain to attach the store to which won't violate the
17031   // required ordering.
17032   bool MadeChangeToSt = false;
17033   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
17034
17035   for (StoreSDNode *ChainedStore : ChainedStores) {
17036     SDValue Chain = ChainedStore->getChain();
17037     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
17038
17039     if (Chain != BetterChain) {
17040       if (ChainedStore == St)
17041         MadeChangeToSt = true;
17042       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
17043     }
17044   }
17045
17046   // Do all replacements after finding the replacements to make to avoid making
17047   // the chains more complicated by introducing new TokenFactors.
17048   for (auto Replacement : BetterChains)
17049     replaceStoreChain(Replacement.first, Replacement.second);
17050
17051   return MadeChangeToSt;
17052 }
17053
17054 /// This is the entry point for the file.
17055 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
17056                            CodeGenOpt::Level OptLevel) {
17057   /// This is the main entry point to this class.
17058   DAGCombiner(*this, AA, OptLevel).Run(Level);
17059 }