]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304659, 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/SelectionDAGTargetInfo.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/KnownBits.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 #include <algorithm>
44 using namespace llvm;
45
46 #define DEBUG_TYPE "dagcombine"
47
48 STATISTIC(NodesCombined   , "Number of dag nodes combined");
49 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
50 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
51 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
52 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
53 STATISTIC(SlicedLoads, "Number of load sliced");
54
55 namespace {
56   static cl::opt<bool>
57     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58                cl::desc("Enable DAG combiner's use of IR alias analysis"));
59
60   static cl::opt<bool>
61     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62                cl::desc("Enable DAG combiner's use of TBAA"));
63
64 #ifndef NDEBUG
65   static cl::opt<std::string>
66     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67                cl::desc("Only use DAG-combiner alias analysis in this"
68                         " function"));
69 #endif
70
71   /// Hidden option to stress test load slicing, i.e., when this option
72   /// is enabled, load slicing bypasses most of its profitability guards.
73   static cl::opt<bool>
74   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75                     cl::desc("Bypass the profitability model of load "
76                              "slicing"),
77                     cl::init(false));
78
79   static cl::opt<bool>
80     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
81                       cl::desc("DAG combiner may split indexing from loads"));
82
83 //------------------------------ DAGCombiner ---------------------------------//
84
85   class DAGCombiner {
86     SelectionDAG &DAG;
87     const TargetLowering &TLI;
88     CombineLevel Level;
89     CodeGenOpt::Level OptLevel;
90     bool LegalOperations;
91     bool LegalTypes;
92     bool ForCodeSize;
93
94     /// \brief Worklist of all of the nodes that need to be simplified.
95     ///
96     /// This must behave as a stack -- new nodes to process are pushed onto the
97     /// back and when processing we pop off of the back.
98     ///
99     /// The worklist will not contain duplicates but may contain null entries
100     /// due to nodes being deleted from the underlying DAG.
101     SmallVector<SDNode *, 64> Worklist;
102
103     /// \brief Mapping from an SDNode to its position on the worklist.
104     ///
105     /// This is used to find and remove nodes from the worklist (by nulling
106     /// them) when they are deleted from the underlying DAG. It relies on
107     /// stable indices of nodes within the worklist.
108     DenseMap<SDNode *, unsigned> WorklistMap;
109
110     /// \brief Set of nodes which have been combined (at least once).
111     ///
112     /// This is used to allow us to reliably add any operands of a DAG node
113     /// which have not yet been combined to the worklist.
114     SmallPtrSet<SDNode *, 32> CombinedNodes;
115
116     // AA - Used for DAG load/store alias analysis.
117     AliasAnalysis *AA;
118
119     /// When an instruction is simplified, add all users of the instruction to
120     /// the work lists because they might get more simplified now.
121     void AddUsersToWorklist(SDNode *N) {
122       for (SDNode *Node : N->uses())
123         AddToWorklist(Node);
124     }
125
126     /// Call the node-specific routine that folds each particular type of node.
127     SDValue visit(SDNode *N);
128
129   public:
130     /// Add to the worklist making sure its instance is at the back (next to be
131     /// processed.)
132     void AddToWorklist(SDNode *N) {
133       assert(N->getOpcode() != ISD::DELETED_NODE &&
134              "Deleted Node added to Worklist");
135
136       // Skip handle nodes as they can't usefully be combined and confuse the
137       // zero-use deletion strategy.
138       if (N->getOpcode() == ISD::HANDLENODE)
139         return;
140
141       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
142         Worklist.push_back(N);
143     }
144
145     /// Remove all instances of N from the worklist.
146     void removeFromWorklist(SDNode *N) {
147       CombinedNodes.erase(N);
148
149       auto It = WorklistMap.find(N);
150       if (It == WorklistMap.end())
151         return; // Not in the worklist.
152
153       // Null out the entry rather than erasing it to avoid a linear operation.
154       Worklist[It->second] = nullptr;
155       WorklistMap.erase(It);
156     }
157
158     void deleteAndRecombine(SDNode *N);
159     bool recursivelyDeleteUnusedNodes(SDNode *N);
160
161     /// Replaces all uses of the results of one DAG node with new values.
162     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
163                       bool AddTo = true);
164
165     /// Replaces all uses of the results of one DAG node with new values.
166     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
167       return CombineTo(N, &Res, 1, AddTo);
168     }
169
170     /// Replaces all uses of the results of one DAG node with new values.
171     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
172                       bool AddTo = true) {
173       SDValue To[] = { Res0, Res1 };
174       return CombineTo(N, To, 2, AddTo);
175     }
176
177     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
178
179   private:
180     unsigned MaximumLegalStoreInBits;
181
182     /// Check the specified integer node value to see if it can be simplified or
183     /// if things it uses can be simplified by bit propagation.
184     /// If so, return true.
185     bool SimplifyDemandedBits(SDValue Op) {
186       unsigned BitWidth = Op.getScalarValueSizeInBits();
187       APInt Demanded = APInt::getAllOnesValue(BitWidth);
188       return SimplifyDemandedBits(Op, Demanded);
189     }
190
191     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
192
193     bool CombineToPreIndexedLoadStore(SDNode *N);
194     bool CombineToPostIndexedLoadStore(SDNode *N);
195     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
196     bool SliceUpLoad(SDNode *N);
197
198     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
199     ///   load.
200     ///
201     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
202     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
203     /// \param EltNo index of the vector element to load.
204     /// \param OriginalLoad load that EVE came from to be replaced.
205     /// \returns EVE on success SDValue() on failure.
206     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
207         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
208     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
209     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
210     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
211     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
212     SDValue PromoteIntBinOp(SDValue Op);
213     SDValue PromoteIntShiftOp(SDValue Op);
214     SDValue PromoteExtend(SDValue Op);
215     bool PromoteLoad(SDValue Op);
216
217     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
218                          SDValue ExtLoad, const SDLoc &DL,
219                          ISD::NodeType ExtType);
220
221     /// Call the node-specific routine that knows how to fold each
222     /// particular type of node. If that doesn't do anything, try the
223     /// target-specific DAG combines.
224     SDValue combine(SDNode *N);
225
226     // Visitation implementation - Implement dag node combining for different
227     // node types.  The semantics are as follows:
228     // Return Value:
229     //   SDValue.getNode() == 0 - No change was made
230     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
231     //   otherwise              - N should be replaced by the returned Operand.
232     //
233     SDValue visitTokenFactor(SDNode *N);
234     SDValue visitMERGE_VALUES(SDNode *N);
235     SDValue visitADD(SDNode *N);
236     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
237     SDValue visitSUB(SDNode *N);
238     SDValue visitADDC(SDNode *N);
239     SDValue visitUADDO(SDNode *N);
240     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
241     SDValue visitSUBC(SDNode *N);
242     SDValue visitUSUBO(SDNode *N);
243     SDValue visitADDE(SDNode *N);
244     SDValue visitADDCARRY(SDNode *N);
245     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
246     SDValue visitSUBE(SDNode *N);
247     SDValue visitSUBCARRY(SDNode *N);
248     SDValue visitMUL(SDNode *N);
249     SDValue useDivRem(SDNode *N);
250     SDValue visitSDIV(SDNode *N);
251     SDValue visitUDIV(SDNode *N);
252     SDValue visitREM(SDNode *N);
253     SDValue visitMULHU(SDNode *N);
254     SDValue visitMULHS(SDNode *N);
255     SDValue visitSMUL_LOHI(SDNode *N);
256     SDValue visitUMUL_LOHI(SDNode *N);
257     SDValue visitSMULO(SDNode *N);
258     SDValue visitUMULO(SDNode *N);
259     SDValue visitIMINMAX(SDNode *N);
260     SDValue visitAND(SDNode *N);
261     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
262     SDValue visitOR(SDNode *N);
263     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
264     SDValue visitXOR(SDNode *N);
265     SDValue SimplifyVBinOp(SDNode *N);
266     SDValue visitSHL(SDNode *N);
267     SDValue visitSRA(SDNode *N);
268     SDValue visitSRL(SDNode *N);
269     SDValue visitRotate(SDNode *N);
270     SDValue visitABS(SDNode *N);
271     SDValue visitBSWAP(SDNode *N);
272     SDValue visitBITREVERSE(SDNode *N);
273     SDValue visitCTLZ(SDNode *N);
274     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
275     SDValue visitCTTZ(SDNode *N);
276     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
277     SDValue visitCTPOP(SDNode *N);
278     SDValue visitSELECT(SDNode *N);
279     SDValue visitVSELECT(SDNode *N);
280     SDValue visitSELECT_CC(SDNode *N);
281     SDValue visitSETCC(SDNode *N);
282     SDValue visitSETCCE(SDNode *N);
283     SDValue visitSETCCCARRY(SDNode *N);
284     SDValue visitSIGN_EXTEND(SDNode *N);
285     SDValue visitZERO_EXTEND(SDNode *N);
286     SDValue visitANY_EXTEND(SDNode *N);
287     SDValue visitAssertZext(SDNode *N);
288     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
289     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
290     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
291     SDValue visitTRUNCATE(SDNode *N);
292     SDValue visitBITCAST(SDNode *N);
293     SDValue visitBUILD_PAIR(SDNode *N);
294     SDValue visitFADD(SDNode *N);
295     SDValue visitFSUB(SDNode *N);
296     SDValue visitFMUL(SDNode *N);
297     SDValue visitFMA(SDNode *N);
298     SDValue visitFDIV(SDNode *N);
299     SDValue visitFREM(SDNode *N);
300     SDValue visitFSQRT(SDNode *N);
301     SDValue visitFCOPYSIGN(SDNode *N);
302     SDValue visitSINT_TO_FP(SDNode *N);
303     SDValue visitUINT_TO_FP(SDNode *N);
304     SDValue visitFP_TO_SINT(SDNode *N);
305     SDValue visitFP_TO_UINT(SDNode *N);
306     SDValue visitFP_ROUND(SDNode *N);
307     SDValue visitFP_ROUND_INREG(SDNode *N);
308     SDValue visitFP_EXTEND(SDNode *N);
309     SDValue visitFNEG(SDNode *N);
310     SDValue visitFABS(SDNode *N);
311     SDValue visitFCEIL(SDNode *N);
312     SDValue visitFTRUNC(SDNode *N);
313     SDValue visitFFLOOR(SDNode *N);
314     SDValue visitFMINNUM(SDNode *N);
315     SDValue visitFMAXNUM(SDNode *N);
316     SDValue visitBRCOND(SDNode *N);
317     SDValue visitBR_CC(SDNode *N);
318     SDValue visitLOAD(SDNode *N);
319
320     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
321     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
322
323     SDValue visitSTORE(SDNode *N);
324     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
325     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
326     SDValue visitBUILD_VECTOR(SDNode *N);
327     SDValue visitCONCAT_VECTORS(SDNode *N);
328     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
329     SDValue visitVECTOR_SHUFFLE(SDNode *N);
330     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
331     SDValue visitINSERT_SUBVECTOR(SDNode *N);
332     SDValue visitMLOAD(SDNode *N);
333     SDValue visitMSTORE(SDNode *N);
334     SDValue visitMGATHER(SDNode *N);
335     SDValue visitMSCATTER(SDNode *N);
336     SDValue visitFP_TO_FP16(SDNode *N);
337     SDValue visitFP16_TO_FP(SDNode *N);
338
339     SDValue visitFADDForFMACombine(SDNode *N);
340     SDValue visitFSUBForFMACombine(SDNode *N);
341     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
342
343     SDValue XformToShuffleWithZero(SDNode *N);
344     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
345                            SDValue RHS);
346
347     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
348
349     SDValue foldSelectOfConstants(SDNode *N);
350     SDValue foldBinOpIntoSelect(SDNode *BO);
351     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
352     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
353     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
354     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
355                              SDValue N2, SDValue N3, ISD::CondCode CC,
356                              bool NotExtCompare = false);
357     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
358                                    SDValue N2, SDValue N3, ISD::CondCode CC);
359     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
360                               const SDLoc &DL);
361     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
362                           const SDLoc &DL, bool foldBooleans = true);
363
364     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
365                            SDValue &CC) const;
366     bool isOneUseSetCC(SDValue N) const;
367
368     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
369                                          unsigned HiOp);
370     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
371     SDValue CombineExtLoad(SDNode *N);
372     SDValue combineRepeatedFPDivisors(SDNode *N);
373     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
374     SDValue BuildSDIV(SDNode *N);
375     SDValue BuildSDIVPow2(SDNode *N);
376     SDValue BuildUDIV(SDNode *N);
377     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
378     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
379     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
380     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
381     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
382     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
383                                 SDNodeFlags Flags, bool Reciprocal);
384     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
385                                 SDNodeFlags Flags, bool Reciprocal);
386     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
387                                bool DemandHighBits = true);
388     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
389     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
390                               SDValue InnerPos, SDValue InnerNeg,
391                               unsigned PosOpcode, unsigned NegOpcode,
392                               const SDLoc &DL);
393     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
394     SDValue MatchLoadCombine(SDNode *N);
395     SDValue ReduceLoadWidth(SDNode *N);
396     SDValue ReduceLoadOpStoreWidth(SDNode *N);
397     SDValue splitMergedValStore(StoreSDNode *ST);
398     SDValue TransformFPLoadStorePair(SDNode *N);
399     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
400     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
401     SDValue reduceBuildVecToShuffle(SDNode *N);
402     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
403                                   ArrayRef<int> VectorMask, SDValue VecIn1,
404                                   SDValue VecIn2, unsigned LeftIdx);
405     SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
406
407     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
408
409     /// Walk up chain skipping non-aliasing memory nodes,
410     /// looking for aliasing nodes and adding them to the Aliases vector.
411     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
412                           SmallVectorImpl<SDValue> &Aliases);
413
414     /// Return true if there is any possibility that the two addresses overlap.
415     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
416
417     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
418     /// chain (aliasing node.)
419     SDValue FindBetterChain(SDNode *N, SDValue Chain);
420
421     /// Try to replace a store and any possibly adjacent stores on
422     /// consecutive chains with better chains. Return true only if St is
423     /// replaced.
424     ///
425     /// Notice that other chains may still be replaced even if the function
426     /// returns false.
427     bool findBetterNeighborChains(StoreSDNode *St);
428
429     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
430     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
431
432     /// Holds a pointer to an LSBaseSDNode as well as information on where it
433     /// is located in a sequence of memory operations connected by a chain.
434     struct MemOpLink {
435       MemOpLink(LSBaseSDNode *N, int64_t Offset)
436           : MemNode(N), OffsetFromBase(Offset) {}
437       // Ptr to the mem node.
438       LSBaseSDNode *MemNode;
439       // Offset from the base ptr.
440       int64_t OffsetFromBase;
441     };
442
443     /// This is a helper function for visitMUL to check the profitability
444     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
445     /// MulNode is the original multiply, AddNode is (add x, c1),
446     /// and ConstNode is c2.
447     bool isMulAddWithConstProfitable(SDNode *MulNode,
448                                      SDValue &AddNode,
449                                      SDValue &ConstNode);
450
451
452     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
453     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
454     /// the type of the loaded value to be extended.  LoadedVT returns the type
455     /// of the original loaded value.  NarrowLoad returns whether the load would
456     /// need to be narrowed in order to match.
457     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
458                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
459                           bool &NarrowLoad);
460
461     /// Helper function for MergeConsecutiveStores which merges the
462     /// component store chains.
463     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
464                                 unsigned NumStores);
465
466     /// This is a helper function for MergeConsecutiveStores. When the source
467     /// elements of the consecutive stores are all constants or all extracted
468     /// vector elements, try to merge them into one larger store.
469     /// \return True if a merged store was created.
470     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
471                                          EVT MemVT, unsigned NumStores,
472                                          bool IsConstantSrc, bool UseVector);
473
474     /// This is a helper function for MergeConsecutiveStores.
475     /// Stores that may be merged are placed in StoreNodes.
476     void getStoreMergeCandidates(StoreSDNode *St,
477                                  SmallVectorImpl<MemOpLink> &StoreNodes);
478
479     /// Helper function for MergeConsecutiveStores. Checks if
480     /// Candidate stores have indirect dependency through their
481     /// operands. \return True if safe to merge
482     bool checkMergeStoreCandidatesForDependencies(
483         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
484
485     /// Merge consecutive store operations into a wide store.
486     /// This optimization uses wide integers or vectors when possible.
487     /// \return number of stores that were merged into a merged store (the
488     /// affected nodes are stored as a prefix in \p StoreNodes).
489     bool MergeConsecutiveStores(StoreSDNode *N);
490
491     /// \brief Try to transform a truncation where C is a constant:
492     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
493     ///
494     /// \p N needs to be a truncation and its first operand an AND. Other
495     /// requirements are checked by the function (e.g. that trunc is
496     /// single-use) and if missed an empty SDValue is returned.
497     SDValue distributeTruncateThroughAnd(SDNode *N);
498
499   public:
500     DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
501         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
502           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(AA) {
503       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
504
505       MaximumLegalStoreInBits = 0;
506       for (MVT VT : MVT::all_valuetypes())
507         if (EVT(VT).isSimple() && VT != MVT::Other &&
508             TLI.isTypeLegal(EVT(VT)) &&
509             VT.getSizeInBits() >= MaximumLegalStoreInBits)
510           MaximumLegalStoreInBits = VT.getSizeInBits();
511     }
512
513     /// Runs the dag combiner on all nodes in the work list
514     void Run(CombineLevel AtLevel);
515
516     SelectionDAG &getDAG() const { return DAG; }
517
518     /// Returns a type large enough to hold any valid shift amount - before type
519     /// legalization these can be huge.
520     EVT getShiftAmountTy(EVT LHSTy) {
521       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
522       if (LHSTy.isVector())
523         return LHSTy;
524       auto &DL = DAG.getDataLayout();
525       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
526                         : TLI.getPointerTy(DL);
527     }
528
529     /// This method returns true if we are running before type legalization or
530     /// if the specified VT is legal.
531     bool isTypeLegal(const EVT &VT) {
532       if (!LegalTypes) return true;
533       return TLI.isTypeLegal(VT);
534     }
535
536     /// Convenience wrapper around TargetLowering::getSetCCResultType
537     EVT getSetCCResultType(EVT VT) const {
538       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
539     }
540   };
541 }
542
543
544 namespace {
545 /// This class is a DAGUpdateListener that removes any deleted
546 /// nodes from the worklist.
547 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
548   DAGCombiner &DC;
549 public:
550   explicit WorklistRemover(DAGCombiner &dc)
551     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
552
553   void NodeDeleted(SDNode *N, SDNode *E) override {
554     DC.removeFromWorklist(N);
555   }
556 };
557 }
558
559 //===----------------------------------------------------------------------===//
560 //  TargetLowering::DAGCombinerInfo implementation
561 //===----------------------------------------------------------------------===//
562
563 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
564   ((DAGCombiner*)DC)->AddToWorklist(N);
565 }
566
567 SDValue TargetLowering::DAGCombinerInfo::
568 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
569   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
570 }
571
572 SDValue TargetLowering::DAGCombinerInfo::
573 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
574   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
575 }
576
577
578 SDValue TargetLowering::DAGCombinerInfo::
579 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
580   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
581 }
582
583 void TargetLowering::DAGCombinerInfo::
584 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
585   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
586 }
587
588 //===----------------------------------------------------------------------===//
589 // Helper Functions
590 //===----------------------------------------------------------------------===//
591
592 void DAGCombiner::deleteAndRecombine(SDNode *N) {
593   removeFromWorklist(N);
594
595   // If the operands of this node are only used by the node, they will now be
596   // dead. Make sure to re-visit them and recursively delete dead nodes.
597   for (const SDValue &Op : N->ops())
598     // For an operand generating multiple values, one of the values may
599     // become dead allowing further simplification (e.g. split index
600     // arithmetic from an indexed load).
601     if (Op->hasOneUse() || Op->getNumValues() > 1)
602       AddToWorklist(Op.getNode());
603
604   DAG.DeleteNode(N);
605 }
606
607 /// Return 1 if we can compute the negated form of the specified expression for
608 /// the same cost as the expression itself, or 2 if we can compute the negated
609 /// form more cheaply than the expression itself.
610 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
611                                const TargetLowering &TLI,
612                                const TargetOptions *Options,
613                                unsigned Depth = 0) {
614   // fneg is removable even if it has multiple uses.
615   if (Op.getOpcode() == ISD::FNEG) return 2;
616
617   // Don't allow anything with multiple uses.
618   if (!Op.hasOneUse()) return 0;
619
620   // Don't recurse exponentially.
621   if (Depth > 6) return 0;
622
623   switch (Op.getOpcode()) {
624   default: return false;
625   case ISD::ConstantFP: {
626     if (!LegalOperations)
627       return 1;
628
629     // Don't invert constant FP values after legalization unless the target says
630     // the negated constant is legal.
631     EVT VT = Op.getValueType();
632     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
633       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
634   }
635   case ISD::FADD:
636     // FIXME: determine better conditions for this xform.
637     if (!Options->UnsafeFPMath) return 0;
638
639     // After operation legalization, it might not be legal to create new FSUBs.
640     if (LegalOperations &&
641         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
642       return 0;
643
644     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
645     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
646                                     Options, Depth + 1))
647       return V;
648     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
649     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
650                               Depth + 1);
651   case ISD::FSUB:
652     // We can't turn -(A-B) into B-A when we honor signed zeros.
653     if (!Options->NoSignedZerosFPMath &&
654         !Op.getNode()->getFlags().hasNoSignedZeros())
655       return 0;
656
657     // fold (fneg (fsub A, B)) -> (fsub B, A)
658     return 1;
659
660   case ISD::FMUL:
661   case ISD::FDIV:
662     if (Options->HonorSignDependentRoundingFPMath()) return 0;
663
664     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
665     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
666                                     Options, Depth + 1))
667       return V;
668
669     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
670                               Depth + 1);
671
672   case ISD::FP_EXTEND:
673   case ISD::FP_ROUND:
674   case ISD::FSIN:
675     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
676                               Depth + 1);
677   }
678 }
679
680 /// If isNegatibleForFree returns true, return the newly negated expression.
681 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
682                                     bool LegalOperations, unsigned Depth = 0) {
683   const TargetOptions &Options = DAG.getTarget().Options;
684   // fneg is removable even if it has multiple uses.
685   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
686
687   // Don't allow anything with multiple uses.
688   assert(Op.hasOneUse() && "Unknown reuse!");
689
690   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
691
692   const SDNodeFlags Flags = Op.getNode()->getFlags();
693
694   switch (Op.getOpcode()) {
695   default: llvm_unreachable("Unknown code");
696   case ISD::ConstantFP: {
697     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
698     V.changeSign();
699     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
700   }
701   case ISD::FADD:
702     // FIXME: determine better conditions for this xform.
703     assert(Options.UnsafeFPMath);
704
705     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
706     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
707                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
708       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
709                          GetNegatedExpression(Op.getOperand(0), DAG,
710                                               LegalOperations, Depth+1),
711                          Op.getOperand(1), Flags);
712     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
713     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
714                        GetNegatedExpression(Op.getOperand(1), DAG,
715                                             LegalOperations, Depth+1),
716                        Op.getOperand(0), Flags);
717   case ISD::FSUB:
718     // fold (fneg (fsub 0, B)) -> B
719     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
720       if (N0CFP->isZero())
721         return Op.getOperand(1);
722
723     // fold (fneg (fsub A, B)) -> (fsub B, A)
724     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
725                        Op.getOperand(1), Op.getOperand(0), Flags);
726
727   case ISD::FMUL:
728   case ISD::FDIV:
729     assert(!Options.HonorSignDependentRoundingFPMath());
730
731     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
732     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
733                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
734       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
735                          GetNegatedExpression(Op.getOperand(0), DAG,
736                                               LegalOperations, Depth+1),
737                          Op.getOperand(1), Flags);
738
739     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
740     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
741                        Op.getOperand(0),
742                        GetNegatedExpression(Op.getOperand(1), DAG,
743                                             LegalOperations, Depth+1), Flags);
744
745   case ISD::FP_EXTEND:
746   case ISD::FSIN:
747     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
748                        GetNegatedExpression(Op.getOperand(0), DAG,
749                                             LegalOperations, Depth+1));
750   case ISD::FP_ROUND:
751       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
752                          GetNegatedExpression(Op.getOperand(0), DAG,
753                                               LegalOperations, Depth+1),
754                          Op.getOperand(1));
755   }
756 }
757
758 // APInts must be the same size for most operations, this helper
759 // function zero extends the shorter of the pair so that they match.
760 // We provide an Offset so that we can create bitwidths that won't overflow.
761 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
762   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
763   LHS = LHS.zextOrSelf(Bits);
764   RHS = RHS.zextOrSelf(Bits);
765 }
766
767 // Return true if this node is a setcc, or is a select_cc
768 // that selects between the target values used for true and false, making it
769 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
770 // the appropriate nodes based on the type of node we are checking. This
771 // simplifies life a bit for the callers.
772 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
773                                     SDValue &CC) const {
774   if (N.getOpcode() == ISD::SETCC) {
775     LHS = N.getOperand(0);
776     RHS = N.getOperand(1);
777     CC  = N.getOperand(2);
778     return true;
779   }
780
781   if (N.getOpcode() != ISD::SELECT_CC ||
782       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
783       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
784     return false;
785
786   if (TLI.getBooleanContents(N.getValueType()) ==
787       TargetLowering::UndefinedBooleanContent)
788     return false;
789
790   LHS = N.getOperand(0);
791   RHS = N.getOperand(1);
792   CC  = N.getOperand(4);
793   return true;
794 }
795
796 /// Return true if this is a SetCC-equivalent operation with only one use.
797 /// If this is true, it allows the users to invert the operation for free when
798 /// it is profitable to do so.
799 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
800   SDValue N0, N1, N2;
801   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
802     return true;
803   return false;
804 }
805
806 // \brief Returns the SDNode if it is a constant float BuildVector
807 // or constant float.
808 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
809   if (isa<ConstantFPSDNode>(N))
810     return N.getNode();
811   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
812     return N.getNode();
813   return nullptr;
814 }
815
816 // Determines if it is a constant integer or a build vector of constant
817 // integers (and undefs).
818 // Do not permit build vector implicit truncation.
819 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
820   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
821     return !(Const->isOpaque() && NoOpaques);
822   if (N.getOpcode() != ISD::BUILD_VECTOR)
823     return false;
824   unsigned BitWidth = N.getScalarValueSizeInBits();
825   for (const SDValue &Op : N->op_values()) {
826     if (Op.isUndef())
827       continue;
828     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
829     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
830         (Const->isOpaque() && NoOpaques))
831       return false;
832   }
833   return true;
834 }
835
836 // Determines if it is a constant null integer or a splatted vector of a
837 // constant null integer (with no undefs).
838 // Build vector implicit truncation is not an issue for null values.
839 static bool isNullConstantOrNullSplatConstant(SDValue N) {
840   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
841     return Splat->isNullValue();
842   return false;
843 }
844
845 // Determines if it is a constant integer of one or a splatted vector of a
846 // constant integer of one (with no undefs).
847 // Do not permit build vector implicit truncation.
848 static bool isOneConstantOrOneSplatConstant(SDValue N) {
849   unsigned BitWidth = N.getScalarValueSizeInBits();
850   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
851     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
852   return false;
853 }
854
855 // Determines if it is a constant integer of all ones or a splatted vector of a
856 // constant integer of all ones (with no undefs).
857 // Do not permit build vector implicit truncation.
858 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
859   unsigned BitWidth = N.getScalarValueSizeInBits();
860   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
861     return Splat->isAllOnesValue() &&
862            Splat->getAPIntValue().getBitWidth() == BitWidth;
863   return false;
864 }
865
866 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
867 // undef's.
868 static bool isAnyConstantBuildVector(const SDNode *N) {
869   return ISD::isBuildVectorOfConstantSDNodes(N) ||
870          ISD::isBuildVectorOfConstantFPSDNodes(N);
871 }
872
873 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
874                                     SDValue N1) {
875   EVT VT = N0.getValueType();
876   if (N0.getOpcode() == Opc) {
877     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
878       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
879         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
880         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
881           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
882         return SDValue();
883       }
884       if (N0.hasOneUse()) {
885         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
886         // use
887         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
888         if (!OpNode.getNode())
889           return SDValue();
890         AddToWorklist(OpNode.getNode());
891         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
892       }
893     }
894   }
895
896   if (N1.getOpcode() == Opc) {
897     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
898       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
899         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
900         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
901           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
902         return SDValue();
903       }
904       if (N1.hasOneUse()) {
905         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
906         // use
907         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
908         if (!OpNode.getNode())
909           return SDValue();
910         AddToWorklist(OpNode.getNode());
911         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
912       }
913     }
914   }
915
916   return SDValue();
917 }
918
919 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
920                                bool AddTo) {
921   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
922   ++NodesCombined;
923   DEBUG(dbgs() << "\nReplacing.1 ";
924         N->dump(&DAG);
925         dbgs() << "\nWith: ";
926         To[0].getNode()->dump(&DAG);
927         dbgs() << " and " << NumTo-1 << " other values\n");
928   for (unsigned i = 0, e = NumTo; i != e; ++i)
929     assert((!To[i].getNode() ||
930             N->getValueType(i) == To[i].getValueType()) &&
931            "Cannot combine value to value of different type!");
932
933   WorklistRemover DeadNodes(*this);
934   DAG.ReplaceAllUsesWith(N, To);
935   if (AddTo) {
936     // Push the new nodes and any users onto the worklist
937     for (unsigned i = 0, e = NumTo; i != e; ++i) {
938       if (To[i].getNode()) {
939         AddToWorklist(To[i].getNode());
940         AddUsersToWorklist(To[i].getNode());
941       }
942     }
943   }
944
945   // Finally, if the node is now dead, remove it from the graph.  The node
946   // may not be dead if the replacement process recursively simplified to
947   // something else needing this node.
948   if (N->use_empty())
949     deleteAndRecombine(N);
950   return SDValue(N, 0);
951 }
952
953 void DAGCombiner::
954 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
955   // Replace all uses.  If any nodes become isomorphic to other nodes and
956   // are deleted, make sure to remove them from our worklist.
957   WorklistRemover DeadNodes(*this);
958   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
959
960   // Push the new node and any (possibly new) users onto the worklist.
961   AddToWorklist(TLO.New.getNode());
962   AddUsersToWorklist(TLO.New.getNode());
963
964   // Finally, if the node is now dead, remove it from the graph.  The node
965   // may not be dead if the replacement process recursively simplified to
966   // something else needing this node.
967   if (TLO.Old.getNode()->use_empty())
968     deleteAndRecombine(TLO.Old.getNode());
969 }
970
971 /// Check the specified integer node value to see if it can be simplified or if
972 /// things it uses can be simplified by bit propagation. If so, return true.
973 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
974   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
975   KnownBits Known;
976   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
977     return false;
978
979   // Revisit the node.
980   AddToWorklist(Op.getNode());
981
982   // Replace the old value with the new one.
983   ++NodesCombined;
984   DEBUG(dbgs() << "\nReplacing.2 ";
985         TLO.Old.getNode()->dump(&DAG);
986         dbgs() << "\nWith: ";
987         TLO.New.getNode()->dump(&DAG);
988         dbgs() << '\n');
989
990   CommitTargetLoweringOpt(TLO);
991   return true;
992 }
993
994 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
995   SDLoc DL(Load);
996   EVT VT = Load->getValueType(0);
997   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
998
999   DEBUG(dbgs() << "\nReplacing.9 ";
1000         Load->dump(&DAG);
1001         dbgs() << "\nWith: ";
1002         Trunc.getNode()->dump(&DAG);
1003         dbgs() << '\n');
1004   WorklistRemover DeadNodes(*this);
1005   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1006   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1007   deleteAndRecombine(Load);
1008   AddToWorklist(Trunc.getNode());
1009 }
1010
1011 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1012   Replace = false;
1013   SDLoc DL(Op);
1014   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1015     LoadSDNode *LD = cast<LoadSDNode>(Op);
1016     EVT MemVT = LD->getMemoryVT();
1017     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1018       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1019                                                        : ISD::EXTLOAD)
1020       : LD->getExtensionType();
1021     Replace = true;
1022     return DAG.getExtLoad(ExtType, DL, PVT,
1023                           LD->getChain(), LD->getBasePtr(),
1024                           MemVT, LD->getMemOperand());
1025   }
1026
1027   unsigned Opc = Op.getOpcode();
1028   switch (Opc) {
1029   default: break;
1030   case ISD::AssertSext:
1031     return DAG.getNode(ISD::AssertSext, DL, PVT,
1032                        SExtPromoteOperand(Op.getOperand(0), PVT),
1033                        Op.getOperand(1));
1034   case ISD::AssertZext:
1035     return DAG.getNode(ISD::AssertZext, DL, PVT,
1036                        ZExtPromoteOperand(Op.getOperand(0), PVT),
1037                        Op.getOperand(1));
1038   case ISD::Constant: {
1039     unsigned ExtOpc =
1040       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1041     return DAG.getNode(ExtOpc, DL, PVT, Op);
1042   }
1043   }
1044
1045   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1046     return SDValue();
1047   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1048 }
1049
1050 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1051   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1052     return SDValue();
1053   EVT OldVT = Op.getValueType();
1054   SDLoc DL(Op);
1055   bool Replace = false;
1056   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1057   if (!NewOp.getNode())
1058     return SDValue();
1059   AddToWorklist(NewOp.getNode());
1060
1061   if (Replace)
1062     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1063   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1064                      DAG.getValueType(OldVT));
1065 }
1066
1067 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1068   EVT OldVT = Op.getValueType();
1069   SDLoc DL(Op);
1070   bool Replace = false;
1071   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1072   if (!NewOp.getNode())
1073     return SDValue();
1074   AddToWorklist(NewOp.getNode());
1075
1076   if (Replace)
1077     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1078   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1079 }
1080
1081 /// Promote the specified integer binary operation if the target indicates it is
1082 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1083 /// i32 since i16 instructions are longer.
1084 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1085   if (!LegalOperations)
1086     return SDValue();
1087
1088   EVT VT = Op.getValueType();
1089   if (VT.isVector() || !VT.isInteger())
1090     return SDValue();
1091
1092   // If operation type is 'undesirable', e.g. i16 on x86, consider
1093   // promoting it.
1094   unsigned Opc = Op.getOpcode();
1095   if (TLI.isTypeDesirableForOp(Opc, VT))
1096     return SDValue();
1097
1098   EVT PVT = VT;
1099   // Consult target whether it is a good idea to promote this operation and
1100   // what's the right type to promote it to.
1101   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1102     assert(PVT != VT && "Don't know what type to promote to!");
1103
1104     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1105
1106     bool Replace0 = false;
1107     SDValue N0 = Op.getOperand(0);
1108     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1109
1110     bool Replace1 = false;
1111     SDValue N1 = Op.getOperand(1);
1112     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1113     SDLoc DL(Op);
1114
1115     SDValue RV =
1116         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1117
1118     // New replace instances of N0 and N1
1119     if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 &&
1120         NN0.getOpcode() != ISD::DELETED_NODE) {
1121       AddToWorklist(NN0.getNode());
1122       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1123     }
1124
1125     if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 &&
1126         NN1.getOpcode() != ISD::DELETED_NODE) {
1127       AddToWorklist(NN1.getNode());
1128       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1129     }
1130
1131     // Deal with Op being deleted.
1132     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1133       return RV;
1134   }
1135   return SDValue();
1136 }
1137
1138 /// Promote the specified integer shift operation if the target indicates it is
1139 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1140 /// i32 since i16 instructions are longer.
1141 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1142   if (!LegalOperations)
1143     return SDValue();
1144
1145   EVT VT = Op.getValueType();
1146   if (VT.isVector() || !VT.isInteger())
1147     return SDValue();
1148
1149   // If operation type is 'undesirable', e.g. i16 on x86, consider
1150   // promoting it.
1151   unsigned Opc = Op.getOpcode();
1152   if (TLI.isTypeDesirableForOp(Opc, VT))
1153     return SDValue();
1154
1155   EVT PVT = VT;
1156   // Consult target whether it is a good idea to promote this operation and
1157   // what's the right type to promote it to.
1158   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1159     assert(PVT != VT && "Don't know what type to promote to!");
1160
1161     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1162
1163     bool Replace = false;
1164     SDValue N0 = Op.getOperand(0);
1165     SDValue N1 = Op.getOperand(1);
1166     if (Opc == ISD::SRA)
1167       N0 = SExtPromoteOperand(N0, PVT);
1168     else if (Opc == ISD::SRL)
1169       N0 = ZExtPromoteOperand(N0, PVT);
1170     else
1171       N0 = PromoteOperand(N0, PVT, Replace);
1172
1173     if (!N0.getNode())
1174       return SDValue();
1175
1176     SDLoc DL(Op);
1177     SDValue RV =
1178         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1179
1180     AddToWorklist(N0.getNode());
1181     if (Replace)
1182       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1183
1184     // Deal with Op being deleted.
1185     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1186       return RV;
1187   }
1188   return SDValue();
1189 }
1190
1191 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1192   if (!LegalOperations)
1193     return SDValue();
1194
1195   EVT VT = Op.getValueType();
1196   if (VT.isVector() || !VT.isInteger())
1197     return SDValue();
1198
1199   // If operation type is 'undesirable', e.g. i16 on x86, consider
1200   // promoting it.
1201   unsigned Opc = Op.getOpcode();
1202   if (TLI.isTypeDesirableForOp(Opc, VT))
1203     return SDValue();
1204
1205   EVT PVT = VT;
1206   // Consult target whether it is a good idea to promote this operation and
1207   // what's the right type to promote it to.
1208   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1209     assert(PVT != VT && "Don't know what type to promote to!");
1210     // fold (aext (aext x)) -> (aext x)
1211     // fold (aext (zext x)) -> (zext x)
1212     // fold (aext (sext x)) -> (sext x)
1213     DEBUG(dbgs() << "\nPromoting ";
1214           Op.getNode()->dump(&DAG));
1215     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1216   }
1217   return SDValue();
1218 }
1219
1220 bool DAGCombiner::PromoteLoad(SDValue Op) {
1221   if (!LegalOperations)
1222     return false;
1223
1224   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1225     return false;
1226
1227   EVT VT = Op.getValueType();
1228   if (VT.isVector() || !VT.isInteger())
1229     return false;
1230
1231   // If operation type is 'undesirable', e.g. i16 on x86, consider
1232   // promoting it.
1233   unsigned Opc = Op.getOpcode();
1234   if (TLI.isTypeDesirableForOp(Opc, VT))
1235     return false;
1236
1237   EVT PVT = VT;
1238   // Consult target whether it is a good idea to promote this operation and
1239   // what's the right type to promote it to.
1240   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1241     assert(PVT != VT && "Don't know what type to promote to!");
1242
1243     SDLoc DL(Op);
1244     SDNode *N = Op.getNode();
1245     LoadSDNode *LD = cast<LoadSDNode>(N);
1246     EVT MemVT = LD->getMemoryVT();
1247     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1248       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1249                                                        : ISD::EXTLOAD)
1250       : LD->getExtensionType();
1251     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1252                                    LD->getChain(), LD->getBasePtr(),
1253                                    MemVT, LD->getMemOperand());
1254     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1255
1256     DEBUG(dbgs() << "\nPromoting ";
1257           N->dump(&DAG);
1258           dbgs() << "\nTo: ";
1259           Result.getNode()->dump(&DAG);
1260           dbgs() << '\n');
1261     WorklistRemover DeadNodes(*this);
1262     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1263     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1264     deleteAndRecombine(N);
1265     AddToWorklist(Result.getNode());
1266     return true;
1267   }
1268   return false;
1269 }
1270
1271 /// \brief Recursively delete a node which has no uses and any operands for
1272 /// which it is the only use.
1273 ///
1274 /// Note that this both deletes the nodes and removes them from the worklist.
1275 /// It also adds any nodes who have had a user deleted to the worklist as they
1276 /// may now have only one use and subject to other combines.
1277 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1278   if (!N->use_empty())
1279     return false;
1280
1281   SmallSetVector<SDNode *, 16> Nodes;
1282   Nodes.insert(N);
1283   do {
1284     N = Nodes.pop_back_val();
1285     if (!N)
1286       continue;
1287
1288     if (N->use_empty()) {
1289       for (const SDValue &ChildN : N->op_values())
1290         Nodes.insert(ChildN.getNode());
1291
1292       removeFromWorklist(N);
1293       DAG.DeleteNode(N);
1294     } else {
1295       AddToWorklist(N);
1296     }
1297   } while (!Nodes.empty());
1298   return true;
1299 }
1300
1301 //===----------------------------------------------------------------------===//
1302 //  Main DAG Combiner implementation
1303 //===----------------------------------------------------------------------===//
1304
1305 void DAGCombiner::Run(CombineLevel AtLevel) {
1306   // set the instance variables, so that the various visit routines may use it.
1307   Level = AtLevel;
1308   LegalOperations = Level >= AfterLegalizeVectorOps;
1309   LegalTypes = Level >= AfterLegalizeTypes;
1310
1311   // Add all the dag nodes to the worklist.
1312   for (SDNode &Node : DAG.allnodes())
1313     AddToWorklist(&Node);
1314
1315   // Create a dummy node (which is not added to allnodes), that adds a reference
1316   // to the root node, preventing it from being deleted, and tracking any
1317   // changes of the root.
1318   HandleSDNode Dummy(DAG.getRoot());
1319
1320   // While the worklist isn't empty, find a node and try to combine it.
1321   while (!WorklistMap.empty()) {
1322     SDNode *N;
1323     // The Worklist holds the SDNodes in order, but it may contain null entries.
1324     do {
1325       N = Worklist.pop_back_val();
1326     } while (!N);
1327
1328     bool GoodWorklistEntry = WorklistMap.erase(N);
1329     (void)GoodWorklistEntry;
1330     assert(GoodWorklistEntry &&
1331            "Found a worklist entry without a corresponding map entry!");
1332
1333     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1334     // N is deleted from the DAG, since they too may now be dead or may have a
1335     // reduced number of uses, allowing other xforms.
1336     if (recursivelyDeleteUnusedNodes(N))
1337       continue;
1338
1339     WorklistRemover DeadNodes(*this);
1340
1341     // If this combine is running after legalizing the DAG, re-legalize any
1342     // nodes pulled off the worklist.
1343     if (Level == AfterLegalizeDAG) {
1344       SmallSetVector<SDNode *, 16> UpdatedNodes;
1345       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1346
1347       for (SDNode *LN : UpdatedNodes) {
1348         AddToWorklist(LN);
1349         AddUsersToWorklist(LN);
1350       }
1351       if (!NIsValid)
1352         continue;
1353     }
1354
1355     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1356
1357     // Add any operands of the new node which have not yet been combined to the
1358     // worklist as well. Because the worklist uniques things already, this
1359     // won't repeatedly process the same operand.
1360     CombinedNodes.insert(N);
1361     for (const SDValue &ChildN : N->op_values())
1362       if (!CombinedNodes.count(ChildN.getNode()))
1363         AddToWorklist(ChildN.getNode());
1364
1365     SDValue RV = combine(N);
1366
1367     if (!RV.getNode())
1368       continue;
1369
1370     ++NodesCombined;
1371
1372     // If we get back the same node we passed in, rather than a new node or
1373     // zero, we know that the node must have defined multiple values and
1374     // CombineTo was used.  Since CombineTo takes care of the worklist
1375     // mechanics for us, we have no work to do in this case.
1376     if (RV.getNode() == N)
1377       continue;
1378
1379     assert(N->getOpcode() != ISD::DELETED_NODE &&
1380            RV.getOpcode() != ISD::DELETED_NODE &&
1381            "Node was deleted but visit returned new node!");
1382
1383     DEBUG(dbgs() << " ... into: ";
1384           RV.getNode()->dump(&DAG));
1385
1386     if (N->getNumValues() == RV.getNode()->getNumValues())
1387       DAG.ReplaceAllUsesWith(N, RV.getNode());
1388     else {
1389       assert(N->getValueType(0) == RV.getValueType() &&
1390              N->getNumValues() == 1 && "Type mismatch");
1391       DAG.ReplaceAllUsesWith(N, &RV);
1392     }
1393
1394     // Push the new node and any users onto the worklist
1395     AddToWorklist(RV.getNode());
1396     AddUsersToWorklist(RV.getNode());
1397
1398     // Finally, if the node is now dead, remove it from the graph.  The node
1399     // may not be dead if the replacement process recursively simplified to
1400     // something else needing this node. This will also take care of adding any
1401     // operands which have lost a user to the worklist.
1402     recursivelyDeleteUnusedNodes(N);
1403   }
1404
1405   // If the root changed (e.g. it was a dead load, update the root).
1406   DAG.setRoot(Dummy.getValue());
1407   DAG.RemoveDeadNodes();
1408 }
1409
1410 SDValue DAGCombiner::visit(SDNode *N) {
1411   switch (N->getOpcode()) {
1412   default: break;
1413   case ISD::TokenFactor:        return visitTokenFactor(N);
1414   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1415   case ISD::ADD:                return visitADD(N);
1416   case ISD::SUB:                return visitSUB(N);
1417   case ISD::ADDC:               return visitADDC(N);
1418   case ISD::UADDO:              return visitUADDO(N);
1419   case ISD::SUBC:               return visitSUBC(N);
1420   case ISD::USUBO:              return visitUSUBO(N);
1421   case ISD::ADDE:               return visitADDE(N);
1422   case ISD::ADDCARRY:           return visitADDCARRY(N);
1423   case ISD::SUBE:               return visitSUBE(N);
1424   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1425   case ISD::MUL:                return visitMUL(N);
1426   case ISD::SDIV:               return visitSDIV(N);
1427   case ISD::UDIV:               return visitUDIV(N);
1428   case ISD::SREM:
1429   case ISD::UREM:               return visitREM(N);
1430   case ISD::MULHU:              return visitMULHU(N);
1431   case ISD::MULHS:              return visitMULHS(N);
1432   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1433   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1434   case ISD::SMULO:              return visitSMULO(N);
1435   case ISD::UMULO:              return visitUMULO(N);
1436   case ISD::SMIN:
1437   case ISD::SMAX:
1438   case ISD::UMIN:
1439   case ISD::UMAX:               return visitIMINMAX(N);
1440   case ISD::AND:                return visitAND(N);
1441   case ISD::OR:                 return visitOR(N);
1442   case ISD::XOR:                return visitXOR(N);
1443   case ISD::SHL:                return visitSHL(N);
1444   case ISD::SRA:                return visitSRA(N);
1445   case ISD::SRL:                return visitSRL(N);
1446   case ISD::ROTR:
1447   case ISD::ROTL:               return visitRotate(N);
1448   case ISD::ABS:                return visitABS(N);
1449   case ISD::BSWAP:              return visitBSWAP(N);
1450   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1451   case ISD::CTLZ:               return visitCTLZ(N);
1452   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1453   case ISD::CTTZ:               return visitCTTZ(N);
1454   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1455   case ISD::CTPOP:              return visitCTPOP(N);
1456   case ISD::SELECT:             return visitSELECT(N);
1457   case ISD::VSELECT:            return visitVSELECT(N);
1458   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1459   case ISD::SETCC:              return visitSETCC(N);
1460   case ISD::SETCCE:             return visitSETCCE(N);
1461   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1462   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1463   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1464   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1465   case ISD::AssertZext:         return visitAssertZext(N);
1466   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1467   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1468   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1469   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1470   case ISD::BITCAST:            return visitBITCAST(N);
1471   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1472   case ISD::FADD:               return visitFADD(N);
1473   case ISD::FSUB:               return visitFSUB(N);
1474   case ISD::FMUL:               return visitFMUL(N);
1475   case ISD::FMA:                return visitFMA(N);
1476   case ISD::FDIV:               return visitFDIV(N);
1477   case ISD::FREM:               return visitFREM(N);
1478   case ISD::FSQRT:              return visitFSQRT(N);
1479   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1480   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1481   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1482   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1483   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1484   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1485   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1486   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1487   case ISD::FNEG:               return visitFNEG(N);
1488   case ISD::FABS:               return visitFABS(N);
1489   case ISD::FFLOOR:             return visitFFLOOR(N);
1490   case ISD::FMINNUM:            return visitFMINNUM(N);
1491   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1492   case ISD::FCEIL:              return visitFCEIL(N);
1493   case ISD::FTRUNC:             return visitFTRUNC(N);
1494   case ISD::BRCOND:             return visitBRCOND(N);
1495   case ISD::BR_CC:              return visitBR_CC(N);
1496   case ISD::LOAD:               return visitLOAD(N);
1497   case ISD::STORE:              return visitSTORE(N);
1498   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1499   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1500   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1501   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1502   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1503   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1504   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1505   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1506   case ISD::MGATHER:            return visitMGATHER(N);
1507   case ISD::MLOAD:              return visitMLOAD(N);
1508   case ISD::MSCATTER:           return visitMSCATTER(N);
1509   case ISD::MSTORE:             return visitMSTORE(N);
1510   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1511   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1512   }
1513   return SDValue();
1514 }
1515
1516 SDValue DAGCombiner::combine(SDNode *N) {
1517   SDValue RV = visit(N);
1518
1519   // If nothing happened, try a target-specific DAG combine.
1520   if (!RV.getNode()) {
1521     assert(N->getOpcode() != ISD::DELETED_NODE &&
1522            "Node was deleted but visit returned NULL!");
1523
1524     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1525         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1526
1527       // Expose the DAG combiner to the target combiner impls.
1528       TargetLowering::DAGCombinerInfo
1529         DagCombineInfo(DAG, Level, false, this);
1530
1531       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1532     }
1533   }
1534
1535   // If nothing happened still, try promoting the operation.
1536   if (!RV.getNode()) {
1537     switch (N->getOpcode()) {
1538     default: break;
1539     case ISD::ADD:
1540     case ISD::SUB:
1541     case ISD::MUL:
1542     case ISD::AND:
1543     case ISD::OR:
1544     case ISD::XOR:
1545       RV = PromoteIntBinOp(SDValue(N, 0));
1546       break;
1547     case ISD::SHL:
1548     case ISD::SRA:
1549     case ISD::SRL:
1550       RV = PromoteIntShiftOp(SDValue(N, 0));
1551       break;
1552     case ISD::SIGN_EXTEND:
1553     case ISD::ZERO_EXTEND:
1554     case ISD::ANY_EXTEND:
1555       RV = PromoteExtend(SDValue(N, 0));
1556       break;
1557     case ISD::LOAD:
1558       if (PromoteLoad(SDValue(N, 0)))
1559         RV = SDValue(N, 0);
1560       break;
1561     }
1562   }
1563
1564   // If N is a commutative binary node, try commuting it to enable more
1565   // sdisel CSE.
1566   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1567       N->getNumValues() == 1) {
1568     SDValue N0 = N->getOperand(0);
1569     SDValue N1 = N->getOperand(1);
1570
1571     // Constant operands are canonicalized to RHS.
1572     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1573       SDValue Ops[] = {N1, N0};
1574       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1575                                             N->getFlags());
1576       if (CSENode)
1577         return SDValue(CSENode, 0);
1578     }
1579   }
1580
1581   return RV;
1582 }
1583
1584 /// Given a node, return its input chain if it has one, otherwise return a null
1585 /// sd operand.
1586 static SDValue getInputChainForNode(SDNode *N) {
1587   if (unsigned NumOps = N->getNumOperands()) {
1588     if (N->getOperand(0).getValueType() == MVT::Other)
1589       return N->getOperand(0);
1590     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1591       return N->getOperand(NumOps-1);
1592     for (unsigned i = 1; i < NumOps-1; ++i)
1593       if (N->getOperand(i).getValueType() == MVT::Other)
1594         return N->getOperand(i);
1595   }
1596   return SDValue();
1597 }
1598
1599 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1600   // If N has two operands, where one has an input chain equal to the other,
1601   // the 'other' chain is redundant.
1602   if (N->getNumOperands() == 2) {
1603     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1604       return N->getOperand(0);
1605     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1606       return N->getOperand(1);
1607   }
1608
1609   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1610   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1611   SmallPtrSet<SDNode*, 16> SeenOps;
1612   bool Changed = false;             // If we should replace this token factor.
1613
1614   // Start out with this token factor.
1615   TFs.push_back(N);
1616
1617   // Iterate through token factors.  The TFs grows when new token factors are
1618   // encountered.
1619   for (unsigned i = 0; i < TFs.size(); ++i) {
1620     SDNode *TF = TFs[i];
1621
1622     // Check each of the operands.
1623     for (const SDValue &Op : TF->op_values()) {
1624
1625       switch (Op.getOpcode()) {
1626       case ISD::EntryToken:
1627         // Entry tokens don't need to be added to the list. They are
1628         // redundant.
1629         Changed = true;
1630         break;
1631
1632       case ISD::TokenFactor:
1633         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1634           // Queue up for processing.
1635           TFs.push_back(Op.getNode());
1636           // Clean up in case the token factor is removed.
1637           AddToWorklist(Op.getNode());
1638           Changed = true;
1639           break;
1640         }
1641         LLVM_FALLTHROUGH;
1642
1643       default:
1644         // Only add if it isn't already in the list.
1645         if (SeenOps.insert(Op.getNode()).second)
1646           Ops.push_back(Op);
1647         else
1648           Changed = true;
1649         break;
1650       }
1651     }
1652   }
1653
1654   // Remove Nodes that are chained to another node in the list. Do so
1655   // by walking up chains breath-first stopping when we've seen
1656   // another operand. In general we must climb to the EntryNode, but we can exit
1657   // early if we find all remaining work is associated with just one operand as
1658   // no further pruning is possible.
1659
1660   // List of nodes to search through and original Ops from which they originate.
1661   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1662   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1663   SmallPtrSet<SDNode *, 16> SeenChains;
1664   bool DidPruneOps = false;
1665
1666   unsigned NumLeftToConsider = 0;
1667   for (const SDValue &Op : Ops) {
1668     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1669     OpWorkCount.push_back(1);
1670   }
1671
1672   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1673     // If this is an Op, we can remove the op from the list. Remark any
1674     // search associated with it as from the current OpNumber.
1675     if (SeenOps.count(Op) != 0) {
1676       Changed = true;
1677       DidPruneOps = true;
1678       unsigned OrigOpNumber = 0;
1679       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1680         OrigOpNumber++;
1681       assert((OrigOpNumber != Ops.size()) &&
1682              "expected to find TokenFactor Operand");
1683       // Re-mark worklist from OrigOpNumber to OpNumber
1684       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1685         if (Worklist[i].second == OrigOpNumber) {
1686           Worklist[i].second = OpNumber;
1687         }
1688       }
1689       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1690       OpWorkCount[OrigOpNumber] = 0;
1691       NumLeftToConsider--;
1692     }
1693     // Add if it's a new chain
1694     if (SeenChains.insert(Op).second) {
1695       OpWorkCount[OpNumber]++;
1696       Worklist.push_back(std::make_pair(Op, OpNumber));
1697     }
1698   };
1699
1700   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1701     // We need at least be consider at least 2 Ops to prune.
1702     if (NumLeftToConsider <= 1)
1703       break;
1704     auto CurNode = Worklist[i].first;
1705     auto CurOpNumber = Worklist[i].second;
1706     assert((OpWorkCount[CurOpNumber] > 0) &&
1707            "Node should not appear in worklist");
1708     switch (CurNode->getOpcode()) {
1709     case ISD::EntryToken:
1710       // Hitting EntryToken is the only way for the search to terminate without
1711       // hitting
1712       // another operand's search. Prevent us from marking this operand
1713       // considered.
1714       NumLeftToConsider++;
1715       break;
1716     case ISD::TokenFactor:
1717       for (const SDValue &Op : CurNode->op_values())
1718         AddToWorklist(i, Op.getNode(), CurOpNumber);
1719       break;
1720     case ISD::CopyFromReg:
1721     case ISD::CopyToReg:
1722       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1723       break;
1724     default:
1725       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1726         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1727       break;
1728     }
1729     OpWorkCount[CurOpNumber]--;
1730     if (OpWorkCount[CurOpNumber] == 0)
1731       NumLeftToConsider--;
1732   }
1733
1734   // If we've changed things around then replace token factor.
1735   if (Changed) {
1736     SDValue Result;
1737     if (Ops.empty()) {
1738       // The entry token is the only possible outcome.
1739       Result = DAG.getEntryNode();
1740     } else {
1741       if (DidPruneOps) {
1742         SmallVector<SDValue, 8> PrunedOps;
1743         //
1744         for (const SDValue &Op : Ops) {
1745           if (SeenChains.count(Op.getNode()) == 0)
1746             PrunedOps.push_back(Op);
1747         }
1748         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1749       } else {
1750         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1751       }
1752     }
1753     return Result;
1754   }
1755   return SDValue();
1756 }
1757
1758 /// MERGE_VALUES can always be eliminated.
1759 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1760   WorklistRemover DeadNodes(*this);
1761   // Replacing results may cause a different MERGE_VALUES to suddenly
1762   // be CSE'd with N, and carry its uses with it. Iterate until no
1763   // uses remain, to ensure that the node can be safely deleted.
1764   // First add the users of this node to the work list so that they
1765   // can be tried again once they have new operands.
1766   AddUsersToWorklist(N);
1767   do {
1768     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1769       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1770   } while (!N->use_empty());
1771   deleteAndRecombine(N);
1772   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1773 }
1774
1775 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1776 /// ConstantSDNode pointer else nullptr.
1777 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1778   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1779   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1780 }
1781
1782 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1783   auto BinOpcode = BO->getOpcode();
1784   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1785           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1786           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1787           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1788           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1789           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1790           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1791           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1792           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1793          "Unexpected binary operator");
1794
1795   // Bail out if any constants are opaque because we can't constant fold those.
1796   SDValue C1 = BO->getOperand(1);
1797   if (!isConstantOrConstantVector(C1, true) &&
1798       !isConstantFPBuildVectorOrConstantFP(C1))
1799     return SDValue();
1800
1801   // Don't do this unless the old select is going away. We want to eliminate the
1802   // binary operator, not replace a binop with a select.
1803   // TODO: Handle ISD::SELECT_CC.
1804   SDValue Sel = BO->getOperand(0);
1805   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1806     return SDValue();
1807
1808   SDValue CT = Sel.getOperand(1);
1809   if (!isConstantOrConstantVector(CT, true) &&
1810       !isConstantFPBuildVectorOrConstantFP(CT))
1811     return SDValue();
1812
1813   SDValue CF = Sel.getOperand(2);
1814   if (!isConstantOrConstantVector(CF, true) &&
1815       !isConstantFPBuildVectorOrConstantFP(CF))
1816     return SDValue();
1817
1818   // We have a select-of-constants followed by a binary operator with a
1819   // constant. Eliminate the binop by pulling the constant math into the select.
1820   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1821   EVT VT = Sel.getValueType();
1822   SDLoc DL(Sel);
1823   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1824   assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1825           isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1826          "Failed to constant fold a binop with constant operands");
1827
1828   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1829   assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1830           isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1831          "Failed to constant fold a binop with constant operands");
1832
1833   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1834 }
1835
1836 SDValue DAGCombiner::visitADD(SDNode *N) {
1837   SDValue N0 = N->getOperand(0);
1838   SDValue N1 = N->getOperand(1);
1839   EVT VT = N0.getValueType();
1840   SDLoc DL(N);
1841
1842   // fold vector ops
1843   if (VT.isVector()) {
1844     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1845       return FoldedVOp;
1846
1847     // fold (add x, 0) -> x, vector edition
1848     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1849       return N0;
1850     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1851       return N1;
1852   }
1853
1854   // fold (add x, undef) -> undef
1855   if (N0.isUndef())
1856     return N0;
1857
1858   if (N1.isUndef())
1859     return N1;
1860
1861   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1862     // canonicalize constant to RHS
1863     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1864       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1865     // fold (add c1, c2) -> c1+c2
1866     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1867                                       N1.getNode());
1868   }
1869
1870   // fold (add x, 0) -> x
1871   if (isNullConstant(N1))
1872     return N0;
1873
1874   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1875     // fold ((c1-A)+c2) -> (c1+c2)-A
1876     if (N0.getOpcode() == ISD::SUB &&
1877         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1878       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1879       return DAG.getNode(ISD::SUB, DL, VT,
1880                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1881                          N0.getOperand(1));
1882     }
1883
1884     // add (sext i1 X), 1 -> zext (not i1 X)
1885     // We don't transform this pattern:
1886     //   add (zext i1 X), -1 -> sext (not i1 X)
1887     // because most (?) targets generate better code for the zext form.
1888     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1889         isOneConstantOrOneSplatConstant(N1)) {
1890       SDValue X = N0.getOperand(0);
1891       if ((!LegalOperations ||
1892            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1893             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1894           X.getScalarValueSizeInBits() == 1) {
1895         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1896         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1897       }
1898     }
1899   }
1900
1901   if (SDValue NewSel = foldBinOpIntoSelect(N))
1902     return NewSel;
1903
1904   // reassociate add
1905   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1906     return RADD;
1907
1908   // fold ((0-A) + B) -> B-A
1909   if (N0.getOpcode() == ISD::SUB &&
1910       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1911     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1912
1913   // fold (A + (0-B)) -> A-B
1914   if (N1.getOpcode() == ISD::SUB &&
1915       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1916     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1917
1918   // fold (A+(B-A)) -> B
1919   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1920     return N1.getOperand(0);
1921
1922   // fold ((B-A)+A) -> B
1923   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1924     return N0.getOperand(0);
1925
1926   // fold (A+(B-(A+C))) to (B-C)
1927   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1928       N0 == N1.getOperand(1).getOperand(0))
1929     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1930                        N1.getOperand(1).getOperand(1));
1931
1932   // fold (A+(B-(C+A))) to (B-C)
1933   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1934       N0 == N1.getOperand(1).getOperand(1))
1935     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1936                        N1.getOperand(1).getOperand(0));
1937
1938   // fold (A+((B-A)+or-C)) to (B+or-C)
1939   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1940       N1.getOperand(0).getOpcode() == ISD::SUB &&
1941       N0 == N1.getOperand(0).getOperand(1))
1942     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1943                        N1.getOperand(1));
1944
1945   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1946   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1947     SDValue N00 = N0.getOperand(0);
1948     SDValue N01 = N0.getOperand(1);
1949     SDValue N10 = N1.getOperand(0);
1950     SDValue N11 = N1.getOperand(1);
1951
1952     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1953       return DAG.getNode(ISD::SUB, DL, VT,
1954                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1955                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1956   }
1957
1958   if (SimplifyDemandedBits(SDValue(N, 0)))
1959     return SDValue(N, 0);
1960
1961   // fold (a+b) -> (a|b) iff a and b share no bits.
1962   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1963       DAG.haveNoCommonBitsSet(N0, N1))
1964     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1965
1966   if (SDValue Combined = visitADDLike(N0, N1, N))
1967     return Combined;
1968
1969   if (SDValue Combined = visitADDLike(N1, N0, N))
1970     return Combined;
1971
1972   return SDValue();
1973 }
1974
1975 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
1976   bool Masked = false;
1977
1978   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
1979   while (true) {
1980     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
1981       V = V.getOperand(0);
1982       continue;
1983     }
1984
1985     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
1986       Masked = true;
1987       V = V.getOperand(0);
1988       continue;
1989     }
1990
1991     break;
1992   }
1993
1994   // If this is not a carry, return.
1995   if (V.getResNo() != 1)
1996     return SDValue();
1997
1998   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
1999       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2000     return SDValue();
2001
2002   // If the result is masked, then no matter what kind of bool it is we can
2003   // return. If it isn't, then we need to make sure the bool type is either 0 or
2004   // 1 and not other values.
2005   if (Masked ||
2006       TLI.getBooleanContents(V.getValueType()) ==
2007           TargetLoweringBase::ZeroOrOneBooleanContent)
2008     return V;
2009
2010   return SDValue();
2011 }
2012
2013 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2014   EVT VT = N0.getValueType();
2015   SDLoc DL(LocReference);
2016
2017   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2018   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2019       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2020     return DAG.getNode(ISD::SUB, DL, VT, N0,
2021                        DAG.getNode(ISD::SHL, DL, VT,
2022                                    N1.getOperand(0).getOperand(1),
2023                                    N1.getOperand(1)));
2024
2025   if (N1.getOpcode() == ISD::AND) {
2026     SDValue AndOp0 = N1.getOperand(0);
2027     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2028     unsigned DestBits = VT.getScalarSizeInBits();
2029
2030     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2031     // and similar xforms where the inner op is either ~0 or 0.
2032     if (NumSignBits == DestBits &&
2033         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2034       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2035   }
2036
2037   // add (sext i1), X -> sub X, (zext i1)
2038   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2039       N0.getOperand(0).getValueType() == MVT::i1 &&
2040       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2041     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2042     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2043   }
2044
2045   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2046   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2047     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2048     if (TN->getVT() == MVT::i1) {
2049       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2050                                  DAG.getConstant(1, DL, VT));
2051       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2052     }
2053   }
2054
2055   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2056   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)))
2057     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2058                        N0, N1.getOperand(0), N1.getOperand(2));
2059
2060   // (add X, Carry) -> (addcarry X, 0, Carry)
2061   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2062     if (SDValue Carry = getAsCarry(TLI, N1))
2063       return DAG.getNode(ISD::ADDCARRY, DL,
2064                          DAG.getVTList(VT, Carry.getValueType()), N0,
2065                          DAG.getConstant(0, DL, VT), Carry);
2066
2067   return SDValue();
2068 }
2069
2070 SDValue DAGCombiner::visitADDC(SDNode *N) {
2071   SDValue N0 = N->getOperand(0);
2072   SDValue N1 = N->getOperand(1);
2073   EVT VT = N0.getValueType();
2074   SDLoc DL(N);
2075
2076   // If the flag result is dead, turn this into an ADD.
2077   if (!N->hasAnyUseOfValue(1))
2078     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2079                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2080
2081   // canonicalize constant to RHS.
2082   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2083   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2084   if (N0C && !N1C)
2085     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2086
2087   // fold (addc x, 0) -> x + no carry out
2088   if (isNullConstant(N1))
2089     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2090                                         DL, MVT::Glue));
2091
2092   // If it cannot overflow, transform into an add.
2093   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2094     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2095                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2096
2097   return SDValue();
2098 }
2099
2100 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2101   SDValue N0 = N->getOperand(0);
2102   SDValue N1 = N->getOperand(1);
2103   EVT VT = N0.getValueType();
2104   if (VT.isVector())
2105     return SDValue();
2106
2107   EVT CarryVT = N->getValueType(1);
2108   SDLoc DL(N);
2109
2110   // If the flag result is dead, turn this into an ADD.
2111   if (!N->hasAnyUseOfValue(1))
2112     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2113                      DAG.getUNDEF(CarryVT));
2114
2115   // canonicalize constant to RHS.
2116   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2117   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2118   if (N0C && !N1C)
2119     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2120
2121   // fold (uaddo x, 0) -> x + no carry out
2122   if (isNullConstant(N1))
2123     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2124
2125   // If it cannot overflow, transform into an add.
2126   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2127     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2128                      DAG.getConstant(0, DL, CarryVT));
2129
2130   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2131     return Combined;
2132
2133   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2134     return Combined;
2135
2136   return SDValue();
2137 }
2138
2139 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2140   auto VT = N0.getValueType();
2141
2142   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2143   // If Y + 1 cannot overflow.
2144   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2145     SDValue Y = N1.getOperand(0);
2146     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2147     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2148       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2149                          N1.getOperand(2));
2150   }
2151
2152   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2153   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2154     if (SDValue Carry = getAsCarry(TLI, N1))
2155       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2156                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2157
2158   return SDValue();
2159 }
2160
2161 SDValue DAGCombiner::visitADDE(SDNode *N) {
2162   SDValue N0 = N->getOperand(0);
2163   SDValue N1 = N->getOperand(1);
2164   SDValue CarryIn = N->getOperand(2);
2165
2166   // canonicalize constant to RHS
2167   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2168   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2169   if (N0C && !N1C)
2170     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2171                        N1, N0, CarryIn);
2172
2173   // fold (adde x, y, false) -> (addc x, y)
2174   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2175     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2176
2177   return SDValue();
2178 }
2179
2180 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2181   SDValue N0 = N->getOperand(0);
2182   SDValue N1 = N->getOperand(1);
2183   SDValue CarryIn = N->getOperand(2);
2184   SDLoc DL(N);
2185
2186   // canonicalize constant to RHS
2187   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2188   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2189   if (N0C && !N1C)
2190     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2191
2192   // fold (addcarry x, y, false) -> (uaddo x, y)
2193   if (isNullConstant(CarryIn))
2194     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2195
2196   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2197   if (isNullConstant(N0) && isNullConstant(N1)) {
2198     EVT VT = N0.getValueType();
2199     EVT CarryVT = CarryIn.getValueType();
2200     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2201     AddToWorklist(CarryExt.getNode());
2202     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2203                                     DAG.getConstant(1, DL, VT)),
2204                      DAG.getConstant(0, DL, CarryVT));
2205   }
2206
2207   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2208     return Combined;
2209
2210   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2211     return Combined;
2212
2213   return SDValue();
2214 }
2215
2216 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2217                                        SDNode *N) {
2218   // Iff the flag result is dead:
2219   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2220   if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::UADDO) &&
2221       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2222     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2223                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2224
2225   /**
2226    * When one of the addcarry argument is itself a carry, we may be facing
2227    * a diamond carry propagation. In which case we try to transform the DAG
2228    * to ensure linear carry propagation if that is possible.
2229    *
2230    * We are trying to get:
2231    *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2232    */
2233   if (auto Y = getAsCarry(TLI, N1)) {
2234     /**
2235      *            (uaddo A, B)
2236      *             /       \
2237      *          Carry      Sum
2238      *            |          \
2239      *            | (addcarry *, 0, Z)
2240      *            |       /
2241      *             \   Carry
2242      *              |   /
2243      * (addcarry X, *, *)
2244      */
2245     if (Y.getOpcode() == ISD::UADDO &&
2246         CarryIn.getResNo() == 1 &&
2247         CarryIn.getOpcode() == ISD::ADDCARRY &&
2248         isNullConstant(CarryIn.getOperand(1)) &&
2249         CarryIn.getOperand(0) == Y.getValue(0)) {
2250       auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2251                               Y.getOperand(0), Y.getOperand(1),
2252                               CarryIn.getOperand(2));
2253       AddToWorklist(NewY.getNode());
2254       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2255                          DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2256                          NewY.getValue(1));
2257     }
2258   }
2259
2260   return SDValue();
2261 }
2262
2263 // Since it may not be valid to emit a fold to zero for vector initializers
2264 // check if we can before folding.
2265 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2266                              SelectionDAG &DAG, bool LegalOperations,
2267                              bool LegalTypes) {
2268   if (!VT.isVector())
2269     return DAG.getConstant(0, DL, VT);
2270   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2271     return DAG.getConstant(0, DL, VT);
2272   return SDValue();
2273 }
2274
2275 SDValue DAGCombiner::visitSUB(SDNode *N) {
2276   SDValue N0 = N->getOperand(0);
2277   SDValue N1 = N->getOperand(1);
2278   EVT VT = N0.getValueType();
2279   SDLoc DL(N);
2280
2281   // fold vector ops
2282   if (VT.isVector()) {
2283     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2284       return FoldedVOp;
2285
2286     // fold (sub x, 0) -> x, vector edition
2287     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2288       return N0;
2289   }
2290
2291   // fold (sub x, x) -> 0
2292   // FIXME: Refactor this and xor and other similar operations together.
2293   if (N0 == N1)
2294     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2295   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2296       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2297     // fold (sub c1, c2) -> c1-c2
2298     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2299                                       N1.getNode());
2300   }
2301
2302   if (SDValue NewSel = foldBinOpIntoSelect(N))
2303     return NewSel;
2304
2305   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2306
2307   // fold (sub x, c) -> (add x, -c)
2308   if (N1C) {
2309     return DAG.getNode(ISD::ADD, DL, VT, N0,
2310                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2311   }
2312
2313   if (isNullConstantOrNullSplatConstant(N0)) {
2314     unsigned BitWidth = VT.getScalarSizeInBits();
2315     // Right-shifting everything out but the sign bit followed by negation is
2316     // the same as flipping arithmetic/logical shift type without the negation:
2317     // -(X >>u 31) -> (X >>s 31)
2318     // -(X >>s 31) -> (X >>u 31)
2319     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2320       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2321       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2322         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2323         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2324           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2325       }
2326     }
2327
2328     // 0 - X --> 0 if the sub is NUW.
2329     if (N->getFlags().hasNoUnsignedWrap())
2330       return N0;
2331
2332     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2333       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2334       // N1 must be 0 because negating the minimum signed value is undefined.
2335       if (N->getFlags().hasNoSignedWrap())
2336         return N0;
2337
2338       // 0 - X --> X if X is 0 or the minimum signed value.
2339       return N1;
2340     }
2341   }
2342
2343   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2344   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2345     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2346
2347   // fold A-(A-B) -> B
2348   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2349     return N1.getOperand(1);
2350
2351   // fold (A+B)-A -> B
2352   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2353     return N0.getOperand(1);
2354
2355   // fold (A+B)-B -> A
2356   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2357     return N0.getOperand(0);
2358
2359   // fold C2-(A+C1) -> (C2-C1)-A
2360   if (N1.getOpcode() == ISD::ADD) {
2361     SDValue N11 = N1.getOperand(1);
2362     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2363         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2364       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2365       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2366     }
2367   }
2368
2369   // fold ((A+(B+or-C))-B) -> A+or-C
2370   if (N0.getOpcode() == ISD::ADD &&
2371       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2372        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2373       N0.getOperand(1).getOperand(0) == N1)
2374     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2375                        N0.getOperand(1).getOperand(1));
2376
2377   // fold ((A+(C+B))-B) -> A+C
2378   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2379       N0.getOperand(1).getOperand(1) == N1)
2380     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2381                        N0.getOperand(1).getOperand(0));
2382
2383   // fold ((A-(B-C))-C) -> A-B
2384   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2385       N0.getOperand(1).getOperand(1) == N1)
2386     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2387                        N0.getOperand(1).getOperand(0));
2388
2389   // If either operand of a sub is undef, the result is undef
2390   if (N0.isUndef())
2391     return N0;
2392   if (N1.isUndef())
2393     return N1;
2394
2395   // If the relocation model supports it, consider symbol offsets.
2396   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2397     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2398       // fold (sub Sym, c) -> Sym-c
2399       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2400         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2401                                     GA->getOffset() -
2402                                         (uint64_t)N1C->getSExtValue());
2403       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2404       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2405         if (GA->getGlobal() == GB->getGlobal())
2406           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2407                                  DL, VT);
2408     }
2409
2410   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2411   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2412     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2413     if (TN->getVT() == MVT::i1) {
2414       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2415                                  DAG.getConstant(1, DL, VT));
2416       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2417     }
2418   }
2419
2420   return SDValue();
2421 }
2422
2423 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2424   SDValue N0 = N->getOperand(0);
2425   SDValue N1 = N->getOperand(1);
2426   EVT VT = N0.getValueType();
2427   SDLoc DL(N);
2428
2429   // If the flag result is dead, turn this into an SUB.
2430   if (!N->hasAnyUseOfValue(1))
2431     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2432                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2433
2434   // fold (subc x, x) -> 0 + no borrow
2435   if (N0 == N1)
2436     return CombineTo(N, DAG.getConstant(0, DL, VT),
2437                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2438
2439   // fold (subc x, 0) -> x + no borrow
2440   if (isNullConstant(N1))
2441     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2442
2443   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2444   if (isAllOnesConstant(N0))
2445     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2446                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2447
2448   return SDValue();
2449 }
2450
2451 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2452   SDValue N0 = N->getOperand(0);
2453   SDValue N1 = N->getOperand(1);
2454   EVT VT = N0.getValueType();
2455   if (VT.isVector())
2456     return SDValue();
2457
2458   EVT CarryVT = N->getValueType(1);
2459   SDLoc DL(N);
2460
2461   // If the flag result is dead, turn this into an SUB.
2462   if (!N->hasAnyUseOfValue(1))
2463     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2464                      DAG.getUNDEF(CarryVT));
2465
2466   // fold (usubo x, x) -> 0 + no borrow
2467   if (N0 == N1)
2468     return CombineTo(N, DAG.getConstant(0, DL, VT),
2469                      DAG.getConstant(0, DL, CarryVT));
2470
2471   // fold (usubo x, 0) -> x + no borrow
2472   if (isNullConstant(N1))
2473     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2474
2475   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2476   if (isAllOnesConstant(N0))
2477     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2478                      DAG.getConstant(0, DL, CarryVT));
2479
2480   return SDValue();
2481 }
2482
2483 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2484   SDValue N0 = N->getOperand(0);
2485   SDValue N1 = N->getOperand(1);
2486   SDValue CarryIn = N->getOperand(2);
2487
2488   // fold (sube x, y, false) -> (subc x, y)
2489   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2490     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2491
2492   return SDValue();
2493 }
2494
2495 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2496   SDValue N0 = N->getOperand(0);
2497   SDValue N1 = N->getOperand(1);
2498   SDValue CarryIn = N->getOperand(2);
2499
2500   // fold (subcarry x, y, false) -> (usubo x, y)
2501   if (isNullConstant(CarryIn))
2502     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2503
2504   return SDValue();
2505 }
2506
2507 SDValue DAGCombiner::visitMUL(SDNode *N) {
2508   SDValue N0 = N->getOperand(0);
2509   SDValue N1 = N->getOperand(1);
2510   EVT VT = N0.getValueType();
2511
2512   // fold (mul x, undef) -> 0
2513   if (N0.isUndef() || N1.isUndef())
2514     return DAG.getConstant(0, SDLoc(N), VT);
2515
2516   bool N0IsConst = false;
2517   bool N1IsConst = false;
2518   bool N1IsOpaqueConst = false;
2519   bool N0IsOpaqueConst = false;
2520   APInt ConstValue0, ConstValue1;
2521   // fold vector ops
2522   if (VT.isVector()) {
2523     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2524       return FoldedVOp;
2525
2526     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2527     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2528   } else {
2529     N0IsConst = isa<ConstantSDNode>(N0);
2530     if (N0IsConst) {
2531       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2532       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2533     }
2534     N1IsConst = isa<ConstantSDNode>(N1);
2535     if (N1IsConst) {
2536       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2537       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2538     }
2539   }
2540
2541   // fold (mul c1, c2) -> c1*c2
2542   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2543     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2544                                       N0.getNode(), N1.getNode());
2545
2546   // canonicalize constant to RHS (vector doesn't have to splat)
2547   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2548      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2549     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2550   // fold (mul x, 0) -> 0
2551   if (N1IsConst && ConstValue1 == 0)
2552     return N1;
2553   // We require a splat of the entire scalar bit width for non-contiguous
2554   // bit patterns.
2555   bool IsFullSplat =
2556     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2557   // fold (mul x, 1) -> x
2558   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2559     return N0;
2560
2561   if (SDValue NewSel = foldBinOpIntoSelect(N))
2562     return NewSel;
2563
2564   // fold (mul x, -1) -> 0-x
2565   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2566     SDLoc DL(N);
2567     return DAG.getNode(ISD::SUB, DL, VT,
2568                        DAG.getConstant(0, DL, VT), N0);
2569   }
2570   // fold (mul x, (1 << c)) -> x << c
2571   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2572       IsFullSplat) {
2573     SDLoc DL(N);
2574     return DAG.getNode(ISD::SHL, DL, VT, N0,
2575                        DAG.getConstant(ConstValue1.logBase2(), DL,
2576                                        getShiftAmountTy(N0.getValueType())));
2577   }
2578   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2579   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2580       IsFullSplat) {
2581     unsigned Log2Val = (-ConstValue1).logBase2();
2582     SDLoc DL(N);
2583     // FIXME: If the input is something that is easily negated (e.g. a
2584     // single-use add), we should put the negate there.
2585     return DAG.getNode(ISD::SUB, DL, VT,
2586                        DAG.getConstant(0, DL, VT),
2587                        DAG.getNode(ISD::SHL, DL, VT, N0,
2588                             DAG.getConstant(Log2Val, DL,
2589                                       getShiftAmountTy(N0.getValueType()))));
2590   }
2591
2592   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2593   if (N0.getOpcode() == ISD::SHL &&
2594       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2595       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2596     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2597     if (isConstantOrConstantVector(C3))
2598       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2599   }
2600
2601   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2602   // use.
2603   {
2604     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2605
2606     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2607     if (N0.getOpcode() == ISD::SHL &&
2608         isConstantOrConstantVector(N0.getOperand(1)) &&
2609         N0.getNode()->hasOneUse()) {
2610       Sh = N0; Y = N1;
2611     } else if (N1.getOpcode() == ISD::SHL &&
2612                isConstantOrConstantVector(N1.getOperand(1)) &&
2613                N1.getNode()->hasOneUse()) {
2614       Sh = N1; Y = N0;
2615     }
2616
2617     if (Sh.getNode()) {
2618       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2619       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2620     }
2621   }
2622
2623   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2624   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2625       N0.getOpcode() == ISD::ADD &&
2626       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2627       isMulAddWithConstProfitable(N, N0, N1))
2628       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2629                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2630                                      N0.getOperand(0), N1),
2631                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2632                                      N0.getOperand(1), N1));
2633
2634   // reassociate mul
2635   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2636     return RMUL;
2637
2638   return SDValue();
2639 }
2640
2641 /// Return true if divmod libcall is available.
2642 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2643                                      const TargetLowering &TLI) {
2644   RTLIB::Libcall LC;
2645   EVT NodeType = Node->getValueType(0);
2646   if (!NodeType.isSimple())
2647     return false;
2648   switch (NodeType.getSimpleVT().SimpleTy) {
2649   default: return false; // No libcall for vector types.
2650   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2651   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2652   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2653   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2654   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2655   }
2656
2657   return TLI.getLibcallName(LC) != nullptr;
2658 }
2659
2660 /// Issue divrem if both quotient and remainder are needed.
2661 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2662   if (Node->use_empty())
2663     return SDValue(); // This is a dead node, leave it alone.
2664
2665   unsigned Opcode = Node->getOpcode();
2666   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2667   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2668
2669   // DivMod lib calls can still work on non-legal types if using lib-calls.
2670   EVT VT = Node->getValueType(0);
2671   if (VT.isVector() || !VT.isInteger())
2672     return SDValue();
2673
2674   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2675     return SDValue();
2676
2677   // If DIVREM is going to get expanded into a libcall,
2678   // but there is no libcall available, then don't combine.
2679   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2680       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2681     return SDValue();
2682
2683   // If div is legal, it's better to do the normal expansion
2684   unsigned OtherOpcode = 0;
2685   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2686     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2687     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2688       return SDValue();
2689   } else {
2690     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2691     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2692       return SDValue();
2693   }
2694
2695   SDValue Op0 = Node->getOperand(0);
2696   SDValue Op1 = Node->getOperand(1);
2697   SDValue combined;
2698   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2699          UE = Op0.getNode()->use_end(); UI != UE;) {
2700     SDNode *User = *UI++;
2701     if (User == Node || User->use_empty())
2702       continue;
2703     // Convert the other matching node(s), too;
2704     // otherwise, the DIVREM may get target-legalized into something
2705     // target-specific that we won't be able to recognize.
2706     unsigned UserOpc = User->getOpcode();
2707     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2708         User->getOperand(0) == Op0 &&
2709         User->getOperand(1) == Op1) {
2710       if (!combined) {
2711         if (UserOpc == OtherOpcode) {
2712           SDVTList VTs = DAG.getVTList(VT, VT);
2713           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2714         } else if (UserOpc == DivRemOpc) {
2715           combined = SDValue(User, 0);
2716         } else {
2717           assert(UserOpc == Opcode);
2718           continue;
2719         }
2720       }
2721       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2722         CombineTo(User, combined);
2723       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2724         CombineTo(User, combined.getValue(1));
2725     }
2726   }
2727   return combined;
2728 }
2729
2730 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2731   SDValue N0 = N->getOperand(0);
2732   SDValue N1 = N->getOperand(1);
2733   EVT VT = N->getValueType(0);
2734   SDLoc DL(N);
2735
2736   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2737     return DAG.getUNDEF(VT);
2738
2739   // undef / X -> 0
2740   // undef % X -> 0
2741   if (N0.isUndef())
2742     return DAG.getConstant(0, DL, VT);
2743
2744   return SDValue();
2745 }
2746
2747 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2748   SDValue N0 = N->getOperand(0);
2749   SDValue N1 = N->getOperand(1);
2750   EVT VT = N->getValueType(0);
2751
2752   // fold vector ops
2753   if (VT.isVector())
2754     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2755       return FoldedVOp;
2756
2757   SDLoc DL(N);
2758
2759   // fold (sdiv c1, c2) -> c1/c2
2760   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2761   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2762   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2763     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2764   // fold (sdiv X, 1) -> X
2765   if (N1C && N1C->isOne())
2766     return N0;
2767   // fold (sdiv X, -1) -> 0-X
2768   if (N1C && N1C->isAllOnesValue())
2769     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2770
2771   if (SDValue V = simplifyDivRem(N, DAG))
2772     return V;
2773
2774   if (SDValue NewSel = foldBinOpIntoSelect(N))
2775     return NewSel;
2776
2777   // If we know the sign bits of both operands are zero, strength reduce to a
2778   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2779   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2780     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2781
2782   // fold (sdiv X, pow2) -> simple ops after legalize
2783   // FIXME: We check for the exact bit here because the generic lowering gives
2784   // better results in that case. The target-specific lowering should learn how
2785   // to handle exact sdivs efficiently.
2786   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2787       !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2788                                     (-N1C->getAPIntValue()).isPowerOf2())) {
2789     // Target-specific implementation of sdiv x, pow2.
2790     if (SDValue Res = BuildSDIVPow2(N))
2791       return Res;
2792
2793     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2794
2795     // Splat the sign bit into the register
2796     SDValue SGN =
2797         DAG.getNode(ISD::SRA, DL, VT, N0,
2798                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2799                                     getShiftAmountTy(N0.getValueType())));
2800     AddToWorklist(SGN.getNode());
2801
2802     // Add (N0 < 0) ? abs2 - 1 : 0;
2803     SDValue SRL =
2804         DAG.getNode(ISD::SRL, DL, VT, SGN,
2805                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2806                                     getShiftAmountTy(SGN.getValueType())));
2807     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2808     AddToWorklist(SRL.getNode());
2809     AddToWorklist(ADD.getNode());    // Divide by pow2
2810     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2811                   DAG.getConstant(lg2, DL,
2812                                   getShiftAmountTy(ADD.getValueType())));
2813
2814     // If we're dividing by a positive value, we're done.  Otherwise, we must
2815     // negate the result.
2816     if (N1C->getAPIntValue().isNonNegative())
2817       return SRA;
2818
2819     AddToWorklist(SRA.getNode());
2820     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2821   }
2822
2823   // If integer divide is expensive and we satisfy the requirements, emit an
2824   // alternate sequence.  Targets may check function attributes for size/speed
2825   // trade-offs.
2826   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2827   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2828     if (SDValue Op = BuildSDIV(N))
2829       return Op;
2830
2831   // sdiv, srem -> sdivrem
2832   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2833   // true.  Otherwise, we break the simplification logic in visitREM().
2834   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2835     if (SDValue DivRem = useDivRem(N))
2836         return DivRem;
2837
2838   return SDValue();
2839 }
2840
2841 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2842   SDValue N0 = N->getOperand(0);
2843   SDValue N1 = N->getOperand(1);
2844   EVT VT = N->getValueType(0);
2845
2846   // fold vector ops
2847   if (VT.isVector())
2848     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2849       return FoldedVOp;
2850
2851   SDLoc DL(N);
2852
2853   // fold (udiv c1, c2) -> c1/c2
2854   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2855   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2856   if (N0C && N1C)
2857     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2858                                                     N0C, N1C))
2859       return Folded;
2860
2861   if (SDValue V = simplifyDivRem(N, DAG))
2862     return V;
2863
2864   if (SDValue NewSel = foldBinOpIntoSelect(N))
2865     return NewSel;
2866
2867   // fold (udiv x, (1 << c)) -> x >>u c
2868   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2869       DAG.isKnownToBeAPowerOfTwo(N1)) {
2870     SDValue LogBase2 = BuildLogBase2(N1, DL);
2871     AddToWorklist(LogBase2.getNode());
2872
2873     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2874     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2875     AddToWorklist(Trunc.getNode());
2876     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2877   }
2878
2879   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2880   if (N1.getOpcode() == ISD::SHL) {
2881     SDValue N10 = N1.getOperand(0);
2882     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2883         DAG.isKnownToBeAPowerOfTwo(N10)) {
2884       SDValue LogBase2 = BuildLogBase2(N10, DL);
2885       AddToWorklist(LogBase2.getNode());
2886
2887       EVT ADDVT = N1.getOperand(1).getValueType();
2888       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2889       AddToWorklist(Trunc.getNode());
2890       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2891       AddToWorklist(Add.getNode());
2892       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2893     }
2894   }
2895
2896   // fold (udiv x, c) -> alternate
2897   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2898   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2899     if (SDValue Op = BuildUDIV(N))
2900       return Op;
2901
2902   // sdiv, srem -> sdivrem
2903   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2904   // true.  Otherwise, we break the simplification logic in visitREM().
2905   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2906     if (SDValue DivRem = useDivRem(N))
2907         return DivRem;
2908
2909   return SDValue();
2910 }
2911
2912 // handles ISD::SREM and ISD::UREM
2913 SDValue DAGCombiner::visitREM(SDNode *N) {
2914   unsigned Opcode = N->getOpcode();
2915   SDValue N0 = N->getOperand(0);
2916   SDValue N1 = N->getOperand(1);
2917   EVT VT = N->getValueType(0);
2918   bool isSigned = (Opcode == ISD::SREM);
2919   SDLoc DL(N);
2920
2921   // fold (rem c1, c2) -> c1%c2
2922   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2923   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2924   if (N0C && N1C)
2925     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2926       return Folded;
2927
2928   if (SDValue V = simplifyDivRem(N, DAG))
2929     return V;
2930
2931   if (SDValue NewSel = foldBinOpIntoSelect(N))
2932     return NewSel;
2933
2934   if (isSigned) {
2935     // If we know the sign bits of both operands are zero, strength reduce to a
2936     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2937     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2938       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2939   } else {
2940     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
2941     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2942       // fold (urem x, pow2) -> (and x, pow2-1)
2943       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2944       AddToWorklist(Add.getNode());
2945       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2946     }
2947     if (N1.getOpcode() == ISD::SHL &&
2948         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2949       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2950       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2951       AddToWorklist(Add.getNode());
2952       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2953     }
2954   }
2955
2956   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2957
2958   // If X/C can be simplified by the division-by-constant logic, lower
2959   // X%C to the equivalent of X-X/C*C.
2960   // To avoid mangling nodes, this simplification requires that the combine()
2961   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2962   // against this by skipping the simplification if isIntDivCheap().  When
2963   // div is not cheap, combine will not return a DIVREM.  Regardless,
2964   // checking cheapness here makes sense since the simplification results in
2965   // fatter code.
2966   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2967     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2968     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2969     AddToWorklist(Div.getNode());
2970     SDValue OptimizedDiv = combine(Div.getNode());
2971     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2972       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2973              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2974       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2975       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2976       AddToWorklist(Mul.getNode());
2977       return Sub;
2978     }
2979   }
2980
2981   // sdiv, srem -> sdivrem
2982   if (SDValue DivRem = useDivRem(N))
2983     return DivRem.getValue(1);
2984
2985   return SDValue();
2986 }
2987
2988 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2989   SDValue N0 = N->getOperand(0);
2990   SDValue N1 = N->getOperand(1);
2991   EVT VT = N->getValueType(0);
2992   SDLoc DL(N);
2993
2994   // fold (mulhs x, 0) -> 0
2995   if (isNullConstant(N1))
2996     return N1;
2997   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2998   if (isOneConstant(N1)) {
2999     SDLoc DL(N);
3000     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3001                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3002                                        getShiftAmountTy(N0.getValueType())));
3003   }
3004   // fold (mulhs x, undef) -> 0
3005   if (N0.isUndef() || N1.isUndef())
3006     return DAG.getConstant(0, SDLoc(N), VT);
3007
3008   // If the type twice as wide is legal, transform the mulhs to a wider multiply
3009   // plus a shift.
3010   if (VT.isSimple() && !VT.isVector()) {
3011     MVT Simple = VT.getSimpleVT();
3012     unsigned SimpleSize = Simple.getSizeInBits();
3013     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3014     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3015       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3016       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3017       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3018       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3019             DAG.getConstant(SimpleSize, DL,
3020                             getShiftAmountTy(N1.getValueType())));
3021       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3022     }
3023   }
3024
3025   return SDValue();
3026 }
3027
3028 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3029   SDValue N0 = N->getOperand(0);
3030   SDValue N1 = N->getOperand(1);
3031   EVT VT = N->getValueType(0);
3032   SDLoc DL(N);
3033
3034   // fold (mulhu x, 0) -> 0
3035   if (isNullConstant(N1))
3036     return N1;
3037   // fold (mulhu x, 1) -> 0
3038   if (isOneConstant(N1))
3039     return DAG.getConstant(0, DL, N0.getValueType());
3040   // fold (mulhu x, undef) -> 0
3041   if (N0.isUndef() || N1.isUndef())
3042     return DAG.getConstant(0, DL, VT);
3043
3044   // If the type twice as wide is legal, transform the mulhu to a wider multiply
3045   // plus a shift.
3046   if (VT.isSimple() && !VT.isVector()) {
3047     MVT Simple = VT.getSimpleVT();
3048     unsigned SimpleSize = Simple.getSizeInBits();
3049     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3050     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3051       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3052       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3053       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3054       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3055             DAG.getConstant(SimpleSize, DL,
3056                             getShiftAmountTy(N1.getValueType())));
3057       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3058     }
3059   }
3060
3061   return SDValue();
3062 }
3063
3064 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3065 /// give the opcodes for the two computations that are being performed. Return
3066 /// true if a simplification was made.
3067 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3068                                                 unsigned HiOp) {
3069   // If the high half is not needed, just compute the low half.
3070   bool HiExists = N->hasAnyUseOfValue(1);
3071   if (!HiExists &&
3072       (!LegalOperations ||
3073        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3074     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3075     return CombineTo(N, Res, Res);
3076   }
3077
3078   // If the low half is not needed, just compute the high half.
3079   bool LoExists = N->hasAnyUseOfValue(0);
3080   if (!LoExists &&
3081       (!LegalOperations ||
3082        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3083     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3084     return CombineTo(N, Res, Res);
3085   }
3086
3087   // If both halves are used, return as it is.
3088   if (LoExists && HiExists)
3089     return SDValue();
3090
3091   // If the two computed results can be simplified separately, separate them.
3092   if (LoExists) {
3093     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3094     AddToWorklist(Lo.getNode());
3095     SDValue LoOpt = combine(Lo.getNode());
3096     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3097         (!LegalOperations ||
3098          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3099       return CombineTo(N, LoOpt, LoOpt);
3100   }
3101
3102   if (HiExists) {
3103     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3104     AddToWorklist(Hi.getNode());
3105     SDValue HiOpt = combine(Hi.getNode());
3106     if (HiOpt.getNode() && HiOpt != Hi &&
3107         (!LegalOperations ||
3108          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3109       return CombineTo(N, HiOpt, HiOpt);
3110   }
3111
3112   return SDValue();
3113 }
3114
3115 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3116   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3117     return Res;
3118
3119   EVT VT = N->getValueType(0);
3120   SDLoc DL(N);
3121
3122   // If the type is twice as wide is legal, transform the mulhu to a wider
3123   // multiply plus a shift.
3124   if (VT.isSimple() && !VT.isVector()) {
3125     MVT Simple = VT.getSimpleVT();
3126     unsigned SimpleSize = Simple.getSizeInBits();
3127     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3128     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3129       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3130       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3131       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3132       // Compute the high part as N1.
3133       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3134             DAG.getConstant(SimpleSize, DL,
3135                             getShiftAmountTy(Lo.getValueType())));
3136       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3137       // Compute the low part as N0.
3138       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3139       return CombineTo(N, Lo, Hi);
3140     }
3141   }
3142
3143   return SDValue();
3144 }
3145
3146 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3147   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3148     return Res;
3149
3150   EVT VT = N->getValueType(0);
3151   SDLoc DL(N);
3152
3153   // If the type is twice as wide is legal, transform the mulhu to a wider
3154   // multiply plus a shift.
3155   if (VT.isSimple() && !VT.isVector()) {
3156     MVT Simple = VT.getSimpleVT();
3157     unsigned SimpleSize = Simple.getSizeInBits();
3158     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3159     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3160       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3161       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3162       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3163       // Compute the high part as N1.
3164       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3165             DAG.getConstant(SimpleSize, DL,
3166                             getShiftAmountTy(Lo.getValueType())));
3167       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3168       // Compute the low part as N0.
3169       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3170       return CombineTo(N, Lo, Hi);
3171     }
3172   }
3173
3174   return SDValue();
3175 }
3176
3177 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3178   // (smulo x, 2) -> (saddo x, x)
3179   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3180     if (C2->getAPIntValue() == 2)
3181       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3182                          N->getOperand(0), N->getOperand(0));
3183
3184   return SDValue();
3185 }
3186
3187 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3188   // (umulo x, 2) -> (uaddo x, x)
3189   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3190     if (C2->getAPIntValue() == 2)
3191       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3192                          N->getOperand(0), N->getOperand(0));
3193
3194   return SDValue();
3195 }
3196
3197 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3198   SDValue N0 = N->getOperand(0);
3199   SDValue N1 = N->getOperand(1);
3200   EVT VT = N0.getValueType();
3201
3202   // fold vector ops
3203   if (VT.isVector())
3204     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3205       return FoldedVOp;
3206
3207   // fold (add c1, c2) -> c1+c2
3208   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3209   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3210   if (N0C && N1C)
3211     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3212
3213   // canonicalize constant to RHS
3214   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3215      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3216     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3217
3218   return SDValue();
3219 }
3220
3221 /// If this is a binary operator with two operands of the same opcode, try to
3222 /// simplify it.
3223 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3224   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3225   EVT VT = N0.getValueType();
3226   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3227
3228   // Bail early if none of these transforms apply.
3229   if (N0.getNumOperands() == 0) return SDValue();
3230
3231   // For each of OP in AND/OR/XOR:
3232   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3233   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3234   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3235   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3236   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3237   //
3238   // do not sink logical op inside of a vector extend, since it may combine
3239   // into a vsetcc.
3240   EVT Op0VT = N0.getOperand(0).getValueType();
3241   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3242        N0.getOpcode() == ISD::SIGN_EXTEND ||
3243        N0.getOpcode() == ISD::BSWAP ||
3244        // Avoid infinite looping with PromoteIntBinOp.
3245        (N0.getOpcode() == ISD::ANY_EXTEND &&
3246         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3247        (N0.getOpcode() == ISD::TRUNCATE &&
3248         (!TLI.isZExtFree(VT, Op0VT) ||
3249          !TLI.isTruncateFree(Op0VT, VT)) &&
3250         TLI.isTypeLegal(Op0VT))) &&
3251       !VT.isVector() &&
3252       Op0VT == N1.getOperand(0).getValueType() &&
3253       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3254     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3255                                  N0.getOperand(0).getValueType(),
3256                                  N0.getOperand(0), N1.getOperand(0));
3257     AddToWorklist(ORNode.getNode());
3258     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3259   }
3260
3261   // For each of OP in SHL/SRL/SRA/AND...
3262   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3263   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3264   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3265   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3266        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3267       N0.getOperand(1) == N1.getOperand(1)) {
3268     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3269                                  N0.getOperand(0).getValueType(),
3270                                  N0.getOperand(0), N1.getOperand(0));
3271     AddToWorklist(ORNode.getNode());
3272     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3273                        ORNode, N0.getOperand(1));
3274   }
3275
3276   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3277   // Only perform this optimization up until type legalization, before
3278   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3279   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3280   // we don't want to undo this promotion.
3281   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3282   // on scalars.
3283   if ((N0.getOpcode() == ISD::BITCAST ||
3284        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3285        Level <= AfterLegalizeTypes) {
3286     SDValue In0 = N0.getOperand(0);
3287     SDValue In1 = N1.getOperand(0);
3288     EVT In0Ty = In0.getValueType();
3289     EVT In1Ty = In1.getValueType();
3290     SDLoc DL(N);
3291     // If both incoming values are integers, and the original types are the
3292     // same.
3293     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3294       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3295       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3296       AddToWorklist(Op.getNode());
3297       return BC;
3298     }
3299   }
3300
3301   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3302   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3303   // If both shuffles use the same mask, and both shuffle within a single
3304   // vector, then it is worthwhile to move the swizzle after the operation.
3305   // The type-legalizer generates this pattern when loading illegal
3306   // vector types from memory. In many cases this allows additional shuffle
3307   // optimizations.
3308   // There are other cases where moving the shuffle after the xor/and/or
3309   // is profitable even if shuffles don't perform a swizzle.
3310   // If both shuffles use the same mask, and both shuffles have the same first
3311   // or second operand, then it might still be profitable to move the shuffle
3312   // after the xor/and/or operation.
3313   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3314     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3315     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3316
3317     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3318            "Inputs to shuffles are not the same type");
3319
3320     // Check that both shuffles use the same mask. The masks are known to be of
3321     // the same length because the result vector type is the same.
3322     // Check also that shuffles have only one use to avoid introducing extra
3323     // instructions.
3324     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3325         SVN0->getMask().equals(SVN1->getMask())) {
3326       SDValue ShOp = N0->getOperand(1);
3327
3328       // Don't try to fold this node if it requires introducing a
3329       // build vector of all zeros that might be illegal at this stage.
3330       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3331         if (!LegalTypes)
3332           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3333         else
3334           ShOp = SDValue();
3335       }
3336
3337       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3338       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3339       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3340       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3341         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3342                                       N0->getOperand(0), N1->getOperand(0));
3343         AddToWorklist(NewNode.getNode());
3344         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3345                                     SVN0->getMask());
3346       }
3347
3348       // Don't try to fold this node if it requires introducing a
3349       // build vector of all zeros that might be illegal at this stage.
3350       ShOp = N0->getOperand(0);
3351       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3352         if (!LegalTypes)
3353           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3354         else
3355           ShOp = SDValue();
3356       }
3357
3358       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3359       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3360       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3361       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3362         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3363                                       N0->getOperand(1), N1->getOperand(1));
3364         AddToWorklist(NewNode.getNode());
3365         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3366                                     SVN0->getMask());
3367       }
3368     }
3369   }
3370
3371   return SDValue();
3372 }
3373
3374 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3375 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3376                                        const SDLoc &DL) {
3377   SDValue LL, LR, RL, RR, N0CC, N1CC;
3378   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3379       !isSetCCEquivalent(N1, RL, RR, N1CC))
3380     return SDValue();
3381
3382   assert(N0.getValueType() == N1.getValueType() &&
3383          "Unexpected operand types for bitwise logic op");
3384   assert(LL.getValueType() == LR.getValueType() &&
3385          RL.getValueType() == RR.getValueType() &&
3386          "Unexpected operand types for setcc");
3387
3388   // If we're here post-legalization or the logic op type is not i1, the logic
3389   // op type must match a setcc result type. Also, all folds require new
3390   // operations on the left and right operands, so those types must match.
3391   EVT VT = N0.getValueType();
3392   EVT OpVT = LL.getValueType();
3393   if (LegalOperations || VT != MVT::i1)
3394     if (VT != getSetCCResultType(OpVT))
3395       return SDValue();
3396   if (OpVT != RL.getValueType())
3397     return SDValue();
3398
3399   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3400   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3401   bool IsInteger = OpVT.isInteger();
3402   if (LR == RR && CC0 == CC1 && IsInteger) {
3403     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3404     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3405
3406     // All bits clear?
3407     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3408     // All sign bits clear?
3409     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3410     // Any bits set?
3411     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3412     // Any sign bits set?
3413     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3414
3415     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3416     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3417     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3418     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3419     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3420       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3421       AddToWorklist(Or.getNode());
3422       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3423     }
3424
3425     // All bits set?
3426     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3427     // All sign bits set?
3428     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3429     // Any bits clear?
3430     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3431     // Any sign bits clear?
3432     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3433
3434     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3435     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3436     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3437     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3438     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3439       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3440       AddToWorklist(And.getNode());
3441       return DAG.getSetCC(DL, VT, And, LR, CC1);
3442     }
3443   }
3444
3445   // TODO: What is the 'or' equivalent of this fold?
3446   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3447   if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3448       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3449        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3450     SDValue One = DAG.getConstant(1, DL, OpVT);
3451     SDValue Two = DAG.getConstant(2, DL, OpVT);
3452     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3453     AddToWorklist(Add.getNode());
3454     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3455   }
3456
3457   // Try more general transforms if the predicates match and the only user of
3458   // the compares is the 'and' or 'or'.
3459   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3460       N0.hasOneUse() && N1.hasOneUse()) {
3461     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3462     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3463     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3464       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3465       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3466       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3467       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3468       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3469     }
3470   }
3471
3472   // Canonicalize equivalent operands to LL == RL.
3473   if (LL == RR && LR == RL) {
3474     CC1 = ISD::getSetCCSwappedOperands(CC1);
3475     std::swap(RL, RR);
3476   }
3477
3478   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3479   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3480   if (LL == RL && LR == RR) {
3481     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3482                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3483     if (NewCC != ISD::SETCC_INVALID &&
3484         (!LegalOperations ||
3485          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3486           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3487       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3488   }
3489
3490   return SDValue();
3491 }
3492
3493 /// This contains all DAGCombine rules which reduce two values combined by
3494 /// an And operation to a single value. This makes them reusable in the context
3495 /// of visitSELECT(). Rules involving constants are not included as
3496 /// visitSELECT() already handles those cases.
3497 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3498   EVT VT = N1.getValueType();
3499   SDLoc DL(N);
3500
3501   // fold (and x, undef) -> 0
3502   if (N0.isUndef() || N1.isUndef())
3503     return DAG.getConstant(0, DL, VT);
3504
3505   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3506     return V;
3507
3508   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3509       VT.getSizeInBits() <= 64) {
3510     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3511       APInt ADDC = ADDI->getAPIntValue();
3512       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3513         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3514         // immediate for an add, but it is legal if its top c2 bits are set,
3515         // transform the ADD so the immediate doesn't need to be materialized
3516         // in a register.
3517         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3518           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3519                                              SRLI->getZExtValue());
3520           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3521             ADDC |= Mask;
3522             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3523               SDLoc DL0(N0);
3524               SDValue NewAdd =
3525                 DAG.getNode(ISD::ADD, DL0, VT,
3526                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3527               CombineTo(N0.getNode(), NewAdd);
3528               // Return N so it doesn't get rechecked!
3529               return SDValue(N, 0);
3530             }
3531           }
3532         }
3533       }
3534     }
3535   }
3536
3537   // Reduce bit extract of low half of an integer to the narrower type.
3538   // (and (srl i64:x, K), KMask) ->
3539   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3540   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3541     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3542       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3543         unsigned Size = VT.getSizeInBits();
3544         const APInt &AndMask = CAnd->getAPIntValue();
3545         unsigned ShiftBits = CShift->getZExtValue();
3546
3547         // Bail out, this node will probably disappear anyway.
3548         if (ShiftBits == 0)
3549           return SDValue();
3550
3551         unsigned MaskBits = AndMask.countTrailingOnes();
3552         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3553
3554         if (AndMask.isMask() &&
3555             // Required bits must not span the two halves of the integer and
3556             // must fit in the half size type.
3557             (ShiftBits + MaskBits <= Size / 2) &&
3558             TLI.isNarrowingProfitable(VT, HalfVT) &&
3559             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3560             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3561             TLI.isTruncateFree(VT, HalfVT) &&
3562             TLI.isZExtFree(HalfVT, VT)) {
3563           // The isNarrowingProfitable is to avoid regressions on PPC and
3564           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3565           // on downstream users of this. Those patterns could probably be
3566           // extended to handle extensions mixed in.
3567
3568           SDValue SL(N0);
3569           assert(MaskBits <= Size);
3570
3571           // Extracting the highest bit of the low half.
3572           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3573           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3574                                       N0.getOperand(0));
3575
3576           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3577           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3578           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3579           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3580           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3581         }
3582       }
3583     }
3584   }
3585
3586   return SDValue();
3587 }
3588
3589 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3590                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3591                                    bool &NarrowLoad) {
3592   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3593
3594   if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3595     return false;
3596
3597   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3598   LoadedVT = LoadN->getMemoryVT();
3599
3600   if (ExtVT == LoadedVT &&
3601       (!LegalOperations ||
3602        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3603     // ZEXTLOAD will match without needing to change the size of the value being
3604     // loaded.
3605     NarrowLoad = false;
3606     return true;
3607   }
3608
3609   // Do not change the width of a volatile load.
3610   if (LoadN->isVolatile())
3611     return false;
3612
3613   // Do not generate loads of non-round integer types since these can
3614   // be expensive (and would be wrong if the type is not byte sized).
3615   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3616     return false;
3617
3618   if (LegalOperations &&
3619       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3620     return false;
3621
3622   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3623     return false;
3624
3625   NarrowLoad = true;
3626   return true;
3627 }
3628
3629 SDValue DAGCombiner::visitAND(SDNode *N) {
3630   SDValue N0 = N->getOperand(0);
3631   SDValue N1 = N->getOperand(1);
3632   EVT VT = N1.getValueType();
3633
3634   // x & x --> x
3635   if (N0 == N1)
3636     return N0;
3637
3638   // fold vector ops
3639   if (VT.isVector()) {
3640     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3641       return FoldedVOp;
3642
3643     // fold (and x, 0) -> 0, vector edition
3644     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3645       // do not return N0, because undef node may exist in N0
3646       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3647                              SDLoc(N), N0.getValueType());
3648     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3649       // do not return N1, because undef node may exist in N1
3650       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3651                              SDLoc(N), N1.getValueType());
3652
3653     // fold (and x, -1) -> x, vector edition
3654     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3655       return N1;
3656     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3657       return N0;
3658   }
3659
3660   // fold (and c1, c2) -> c1&c2
3661   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3662   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3663   if (N0C && N1C && !N1C->isOpaque())
3664     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3665   // canonicalize constant to RHS
3666   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3667      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3668     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3669   // fold (and x, -1) -> x
3670   if (isAllOnesConstant(N1))
3671     return N0;
3672   // if (and x, c) is known to be zero, return 0
3673   unsigned BitWidth = VT.getScalarSizeInBits();
3674   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3675                                    APInt::getAllOnesValue(BitWidth)))
3676     return DAG.getConstant(0, SDLoc(N), VT);
3677
3678   if (SDValue NewSel = foldBinOpIntoSelect(N))
3679     return NewSel;
3680
3681   // reassociate and
3682   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3683     return RAND;
3684   // fold (and (or x, C), D) -> D if (C & D) == D
3685   if (N1C && N0.getOpcode() == ISD::OR)
3686     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3687       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3688         return N1;
3689   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3690   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3691     SDValue N0Op0 = N0.getOperand(0);
3692     APInt Mask = ~N1C->getAPIntValue();
3693     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3694     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3695       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3696                                  N0.getValueType(), N0Op0);
3697
3698       // Replace uses of the AND with uses of the Zero extend node.
3699       CombineTo(N, Zext);
3700
3701       // We actually want to replace all uses of the any_extend with the
3702       // zero_extend, to avoid duplicating things.  This will later cause this
3703       // AND to be folded.
3704       CombineTo(N0.getNode(), Zext);
3705       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3706     }
3707   }
3708   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3709   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3710   // already be zero by virtue of the width of the base type of the load.
3711   //
3712   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3713   // more cases.
3714   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3715        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3716        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3717        N0.getOperand(0).getResNo() == 0) ||
3718       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3719     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3720                                          N0 : N0.getOperand(0) );
3721
3722     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3723     // This can be a pure constant or a vector splat, in which case we treat the
3724     // vector as a scalar and use the splat value.
3725     APInt Constant = APInt::getNullValue(1);
3726     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3727       Constant = C->getAPIntValue();
3728     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3729       APInt SplatValue, SplatUndef;
3730       unsigned SplatBitSize;
3731       bool HasAnyUndefs;
3732       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3733                                              SplatBitSize, HasAnyUndefs);
3734       if (IsSplat) {
3735         // Undef bits can contribute to a possible optimisation if set, so
3736         // set them.
3737         SplatValue |= SplatUndef;
3738
3739         // The splat value may be something like "0x00FFFFFF", which means 0 for
3740         // the first vector value and FF for the rest, repeating. We need a mask
3741         // that will apply equally to all members of the vector, so AND all the
3742         // lanes of the constant together.
3743         EVT VT = Vector->getValueType(0);
3744         unsigned BitWidth = VT.getScalarSizeInBits();
3745
3746         // If the splat value has been compressed to a bitlength lower
3747         // than the size of the vector lane, we need to re-expand it to
3748         // the lane size.
3749         if (BitWidth > SplatBitSize)
3750           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3751                SplatBitSize < BitWidth;
3752                SplatBitSize = SplatBitSize * 2)
3753             SplatValue |= SplatValue.shl(SplatBitSize);
3754
3755         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3756         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3757         if (SplatBitSize % BitWidth == 0) {
3758           Constant = APInt::getAllOnesValue(BitWidth);
3759           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3760             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3761         }
3762       }
3763     }
3764
3765     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3766     // actually legal and isn't going to get expanded, else this is a false
3767     // optimisation.
3768     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3769                                                     Load->getValueType(0),
3770                                                     Load->getMemoryVT());
3771
3772     // Resize the constant to the same size as the original memory access before
3773     // extension. If it is still the AllOnesValue then this AND is completely
3774     // unneeded.
3775     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3776
3777     bool B;
3778     switch (Load->getExtensionType()) {
3779     default: B = false; break;
3780     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3781     case ISD::ZEXTLOAD:
3782     case ISD::NON_EXTLOAD: B = true; break;
3783     }
3784
3785     if (B && Constant.isAllOnesValue()) {
3786       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3787       // preserve semantics once we get rid of the AND.
3788       SDValue NewLoad(Load, 0);
3789
3790       // Fold the AND away. NewLoad may get replaced immediately.
3791       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3792
3793       if (Load->getExtensionType() == ISD::EXTLOAD) {
3794         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3795                               Load->getValueType(0), SDLoc(Load),
3796                               Load->getChain(), Load->getBasePtr(),
3797                               Load->getOffset(), Load->getMemoryVT(),
3798                               Load->getMemOperand());
3799         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3800         if (Load->getNumValues() == 3) {
3801           // PRE/POST_INC loads have 3 values.
3802           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3803                            NewLoad.getValue(2) };
3804           CombineTo(Load, To, 3, true);
3805         } else {
3806           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3807         }
3808       }
3809
3810       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3811     }
3812   }
3813
3814   // fold (and (load x), 255) -> (zextload x, i8)
3815   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3816   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3817   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3818                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3819                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3820     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3821     LoadSDNode *LN0 = HasAnyExt
3822       ? cast<LoadSDNode>(N0.getOperand(0))
3823       : cast<LoadSDNode>(N0);
3824     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3825         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3826       auto NarrowLoad = false;
3827       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3828       EVT ExtVT, LoadedVT;
3829       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3830                            NarrowLoad)) {
3831         if (!NarrowLoad) {
3832           SDValue NewLoad =
3833             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3834                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3835                            LN0->getMemOperand());
3836           AddToWorklist(N);
3837           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3838           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3839         } else {
3840           EVT PtrType = LN0->getOperand(1).getValueType();
3841
3842           unsigned Alignment = LN0->getAlignment();
3843           SDValue NewPtr = LN0->getBasePtr();
3844
3845           // For big endian targets, we need to add an offset to the pointer
3846           // to load the correct bytes.  For little endian systems, we merely
3847           // need to read fewer bytes from the same pointer.
3848           if (DAG.getDataLayout().isBigEndian()) {
3849             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3850             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3851             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3852             SDLoc DL(LN0);
3853             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3854                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3855             Alignment = MinAlign(Alignment, PtrOff);
3856           }
3857
3858           AddToWorklist(NewPtr.getNode());
3859
3860           SDValue Load = DAG.getExtLoad(
3861               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3862               LN0->getPointerInfo(), ExtVT, Alignment,
3863               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3864           AddToWorklist(N);
3865           CombineTo(LN0, Load, Load.getValue(1));
3866           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3867         }
3868       }
3869     }
3870   }
3871
3872   if (SDValue Combined = visitANDLike(N0, N1, N))
3873     return Combined;
3874
3875   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3876   if (N0.getOpcode() == N1.getOpcode())
3877     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3878       return Tmp;
3879
3880   // Masking the negated extension of a boolean is just the zero-extended
3881   // boolean:
3882   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3883   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3884   //
3885   // Note: the SimplifyDemandedBits fold below can make an information-losing
3886   // transform, and then we have no way to find this better fold.
3887   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3888     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3889     SDValue SubRHS = N0.getOperand(1);
3890     if (SubLHS && SubLHS->isNullValue()) {
3891       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3892           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3893         return SubRHS;
3894       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3895           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3896         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3897     }
3898   }
3899
3900   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3901   // fold (and (sra)) -> (and (srl)) when possible.
3902   if (SimplifyDemandedBits(SDValue(N, 0)))
3903     return SDValue(N, 0);
3904
3905   // fold (zext_inreg (extload x)) -> (zextload x)
3906   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3907     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3908     EVT MemVT = LN0->getMemoryVT();
3909     // If we zero all the possible extended bits, then we can turn this into
3910     // a zextload if we are running before legalize or the operation is legal.
3911     unsigned BitWidth = N1.getScalarValueSizeInBits();
3912     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3913                            BitWidth - MemVT.getScalarSizeInBits())) &&
3914         ((!LegalOperations && !LN0->isVolatile()) ||
3915          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3916       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3917                                        LN0->getChain(), LN0->getBasePtr(),
3918                                        MemVT, LN0->getMemOperand());
3919       AddToWorklist(N);
3920       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3921       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3922     }
3923   }
3924   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3925   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3926       N0.hasOneUse()) {
3927     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3928     EVT MemVT = LN0->getMemoryVT();
3929     // If we zero all the possible extended bits, then we can turn this into
3930     // a zextload if we are running before legalize or the operation is legal.
3931     unsigned BitWidth = N1.getScalarValueSizeInBits();
3932     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3933                            BitWidth - MemVT.getScalarSizeInBits())) &&
3934         ((!LegalOperations && !LN0->isVolatile()) ||
3935          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3936       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3937                                        LN0->getChain(), LN0->getBasePtr(),
3938                                        MemVT, LN0->getMemOperand());
3939       AddToWorklist(N);
3940       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3941       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3942     }
3943   }
3944   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3945   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3946     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3947                                            N0.getOperand(1), false))
3948       return BSwap;
3949   }
3950
3951   return SDValue();
3952 }
3953
3954 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3955 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3956                                         bool DemandHighBits) {
3957   if (!LegalOperations)
3958     return SDValue();
3959
3960   EVT VT = N->getValueType(0);
3961   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3962     return SDValue();
3963   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
3964     return SDValue();
3965
3966   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3967   bool LookPassAnd0 = false;
3968   bool LookPassAnd1 = false;
3969   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3970       std::swap(N0, N1);
3971   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3972       std::swap(N0, N1);
3973   if (N0.getOpcode() == ISD::AND) {
3974     if (!N0.getNode()->hasOneUse())
3975       return SDValue();
3976     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3977     if (!N01C || N01C->getZExtValue() != 0xFF00)
3978       return SDValue();
3979     N0 = N0.getOperand(0);
3980     LookPassAnd0 = true;
3981   }
3982
3983   if (N1.getOpcode() == ISD::AND) {
3984     if (!N1.getNode()->hasOneUse())
3985       return SDValue();
3986     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3987     if (!N11C || N11C->getZExtValue() != 0xFF)
3988       return SDValue();
3989     N1 = N1.getOperand(0);
3990     LookPassAnd1 = true;
3991   }
3992
3993   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3994     std::swap(N0, N1);
3995   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3996     return SDValue();
3997   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3998     return SDValue();
3999
4000   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4001   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4002   if (!N01C || !N11C)
4003     return SDValue();
4004   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4005     return SDValue();
4006
4007   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4008   SDValue N00 = N0->getOperand(0);
4009   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4010     if (!N00.getNode()->hasOneUse())
4011       return SDValue();
4012     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4013     if (!N001C || N001C->getZExtValue() != 0xFF)
4014       return SDValue();
4015     N00 = N00.getOperand(0);
4016     LookPassAnd0 = true;
4017   }
4018
4019   SDValue N10 = N1->getOperand(0);
4020   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4021     if (!N10.getNode()->hasOneUse())
4022       return SDValue();
4023     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4024     if (!N101C || N101C->getZExtValue() != 0xFF00)
4025       return SDValue();
4026     N10 = N10.getOperand(0);
4027     LookPassAnd1 = true;
4028   }
4029
4030   if (N00 != N10)
4031     return SDValue();
4032
4033   // Make sure everything beyond the low halfword gets set to zero since the SRL
4034   // 16 will clear the top bits.
4035   unsigned OpSizeInBits = VT.getSizeInBits();
4036   if (DemandHighBits && OpSizeInBits > 16) {
4037     // If the left-shift isn't masked out then the only way this is a bswap is
4038     // if all bits beyond the low 8 are 0. In that case the entire pattern
4039     // reduces to a left shift anyway: leave it for other parts of the combiner.
4040     if (!LookPassAnd0)
4041       return SDValue();
4042
4043     // However, if the right shift isn't masked out then it might be because
4044     // it's not needed. See if we can spot that too.
4045     if (!LookPassAnd1 &&
4046         !DAG.MaskedValueIsZero(
4047             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4048       return SDValue();
4049   }
4050
4051   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4052   if (OpSizeInBits > 16) {
4053     SDLoc DL(N);
4054     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4055                       DAG.getConstant(OpSizeInBits - 16, DL,
4056                                       getShiftAmountTy(VT)));
4057   }
4058   return Res;
4059 }
4060
4061 /// Return true if the specified node is an element that makes up a 32-bit
4062 /// packed halfword byteswap.
4063 /// ((x & 0x000000ff) << 8) |
4064 /// ((x & 0x0000ff00) >> 8) |
4065 /// ((x & 0x00ff0000) << 8) |
4066 /// ((x & 0xff000000) >> 8)
4067 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4068   if (!N.getNode()->hasOneUse())
4069     return false;
4070
4071   unsigned Opc = N.getOpcode();
4072   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4073     return false;
4074
4075   SDValue N0 = N.getOperand(0);
4076   unsigned Opc0 = N0.getOpcode();
4077   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4078     return false;
4079
4080   ConstantSDNode *N1C = nullptr;
4081   // SHL or SRL: look upstream for AND mask operand
4082   if (Opc == ISD::AND)
4083     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4084   else if (Opc0 == ISD::AND)
4085     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4086   if (!N1C)
4087     return false;
4088
4089   unsigned MaskByteOffset;
4090   switch (N1C->getZExtValue()) {
4091   default:
4092     return false;
4093   case 0xFF:       MaskByteOffset = 0; break;
4094   case 0xFF00:     MaskByteOffset = 1; break;
4095   case 0xFF0000:   MaskByteOffset = 2; break;
4096   case 0xFF000000: MaskByteOffset = 3; break;
4097   }
4098
4099   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4100   if (Opc == ISD::AND) {
4101     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4102       // (x >> 8) & 0xff
4103       // (x >> 8) & 0xff0000
4104       if (Opc0 != ISD::SRL)
4105         return false;
4106       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4107       if (!C || C->getZExtValue() != 8)
4108         return false;
4109     } else {
4110       // (x << 8) & 0xff00
4111       // (x << 8) & 0xff000000
4112       if (Opc0 != ISD::SHL)
4113         return false;
4114       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4115       if (!C || C->getZExtValue() != 8)
4116         return false;
4117     }
4118   } else if (Opc == ISD::SHL) {
4119     // (x & 0xff) << 8
4120     // (x & 0xff0000) << 8
4121     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4122       return false;
4123     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4124     if (!C || C->getZExtValue() != 8)
4125       return false;
4126   } else { // Opc == ISD::SRL
4127     // (x & 0xff00) >> 8
4128     // (x & 0xff000000) >> 8
4129     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4130       return false;
4131     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4132     if (!C || C->getZExtValue() != 8)
4133       return false;
4134   }
4135
4136   if (Parts[MaskByteOffset])
4137     return false;
4138
4139   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4140   return true;
4141 }
4142
4143 /// Match a 32-bit packed halfword bswap. That is
4144 /// ((x & 0x000000ff) << 8) |
4145 /// ((x & 0x0000ff00) >> 8) |
4146 /// ((x & 0x00ff0000) << 8) |
4147 /// ((x & 0xff000000) >> 8)
4148 /// => (rotl (bswap x), 16)
4149 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4150   if (!LegalOperations)
4151     return SDValue();
4152
4153   EVT VT = N->getValueType(0);
4154   if (VT != MVT::i32)
4155     return SDValue();
4156   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4157     return SDValue();
4158
4159   // Look for either
4160   // (or (or (and), (and)), (or (and), (and)))
4161   // (or (or (or (and), (and)), (and)), (and))
4162   if (N0.getOpcode() != ISD::OR)
4163     return SDValue();
4164   SDValue N00 = N0.getOperand(0);
4165   SDValue N01 = N0.getOperand(1);
4166   SDNode *Parts[4] = {};
4167
4168   if (N1.getOpcode() == ISD::OR &&
4169       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4170     // (or (or (and), (and)), (or (and), (and)))
4171     if (!isBSwapHWordElement(N00, Parts))
4172       return SDValue();
4173
4174     if (!isBSwapHWordElement(N01, Parts))
4175       return SDValue();
4176     SDValue N10 = N1.getOperand(0);
4177     if (!isBSwapHWordElement(N10, Parts))
4178       return SDValue();
4179     SDValue N11 = N1.getOperand(1);
4180     if (!isBSwapHWordElement(N11, Parts))
4181       return SDValue();
4182   } else {
4183     // (or (or (or (and), (and)), (and)), (and))
4184     if (!isBSwapHWordElement(N1, Parts))
4185       return SDValue();
4186     if (!isBSwapHWordElement(N01, Parts))
4187       return SDValue();
4188     if (N00.getOpcode() != ISD::OR)
4189       return SDValue();
4190     SDValue N000 = N00.getOperand(0);
4191     if (!isBSwapHWordElement(N000, Parts))
4192       return SDValue();
4193     SDValue N001 = N00.getOperand(1);
4194     if (!isBSwapHWordElement(N001, Parts))
4195       return SDValue();
4196   }
4197
4198   // Make sure the parts are all coming from the same node.
4199   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4200     return SDValue();
4201
4202   SDLoc DL(N);
4203   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4204                               SDValue(Parts[0], 0));
4205
4206   // Result of the bswap should be rotated by 16. If it's not legal, then
4207   // do  (x << 16) | (x >> 16).
4208   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4209   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4210     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4211   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4212     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4213   return DAG.getNode(ISD::OR, DL, VT,
4214                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4215                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4216 }
4217
4218 /// This contains all DAGCombine rules which reduce two values combined by
4219 /// an Or operation to a single value \see visitANDLike().
4220 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4221   EVT VT = N1.getValueType();
4222   SDLoc DL(N);
4223
4224   // fold (or x, undef) -> -1
4225   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4226     return DAG.getAllOnesConstant(DL, VT);
4227
4228   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4229     return V;
4230
4231   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4232   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4233       // Don't increase # computations.
4234       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4235     // We can only do this xform if we know that bits from X that are set in C2
4236     // but not in C1 are already zero.  Likewise for Y.
4237     if (const ConstantSDNode *N0O1C =
4238         getAsNonOpaqueConstant(N0.getOperand(1))) {
4239       if (const ConstantSDNode *N1O1C =
4240           getAsNonOpaqueConstant(N1.getOperand(1))) {
4241         // We can only do this xform if we know that bits from X that are set in
4242         // C2 but not in C1 are already zero.  Likewise for Y.
4243         const APInt &LHSMask = N0O1C->getAPIntValue();
4244         const APInt &RHSMask = N1O1C->getAPIntValue();
4245
4246         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4247             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4248           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4249                                   N0.getOperand(0), N1.getOperand(0));
4250           return DAG.getNode(ISD::AND, DL, VT, X,
4251                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4252         }
4253       }
4254     }
4255   }
4256
4257   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4258   if (N0.getOpcode() == ISD::AND &&
4259       N1.getOpcode() == ISD::AND &&
4260       N0.getOperand(0) == N1.getOperand(0) &&
4261       // Don't increase # computations.
4262       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4263     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4264                             N0.getOperand(1), N1.getOperand(1));
4265     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4266   }
4267
4268   return SDValue();
4269 }
4270
4271 SDValue DAGCombiner::visitOR(SDNode *N) {
4272   SDValue N0 = N->getOperand(0);
4273   SDValue N1 = N->getOperand(1);
4274   EVT VT = N1.getValueType();
4275
4276   // x | x --> x
4277   if (N0 == N1)
4278     return N0;
4279
4280   // fold vector ops
4281   if (VT.isVector()) {
4282     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4283       return FoldedVOp;
4284
4285     // fold (or x, 0) -> x, vector edition
4286     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4287       return N1;
4288     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4289       return N0;
4290
4291     // fold (or x, -1) -> -1, vector edition
4292     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4293       // do not return N0, because undef node may exist in N0
4294       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4295     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4296       // do not return N1, because undef node may exist in N1
4297       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4298
4299     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4300     // Do this only if the resulting shuffle is legal.
4301     if (isa<ShuffleVectorSDNode>(N0) &&
4302         isa<ShuffleVectorSDNode>(N1) &&
4303         // Avoid folding a node with illegal type.
4304         TLI.isTypeLegal(VT)) {
4305       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4306       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4307       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4308       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4309       // Ensure both shuffles have a zero input.
4310       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4311         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4312         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4313         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4314         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4315         bool CanFold = true;
4316         int NumElts = VT.getVectorNumElements();
4317         SmallVector<int, 4> Mask(NumElts);
4318
4319         for (int i = 0; i != NumElts; ++i) {
4320           int M0 = SV0->getMaskElt(i);
4321           int M1 = SV1->getMaskElt(i);
4322
4323           // Determine if either index is pointing to a zero vector.
4324           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4325           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4326
4327           // If one element is zero and the otherside is undef, keep undef.
4328           // This also handles the case that both are undef.
4329           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4330             Mask[i] = -1;
4331             continue;
4332           }
4333
4334           // Make sure only one of the elements is zero.
4335           if (M0Zero == M1Zero) {
4336             CanFold = false;
4337             break;
4338           }
4339
4340           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4341
4342           // We have a zero and non-zero element. If the non-zero came from
4343           // SV0 make the index a LHS index. If it came from SV1, make it
4344           // a RHS index. We need to mod by NumElts because we don't care
4345           // which operand it came from in the original shuffles.
4346           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4347         }
4348
4349         if (CanFold) {
4350           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4351           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4352
4353           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4354           if (!LegalMask) {
4355             std::swap(NewLHS, NewRHS);
4356             ShuffleVectorSDNode::commuteMask(Mask);
4357             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4358           }
4359
4360           if (LegalMask)
4361             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4362         }
4363       }
4364     }
4365   }
4366
4367   // fold (or c1, c2) -> c1|c2
4368   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4369   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4370   if (N0C && N1C && !N1C->isOpaque())
4371     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4372   // canonicalize constant to RHS
4373   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4374      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4375     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4376   // fold (or x, 0) -> x
4377   if (isNullConstant(N1))
4378     return N0;
4379   // fold (or x, -1) -> -1
4380   if (isAllOnesConstant(N1))
4381     return N1;
4382
4383   if (SDValue NewSel = foldBinOpIntoSelect(N))
4384     return NewSel;
4385
4386   // fold (or x, c) -> c iff (x & ~c) == 0
4387   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4388     return N1;
4389
4390   if (SDValue Combined = visitORLike(N0, N1, N))
4391     return Combined;
4392
4393   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4394   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4395     return BSwap;
4396   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4397     return BSwap;
4398
4399   // reassociate or
4400   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4401     return ROR;
4402
4403   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4404   // iff (c1 & c2) != 0.
4405   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4406     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4407       if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4408         if (SDValue COR =
4409                 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4410           return DAG.getNode(
4411               ISD::AND, SDLoc(N), VT,
4412               DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4413         return SDValue();
4414       }
4415     }
4416   }
4417
4418   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4419   if (N0.getOpcode() == N1.getOpcode())
4420     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4421       return Tmp;
4422
4423   // See if this is some rotate idiom.
4424   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4425     return SDValue(Rot, 0);
4426
4427   if (SDValue Load = MatchLoadCombine(N))
4428     return Load;
4429
4430   // Simplify the operands using demanded-bits information.
4431   if (SimplifyDemandedBits(SDValue(N, 0)))
4432     return SDValue(N, 0);
4433
4434   return SDValue();
4435 }
4436
4437 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4438 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4439   if (Op.getOpcode() == ISD::AND) {
4440     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4441       Mask = Op.getOperand(1);
4442       Op = Op.getOperand(0);
4443     } else {
4444       return false;
4445     }
4446   }
4447
4448   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4449     Shift = Op;
4450     return true;
4451   }
4452
4453   return false;
4454 }
4455
4456 // Return true if we can prove that, whenever Neg and Pos are both in the
4457 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4458 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4459 //
4460 //     (or (shift1 X, Neg), (shift2 X, Pos))
4461 //
4462 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4463 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4464 // to consider shift amounts with defined behavior.
4465 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4466   // If EltSize is a power of 2 then:
4467   //
4468   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4469   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4470   //
4471   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4472   // for the stronger condition:
4473   //
4474   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4475   //
4476   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4477   // we can just replace Neg with Neg' for the rest of the function.
4478   //
4479   // In other cases we check for the even stronger condition:
4480   //
4481   //     Neg == EltSize - Pos                                    [B]
4482   //
4483   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4484   // behavior if Pos == 0 (and consequently Neg == EltSize).
4485   //
4486   // We could actually use [A] whenever EltSize is a power of 2, but the
4487   // only extra cases that it would match are those uninteresting ones
4488   // where Neg and Pos are never in range at the same time.  E.g. for
4489   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4490   // as well as (sub 32, Pos), but:
4491   //
4492   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4493   //
4494   // always invokes undefined behavior for 32-bit X.
4495   //
4496   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4497   unsigned MaskLoBits = 0;
4498   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4499     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4500       if (NegC->getAPIntValue() == EltSize - 1) {
4501         Neg = Neg.getOperand(0);
4502         MaskLoBits = Log2_64(EltSize);
4503       }
4504     }
4505   }
4506
4507   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4508   if (Neg.getOpcode() != ISD::SUB)
4509     return false;
4510   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4511   if (!NegC)
4512     return false;
4513   SDValue NegOp1 = Neg.getOperand(1);
4514
4515   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4516   // Pos'.  The truncation is redundant for the purpose of the equality.
4517   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4518     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4519       if (PosC->getAPIntValue() == EltSize - 1)
4520         Pos = Pos.getOperand(0);
4521
4522   // The condition we need is now:
4523   //
4524   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4525   //
4526   // If NegOp1 == Pos then we need:
4527   //
4528   //              EltSize & Mask == NegC & Mask
4529   //
4530   // (because "x & Mask" is a truncation and distributes through subtraction).
4531   APInt Width;
4532   if (Pos == NegOp1)
4533     Width = NegC->getAPIntValue();
4534
4535   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4536   // Then the condition we want to prove becomes:
4537   //
4538   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4539   //
4540   // which, again because "x & Mask" is a truncation, becomes:
4541   //
4542   //                NegC & Mask == (EltSize - PosC) & Mask
4543   //             EltSize & Mask == (NegC + PosC) & Mask
4544   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4545     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4546       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4547     else
4548       return false;
4549   } else
4550     return false;
4551
4552   // Now we just need to check that EltSize & Mask == Width & Mask.
4553   if (MaskLoBits)
4554     // EltSize & Mask is 0 since Mask is EltSize - 1.
4555     return Width.getLoBits(MaskLoBits) == 0;
4556   return Width == EltSize;
4557 }
4558
4559 // A subroutine of MatchRotate used once we have found an OR of two opposite
4560 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4561 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4562 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4563 // Neg with outer conversions stripped away.
4564 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4565                                        SDValue Neg, SDValue InnerPos,
4566                                        SDValue InnerNeg, unsigned PosOpcode,
4567                                        unsigned NegOpcode, const SDLoc &DL) {
4568   // fold (or (shl x, (*ext y)),
4569   //          (srl x, (*ext (sub 32, y)))) ->
4570   //   (rotl x, y) or (rotr x, (sub 32, y))
4571   //
4572   // fold (or (shl x, (*ext (sub 32, y))),
4573   //          (srl x, (*ext y))) ->
4574   //   (rotr x, y) or (rotl x, (sub 32, y))
4575   EVT VT = Shifted.getValueType();
4576   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4577     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4578     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4579                        HasPos ? Pos : Neg).getNode();
4580   }
4581
4582   return nullptr;
4583 }
4584
4585 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4586 // idioms for rotate, and if the target supports rotation instructions, generate
4587 // a rot[lr].
4588 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4589   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4590   EVT VT = LHS.getValueType();
4591   if (!TLI.isTypeLegal(VT)) return nullptr;
4592
4593   // The target must have at least one rotate flavor.
4594   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4595   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4596   if (!HasROTL && !HasROTR) return nullptr;
4597
4598   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4599   SDValue LHSShift;   // The shift.
4600   SDValue LHSMask;    // AND value if any.
4601   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4602     return nullptr; // Not part of a rotate.
4603
4604   SDValue RHSShift;   // The shift.
4605   SDValue RHSMask;    // AND value if any.
4606   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4607     return nullptr; // Not part of a rotate.
4608
4609   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4610     return nullptr;   // Not shifting the same value.
4611
4612   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4613     return nullptr;   // Shifts must disagree.
4614
4615   // Canonicalize shl to left side in a shl/srl pair.
4616   if (RHSShift.getOpcode() == ISD::SHL) {
4617     std::swap(LHS, RHS);
4618     std::swap(LHSShift, RHSShift);
4619     std::swap(LHSMask, RHSMask);
4620   }
4621
4622   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4623   SDValue LHSShiftArg = LHSShift.getOperand(0);
4624   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4625   SDValue RHSShiftArg = RHSShift.getOperand(0);
4626   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4627
4628   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4629   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4630   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4631     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4632     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4633     if ((LShVal + RShVal) != EltSizeInBits)
4634       return nullptr;
4635
4636     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4637                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4638
4639     // If there is an AND of either shifted operand, apply it to the result.
4640     if (LHSMask.getNode() || RHSMask.getNode()) {
4641       SDValue Mask = DAG.getAllOnesConstant(DL, VT);
4642
4643       if (LHSMask.getNode()) {
4644         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4645         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4646                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4647                                        DAG.getConstant(RHSBits, DL, VT)));
4648       }
4649       if (RHSMask.getNode()) {
4650         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4651         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4652                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4653                                        DAG.getConstant(LHSBits, DL, VT)));
4654       }
4655
4656       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4657     }
4658
4659     return Rot.getNode();
4660   }
4661
4662   // If there is a mask here, and we have a variable shift, we can't be sure
4663   // that we're masking out the right stuff.
4664   if (LHSMask.getNode() || RHSMask.getNode())
4665     return nullptr;
4666
4667   // If the shift amount is sign/zext/any-extended just peel it off.
4668   SDValue LExtOp0 = LHSShiftAmt;
4669   SDValue RExtOp0 = RHSShiftAmt;
4670   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4671        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4672        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4673        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4674       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4675        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4676        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4677        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4678     LExtOp0 = LHSShiftAmt.getOperand(0);
4679     RExtOp0 = RHSShiftAmt.getOperand(0);
4680   }
4681
4682   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4683                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4684   if (TryL)
4685     return TryL;
4686
4687   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4688                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4689   if (TryR)
4690     return TryR;
4691
4692   return nullptr;
4693 }
4694
4695 namespace {
4696 /// Helper struct to parse and store a memory address as base + index + offset.
4697 /// We ignore sign extensions when it is safe to do so.
4698 /// The following two expressions are not equivalent. To differentiate we need
4699 /// to store whether there was a sign extension involved in the index
4700 /// computation.
4701 ///  (load (i64 add (i64 copyfromreg %c)
4702 ///                 (i64 signextend (add (i8 load %index)
4703 ///                                      (i8 1))))
4704 /// vs
4705 ///
4706 /// (load (i64 add (i64 copyfromreg %c)
4707 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
4708 ///                                         (i32 1)))))
4709 struct BaseIndexOffset {
4710   SDValue Base;
4711   SDValue Index;
4712   int64_t Offset;
4713   bool IsIndexSignExt;
4714
4715   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
4716
4717   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
4718                   bool IsIndexSignExt) :
4719     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
4720
4721   bool equalBaseIndex(const BaseIndexOffset &Other) {
4722     return Other.Base == Base && Other.Index == Index &&
4723       Other.IsIndexSignExt == IsIndexSignExt;
4724   }
4725
4726   /// Parses tree in Ptr for base, index, offset addresses.
4727   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG,
4728                                int64_t PartialOffset = 0) {
4729     bool IsIndexSignExt = false;
4730
4731     // Split up a folded GlobalAddress+Offset into its component parts.
4732     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
4733       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
4734         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
4735                                                     SDLoc(GA),
4736                                                     GA->getValueType(0),
4737                                                     /*Offset=*/PartialOffset,
4738                                                     /*isTargetGA=*/false,
4739                                                     GA->getTargetFlags()),
4740                                SDValue(),
4741                                GA->getOffset(),
4742                                IsIndexSignExt);
4743       }
4744
4745     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
4746     // instruction, then it could be just the BASE or everything else we don't
4747     // know how to handle. Just use Ptr as BASE and give up.
4748     if (Ptr->getOpcode() != ISD::ADD)
4749       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4750
4751     // We know that we have at least an ADD instruction. Try to pattern match
4752     // the simple case of BASE + OFFSET.
4753     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
4754       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
4755       return match(Ptr->getOperand(0), DAG, Offset + PartialOffset);
4756     }
4757
4758     // Inside a loop the current BASE pointer is calculated using an ADD and a
4759     // MUL instruction. In this case Ptr is the actual BASE pointer.
4760     // (i64 add (i64 %array_ptr)
4761     //          (i64 mul (i64 %induction_var)
4762     //                   (i64 %element_size)))
4763     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
4764       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4765
4766     // Look at Base + Index + Offset cases.
4767     SDValue Base = Ptr->getOperand(0);
4768     SDValue IndexOffset = Ptr->getOperand(1);
4769
4770     // Skip signextends.
4771     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
4772       IndexOffset = IndexOffset->getOperand(0);
4773       IsIndexSignExt = true;
4774     }
4775
4776     // Either the case of Base + Index (no offset) or something else.
4777     if (IndexOffset->getOpcode() != ISD::ADD)
4778       return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt);
4779
4780     // Now we have the case of Base + Index + offset.
4781     SDValue Index = IndexOffset->getOperand(0);
4782     SDValue Offset = IndexOffset->getOperand(1);
4783
4784     if (!isa<ConstantSDNode>(Offset))
4785       return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4786
4787     // Ignore signextends.
4788     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
4789       Index = Index->getOperand(0);
4790       IsIndexSignExt = true;
4791     } else IsIndexSignExt = false;
4792
4793     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
4794     return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt);
4795   }
4796 };
4797 } // namespace
4798
4799 namespace {
4800 /// Represents known origin of an individual byte in load combine pattern. The
4801 /// value of the byte is either constant zero or comes from memory.
4802 struct ByteProvider {
4803   // For constant zero providers Load is set to nullptr. For memory providers
4804   // Load represents the node which loads the byte from memory.
4805   // ByteOffset is the offset of the byte in the value produced by the load.
4806   LoadSDNode *Load;
4807   unsigned ByteOffset;
4808
4809   ByteProvider() : Load(nullptr), ByteOffset(0) {}
4810
4811   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4812     return ByteProvider(Load, ByteOffset);
4813   }
4814   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4815
4816   bool isConstantZero() const { return !Load; }
4817   bool isMemory() const { return Load; }
4818
4819   bool operator==(const ByteProvider &Other) const {
4820     return Other.Load == Load && Other.ByteOffset == ByteOffset;
4821   }
4822
4823 private:
4824   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4825       : Load(Load), ByteOffset(ByteOffset) {}
4826 };
4827
4828 /// Recursively traverses the expression calculating the origin of the requested
4829 /// byte of the given value. Returns None if the provider can't be calculated.
4830 ///
4831 /// For all the values except the root of the expression verifies that the value
4832 /// has exactly one use and if it's not true return None. This way if the origin
4833 /// of the byte is returned it's guaranteed that the values which contribute to
4834 /// the byte are not used outside of this expression.
4835 ///
4836 /// Because the parts of the expression are not allowed to have more than one
4837 /// use this function iterates over trees, not DAGs. So it never visits the same
4838 /// node more than once.
4839 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4840                                                    unsigned Depth,
4841                                                    bool Root = false) {
4842   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4843   if (Depth == 10)
4844     return None;
4845
4846   if (!Root && !Op.hasOneUse())
4847     return None;
4848
4849   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4850   unsigned BitWidth = Op.getValueSizeInBits();
4851   if (BitWidth % 8 != 0)
4852     return None;
4853   unsigned ByteWidth = BitWidth / 8;
4854   assert(Index < ByteWidth && "invalid index requested");
4855   (void) ByteWidth;
4856
4857   switch (Op.getOpcode()) {
4858   case ISD::OR: {
4859     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4860     if (!LHS)
4861       return None;
4862     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4863     if (!RHS)
4864       return None;
4865
4866     if (LHS->isConstantZero())
4867       return RHS;
4868     if (RHS->isConstantZero())
4869       return LHS;
4870     return None;
4871   }
4872   case ISD::SHL: {
4873     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4874     if (!ShiftOp)
4875       return None;
4876
4877     uint64_t BitShift = ShiftOp->getZExtValue();
4878     if (BitShift % 8 != 0)
4879       return None;
4880     uint64_t ByteShift = BitShift / 8;
4881
4882     return Index < ByteShift
4883                ? ByteProvider::getConstantZero()
4884                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4885                                        Depth + 1);
4886   }
4887   case ISD::ANY_EXTEND:
4888   case ISD::SIGN_EXTEND:
4889   case ISD::ZERO_EXTEND: {
4890     SDValue NarrowOp = Op->getOperand(0);
4891     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4892     if (NarrowBitWidth % 8 != 0)
4893       return None;
4894     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4895
4896     if (Index >= NarrowByteWidth)
4897       return Op.getOpcode() == ISD::ZERO_EXTEND
4898                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4899                  : None;
4900     return calculateByteProvider(NarrowOp, Index, Depth + 1);
4901   }
4902   case ISD::BSWAP:
4903     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4904                                  Depth + 1);
4905   case ISD::LOAD: {
4906     auto L = cast<LoadSDNode>(Op.getNode());
4907     if (L->isVolatile() || L->isIndexed())
4908       return None;
4909
4910     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4911     if (NarrowBitWidth % 8 != 0)
4912       return None;
4913     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4914
4915     if (Index >= NarrowByteWidth)
4916       return L->getExtensionType() == ISD::ZEXTLOAD
4917                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4918                  : None;
4919     return ByteProvider::getMemory(L, Index);
4920   }
4921   }
4922
4923   return None;
4924 }
4925 } // namespace
4926
4927 /// Match a pattern where a wide type scalar value is loaded by several narrow
4928 /// loads and combined by shifts and ors. Fold it into a single load or a load
4929 /// and a BSWAP if the targets supports it.
4930 ///
4931 /// Assuming little endian target:
4932 ///  i8 *a = ...
4933 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4934 /// =>
4935 ///  i32 val = *((i32)a)
4936 ///
4937 ///  i8 *a = ...
4938 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4939 /// =>
4940 ///  i32 val = BSWAP(*((i32)a))
4941 ///
4942 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4943 /// interact well with the worklist mechanism. When a part of the pattern is
4944 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4945 /// but the root node of the pattern which triggers the load combine is not
4946 /// necessarily a direct user of the changed node. For example, once the address
4947 /// of t28 load is reassociated load combine won't be triggered:
4948 ///             t25: i32 = add t4, Constant:i32<2>
4949 ///           t26: i64 = sign_extend t25
4950 ///        t27: i64 = add t2, t26
4951 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4952 ///     t29: i32 = zero_extend t28
4953 ///   t32: i32 = shl t29, Constant:i8<8>
4954 /// t33: i32 = or t23, t32
4955 /// As a possible fix visitLoad can check if the load can be a part of a load
4956 /// combine pattern and add corresponding OR roots to the worklist.
4957 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4958   assert(N->getOpcode() == ISD::OR &&
4959          "Can only match load combining against OR nodes");
4960
4961   // Handles simple types only
4962   EVT VT = N->getValueType(0);
4963   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4964     return SDValue();
4965   unsigned ByteWidth = VT.getSizeInBits() / 8;
4966
4967   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4968   // Before legalize we can introduce too wide illegal loads which will be later
4969   // split into legal sized loads. This enables us to combine i64 load by i8
4970   // patterns to a couple of i32 loads on 32 bit targets.
4971   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4972     return SDValue();
4973
4974   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4975     unsigned BW, unsigned i) { return i; };
4976   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4977     unsigned BW, unsigned i) { return BW - i - 1; };
4978
4979   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4980   auto MemoryByteOffset = [&] (ByteProvider P) {
4981     assert(P.isMemory() && "Must be a memory byte provider");
4982     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4983     assert(LoadBitWidth % 8 == 0 &&
4984            "can only analyze providers for individual bytes not bit");
4985     unsigned LoadByteWidth = LoadBitWidth / 8;
4986     return IsBigEndianTarget
4987             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4988             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4989   };
4990
4991   Optional<BaseIndexOffset> Base;
4992   SDValue Chain;
4993
4994   SmallSet<LoadSDNode *, 8> Loads;
4995   Optional<ByteProvider> FirstByteProvider;
4996   int64_t FirstOffset = INT64_MAX;
4997
4998   // Check if all the bytes of the OR we are looking at are loaded from the same
4999   // base address. Collect bytes offsets from Base address in ByteOffsets.
5000   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
5001   for (unsigned i = 0; i < ByteWidth; i++) {
5002     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
5003     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
5004       return SDValue();
5005
5006     LoadSDNode *L = P->Load;
5007     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
5008            "Must be enforced by calculateByteProvider");
5009     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
5010
5011     // All loads must share the same chain
5012     SDValue LChain = L->getChain();
5013     if (!Chain)
5014       Chain = LChain;
5015     else if (Chain != LChain)
5016       return SDValue();
5017
5018     // Loads must share the same base address
5019     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
5020     if (!Base)
5021       Base = Ptr;
5022     else if (!Base->equalBaseIndex(Ptr))
5023       return SDValue();
5024
5025     // Calculate the offset of the current byte from the base address
5026     int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P);
5027     ByteOffsets[i] = ByteOffsetFromBase;
5028
5029     // Remember the first byte load
5030     if (ByteOffsetFromBase < FirstOffset) {
5031       FirstByteProvider = P;
5032       FirstOffset = ByteOffsetFromBase;
5033     }
5034
5035     Loads.insert(L);
5036   }
5037   assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
5038          "memory, so there must be at least one load which produces the value");
5039   assert(Base && "Base address of the accessed memory location must be set");
5040   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
5041
5042   // Check if the bytes of the OR we are looking at match with either big or
5043   // little endian value load
5044   bool BigEndian = true, LittleEndian = true;
5045   for (unsigned i = 0; i < ByteWidth; i++) {
5046     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
5047     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
5048     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
5049     if (!BigEndian && !LittleEndian)
5050       return SDValue();
5051   }
5052   assert((BigEndian != LittleEndian) && "should be either or");
5053   assert(FirstByteProvider && "must be set");
5054
5055   // Ensure that the first byte is loaded from zero offset of the first load.
5056   // So the combined value can be loaded from the first load address.
5057   if (MemoryByteOffset(*FirstByteProvider) != 0)
5058     return SDValue();
5059   LoadSDNode *FirstLoad = FirstByteProvider->Load;
5060
5061   // The node we are looking at matches with the pattern, check if we can
5062   // replace it with a single load and bswap if needed.
5063
5064   // If the load needs byte swap check if the target supports it
5065   bool NeedsBswap = IsBigEndianTarget != BigEndian;
5066
5067   // Before legalize we can introduce illegal bswaps which will be later
5068   // converted to an explicit bswap sequence. This way we end up with a single
5069   // load and byte shuffling instead of several loads and byte shuffling.
5070   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
5071     return SDValue();
5072
5073   // Check that a load of the wide type is both allowed and fast on the target
5074   bool Fast = false;
5075   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
5076                                         VT, FirstLoad->getAddressSpace(),
5077                                         FirstLoad->getAlignment(), &Fast);
5078   if (!Allowed || !Fast)
5079     return SDValue();
5080
5081   SDValue NewLoad =
5082       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
5083                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
5084
5085   // Transfer chain users from old loads to the new load.
5086   for (LoadSDNode *L : Loads)
5087     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
5088
5089   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5090 }
5091
5092 SDValue DAGCombiner::visitXOR(SDNode *N) {
5093   SDValue N0 = N->getOperand(0);
5094   SDValue N1 = N->getOperand(1);
5095   EVT VT = N0.getValueType();
5096
5097   // fold vector ops
5098   if (VT.isVector()) {
5099     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5100       return FoldedVOp;
5101
5102     // fold (xor x, 0) -> x, vector edition
5103     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5104       return N1;
5105     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5106       return N0;
5107   }
5108
5109   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5110   if (N0.isUndef() && N1.isUndef())
5111     return DAG.getConstant(0, SDLoc(N), VT);
5112   // fold (xor x, undef) -> undef
5113   if (N0.isUndef())
5114     return N0;
5115   if (N1.isUndef())
5116     return N1;
5117   // fold (xor c1, c2) -> c1^c2
5118   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5119   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5120   if (N0C && N1C)
5121     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5122   // canonicalize constant to RHS
5123   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5124      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5125     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5126   // fold (xor x, 0) -> x
5127   if (isNullConstant(N1))
5128     return N0;
5129
5130   if (SDValue NewSel = foldBinOpIntoSelect(N))
5131     return NewSel;
5132
5133   // reassociate xor
5134   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5135     return RXOR;
5136
5137   // fold !(x cc y) -> (x !cc y)
5138   SDValue LHS, RHS, CC;
5139   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5140     bool isInt = LHS.getValueType().isInteger();
5141     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5142                                                isInt);
5143
5144     if (!LegalOperations ||
5145         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5146       switch (N0.getOpcode()) {
5147       default:
5148         llvm_unreachable("Unhandled SetCC Equivalent!");
5149       case ISD::SETCC:
5150         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5151       case ISD::SELECT_CC:
5152         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5153                                N0.getOperand(3), NotCC);
5154       }
5155     }
5156   }
5157
5158   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5159   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5160       N0.getNode()->hasOneUse() &&
5161       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5162     SDValue V = N0.getOperand(0);
5163     SDLoc DL(N0);
5164     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5165                     DAG.getConstant(1, DL, V.getValueType()));
5166     AddToWorklist(V.getNode());
5167     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5168   }
5169
5170   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5171   if (isOneConstant(N1) && VT == MVT::i1 &&
5172       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5173     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5174     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5175       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5176       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5177       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5178       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5179       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5180     }
5181   }
5182   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5183   if (isAllOnesConstant(N1) &&
5184       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5185     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5186     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5187       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5188       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5189       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5190       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5191       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5192     }
5193   }
5194   // fold (xor (and x, y), y) -> (and (not x), y)
5195   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5196       N0->getOperand(1) == N1) {
5197     SDValue X = N0->getOperand(0);
5198     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5199     AddToWorklist(NotX.getNode());
5200     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5201   }
5202   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5203   if (N1C && N0.getOpcode() == ISD::XOR) {
5204     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5205       SDLoc DL(N);
5206       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5207                          DAG.getConstant(N1C->getAPIntValue() ^
5208                                          N00C->getAPIntValue(), DL, VT));
5209     }
5210     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5211       SDLoc DL(N);
5212       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5213                          DAG.getConstant(N1C->getAPIntValue() ^
5214                                          N01C->getAPIntValue(), DL, VT));
5215     }
5216   }
5217
5218   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5219   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5220   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5221       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5222       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5223     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5224       if (C->getAPIntValue() == (OpSizeInBits - 1))
5225         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5226   }
5227
5228   // fold (xor x, x) -> 0
5229   if (N0 == N1)
5230     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5231
5232   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5233   // Here is a concrete example of this equivalence:
5234   // i16   x ==  14
5235   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5236   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5237   //
5238   // =>
5239   //
5240   // i16     ~1      == 0b1111111111111110
5241   // i16 rol(~1, 14) == 0b1011111111111111
5242   //
5243   // Some additional tips to help conceptualize this transform:
5244   // - Try to see the operation as placing a single zero in a value of all ones.
5245   // - There exists no value for x which would allow the result to contain zero.
5246   // - Values of x larger than the bitwidth are undefined and do not require a
5247   //   consistent result.
5248   // - Pushing the zero left requires shifting one bits in from the right.
5249   // A rotate left of ~1 is a nice way of achieving the desired result.
5250   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5251       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5252     SDLoc DL(N);
5253     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5254                        N0.getOperand(1));
5255   }
5256
5257   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5258   if (N0.getOpcode() == N1.getOpcode())
5259     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5260       return Tmp;
5261
5262   // Simplify the expression using non-local knowledge.
5263   if (SimplifyDemandedBits(SDValue(N, 0)))
5264     return SDValue(N, 0);
5265
5266   return SDValue();
5267 }
5268
5269 /// Handle transforms common to the three shifts, when the shift amount is a
5270 /// constant.
5271 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5272   SDNode *LHS = N->getOperand(0).getNode();
5273   if (!LHS->hasOneUse()) return SDValue();
5274
5275   // We want to pull some binops through shifts, so that we have (and (shift))
5276   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5277   // thing happens with address calculations, so it's important to canonicalize
5278   // it.
5279   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5280
5281   switch (LHS->getOpcode()) {
5282   default: return SDValue();
5283   case ISD::OR:
5284   case ISD::XOR:
5285     HighBitSet = false; // We can only transform sra if the high bit is clear.
5286     break;
5287   case ISD::AND:
5288     HighBitSet = true;  // We can only transform sra if the high bit is set.
5289     break;
5290   case ISD::ADD:
5291     if (N->getOpcode() != ISD::SHL)
5292       return SDValue(); // only shl(add) not sr[al](add).
5293     HighBitSet = false; // We can only transform sra if the high bit is clear.
5294     break;
5295   }
5296
5297   // We require the RHS of the binop to be a constant and not opaque as well.
5298   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5299   if (!BinOpCst) return SDValue();
5300
5301   // FIXME: disable this unless the input to the binop is a shift by a constant
5302   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5303   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5304   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5305                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5306                  BinOpLHSVal->getOpcode() == ISD::SRL;
5307   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5308                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5309
5310   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5311       !isCopyOrSelect)
5312     return SDValue();
5313
5314   if (isCopyOrSelect && N->hasOneUse())
5315     return SDValue();
5316
5317   EVT VT = N->getValueType(0);
5318
5319   // If this is a signed shift right, and the high bit is modified by the
5320   // logical operation, do not perform the transformation. The highBitSet
5321   // boolean indicates the value of the high bit of the constant which would
5322   // cause it to be modified for this operation.
5323   if (N->getOpcode() == ISD::SRA) {
5324     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5325     if (BinOpRHSSignSet != HighBitSet)
5326       return SDValue();
5327   }
5328
5329   if (!TLI.isDesirableToCommuteWithShift(LHS))
5330     return SDValue();
5331
5332   // Fold the constants, shifting the binop RHS by the shift amount.
5333   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5334                                N->getValueType(0),
5335                                LHS->getOperand(1), N->getOperand(1));
5336   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5337
5338   // Create the new shift.
5339   SDValue NewShift = DAG.getNode(N->getOpcode(),
5340                                  SDLoc(LHS->getOperand(0)),
5341                                  VT, LHS->getOperand(0), N->getOperand(1));
5342
5343   // Create the new binop.
5344   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5345 }
5346
5347 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5348   assert(N->getOpcode() == ISD::TRUNCATE);
5349   assert(N->getOperand(0).getOpcode() == ISD::AND);
5350
5351   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5352   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5353     SDValue N01 = N->getOperand(0).getOperand(1);
5354     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5355       SDLoc DL(N);
5356       EVT TruncVT = N->getValueType(0);
5357       SDValue N00 = N->getOperand(0).getOperand(0);
5358       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5359       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5360       AddToWorklist(Trunc00.getNode());
5361       AddToWorklist(Trunc01.getNode());
5362       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5363     }
5364   }
5365
5366   return SDValue();
5367 }
5368
5369 SDValue DAGCombiner::visitRotate(SDNode *N) {
5370   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5371   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
5372       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
5373     if (SDValue NewOp1 =
5374             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
5375       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
5376                          N->getOperand(0), NewOp1);
5377   }
5378   return SDValue();
5379 }
5380
5381 SDValue DAGCombiner::visitSHL(SDNode *N) {
5382   SDValue N0 = N->getOperand(0);
5383   SDValue N1 = N->getOperand(1);
5384   EVT VT = N0.getValueType();
5385   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5386
5387   // fold vector ops
5388   if (VT.isVector()) {
5389     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5390       return FoldedVOp;
5391
5392     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5393     // If setcc produces all-one true value then:
5394     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5395     if (N1CV && N1CV->isConstant()) {
5396       if (N0.getOpcode() == ISD::AND) {
5397         SDValue N00 = N0->getOperand(0);
5398         SDValue N01 = N0->getOperand(1);
5399         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5400
5401         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5402             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5403                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5404           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5405                                                      N01CV, N1CV))
5406             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5407         }
5408       }
5409     }
5410   }
5411
5412   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5413
5414   // fold (shl c1, c2) -> c1<<c2
5415   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5416   if (N0C && N1C && !N1C->isOpaque())
5417     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5418   // fold (shl 0, x) -> 0
5419   if (isNullConstantOrNullSplatConstant(N0))
5420     return N0;
5421   // fold (shl x, c >= size(x)) -> undef
5422   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5423     return DAG.getUNDEF(VT);
5424   // fold (shl x, 0) -> x
5425   if (N1C && N1C->isNullValue())
5426     return N0;
5427   // fold (shl undef, x) -> 0
5428   if (N0.isUndef())
5429     return DAG.getConstant(0, SDLoc(N), VT);
5430
5431   if (SDValue NewSel = foldBinOpIntoSelect(N))
5432     return NewSel;
5433
5434   // if (shl x, c) is known to be zero, return 0
5435   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5436                             APInt::getAllOnesValue(OpSizeInBits)))
5437     return DAG.getConstant(0, SDLoc(N), VT);
5438   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5439   if (N1.getOpcode() == ISD::TRUNCATE &&
5440       N1.getOperand(0).getOpcode() == ISD::AND) {
5441     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5442       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5443   }
5444
5445   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5446     return SDValue(N, 0);
5447
5448   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5449   if (N1C && N0.getOpcode() == ISD::SHL) {
5450     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5451       SDLoc DL(N);
5452       APInt c1 = N0C1->getAPIntValue();
5453       APInt c2 = N1C->getAPIntValue();
5454       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5455
5456       APInt Sum = c1 + c2;
5457       if (Sum.uge(OpSizeInBits))
5458         return DAG.getConstant(0, DL, VT);
5459
5460       return DAG.getNode(
5461           ISD::SHL, DL, VT, N0.getOperand(0),
5462           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5463     }
5464   }
5465
5466   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5467   // For this to be valid, the second form must not preserve any of the bits
5468   // that are shifted out by the inner shift in the first form.  This means
5469   // the outer shift size must be >= the number of bits added by the ext.
5470   // As a corollary, we don't care what kind of ext it is.
5471   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5472               N0.getOpcode() == ISD::ANY_EXTEND ||
5473               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5474       N0.getOperand(0).getOpcode() == ISD::SHL) {
5475     SDValue N0Op0 = N0.getOperand(0);
5476     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5477       APInt c1 = N0Op0C1->getAPIntValue();
5478       APInt c2 = N1C->getAPIntValue();
5479       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5480
5481       EVT InnerShiftVT = N0Op0.getValueType();
5482       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5483       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5484         SDLoc DL(N0);
5485         APInt Sum = c1 + c2;
5486         if (Sum.uge(OpSizeInBits))
5487           return DAG.getConstant(0, DL, VT);
5488
5489         return DAG.getNode(
5490             ISD::SHL, DL, VT,
5491             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5492             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5493       }
5494     }
5495   }
5496
5497   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5498   // Only fold this if the inner zext has no other uses to avoid increasing
5499   // the total number of instructions.
5500   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5501       N0.getOperand(0).getOpcode() == ISD::SRL) {
5502     SDValue N0Op0 = N0.getOperand(0);
5503     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5504       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5505         uint64_t c1 = N0Op0C1->getZExtValue();
5506         uint64_t c2 = N1C->getZExtValue();
5507         if (c1 == c2) {
5508           SDValue NewOp0 = N0.getOperand(0);
5509           EVT CountVT = NewOp0.getOperand(1).getValueType();
5510           SDLoc DL(N);
5511           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5512                                        NewOp0,
5513                                        DAG.getConstant(c2, DL, CountVT));
5514           AddToWorklist(NewSHL.getNode());
5515           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5516         }
5517       }
5518     }
5519   }
5520
5521   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5522   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5523   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5524       N0->getFlags().hasExact()) {
5525     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5526       uint64_t C1 = N0C1->getZExtValue();
5527       uint64_t C2 = N1C->getZExtValue();
5528       SDLoc DL(N);
5529       if (C1 <= C2)
5530         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5531                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5532       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5533                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5534     }
5535   }
5536
5537   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5538   //                               (and (srl x, (sub c1, c2), MASK)
5539   // Only fold this if the inner shift has no other uses -- if it does, folding
5540   // this will increase the total number of instructions.
5541   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5542     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5543       uint64_t c1 = N0C1->getZExtValue();
5544       if (c1 < OpSizeInBits) {
5545         uint64_t c2 = N1C->getZExtValue();
5546         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5547         SDValue Shift;
5548         if (c2 > c1) {
5549           Mask <<= c2 - c1;
5550           SDLoc DL(N);
5551           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5552                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5553         } else {
5554           Mask.lshrInPlace(c1 - c2);
5555           SDLoc DL(N);
5556           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5557                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5558         }
5559         SDLoc DL(N0);
5560         return DAG.getNode(ISD::AND, DL, VT, Shift,
5561                            DAG.getConstant(Mask, DL, VT));
5562       }
5563     }
5564   }
5565
5566   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5567   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5568       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5569     SDLoc DL(N);
5570     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5571     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5572     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5573   }
5574
5575   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5576   // Variant of version done on multiply, except mul by a power of 2 is turned
5577   // into a shift.
5578   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5579       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5580       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5581     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5582     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5583     AddToWorklist(Shl0.getNode());
5584     AddToWorklist(Shl1.getNode());
5585     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5586   }
5587
5588   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5589   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5590       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5591       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5592     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5593     if (isConstantOrConstantVector(Shl))
5594       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5595   }
5596
5597   if (N1C && !N1C->isOpaque())
5598     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5599       return NewSHL;
5600
5601   return SDValue();
5602 }
5603
5604 SDValue DAGCombiner::visitSRA(SDNode *N) {
5605   SDValue N0 = N->getOperand(0);
5606   SDValue N1 = N->getOperand(1);
5607   EVT VT = N0.getValueType();
5608   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5609
5610   // Arithmetic shifting an all-sign-bit value is a no-op.
5611   // fold (sra 0, x) -> 0
5612   // fold (sra -1, x) -> -1
5613   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5614     return N0;
5615
5616   // fold vector ops
5617   if (VT.isVector())
5618     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5619       return FoldedVOp;
5620
5621   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5622
5623   // fold (sra c1, c2) -> (sra c1, c2)
5624   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5625   if (N0C && N1C && !N1C->isOpaque())
5626     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5627   // fold (sra x, c >= size(x)) -> undef
5628   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5629     return DAG.getUNDEF(VT);
5630   // fold (sra x, 0) -> x
5631   if (N1C && N1C->isNullValue())
5632     return N0;
5633
5634   if (SDValue NewSel = foldBinOpIntoSelect(N))
5635     return NewSel;
5636
5637   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5638   // sext_inreg.
5639   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5640     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5641     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5642     if (VT.isVector())
5643       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5644                                ExtVT, VT.getVectorNumElements());
5645     if ((!LegalOperations ||
5646          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5647       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5648                          N0.getOperand(0), DAG.getValueType(ExtVT));
5649   }
5650
5651   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5652   if (N1C && N0.getOpcode() == ISD::SRA) {
5653     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5654       SDLoc DL(N);
5655       APInt c1 = N0C1->getAPIntValue();
5656       APInt c2 = N1C->getAPIntValue();
5657       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5658
5659       APInt Sum = c1 + c2;
5660       if (Sum.uge(OpSizeInBits))
5661         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5662
5663       return DAG.getNode(
5664           ISD::SRA, DL, VT, N0.getOperand(0),
5665           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5666     }
5667   }
5668
5669   // fold (sra (shl X, m), (sub result_size, n))
5670   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5671   // result_size - n != m.
5672   // If truncate is free for the target sext(shl) is likely to result in better
5673   // code.
5674   if (N0.getOpcode() == ISD::SHL && N1C) {
5675     // Get the two constanst of the shifts, CN0 = m, CN = n.
5676     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5677     if (N01C) {
5678       LLVMContext &Ctx = *DAG.getContext();
5679       // Determine what the truncate's result bitsize and type would be.
5680       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5681
5682       if (VT.isVector())
5683         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5684
5685       // Determine the residual right-shift amount.
5686       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5687
5688       // If the shift is not a no-op (in which case this should be just a sign
5689       // extend already), the truncated to type is legal, sign_extend is legal
5690       // on that type, and the truncate to that type is both legal and free,
5691       // perform the transform.
5692       if ((ShiftAmt > 0) &&
5693           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5694           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5695           TLI.isTruncateFree(VT, TruncVT)) {
5696
5697         SDLoc DL(N);
5698         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5699             getShiftAmountTy(N0.getOperand(0).getValueType()));
5700         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5701                                     N0.getOperand(0), Amt);
5702         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5703                                     Shift);
5704         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5705                            N->getValueType(0), Trunc);
5706       }
5707     }
5708   }
5709
5710   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5711   if (N1.getOpcode() == ISD::TRUNCATE &&
5712       N1.getOperand(0).getOpcode() == ISD::AND) {
5713     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5714       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5715   }
5716
5717   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5718   //      if c1 is equal to the number of bits the trunc removes
5719   if (N0.getOpcode() == ISD::TRUNCATE &&
5720       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5721        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5722       N0.getOperand(0).hasOneUse() &&
5723       N0.getOperand(0).getOperand(1).hasOneUse() &&
5724       N1C) {
5725     SDValue N0Op0 = N0.getOperand(0);
5726     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5727       unsigned LargeShiftVal = LargeShift->getZExtValue();
5728       EVT LargeVT = N0Op0.getValueType();
5729
5730       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5731         SDLoc DL(N);
5732         SDValue Amt =
5733           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5734                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5735         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5736                                   N0Op0.getOperand(0), Amt);
5737         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5738       }
5739     }
5740   }
5741
5742   // Simplify, based on bits shifted out of the LHS.
5743   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5744     return SDValue(N, 0);
5745
5746
5747   // If the sign bit is known to be zero, switch this to a SRL.
5748   if (DAG.SignBitIsZero(N0))
5749     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5750
5751   if (N1C && !N1C->isOpaque())
5752     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5753       return NewSRA;
5754
5755   return SDValue();
5756 }
5757
5758 SDValue DAGCombiner::visitSRL(SDNode *N) {
5759   SDValue N0 = N->getOperand(0);
5760   SDValue N1 = N->getOperand(1);
5761   EVT VT = N0.getValueType();
5762   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5763
5764   // fold vector ops
5765   if (VT.isVector())
5766     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5767       return FoldedVOp;
5768
5769   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5770
5771   // fold (srl c1, c2) -> c1 >>u c2
5772   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5773   if (N0C && N1C && !N1C->isOpaque())
5774     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5775   // fold (srl 0, x) -> 0
5776   if (isNullConstantOrNullSplatConstant(N0))
5777     return N0;
5778   // fold (srl x, c >= size(x)) -> undef
5779   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5780     return DAG.getUNDEF(VT);
5781   // fold (srl x, 0) -> x
5782   if (N1C && N1C->isNullValue())
5783     return N0;
5784
5785   if (SDValue NewSel = foldBinOpIntoSelect(N))
5786     return NewSel;
5787
5788   // if (srl x, c) is known to be zero, return 0
5789   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5790                                    APInt::getAllOnesValue(OpSizeInBits)))
5791     return DAG.getConstant(0, SDLoc(N), VT);
5792
5793   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5794   if (N1C && N0.getOpcode() == ISD::SRL) {
5795     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5796       SDLoc DL(N);
5797       APInt c1 = N0C1->getAPIntValue();
5798       APInt c2 = N1C->getAPIntValue();
5799       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5800
5801       APInt Sum = c1 + c2;
5802       if (Sum.uge(OpSizeInBits))
5803         return DAG.getConstant(0, DL, VT);
5804
5805       return DAG.getNode(
5806           ISD::SRL, DL, VT, N0.getOperand(0),
5807           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5808     }
5809   }
5810
5811   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5812   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5813       N0.getOperand(0).getOpcode() == ISD::SRL) {
5814     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5815       uint64_t c1 = N001C->getZExtValue();
5816       uint64_t c2 = N1C->getZExtValue();
5817       EVT InnerShiftVT = N0.getOperand(0).getValueType();
5818       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5819       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5820       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5821       if (c1 + OpSizeInBits == InnerShiftSize) {
5822         SDLoc DL(N0);
5823         if (c1 + c2 >= InnerShiftSize)
5824           return DAG.getConstant(0, DL, VT);
5825         return DAG.getNode(ISD::TRUNCATE, DL, VT,
5826                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5827                                        N0.getOperand(0).getOperand(0),
5828                                        DAG.getConstant(c1 + c2, DL,
5829                                                        ShiftCountVT)));
5830       }
5831     }
5832   }
5833
5834   // fold (srl (shl x, c), c) -> (and x, cst2)
5835   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5836       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5837     SDLoc DL(N);
5838     SDValue Mask =
5839         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5840     AddToWorklist(Mask.getNode());
5841     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5842   }
5843
5844   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5845   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5846     // Shifting in all undef bits?
5847     EVT SmallVT = N0.getOperand(0).getValueType();
5848     unsigned BitSize = SmallVT.getScalarSizeInBits();
5849     if (N1C->getZExtValue() >= BitSize)
5850       return DAG.getUNDEF(VT);
5851
5852     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5853       uint64_t ShiftAmt = N1C->getZExtValue();
5854       SDLoc DL0(N0);
5855       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5856                                        N0.getOperand(0),
5857                           DAG.getConstant(ShiftAmt, DL0,
5858                                           getShiftAmountTy(SmallVT)));
5859       AddToWorklist(SmallShift.getNode());
5860       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5861       SDLoc DL(N);
5862       return DAG.getNode(ISD::AND, DL, VT,
5863                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5864                          DAG.getConstant(Mask, DL, VT));
5865     }
5866   }
5867
5868   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
5869   // bit, which is unmodified by sra.
5870   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5871     if (N0.getOpcode() == ISD::SRA)
5872       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5873   }
5874
5875   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5876   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5877       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5878     KnownBits Known;
5879     DAG.computeKnownBits(N0.getOperand(0), Known);
5880
5881     // If any of the input bits are KnownOne, then the input couldn't be all
5882     // zeros, thus the result of the srl will always be zero.
5883     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5884
5885     // If all of the bits input the to ctlz node are known to be zero, then
5886     // the result of the ctlz is "32" and the result of the shift is one.
5887     APInt UnknownBits = ~Known.Zero;
5888     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5889
5890     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5891     if (UnknownBits.isPowerOf2()) {
5892       // Okay, we know that only that the single bit specified by UnknownBits
5893       // could be set on input to the CTLZ node. If this bit is set, the SRL
5894       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5895       // to an SRL/XOR pair, which is likely to simplify more.
5896       unsigned ShAmt = UnknownBits.countTrailingZeros();
5897       SDValue Op = N0.getOperand(0);
5898
5899       if (ShAmt) {
5900         SDLoc DL(N0);
5901         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5902                   DAG.getConstant(ShAmt, DL,
5903                                   getShiftAmountTy(Op.getValueType())));
5904         AddToWorklist(Op.getNode());
5905       }
5906
5907       SDLoc DL(N);
5908       return DAG.getNode(ISD::XOR, DL, VT,
5909                          Op, DAG.getConstant(1, DL, VT));
5910     }
5911   }
5912
5913   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5914   if (N1.getOpcode() == ISD::TRUNCATE &&
5915       N1.getOperand(0).getOpcode() == ISD::AND) {
5916     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5917       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5918   }
5919
5920   // fold operands of srl based on knowledge that the low bits are not
5921   // demanded.
5922   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5923     return SDValue(N, 0);
5924
5925   if (N1C && !N1C->isOpaque())
5926     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5927       return NewSRL;
5928
5929   // Attempt to convert a srl of a load into a narrower zero-extending load.
5930   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5931     return NarrowLoad;
5932
5933   // Here is a common situation. We want to optimize:
5934   //
5935   //   %a = ...
5936   //   %b = and i32 %a, 2
5937   //   %c = srl i32 %b, 1
5938   //   brcond i32 %c ...
5939   //
5940   // into
5941   //
5942   //   %a = ...
5943   //   %b = and %a, 2
5944   //   %c = setcc eq %b, 0
5945   //   brcond %c ...
5946   //
5947   // However when after the source operand of SRL is optimized into AND, the SRL
5948   // itself may not be optimized further. Look for it and add the BRCOND into
5949   // the worklist.
5950   if (N->hasOneUse()) {
5951     SDNode *Use = *N->use_begin();
5952     if (Use->getOpcode() == ISD::BRCOND)
5953       AddToWorklist(Use);
5954     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5955       // Also look pass the truncate.
5956       Use = *Use->use_begin();
5957       if (Use->getOpcode() == ISD::BRCOND)
5958         AddToWorklist(Use);
5959     }
5960   }
5961
5962   return SDValue();
5963 }
5964
5965 SDValue DAGCombiner::visitABS(SDNode *N) {
5966   SDValue N0 = N->getOperand(0);
5967   EVT VT = N->getValueType(0);
5968
5969   // fold (abs c1) -> c2
5970   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5971     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
5972   // fold (abs (abs x)) -> (abs x)
5973   if (N0.getOpcode() == ISD::ABS)
5974     return N0;
5975   // fold (abs x) -> x iff not-negative
5976   if (DAG.SignBitIsZero(N0))
5977     return N0;
5978   return SDValue();
5979 }
5980
5981 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5982   SDValue N0 = N->getOperand(0);
5983   EVT VT = N->getValueType(0);
5984
5985   // fold (bswap c1) -> c2
5986   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5987     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5988   // fold (bswap (bswap x)) -> x
5989   if (N0.getOpcode() == ISD::BSWAP)
5990     return N0->getOperand(0);
5991   return SDValue();
5992 }
5993
5994 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5995   SDValue N0 = N->getOperand(0);
5996   EVT VT = N->getValueType(0);
5997
5998   // fold (bitreverse c1) -> c2
5999   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6000     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
6001   // fold (bitreverse (bitreverse x)) -> x
6002   if (N0.getOpcode() == ISD::BITREVERSE)
6003     return N0.getOperand(0);
6004   return SDValue();
6005 }
6006
6007 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
6008   SDValue N0 = N->getOperand(0);
6009   EVT VT = N->getValueType(0);
6010
6011   // fold (ctlz c1) -> c2
6012   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6013     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
6014   return SDValue();
6015 }
6016
6017 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
6018   SDValue N0 = N->getOperand(0);
6019   EVT VT = N->getValueType(0);
6020
6021   // fold (ctlz_zero_undef c1) -> c2
6022   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6023     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6024   return SDValue();
6025 }
6026
6027 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
6028   SDValue N0 = N->getOperand(0);
6029   EVT VT = N->getValueType(0);
6030
6031   // fold (cttz c1) -> c2
6032   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6033     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
6034   return SDValue();
6035 }
6036
6037 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
6038   SDValue N0 = N->getOperand(0);
6039   EVT VT = N->getValueType(0);
6040
6041   // fold (cttz_zero_undef c1) -> c2
6042   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6043     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6044   return SDValue();
6045 }
6046
6047 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
6048   SDValue N0 = N->getOperand(0);
6049   EVT VT = N->getValueType(0);
6050
6051   // fold (ctpop c1) -> c2
6052   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6053     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6054   return SDValue();
6055 }
6056
6057
6058 /// \brief Generate Min/Max node
6059 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6060                                    SDValue RHS, SDValue True, SDValue False,
6061                                    ISD::CondCode CC, const TargetLowering &TLI,
6062                                    SelectionDAG &DAG) {
6063   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6064     return SDValue();
6065
6066   switch (CC) {
6067   case ISD::SETOLT:
6068   case ISD::SETOLE:
6069   case ISD::SETLT:
6070   case ISD::SETLE:
6071   case ISD::SETULT:
6072   case ISD::SETULE: {
6073     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6074     if (TLI.isOperationLegal(Opcode, VT))
6075       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6076     return SDValue();
6077   }
6078   case ISD::SETOGT:
6079   case ISD::SETOGE:
6080   case ISD::SETGT:
6081   case ISD::SETGE:
6082   case ISD::SETUGT:
6083   case ISD::SETUGE: {
6084     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6085     if (TLI.isOperationLegal(Opcode, VT))
6086       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6087     return SDValue();
6088   }
6089   default:
6090     return SDValue();
6091   }
6092 }
6093
6094 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6095   SDValue Cond = N->getOperand(0);
6096   SDValue N1 = N->getOperand(1);
6097   SDValue N2 = N->getOperand(2);
6098   EVT VT = N->getValueType(0);
6099   EVT CondVT = Cond.getValueType();
6100   SDLoc DL(N);
6101
6102   if (!VT.isInteger())
6103     return SDValue();
6104
6105   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6106   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6107   if (!C1 || !C2)
6108     return SDValue();
6109
6110   // Only do this before legalization to avoid conflicting with target-specific
6111   // transforms in the other direction (create a select from a zext/sext). There
6112   // is also a target-independent combine here in DAGCombiner in the other
6113   // direction for (select Cond, -1, 0) when the condition is not i1.
6114   if (CondVT == MVT::i1 && !LegalOperations) {
6115     if (C1->isNullValue() && C2->isOne()) {
6116       // select Cond, 0, 1 --> zext (!Cond)
6117       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6118       if (VT != MVT::i1)
6119         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6120       return NotCond;
6121     }
6122     if (C1->isNullValue() && C2->isAllOnesValue()) {
6123       // select Cond, 0, -1 --> sext (!Cond)
6124       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6125       if (VT != MVT::i1)
6126         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6127       return NotCond;
6128     }
6129     if (C1->isOne() && C2->isNullValue()) {
6130       // select Cond, 1, 0 --> zext (Cond)
6131       if (VT != MVT::i1)
6132         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6133       return Cond;
6134     }
6135     if (C1->isAllOnesValue() && C2->isNullValue()) {
6136       // select Cond, -1, 0 --> sext (Cond)
6137       if (VT != MVT::i1)
6138         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6139       return Cond;
6140     }
6141
6142     // For any constants that differ by 1, we can transform the select into an
6143     // extend and add. Use a target hook because some targets may prefer to
6144     // transform in the other direction.
6145     if (TLI.convertSelectOfConstantsToMath()) {
6146       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6147         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6148         if (VT != MVT::i1)
6149           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6150         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6151       }
6152       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6153         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6154         if (VT != MVT::i1)
6155           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6156         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6157       }
6158     }
6159
6160     return SDValue();
6161   }
6162
6163   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6164   // We can't do this reliably if integer based booleans have different contents
6165   // to floating point based booleans. This is because we can't tell whether we
6166   // have an integer-based boolean or a floating-point-based boolean unless we
6167   // can find the SETCC that produced it and inspect its operands. This is
6168   // fairly easy if C is the SETCC node, but it can potentially be
6169   // undiscoverable (or not reasonably discoverable). For example, it could be
6170   // in another basic block or it could require searching a complicated
6171   // expression.
6172   if (CondVT.isInteger() &&
6173       TLI.getBooleanContents(false, true) ==
6174           TargetLowering::ZeroOrOneBooleanContent &&
6175       TLI.getBooleanContents(false, false) ==
6176           TargetLowering::ZeroOrOneBooleanContent &&
6177       C1->isNullValue() && C2->isOne()) {
6178     SDValue NotCond =
6179         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6180     if (VT.bitsEq(CondVT))
6181       return NotCond;
6182     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6183   }
6184
6185   return SDValue();
6186 }
6187
6188 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6189   SDValue N0 = N->getOperand(0);
6190   SDValue N1 = N->getOperand(1);
6191   SDValue N2 = N->getOperand(2);
6192   EVT VT = N->getValueType(0);
6193   EVT VT0 = N0.getValueType();
6194
6195   // fold (select C, X, X) -> X
6196   if (N1 == N2)
6197     return N1;
6198   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6199     // fold (select true, X, Y) -> X
6200     // fold (select false, X, Y) -> Y
6201     return !N0C->isNullValue() ? N1 : N2;
6202   }
6203   // fold (select X, X, Y) -> (or X, Y)
6204   // fold (select X, 1, Y) -> (or C, Y)
6205   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6206     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
6207
6208   if (SDValue V = foldSelectOfConstants(N))
6209     return V;
6210
6211   // fold (select C, 0, X) -> (and (not C), X)
6212   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6213     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6214     AddToWorklist(NOTNode.getNode());
6215     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
6216   }
6217   // fold (select C, X, 1) -> (or (not C), X)
6218   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6219     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6220     AddToWorklist(NOTNode.getNode());
6221     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
6222   }
6223   // fold (select X, Y, X) -> (and X, Y)
6224   // fold (select X, Y, 0) -> (and X, Y)
6225   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6226     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
6227
6228   // If we can fold this based on the true/false value, do so.
6229   if (SimplifySelectOps(N, N1, N2))
6230     return SDValue(N, 0);  // Don't revisit N.
6231
6232   if (VT0 == MVT::i1) {
6233     // The code in this block deals with the following 2 equivalences:
6234     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6235     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6236     // The target can specify its preferred form with the
6237     // shouldNormalizeToSelectSequence() callback. However we always transform
6238     // to the right anyway if we find the inner select exists in the DAG anyway
6239     // and we always transform to the left side if we know that we can further
6240     // optimize the combination of the conditions.
6241     bool normalizeToSequence
6242       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6243     // select (and Cond0, Cond1), X, Y
6244     //   -> select Cond0, (select Cond1, X, Y), Y
6245     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6246       SDValue Cond0 = N0->getOperand(0);
6247       SDValue Cond1 = N0->getOperand(1);
6248       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6249                                         N1.getValueType(), Cond1, N1, N2);
6250       if (normalizeToSequence || !InnerSelect.use_empty())
6251         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
6252                            InnerSelect, N2);
6253     }
6254     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6255     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6256       SDValue Cond0 = N0->getOperand(0);
6257       SDValue Cond1 = N0->getOperand(1);
6258       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6259                                         N1.getValueType(), Cond1, N1, N2);
6260       if (normalizeToSequence || !InnerSelect.use_empty())
6261         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
6262                            InnerSelect);
6263     }
6264
6265     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6266     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6267       SDValue N1_0 = N1->getOperand(0);
6268       SDValue N1_1 = N1->getOperand(1);
6269       SDValue N1_2 = N1->getOperand(2);
6270       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6271         // Create the actual and node if we can generate good code for it.
6272         if (!normalizeToSequence) {
6273           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
6274                                     N0, N1_0);
6275           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
6276                              N1_1, N2);
6277         }
6278         // Otherwise see if we can optimize the "and" to a better pattern.
6279         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6280           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6281                              N1_1, N2);
6282       }
6283     }
6284     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6285     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6286       SDValue N2_0 = N2->getOperand(0);
6287       SDValue N2_1 = N2->getOperand(1);
6288       SDValue N2_2 = N2->getOperand(2);
6289       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6290         // Create the actual or node if we can generate good code for it.
6291         if (!normalizeToSequence) {
6292           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
6293                                    N0, N2_0);
6294           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
6295                              N1, N2_2);
6296         }
6297         // Otherwise see if we can optimize to a better pattern.
6298         if (SDValue Combined = visitORLike(N0, N2_0, N))
6299           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6300                              N1, N2_2);
6301       }
6302     }
6303   }
6304
6305   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6306   if (VT0 == MVT::i1) {
6307     if (N0->getOpcode() == ISD::XOR) {
6308       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6309         SDValue Cond0 = N0->getOperand(0);
6310         if (C->isOne())
6311           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
6312                              Cond0, N2, N1);
6313       }
6314     }
6315   }
6316
6317   // fold selects based on a setcc into other things, such as min/max/abs
6318   if (N0.getOpcode() == ISD::SETCC) {
6319     // select x, y (fcmp lt x, y) -> fminnum x, y
6320     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6321     //
6322     // This is OK if we don't care about what happens if either operand is a
6323     // NaN.
6324     //
6325
6326     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6327     // no signed zeros as well as no nans.
6328     const TargetOptions &Options = DAG.getTarget().Options;
6329     if (Options.UnsafeFPMath &&
6330         VT.isFloatingPoint() && N0.hasOneUse() &&
6331         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6332       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6333
6334       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
6335                                                 N0.getOperand(1), N1, N2, CC,
6336                                                 TLI, DAG))
6337         return FMinMax;
6338     }
6339
6340     if ((!LegalOperations &&
6341          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6342         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6343       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
6344                          N0.getOperand(0), N0.getOperand(1),
6345                          N1, N2, N0.getOperand(2));
6346     return SimplifySelect(SDLoc(N), N0, N1, N2);
6347   }
6348
6349   return SDValue();
6350 }
6351
6352 static
6353 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6354   SDLoc DL(N);
6355   EVT LoVT, HiVT;
6356   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6357
6358   // Split the inputs.
6359   SDValue Lo, Hi, LL, LH, RL, RH;
6360   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6361   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6362
6363   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6364   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6365
6366   return std::make_pair(Lo, Hi);
6367 }
6368
6369 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6370 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6371 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6372   SDLoc DL(N);
6373   SDValue Cond = N->getOperand(0);
6374   SDValue LHS = N->getOperand(1);
6375   SDValue RHS = N->getOperand(2);
6376   EVT VT = N->getValueType(0);
6377   int NumElems = VT.getVectorNumElements();
6378   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6379          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6380          Cond.getOpcode() == ISD::BUILD_VECTOR);
6381
6382   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6383   // binary ones here.
6384   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6385     return SDValue();
6386
6387   // We're sure we have an even number of elements due to the
6388   // concat_vectors we have as arguments to vselect.
6389   // Skip BV elements until we find one that's not an UNDEF
6390   // After we find an UNDEF element, keep looping until we get to half the
6391   // length of the BV and see if all the non-undef nodes are the same.
6392   ConstantSDNode *BottomHalf = nullptr;
6393   for (int i = 0; i < NumElems / 2; ++i) {
6394     if (Cond->getOperand(i)->isUndef())
6395       continue;
6396
6397     if (BottomHalf == nullptr)
6398       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6399     else if (Cond->getOperand(i).getNode() != BottomHalf)
6400       return SDValue();
6401   }
6402
6403   // Do the same for the second half of the BuildVector
6404   ConstantSDNode *TopHalf = nullptr;
6405   for (int i = NumElems / 2; i < NumElems; ++i) {
6406     if (Cond->getOperand(i)->isUndef())
6407       continue;
6408
6409     if (TopHalf == nullptr)
6410       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6411     else if (Cond->getOperand(i).getNode() != TopHalf)
6412       return SDValue();
6413   }
6414
6415   assert(TopHalf && BottomHalf &&
6416          "One half of the selector was all UNDEFs and the other was all the "
6417          "same value. This should have been addressed before this function.");
6418   return DAG.getNode(
6419       ISD::CONCAT_VECTORS, DL, VT,
6420       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6421       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6422 }
6423
6424 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6425
6426   if (Level >= AfterLegalizeTypes)
6427     return SDValue();
6428
6429   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6430   SDValue Mask = MSC->getMask();
6431   SDValue Data  = MSC->getValue();
6432   SDLoc DL(N);
6433
6434   // If the MSCATTER data type requires splitting and the mask is provided by a
6435   // SETCC, then split both nodes and its operands before legalization. This
6436   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6437   // and enables future optimizations (e.g. min/max pattern matching on X86).
6438   if (Mask.getOpcode() != ISD::SETCC)
6439     return SDValue();
6440
6441   // Check if any splitting is required.
6442   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6443       TargetLowering::TypeSplitVector)
6444     return SDValue();
6445   SDValue MaskLo, MaskHi, Lo, Hi;
6446   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6447
6448   EVT LoVT, HiVT;
6449   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6450
6451   SDValue Chain = MSC->getChain();
6452
6453   EVT MemoryVT = MSC->getMemoryVT();
6454   unsigned Alignment = MSC->getOriginalAlignment();
6455
6456   EVT LoMemVT, HiMemVT;
6457   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6458
6459   SDValue DataLo, DataHi;
6460   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6461
6462   SDValue BasePtr = MSC->getBasePtr();
6463   SDValue IndexLo, IndexHi;
6464   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6465
6466   MachineMemOperand *MMO = DAG.getMachineFunction().
6467     getMachineMemOperand(MSC->getPointerInfo(),
6468                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6469                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6470
6471   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6472   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6473                             DL, OpsLo, MMO);
6474
6475   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6476   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6477                             DL, OpsHi, MMO);
6478
6479   AddToWorklist(Lo.getNode());
6480   AddToWorklist(Hi.getNode());
6481
6482   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6483 }
6484
6485 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6486
6487   if (Level >= AfterLegalizeTypes)
6488     return SDValue();
6489
6490   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6491   SDValue Mask = MST->getMask();
6492   SDValue Data  = MST->getValue();
6493   EVT VT = Data.getValueType();
6494   SDLoc DL(N);
6495
6496   // If the MSTORE data type requires splitting and the mask is provided by a
6497   // SETCC, then split both nodes and its operands before legalization. This
6498   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6499   // and enables future optimizations (e.g. min/max pattern matching on X86).
6500   if (Mask.getOpcode() == ISD::SETCC) {
6501
6502     // Check if any splitting is required.
6503     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6504         TargetLowering::TypeSplitVector)
6505       return SDValue();
6506
6507     SDValue MaskLo, MaskHi, Lo, Hi;
6508     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6509
6510     SDValue Chain = MST->getChain();
6511     SDValue Ptr   = MST->getBasePtr();
6512
6513     EVT MemoryVT = MST->getMemoryVT();
6514     unsigned Alignment = MST->getOriginalAlignment();
6515
6516     // if Alignment is equal to the vector size,
6517     // take the half of it for the second part
6518     unsigned SecondHalfAlignment =
6519       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6520
6521     EVT LoMemVT, HiMemVT;
6522     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6523
6524     SDValue DataLo, DataHi;
6525     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6526
6527     MachineMemOperand *MMO = DAG.getMachineFunction().
6528       getMachineMemOperand(MST->getPointerInfo(),
6529                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6530                            Alignment, MST->getAAInfo(), MST->getRanges());
6531
6532     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6533                             MST->isTruncatingStore(),
6534                             MST->isCompressingStore());
6535
6536     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6537                                      MST->isCompressingStore());
6538
6539     MMO = DAG.getMachineFunction().
6540       getMachineMemOperand(MST->getPointerInfo(),
6541                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6542                            SecondHalfAlignment, MST->getAAInfo(),
6543                            MST->getRanges());
6544
6545     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6546                             MST->isTruncatingStore(),
6547                             MST->isCompressingStore());
6548
6549     AddToWorklist(Lo.getNode());
6550     AddToWorklist(Hi.getNode());
6551
6552     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6553   }
6554   return SDValue();
6555 }
6556
6557 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6558
6559   if (Level >= AfterLegalizeTypes)
6560     return SDValue();
6561
6562   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6563   SDValue Mask = MGT->getMask();
6564   SDLoc DL(N);
6565
6566   // If the MGATHER result requires splitting and the mask is provided by a
6567   // SETCC, then split both nodes and its operands before legalization. This
6568   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6569   // and enables future optimizations (e.g. min/max pattern matching on X86).
6570
6571   if (Mask.getOpcode() != ISD::SETCC)
6572     return SDValue();
6573
6574   EVT VT = N->getValueType(0);
6575
6576   // Check if any splitting is required.
6577   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6578       TargetLowering::TypeSplitVector)
6579     return SDValue();
6580
6581   SDValue MaskLo, MaskHi, Lo, Hi;
6582   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6583
6584   SDValue Src0 = MGT->getValue();
6585   SDValue Src0Lo, Src0Hi;
6586   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6587
6588   EVT LoVT, HiVT;
6589   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6590
6591   SDValue Chain = MGT->getChain();
6592   EVT MemoryVT = MGT->getMemoryVT();
6593   unsigned Alignment = MGT->getOriginalAlignment();
6594
6595   EVT LoMemVT, HiMemVT;
6596   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6597
6598   SDValue BasePtr = MGT->getBasePtr();
6599   SDValue Index = MGT->getIndex();
6600   SDValue IndexLo, IndexHi;
6601   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6602
6603   MachineMemOperand *MMO = DAG.getMachineFunction().
6604     getMachineMemOperand(MGT->getPointerInfo(),
6605                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6606                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6607
6608   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6609   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6610                             MMO);
6611
6612   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6613   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6614                             MMO);
6615
6616   AddToWorklist(Lo.getNode());
6617   AddToWorklist(Hi.getNode());
6618
6619   // Build a factor node to remember that this load is independent of the
6620   // other one.
6621   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6622                       Hi.getValue(1));
6623
6624   // Legalized the chain result - switch anything that used the old chain to
6625   // use the new one.
6626   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6627
6628   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6629
6630   SDValue RetOps[] = { GatherRes, Chain };
6631   return DAG.getMergeValues(RetOps, DL);
6632 }
6633
6634 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6635
6636   if (Level >= AfterLegalizeTypes)
6637     return SDValue();
6638
6639   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6640   SDValue Mask = MLD->getMask();
6641   SDLoc DL(N);
6642
6643   // If the MLOAD result requires splitting and the mask is provided by a
6644   // SETCC, then split both nodes and its operands before legalization. This
6645   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6646   // and enables future optimizations (e.g. min/max pattern matching on X86).
6647
6648   if (Mask.getOpcode() == ISD::SETCC) {
6649     EVT VT = N->getValueType(0);
6650
6651     // Check if any splitting is required.
6652     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6653         TargetLowering::TypeSplitVector)
6654       return SDValue();
6655
6656     SDValue MaskLo, MaskHi, Lo, Hi;
6657     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6658
6659     SDValue Src0 = MLD->getSrc0();
6660     SDValue Src0Lo, Src0Hi;
6661     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6662
6663     EVT LoVT, HiVT;
6664     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6665
6666     SDValue Chain = MLD->getChain();
6667     SDValue Ptr   = MLD->getBasePtr();
6668     EVT MemoryVT = MLD->getMemoryVT();
6669     unsigned Alignment = MLD->getOriginalAlignment();
6670
6671     // if Alignment is equal to the vector size,
6672     // take the half of it for the second part
6673     unsigned SecondHalfAlignment =
6674       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6675          Alignment/2 : Alignment;
6676
6677     EVT LoMemVT, HiMemVT;
6678     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6679
6680     MachineMemOperand *MMO = DAG.getMachineFunction().
6681     getMachineMemOperand(MLD->getPointerInfo(),
6682                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6683                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6684
6685     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6686                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6687
6688     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6689                                      MLD->isExpandingLoad());
6690
6691     MMO = DAG.getMachineFunction().
6692     getMachineMemOperand(MLD->getPointerInfo(),
6693                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6694                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6695
6696     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6697                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6698
6699     AddToWorklist(Lo.getNode());
6700     AddToWorklist(Hi.getNode());
6701
6702     // Build a factor node to remember that this load is independent of the
6703     // other one.
6704     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6705                         Hi.getValue(1));
6706
6707     // Legalized the chain result - switch anything that used the old chain to
6708     // use the new one.
6709     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6710
6711     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6712
6713     SDValue RetOps[] = { LoadRes, Chain };
6714     return DAG.getMergeValues(RetOps, DL);
6715   }
6716   return SDValue();
6717 }
6718
6719 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6720   SDValue N0 = N->getOperand(0);
6721   SDValue N1 = N->getOperand(1);
6722   SDValue N2 = N->getOperand(2);
6723   SDLoc DL(N);
6724
6725   // fold (vselect C, X, X) -> X
6726   if (N1 == N2)
6727     return N1;
6728
6729   // Canonicalize integer abs.
6730   // vselect (setg[te] X,  0),  X, -X ->
6731   // vselect (setgt    X, -1),  X, -X ->
6732   // vselect (setl[te] X,  0), -X,  X ->
6733   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6734   if (N0.getOpcode() == ISD::SETCC) {
6735     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6736     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6737     bool isAbs = false;
6738     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6739
6740     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6741          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6742         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6743       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6744     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6745              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6746       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6747
6748     if (isAbs) {
6749       EVT VT = LHS.getValueType();
6750       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
6751         return DAG.getNode(ISD::ABS, DL, VT, LHS);
6752
6753       SDValue Shift = DAG.getNode(
6754           ISD::SRA, DL, VT, LHS,
6755           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6756       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6757       AddToWorklist(Shift.getNode());
6758       AddToWorklist(Add.getNode());
6759       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6760     }
6761   }
6762
6763   if (SimplifySelectOps(N, N1, N2))
6764     return SDValue(N, 0);  // Don't revisit N.
6765
6766   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6767   if (ISD::isBuildVectorAllOnes(N0.getNode()))
6768     return N1;
6769   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6770   if (ISD::isBuildVectorAllZeros(N0.getNode()))
6771     return N2;
6772
6773   // The ConvertSelectToConcatVector function is assuming both the above
6774   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6775   // and addressed.
6776   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6777       N2.getOpcode() == ISD::CONCAT_VECTORS &&
6778       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6779     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6780       return CV;
6781   }
6782
6783   return SDValue();
6784 }
6785
6786 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6787   SDValue N0 = N->getOperand(0);
6788   SDValue N1 = N->getOperand(1);
6789   SDValue N2 = N->getOperand(2);
6790   SDValue N3 = N->getOperand(3);
6791   SDValue N4 = N->getOperand(4);
6792   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6793
6794   // fold select_cc lhs, rhs, x, x, cc -> x
6795   if (N2 == N3)
6796     return N2;
6797
6798   // Determine if the condition we're dealing with is constant
6799   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6800                                   CC, SDLoc(N), false)) {
6801     AddToWorklist(SCC.getNode());
6802
6803     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6804       if (!SCCC->isNullValue())
6805         return N2;    // cond always true -> true val
6806       else
6807         return N3;    // cond always false -> false val
6808     } else if (SCC->isUndef()) {
6809       // When the condition is UNDEF, just return the first operand. This is
6810       // coherent the DAG creation, no setcc node is created in this case
6811       return N2;
6812     } else if (SCC.getOpcode() == ISD::SETCC) {
6813       // Fold to a simpler select_cc
6814       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6815                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6816                          SCC.getOperand(2));
6817     }
6818   }
6819
6820   // If we can fold this based on the true/false value, do so.
6821   if (SimplifySelectOps(N, N2, N3))
6822     return SDValue(N, 0);  // Don't revisit N.
6823
6824   // fold select_cc into other things, such as min/max/abs
6825   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6826 }
6827
6828 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6829   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6830                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
6831                        SDLoc(N));
6832 }
6833
6834 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6835   SDValue LHS = N->getOperand(0);
6836   SDValue RHS = N->getOperand(1);
6837   SDValue Carry = N->getOperand(2);
6838   SDValue Cond = N->getOperand(3);
6839
6840   // If Carry is false, fold to a regular SETCC.
6841   if (Carry.getOpcode() == ISD::CARRY_FALSE)
6842     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6843
6844   return SDValue();
6845 }
6846
6847 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
6848   SDValue LHS = N->getOperand(0);
6849   SDValue RHS = N->getOperand(1);
6850   SDValue Carry = N->getOperand(2);
6851   SDValue Cond = N->getOperand(3);
6852
6853   // If Carry is false, fold to a regular SETCC.
6854   if (isNullConstant(Carry))
6855     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6856
6857   return SDValue();
6858 }
6859
6860 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6861 /// a build_vector of constants.
6862 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6863 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6864 /// Vector extends are not folded if operations are legal; this is to
6865 /// avoid introducing illegal build_vector dag nodes.
6866 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6867                                          SelectionDAG &DAG, bool LegalTypes,
6868                                          bool LegalOperations) {
6869   unsigned Opcode = N->getOpcode();
6870   SDValue N0 = N->getOperand(0);
6871   EVT VT = N->getValueType(0);
6872
6873   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6874          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6875          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6876          && "Expected EXTEND dag node in input!");
6877
6878   // fold (sext c1) -> c1
6879   // fold (zext c1) -> c1
6880   // fold (aext c1) -> c1
6881   if (isa<ConstantSDNode>(N0))
6882     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6883
6884   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6885   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6886   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6887   EVT SVT = VT.getScalarType();
6888   if (!(VT.isVector() &&
6889       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6890       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6891     return nullptr;
6892
6893   // We can fold this node into a build_vector.
6894   unsigned VTBits = SVT.getSizeInBits();
6895   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6896   SmallVector<SDValue, 8> Elts;
6897   unsigned NumElts = VT.getVectorNumElements();
6898   SDLoc DL(N);
6899
6900   for (unsigned i=0; i != NumElts; ++i) {
6901     SDValue Op = N0->getOperand(i);
6902     if (Op->isUndef()) {
6903       Elts.push_back(DAG.getUNDEF(SVT));
6904       continue;
6905     }
6906
6907     SDLoc DL(Op);
6908     // Get the constant value and if needed trunc it to the size of the type.
6909     // Nodes like build_vector might have constants wider than the scalar type.
6910     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6911     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6912       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6913     else
6914       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6915   }
6916
6917   return DAG.getBuildVector(VT, DL, Elts).getNode();
6918 }
6919
6920 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6921 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6922 // transformation. Returns true if extension are possible and the above
6923 // mentioned transformation is profitable.
6924 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6925                                     unsigned ExtOpc,
6926                                     SmallVectorImpl<SDNode *> &ExtendNodes,
6927                                     const TargetLowering &TLI) {
6928   bool HasCopyToRegUses = false;
6929   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6930   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6931                             UE = N0.getNode()->use_end();
6932        UI != UE; ++UI) {
6933     SDNode *User = *UI;
6934     if (User == N)
6935       continue;
6936     if (UI.getUse().getResNo() != N0.getResNo())
6937       continue;
6938     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6939     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6940       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6941       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6942         // Sign bits will be lost after a zext.
6943         return false;
6944       bool Add = false;
6945       for (unsigned i = 0; i != 2; ++i) {
6946         SDValue UseOp = User->getOperand(i);
6947         if (UseOp == N0)
6948           continue;
6949         if (!isa<ConstantSDNode>(UseOp))
6950           return false;
6951         Add = true;
6952       }
6953       if (Add)
6954         ExtendNodes.push_back(User);
6955       continue;
6956     }
6957     // If truncates aren't free and there are users we can't
6958     // extend, it isn't worthwhile.
6959     if (!isTruncFree)
6960       return false;
6961     // Remember if this value is live-out.
6962     if (User->getOpcode() == ISD::CopyToReg)
6963       HasCopyToRegUses = true;
6964   }
6965
6966   if (HasCopyToRegUses) {
6967     bool BothLiveOut = false;
6968     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6969          UI != UE; ++UI) {
6970       SDUse &Use = UI.getUse();
6971       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6972         BothLiveOut = true;
6973         break;
6974       }
6975     }
6976     if (BothLiveOut)
6977       // Both unextended and extended values are live out. There had better be
6978       // a good reason for the transformation.
6979       return ExtendNodes.size();
6980   }
6981   return true;
6982 }
6983
6984 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6985                                   SDValue Trunc, SDValue ExtLoad,
6986                                   const SDLoc &DL, ISD::NodeType ExtType) {
6987   // Extend SetCC uses if necessary.
6988   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6989     SDNode *SetCC = SetCCs[i];
6990     SmallVector<SDValue, 4> Ops;
6991
6992     for (unsigned j = 0; j != 2; ++j) {
6993       SDValue SOp = SetCC->getOperand(j);
6994       if (SOp == Trunc)
6995         Ops.push_back(ExtLoad);
6996       else
6997         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6998     }
6999
7000     Ops.push_back(SetCC->getOperand(2));
7001     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7002   }
7003 }
7004
7005 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
7006 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
7007   SDValue N0 = N->getOperand(0);
7008   EVT DstVT = N->getValueType(0);
7009   EVT SrcVT = N0.getValueType();
7010
7011   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
7012           N->getOpcode() == ISD::ZERO_EXTEND) &&
7013          "Unexpected node type (not an extend)!");
7014
7015   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
7016   // For example, on a target with legal v4i32, but illegal v8i32, turn:
7017   //   (v8i32 (sext (v8i16 (load x))))
7018   // into:
7019   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
7020   //                          (v4i32 (sextload (x + 16)))))
7021   // Where uses of the original load, i.e.:
7022   //   (v8i16 (load x))
7023   // are replaced with:
7024   //   (v8i16 (truncate
7025   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
7026   //                            (v4i32 (sextload (x + 16)))))))
7027   //
7028   // This combine is only applicable to illegal, but splittable, vectors.
7029   // All legal types, and illegal non-vector types, are handled elsewhere.
7030   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
7031   //
7032   if (N0->getOpcode() != ISD::LOAD)
7033     return SDValue();
7034
7035   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7036
7037   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
7038       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
7039       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
7040     return SDValue();
7041
7042   SmallVector<SDNode *, 4> SetCCs;
7043   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
7044     return SDValue();
7045
7046   ISD::LoadExtType ExtType =
7047       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
7048
7049   // Try to split the vector types to get down to legal types.
7050   EVT SplitSrcVT = SrcVT;
7051   EVT SplitDstVT = DstVT;
7052   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
7053          SplitSrcVT.getVectorNumElements() > 1) {
7054     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
7055     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
7056   }
7057
7058   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7059     return SDValue();
7060
7061   SDLoc DL(N);
7062   const unsigned NumSplits =
7063       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7064   const unsigned Stride = SplitSrcVT.getStoreSize();
7065   SmallVector<SDValue, 4> Loads;
7066   SmallVector<SDValue, 4> Chains;
7067
7068   SDValue BasePtr = LN0->getBasePtr();
7069   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7070     const unsigned Offset = Idx * Stride;
7071     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7072
7073     SDValue SplitLoad = DAG.getExtLoad(
7074         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7075         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7076         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7077
7078     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7079                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7080
7081     Loads.push_back(SplitLoad.getValue(0));
7082     Chains.push_back(SplitLoad.getValue(1));
7083   }
7084
7085   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7086   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7087
7088   // Simplify TF.
7089   AddToWorklist(NewChain.getNode());
7090
7091   CombineTo(N, NewValue);
7092
7093   // Replace uses of the original load (before extension)
7094   // with a truncate of the concatenated sextloaded vectors.
7095   SDValue Trunc =
7096       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7097   CombineTo(N0.getNode(), Trunc, NewChain);
7098   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
7099                   (ISD::NodeType)N->getOpcode());
7100   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7101 }
7102
7103 /// If we're narrowing or widening the result of a vector select and the final
7104 /// size is the same size as a setcc (compare) feeding the select, then try to
7105 /// apply the cast operation to the select's operands because matching vector
7106 /// sizes for a select condition and other operands should be more efficient.
7107 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7108   unsigned CastOpcode = Cast->getOpcode();
7109   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7110           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7111           CastOpcode == ISD::FP_ROUND) &&
7112          "Unexpected opcode for vector select narrowing/widening");
7113
7114   // We only do this transform before legal ops because the pattern may be
7115   // obfuscated by target-specific operations after legalization. Do not create
7116   // an illegal select op, however, because that may be difficult to lower.
7117   EVT VT = Cast->getValueType(0);
7118   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7119     return SDValue();
7120
7121   SDValue VSel = Cast->getOperand(0);
7122   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7123       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7124     return SDValue();
7125
7126   // Does the setcc have the same vector size as the casted select?
7127   SDValue SetCC = VSel.getOperand(0);
7128   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7129   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7130     return SDValue();
7131
7132   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7133   SDValue A = VSel.getOperand(1);
7134   SDValue B = VSel.getOperand(2);
7135   SDValue CastA, CastB;
7136   SDLoc DL(Cast);
7137   if (CastOpcode == ISD::FP_ROUND) {
7138     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7139     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7140     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7141   } else {
7142     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7143     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7144   }
7145   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7146 }
7147
7148 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7149   SDValue N0 = N->getOperand(0);
7150   EVT VT = N->getValueType(0);
7151   SDLoc DL(N);
7152
7153   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7154                                               LegalOperations))
7155     return SDValue(Res, 0);
7156
7157   // fold (sext (sext x)) -> (sext x)
7158   // fold (sext (aext x)) -> (sext x)
7159   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7160     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7161
7162   if (N0.getOpcode() == ISD::TRUNCATE) {
7163     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7164     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7165     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7166       SDNode *oye = N0.getOperand(0).getNode();
7167       if (NarrowLoad.getNode() != N0.getNode()) {
7168         CombineTo(N0.getNode(), NarrowLoad);
7169         // CombineTo deleted the truncate, if needed, but not what's under it.
7170         AddToWorklist(oye);
7171       }
7172       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7173     }
7174
7175     // See if the value being truncated is already sign extended.  If so, just
7176     // eliminate the trunc/sext pair.
7177     SDValue Op = N0.getOperand(0);
7178     unsigned OpBits   = Op.getScalarValueSizeInBits();
7179     unsigned MidBits  = N0.getScalarValueSizeInBits();
7180     unsigned DestBits = VT.getScalarSizeInBits();
7181     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7182
7183     if (OpBits == DestBits) {
7184       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7185       // bits, it is already ready.
7186       if (NumSignBits > DestBits-MidBits)
7187         return Op;
7188     } else if (OpBits < DestBits) {
7189       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7190       // bits, just sext from i32.
7191       if (NumSignBits > OpBits-MidBits)
7192         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7193     } else {
7194       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7195       // bits, just truncate to i32.
7196       if (NumSignBits > OpBits-MidBits)
7197         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7198     }
7199
7200     // fold (sext (truncate x)) -> (sextinreg x).
7201     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7202                                                  N0.getValueType())) {
7203       if (OpBits < DestBits)
7204         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7205       else if (OpBits > DestBits)
7206         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7207       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7208                          DAG.getValueType(N0.getValueType()));
7209     }
7210   }
7211
7212   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7213   // Only generate vector extloads when 1) they're legal, and 2) they are
7214   // deemed desirable by the target.
7215   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7216       ((!LegalOperations && !VT.isVector() &&
7217         !cast<LoadSDNode>(N0)->isVolatile()) ||
7218        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7219     bool DoXform = true;
7220     SmallVector<SDNode*, 4> SetCCs;
7221     if (!N0.hasOneUse())
7222       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7223     if (VT.isVector())
7224       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7225     if (DoXform) {
7226       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7227       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7228                                        LN0->getBasePtr(), N0.getValueType(),
7229                                        LN0->getMemOperand());
7230       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7231                                   N0.getValueType(), ExtLoad);
7232       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7233       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7234       return CombineTo(N, ExtLoad); // Return N so it doesn't get rechecked!
7235     }
7236   }
7237
7238   // fold (sext (load x)) to multiple smaller sextloads.
7239   // Only on illegal but splittable vectors.
7240   if (SDValue ExtLoad = CombineExtLoad(N))
7241     return ExtLoad;
7242
7243   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7244   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7245   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7246       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7247     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7248     EVT MemVT = LN0->getMemoryVT();
7249     if ((!LegalOperations && !LN0->isVolatile()) ||
7250         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7251       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7252                                        LN0->getBasePtr(), MemVT,
7253                                        LN0->getMemOperand());
7254       CombineTo(N, ExtLoad);
7255       CombineTo(N0.getNode(),
7256                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7257                             N0.getValueType(), ExtLoad),
7258                 ExtLoad.getValue(1));
7259       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7260     }
7261   }
7262
7263   // fold (sext (and/or/xor (load x), cst)) ->
7264   //      (and/or/xor (sextload x), (sext cst))
7265   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7266        N0.getOpcode() == ISD::XOR) &&
7267       isa<LoadSDNode>(N0.getOperand(0)) &&
7268       N0.getOperand(1).getOpcode() == ISD::Constant &&
7269       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7270       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7271     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7272     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7273       bool DoXform = true;
7274       SmallVector<SDNode*, 4> SetCCs;
7275       if (!N0.hasOneUse())
7276         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7277                                           SetCCs, TLI);
7278       if (DoXform) {
7279         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7280                                          LN0->getChain(), LN0->getBasePtr(),
7281                                          LN0->getMemoryVT(),
7282                                          LN0->getMemOperand());
7283         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7284         Mask = Mask.sext(VT.getSizeInBits());
7285         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7286                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7287         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7288                                     SDLoc(N0.getOperand(0)),
7289                                     N0.getOperand(0).getValueType(), ExtLoad);
7290         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7291         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7292         return CombineTo(N, And); // Return N so it doesn't get rechecked!
7293       }
7294     }
7295   }
7296
7297   if (N0.getOpcode() == ISD::SETCC) {
7298     SDValue N00 = N0.getOperand(0);
7299     SDValue N01 = N0.getOperand(1);
7300     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7301     EVT N00VT = N0.getOperand(0).getValueType();
7302
7303     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7304     // Only do this before legalize for now.
7305     if (VT.isVector() && !LegalOperations &&
7306         TLI.getBooleanContents(N00VT) ==
7307             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7308       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7309       // of the same size as the compared operands. Only optimize sext(setcc())
7310       // if this is the case.
7311       EVT SVT = getSetCCResultType(N00VT);
7312
7313       // We know that the # elements of the results is the same as the
7314       // # elements of the compare (and the # elements of the compare result
7315       // for that matter).  Check to see that they are the same size.  If so,
7316       // we know that the element size of the sext'd result matches the
7317       // element size of the compare operands.
7318       if (VT.getSizeInBits() == SVT.getSizeInBits())
7319         return DAG.getSetCC(DL, VT, N00, N01, CC);
7320
7321       // If the desired elements are smaller or larger than the source
7322       // elements, we can use a matching integer vector type and then
7323       // truncate/sign extend.
7324       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7325       if (SVT == MatchingVecType) {
7326         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7327         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7328       }
7329     }
7330
7331     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7332     // Here, T can be 1 or -1, depending on the type of the setcc and
7333     // getBooleanContents().
7334     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7335
7336     // To determine the "true" side of the select, we need to know the high bit
7337     // of the value returned by the setcc if it evaluates to true.
7338     // If the type of the setcc is i1, then the true case of the select is just
7339     // sext(i1 1), that is, -1.
7340     // If the type of the setcc is larger (say, i8) then the value of the high
7341     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7342     // of the appropriate width.
7343     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7344                                            : TLI.getConstTrueVal(DAG, VT, DL);
7345     SDValue Zero = DAG.getConstant(0, DL, VT);
7346     if (SDValue SCC =
7347             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7348       return SCC;
7349
7350     if (!VT.isVector()) {
7351       EVT SetCCVT = getSetCCResultType(N00VT);
7352       // Don't do this transform for i1 because there's a select transform
7353       // that would reverse it.
7354       // TODO: We should not do this transform at all without a target hook
7355       // because a sext is likely cheaper than a select?
7356       if (SetCCVT.getScalarSizeInBits() != 1 &&
7357           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7358         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7359         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7360       }
7361     }
7362   }
7363
7364   // fold (sext x) -> (zext x) if the sign bit is known zero.
7365   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7366       DAG.SignBitIsZero(N0))
7367     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7368
7369   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7370     return NewVSel;
7371
7372   return SDValue();
7373 }
7374
7375 // isTruncateOf - If N is a truncate of some other value, return true, record
7376 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7377 // This function computes KnownBits to avoid a duplicated call to
7378 // computeKnownBits in the caller.
7379 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7380                          KnownBits &Known) {
7381   if (N->getOpcode() == ISD::TRUNCATE) {
7382     Op = N->getOperand(0);
7383     DAG.computeKnownBits(Op, Known);
7384     return true;
7385   }
7386
7387   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7388       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7389     return false;
7390
7391   SDValue Op0 = N->getOperand(0);
7392   SDValue Op1 = N->getOperand(1);
7393   assert(Op0.getValueType() == Op1.getValueType());
7394
7395   if (isNullConstant(Op0))
7396     Op = Op1;
7397   else if (isNullConstant(Op1))
7398     Op = Op0;
7399   else
7400     return false;
7401
7402   DAG.computeKnownBits(Op, Known);
7403
7404   if (!(Known.Zero | 1).isAllOnesValue())
7405     return false;
7406
7407   return true;
7408 }
7409
7410 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7411   SDValue N0 = N->getOperand(0);
7412   EVT VT = N->getValueType(0);
7413
7414   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7415                                               LegalOperations))
7416     return SDValue(Res, 0);
7417
7418   // fold (zext (zext x)) -> (zext x)
7419   // fold (zext (aext x)) -> (zext x)
7420   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7421     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7422                        N0.getOperand(0));
7423
7424   // fold (zext (truncate x)) -> (zext x) or
7425   //      (zext (truncate x)) -> (truncate x)
7426   // This is valid when the truncated bits of x are already zero.
7427   // FIXME: We should extend this to work for vectors too.
7428   SDValue Op;
7429   KnownBits Known;
7430   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7431     APInt TruncatedBits =
7432       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7433       APInt(Op.getValueSizeInBits(), 0) :
7434       APInt::getBitsSet(Op.getValueSizeInBits(),
7435                         N0.getValueSizeInBits(),
7436                         std::min(Op.getValueSizeInBits(),
7437                                  VT.getSizeInBits()));
7438     if (TruncatedBits.isSubsetOf(Known.Zero))
7439       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7440   }
7441
7442   // fold (zext (truncate (load x))) -> (zext (smaller load x))
7443   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7444   if (N0.getOpcode() == ISD::TRUNCATE) {
7445     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7446       SDNode *oye = N0.getOperand(0).getNode();
7447       if (NarrowLoad.getNode() != N0.getNode()) {
7448         CombineTo(N0.getNode(), NarrowLoad);
7449         // CombineTo deleted the truncate, if needed, but not what's under it.
7450         AddToWorklist(oye);
7451       }
7452       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7453     }
7454   }
7455
7456   // fold (zext (truncate x)) -> (and x, mask)
7457   if (N0.getOpcode() == ISD::TRUNCATE) {
7458     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7459     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7460     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7461       SDNode *oye = N0.getOperand(0).getNode();
7462       if (NarrowLoad.getNode() != N0.getNode()) {
7463         CombineTo(N0.getNode(), NarrowLoad);
7464         // CombineTo deleted the truncate, if needed, but not what's under it.
7465         AddToWorklist(oye);
7466       }
7467       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7468     }
7469
7470     EVT SrcVT = N0.getOperand(0).getValueType();
7471     EVT MinVT = N0.getValueType();
7472
7473     // Try to mask before the extension to avoid having to generate a larger mask,
7474     // possibly over several sub-vectors.
7475     if (SrcVT.bitsLT(VT)) {
7476       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7477                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7478         SDValue Op = N0.getOperand(0);
7479         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7480         AddToWorklist(Op.getNode());
7481         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7482       }
7483     }
7484
7485     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7486       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7487       AddToWorklist(Op.getNode());
7488       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7489     }
7490   }
7491
7492   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7493   // if either of the casts is not free.
7494   if (N0.getOpcode() == ISD::AND &&
7495       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7496       N0.getOperand(1).getOpcode() == ISD::Constant &&
7497       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7498                            N0.getValueType()) ||
7499        !TLI.isZExtFree(N0.getValueType(), VT))) {
7500     SDValue X = N0.getOperand(0).getOperand(0);
7501     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7502     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7503     Mask = Mask.zext(VT.getSizeInBits());
7504     SDLoc DL(N);
7505     return DAG.getNode(ISD::AND, DL, VT,
7506                        X, DAG.getConstant(Mask, DL, VT));
7507   }
7508
7509   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7510   // Only generate vector extloads when 1) they're legal, and 2) they are
7511   // deemed desirable by the target.
7512   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7513       ((!LegalOperations && !VT.isVector() &&
7514         !cast<LoadSDNode>(N0)->isVolatile()) ||
7515        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7516     bool DoXform = true;
7517     SmallVector<SDNode*, 4> SetCCs;
7518     if (!N0.hasOneUse())
7519       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7520     if (VT.isVector())
7521       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7522     if (DoXform) {
7523       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7524       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7525                                        LN0->getChain(),
7526                                        LN0->getBasePtr(), N0.getValueType(),
7527                                        LN0->getMemOperand());
7528
7529       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7530                                   N0.getValueType(), ExtLoad);
7531       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
7532       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7533       return CombineTo(N, ExtLoad); // Return N so it doesn't get rechecked!
7534     }
7535   }
7536
7537   // fold (zext (load x)) to multiple smaller zextloads.
7538   // Only on illegal but splittable vectors.
7539   if (SDValue ExtLoad = CombineExtLoad(N))
7540     return ExtLoad;
7541
7542   // fold (zext (and/or/xor (load x), cst)) ->
7543   //      (and/or/xor (zextload x), (zext cst))
7544   // Unless (and (load x) cst) will match as a zextload already and has
7545   // additional users.
7546   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7547        N0.getOpcode() == ISD::XOR) &&
7548       isa<LoadSDNode>(N0.getOperand(0)) &&
7549       N0.getOperand(1).getOpcode() == ISD::Constant &&
7550       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7551       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7552     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7553     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7554       bool DoXform = true;
7555       SmallVector<SDNode*, 4> SetCCs;
7556       if (!N0.hasOneUse()) {
7557         if (N0.getOpcode() == ISD::AND) {
7558           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7559           auto NarrowLoad = false;
7560           EVT LoadResultTy = AndC->getValueType(0);
7561           EVT ExtVT, LoadedVT;
7562           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7563                                NarrowLoad))
7564             DoXform = false;
7565         }
7566         if (DoXform)
7567           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7568                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7569       }
7570       if (DoXform) {
7571         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7572                                          LN0->getChain(), LN0->getBasePtr(),
7573                                          LN0->getMemoryVT(),
7574                                          LN0->getMemOperand());
7575         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7576         Mask = Mask.zext(VT.getSizeInBits());
7577         SDLoc DL(N);
7578         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7579                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7580         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7581                                     SDLoc(N0.getOperand(0)),
7582                                     N0.getOperand(0).getValueType(), ExtLoad);
7583         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND);
7584         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7585         return CombineTo(N, And); // Return N so it doesn't get rechecked!
7586       }
7587     }
7588   }
7589
7590   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7591   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7592   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7593       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7594     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7595     EVT MemVT = LN0->getMemoryVT();
7596     if ((!LegalOperations && !LN0->isVolatile()) ||
7597         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7598       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7599                                        LN0->getChain(),
7600                                        LN0->getBasePtr(), MemVT,
7601                                        LN0->getMemOperand());
7602       CombineTo(N, ExtLoad);
7603       CombineTo(N0.getNode(),
7604                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7605                             ExtLoad),
7606                 ExtLoad.getValue(1));
7607       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7608     }
7609   }
7610
7611   if (N0.getOpcode() == ISD::SETCC) {
7612     // Only do this before legalize for now.
7613     if (!LegalOperations && VT.isVector() &&
7614         N0.getValueType().getVectorElementType() == MVT::i1) {
7615       EVT N00VT = N0.getOperand(0).getValueType();
7616       if (getSetCCResultType(N00VT) == N0.getValueType())
7617         return SDValue();
7618
7619       // We know that the # elements of the results is the same as the #
7620       // elements of the compare (and the # elements of the compare result for
7621       // that matter). Check to see that they are the same size. If so, we know
7622       // that the element size of the sext'd result matches the element size of
7623       // the compare operands.
7624       SDLoc DL(N);
7625       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7626       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7627         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7628         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7629                                      N0.getOperand(1), N0.getOperand(2));
7630         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7631       }
7632
7633       // If the desired elements are smaller or larger than the source
7634       // elements we can use a matching integer vector type and then
7635       // truncate/sign extend.
7636       EVT MatchingElementType = EVT::getIntegerVT(
7637           *DAG.getContext(), N00VT.getScalarSizeInBits());
7638       EVT MatchingVectorType = EVT::getVectorVT(
7639           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7640       SDValue VsetCC =
7641           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7642                       N0.getOperand(1), N0.getOperand(2));
7643       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7644                          VecOnes);
7645     }
7646
7647     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7648     SDLoc DL(N);
7649     if (SDValue SCC = SimplifySelectCC(
7650             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7651             DAG.getConstant(0, DL, VT),
7652             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7653       return SCC;
7654   }
7655
7656   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7657   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7658       isa<ConstantSDNode>(N0.getOperand(1)) &&
7659       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7660       N0.hasOneUse()) {
7661     SDValue ShAmt = N0.getOperand(1);
7662     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7663     if (N0.getOpcode() == ISD::SHL) {
7664       SDValue InnerZExt = N0.getOperand(0);
7665       // If the original shl may be shifting out bits, do not perform this
7666       // transformation.
7667       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7668         InnerZExt.getOperand(0).getValueSizeInBits();
7669       if (ShAmtVal > KnownZeroBits)
7670         return SDValue();
7671     }
7672
7673     SDLoc DL(N);
7674
7675     // Ensure that the shift amount is wide enough for the shifted value.
7676     if (VT.getSizeInBits() >= 256)
7677       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7678
7679     return DAG.getNode(N0.getOpcode(), DL, VT,
7680                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7681                        ShAmt);
7682   }
7683
7684   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7685     return NewVSel;
7686
7687   return SDValue();
7688 }
7689
7690 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7691   SDValue N0 = N->getOperand(0);
7692   EVT VT = N->getValueType(0);
7693
7694   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7695                                               LegalOperations))
7696     return SDValue(Res, 0);
7697
7698   // fold (aext (aext x)) -> (aext x)
7699   // fold (aext (zext x)) -> (zext x)
7700   // fold (aext (sext x)) -> (sext x)
7701   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
7702       N0.getOpcode() == ISD::ZERO_EXTEND ||
7703       N0.getOpcode() == ISD::SIGN_EXTEND)
7704     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7705
7706   // fold (aext (truncate (load x))) -> (aext (smaller load x))
7707   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7708   if (N0.getOpcode() == ISD::TRUNCATE) {
7709     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7710       SDNode *oye = N0.getOperand(0).getNode();
7711       if (NarrowLoad.getNode() != N0.getNode()) {
7712         CombineTo(N0.getNode(), NarrowLoad);
7713         // CombineTo deleted the truncate, if needed, but not what's under it.
7714         AddToWorklist(oye);
7715       }
7716       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7717     }
7718   }
7719
7720   // fold (aext (truncate x))
7721   if (N0.getOpcode() == ISD::TRUNCATE)
7722     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7723
7724   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7725   // if the trunc is not free.
7726   if (N0.getOpcode() == ISD::AND &&
7727       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7728       N0.getOperand(1).getOpcode() == ISD::Constant &&
7729       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7730                           N0.getValueType())) {
7731     SDLoc DL(N);
7732     SDValue X = N0.getOperand(0).getOperand(0);
7733     X = DAG.getAnyExtOrTrunc(X, DL, VT);
7734     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7735     Mask = Mask.zext(VT.getSizeInBits());
7736     return DAG.getNode(ISD::AND, DL, VT,
7737                        X, DAG.getConstant(Mask, DL, VT));
7738   }
7739
7740   // fold (aext (load x)) -> (aext (truncate (extload x)))
7741   // None of the supported targets knows how to perform load and any_ext
7742   // on vectors in one instruction.  We only perform this transformation on
7743   // scalars.
7744   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7745       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7746       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7747     bool DoXform = true;
7748     SmallVector<SDNode*, 4> SetCCs;
7749     if (!N0.hasOneUse())
7750       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7751     if (DoXform) {
7752       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7753       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7754                                        LN0->getChain(),
7755                                        LN0->getBasePtr(), N0.getValueType(),
7756                                        LN0->getMemOperand());
7757       CombineTo(N, ExtLoad);
7758       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7759                                   N0.getValueType(), ExtLoad);
7760       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7761       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7762                       ISD::ANY_EXTEND);
7763       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7764     }
7765   }
7766
7767   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7768   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7769   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
7770   if (N0.getOpcode() == ISD::LOAD &&
7771       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7772       N0.hasOneUse()) {
7773     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7774     ISD::LoadExtType ExtType = LN0->getExtensionType();
7775     EVT MemVT = LN0->getMemoryVT();
7776     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7777       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7778                                        VT, LN0->getChain(), LN0->getBasePtr(),
7779                                        MemVT, LN0->getMemOperand());
7780       CombineTo(N, ExtLoad);
7781       CombineTo(N0.getNode(),
7782                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7783                             N0.getValueType(), ExtLoad),
7784                 ExtLoad.getValue(1));
7785       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7786     }
7787   }
7788
7789   if (N0.getOpcode() == ISD::SETCC) {
7790     // For vectors:
7791     // aext(setcc) -> vsetcc
7792     // aext(setcc) -> truncate(vsetcc)
7793     // aext(setcc) -> aext(vsetcc)
7794     // Only do this before legalize for now.
7795     if (VT.isVector() && !LegalOperations) {
7796       EVT N0VT = N0.getOperand(0).getValueType();
7797         // We know that the # elements of the results is the same as the
7798         // # elements of the compare (and the # elements of the compare result
7799         // for that matter).  Check to see that they are the same size.  If so,
7800         // we know that the element size of the sext'd result matches the
7801         // element size of the compare operands.
7802       if (VT.getSizeInBits() == N0VT.getSizeInBits())
7803         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7804                              N0.getOperand(1),
7805                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
7806       // If the desired elements are smaller or larger than the source
7807       // elements we can use a matching integer vector type and then
7808       // truncate/any extend
7809       else {
7810         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7811         SDValue VsetCC =
7812           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7813                         N0.getOperand(1),
7814                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
7815         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7816       }
7817     }
7818
7819     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7820     SDLoc DL(N);
7821     if (SDValue SCC = SimplifySelectCC(
7822             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7823             DAG.getConstant(0, DL, VT),
7824             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7825       return SCC;
7826   }
7827
7828   return SDValue();
7829 }
7830
7831 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7832   SDValue N0 = N->getOperand(0);
7833   SDValue N1 = N->getOperand(1);
7834   EVT EVT = cast<VTSDNode>(N1)->getVT();
7835
7836   // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7837   if (N0.getOpcode() == ISD::AssertZext &&
7838       EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7839     return N0;
7840
7841   return SDValue();
7842 }
7843
7844 /// See if the specified operand can be simplified with the knowledge that only
7845 /// the bits specified by Mask are used.  If so, return the simpler operand,
7846 /// otherwise return a null SDValue.
7847 ///
7848 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
7849 /// simplify nodes with multiple uses more aggressively.)
7850 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7851   switch (V.getOpcode()) {
7852   default: break;
7853   case ISD::Constant: {
7854     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7855     assert(CV && "Const value should be ConstSDNode.");
7856     const APInt &CVal = CV->getAPIntValue();
7857     APInt NewVal = CVal & Mask;
7858     if (NewVal != CVal)
7859       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7860     break;
7861   }
7862   case ISD::OR:
7863   case ISD::XOR:
7864     // If the LHS or RHS don't contribute bits to the or, drop them.
7865     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7866       return V.getOperand(1);
7867     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7868       return V.getOperand(0);
7869     break;
7870   case ISD::SRL:
7871     // Only look at single-use SRLs.
7872     if (!V.getNode()->hasOneUse())
7873       break;
7874     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7875       // See if we can recursively simplify the LHS.
7876       unsigned Amt = RHSC->getZExtValue();
7877
7878       // Watch out for shift count overflow though.
7879       if (Amt >= Mask.getBitWidth()) break;
7880       APInt NewMask = Mask << Amt;
7881       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7882         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7883                            SimplifyLHS, V.getOperand(1));
7884     }
7885     break;
7886   case ISD::AND: {
7887     // X & -1 -> X (ignoring bits which aren't demanded).
7888     ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
7889     if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
7890       return V.getOperand(0);
7891     break;
7892   }
7893   }
7894   return SDValue();
7895 }
7896
7897 /// If the result of a wider load is shifted to right of N  bits and then
7898 /// truncated to a narrower type and where N is a multiple of number of bits of
7899 /// the narrower type, transform it to a narrower load from address + N / num of
7900 /// bits of new type. If the result is to be extended, also fold the extension
7901 /// to form a extending load.
7902 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7903   unsigned Opc = N->getOpcode();
7904
7905   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7906   SDValue N0 = N->getOperand(0);
7907   EVT VT = N->getValueType(0);
7908   EVT ExtVT = VT;
7909
7910   // This transformation isn't valid for vector loads.
7911   if (VT.isVector())
7912     return SDValue();
7913
7914   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7915   // extended to VT.
7916   if (Opc == ISD::SIGN_EXTEND_INREG) {
7917     ExtType = ISD::SEXTLOAD;
7918     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7919   } else if (Opc == ISD::SRL) {
7920     // Another special-case: SRL is basically zero-extending a narrower value.
7921     ExtType = ISD::ZEXTLOAD;
7922     N0 = SDValue(N, 0);
7923     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7924     if (!N01) return SDValue();
7925     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7926                               VT.getSizeInBits() - N01->getZExtValue());
7927   }
7928   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7929     return SDValue();
7930
7931   unsigned EVTBits = ExtVT.getSizeInBits();
7932
7933   // Do not generate loads of non-round integer types since these can
7934   // be expensive (and would be wrong if the type is not byte sized).
7935   if (!ExtVT.isRound())
7936     return SDValue();
7937
7938   unsigned ShAmt = 0;
7939   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7940     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7941       ShAmt = N01->getZExtValue();
7942       // Is the shift amount a multiple of size of VT?
7943       if ((ShAmt & (EVTBits-1)) == 0) {
7944         N0 = N0.getOperand(0);
7945         // Is the load width a multiple of size of VT?
7946         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7947           return SDValue();
7948       }
7949
7950       // At this point, we must have a load or else we can't do the transform.
7951       if (!isa<LoadSDNode>(N0)) return SDValue();
7952
7953       // Because a SRL must be assumed to *need* to zero-extend the high bits
7954       // (as opposed to anyext the high bits), we can't combine the zextload
7955       // lowering of SRL and an sextload.
7956       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7957         return SDValue();
7958
7959       // If the shift amount is larger than the input type then we're not
7960       // accessing any of the loaded bytes.  If the load was a zextload/extload
7961       // then the result of the shift+trunc is zero/undef (handled elsewhere).
7962       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7963         return SDValue();
7964     }
7965   }
7966
7967   // If the load is shifted left (and the result isn't shifted back right),
7968   // we can fold the truncate through the shift.
7969   unsigned ShLeftAmt = 0;
7970   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7971       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7972     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7973       ShLeftAmt = N01->getZExtValue();
7974       N0 = N0.getOperand(0);
7975     }
7976   }
7977
7978   // If we haven't found a load, we can't narrow it.  Don't transform one with
7979   // multiple uses, this would require adding a new load.
7980   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7981     return SDValue();
7982
7983   // Don't change the width of a volatile load.
7984   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7985   if (LN0->isVolatile())
7986     return SDValue();
7987
7988   // Verify that we are actually reducing a load width here.
7989   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7990     return SDValue();
7991
7992   // For the transform to be legal, the load must produce only two values
7993   // (the value loaded and the chain).  Don't transform a pre-increment
7994   // load, for example, which produces an extra value.  Otherwise the
7995   // transformation is not equivalent, and the downstream logic to replace
7996   // uses gets things wrong.
7997   if (LN0->getNumValues() > 2)
7998     return SDValue();
7999
8000   // If the load that we're shrinking is an extload and we're not just
8001   // discarding the extension we can't simply shrink the load. Bail.
8002   // TODO: It would be possible to merge the extensions in some cases.
8003   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
8004       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
8005     return SDValue();
8006
8007   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
8008     return SDValue();
8009
8010   EVT PtrType = N0.getOperand(1).getValueType();
8011
8012   if (PtrType == MVT::Untyped || PtrType.isExtended())
8013     // It's not possible to generate a constant of extended or untyped type.
8014     return SDValue();
8015
8016   // For big endian targets, we need to adjust the offset to the pointer to
8017   // load the correct bytes.
8018   if (DAG.getDataLayout().isBigEndian()) {
8019     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
8020     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
8021     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
8022   }
8023
8024   uint64_t PtrOff = ShAmt / 8;
8025   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
8026   SDLoc DL(LN0);
8027   // The original load itself didn't wrap, so an offset within it doesn't.
8028   SDNodeFlags Flags;
8029   Flags.setNoUnsignedWrap(true);
8030   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
8031                                PtrType, LN0->getBasePtr(),
8032                                DAG.getConstant(PtrOff, DL, PtrType),
8033                                Flags);
8034   AddToWorklist(NewPtr.getNode());
8035
8036   SDValue Load;
8037   if (ExtType == ISD::NON_EXTLOAD)
8038     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8039                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8040                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8041   else
8042     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8043                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8044                           NewAlign, LN0->getMemOperand()->getFlags(),
8045                           LN0->getAAInfo());
8046
8047   // Replace the old load's chain with the new load's chain.
8048   WorklistRemover DeadNodes(*this);
8049   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8050
8051   // Shift the result left, if we've swallowed a left shift.
8052   SDValue Result = Load;
8053   if (ShLeftAmt != 0) {
8054     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8055     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8056       ShImmTy = VT;
8057     // If the shift amount is as large as the result size (but, presumably,
8058     // no larger than the source) then the useful bits of the result are
8059     // zero; we can't simply return the shortened shift, because the result
8060     // of that operation is undefined.
8061     SDLoc DL(N0);
8062     if (ShLeftAmt >= VT.getSizeInBits())
8063       Result = DAG.getConstant(0, DL, VT);
8064     else
8065       Result = DAG.getNode(ISD::SHL, DL, VT,
8066                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8067   }
8068
8069   // Return the new loaded value.
8070   return Result;
8071 }
8072
8073 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8074   SDValue N0 = N->getOperand(0);
8075   SDValue N1 = N->getOperand(1);
8076   EVT VT = N->getValueType(0);
8077   EVT EVT = cast<VTSDNode>(N1)->getVT();
8078   unsigned VTBits = VT.getScalarSizeInBits();
8079   unsigned EVTBits = EVT.getScalarSizeInBits();
8080
8081   if (N0.isUndef())
8082     return DAG.getUNDEF(VT);
8083
8084   // fold (sext_in_reg c1) -> c1
8085   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8086     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8087
8088   // If the input is already sign extended, just drop the extension.
8089   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8090     return N0;
8091
8092   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8093   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8094       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8095     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8096                        N0.getOperand(0), N1);
8097
8098   // fold (sext_in_reg (sext x)) -> (sext x)
8099   // fold (sext_in_reg (aext x)) -> (sext x)
8100   // if x is small enough.
8101   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8102     SDValue N00 = N0.getOperand(0);
8103     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8104         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8105       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8106   }
8107
8108   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8109   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8110        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8111        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8112       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8113     if (!LegalOperations ||
8114         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8115       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8116   }
8117
8118   // fold (sext_in_reg (zext x)) -> (sext x)
8119   // iff we are extending the source sign bit.
8120   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8121     SDValue N00 = N0.getOperand(0);
8122     if (N00.getScalarValueSizeInBits() == EVTBits &&
8123         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8124       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8125   }
8126
8127   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8128   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8129     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8130
8131   // fold operands of sext_in_reg based on knowledge that the top bits are not
8132   // demanded.
8133   if (SimplifyDemandedBits(SDValue(N, 0)))
8134     return SDValue(N, 0);
8135
8136   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8137   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8138   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8139     return NarrowLoad;
8140
8141   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8142   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8143   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8144   if (N0.getOpcode() == ISD::SRL) {
8145     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8146       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8147         // We can turn this into an SRA iff the input to the SRL is already sign
8148         // extended enough.
8149         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8150         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8151           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8152                              N0.getOperand(0), N0.getOperand(1));
8153       }
8154   }
8155
8156   // fold (sext_inreg (extload x)) -> (sextload x)
8157   if (ISD::isEXTLoad(N0.getNode()) &&
8158       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8159       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8160       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8161        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8162     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8163     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8164                                      LN0->getChain(),
8165                                      LN0->getBasePtr(), EVT,
8166                                      LN0->getMemOperand());
8167     CombineTo(N, ExtLoad);
8168     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8169     AddToWorklist(ExtLoad.getNode());
8170     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8171   }
8172   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8173   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8174       N0.hasOneUse() &&
8175       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8176       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8177        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8178     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8179     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8180                                      LN0->getChain(),
8181                                      LN0->getBasePtr(), EVT,
8182                                      LN0->getMemOperand());
8183     CombineTo(N, ExtLoad);
8184     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8185     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8186   }
8187
8188   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8189   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8190     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8191                                            N0.getOperand(1), false))
8192       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8193                          BSwap, N1);
8194   }
8195
8196   return SDValue();
8197 }
8198
8199 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8200   SDValue N0 = N->getOperand(0);
8201   EVT VT = N->getValueType(0);
8202
8203   if (N0.isUndef())
8204     return DAG.getUNDEF(VT);
8205
8206   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8207                                               LegalOperations))
8208     return SDValue(Res, 0);
8209
8210   return SDValue();
8211 }
8212
8213 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8214   SDValue N0 = N->getOperand(0);
8215   EVT VT = N->getValueType(0);
8216
8217   if (N0.isUndef())
8218     return DAG.getUNDEF(VT);
8219
8220   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8221                                               LegalOperations))
8222     return SDValue(Res, 0);
8223
8224   return SDValue();
8225 }
8226
8227 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8228   SDValue N0 = N->getOperand(0);
8229   EVT VT = N->getValueType(0);
8230   bool isLE = DAG.getDataLayout().isLittleEndian();
8231
8232   // noop truncate
8233   if (N0.getValueType() == N->getValueType(0))
8234     return N0;
8235   // fold (truncate c1) -> c1
8236   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8237     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8238   // fold (truncate (truncate x)) -> (truncate x)
8239   if (N0.getOpcode() == ISD::TRUNCATE)
8240     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8241   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8242   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8243       N0.getOpcode() == ISD::SIGN_EXTEND ||
8244       N0.getOpcode() == ISD::ANY_EXTEND) {
8245     // if the source is smaller than the dest, we still need an extend.
8246     if (N0.getOperand(0).getValueType().bitsLT(VT))
8247       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8248     // if the source is larger than the dest, than we just need the truncate.
8249     if (N0.getOperand(0).getValueType().bitsGT(VT))
8250       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8251     // if the source and dest are the same type, we can drop both the extend
8252     // and the truncate.
8253     return N0.getOperand(0);
8254   }
8255
8256   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8257   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8258     return SDValue();
8259
8260   // Fold extract-and-trunc into a narrow extract. For example:
8261   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8262   //   i32 y = TRUNCATE(i64 x)
8263   //        -- becomes --
8264   //   v16i8 b = BITCAST (v2i64 val)
8265   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8266   //
8267   // Note: We only run this optimization after type legalization (which often
8268   // creates this pattern) and before operation legalization after which
8269   // we need to be more careful about the vector instructions that we generate.
8270   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8271       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8272
8273     EVT VecTy = N0.getOperand(0).getValueType();
8274     EVT ExTy = N0.getValueType();
8275     EVT TrTy = N->getValueType(0);
8276
8277     unsigned NumElem = VecTy.getVectorNumElements();
8278     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8279
8280     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8281     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8282
8283     SDValue EltNo = N0->getOperand(1);
8284     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8285       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8286       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8287       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8288
8289       SDLoc DL(N);
8290       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8291                          DAG.getBitcast(NVT, N0.getOperand(0)),
8292                          DAG.getConstant(Index, DL, IndexTy));
8293     }
8294   }
8295
8296   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8297   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8298     EVT SrcVT = N0.getValueType();
8299     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8300         TLI.isTruncateFree(SrcVT, VT)) {
8301       SDLoc SL(N0);
8302       SDValue Cond = N0.getOperand(0);
8303       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8304       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8305       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8306     }
8307   }
8308
8309   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8310   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8311       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8312       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8313     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
8314       uint64_t Amt = CAmt->getZExtValue();
8315       unsigned Size = VT.getScalarSizeInBits();
8316
8317       if (Amt < Size) {
8318         SDLoc SL(N);
8319         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8320
8321         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8322         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
8323                            DAG.getConstant(Amt, SL, AmtVT));
8324       }
8325     }
8326   }
8327
8328   // Fold a series of buildvector, bitcast, and truncate if possible.
8329   // For example fold
8330   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8331   //   (2xi32 (buildvector x, y)).
8332   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8333       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8334       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8335       N0.getOperand(0).hasOneUse()) {
8336
8337     SDValue BuildVect = N0.getOperand(0);
8338     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8339     EVT TruncVecEltTy = VT.getVectorElementType();
8340
8341     // Check that the element types match.
8342     if (BuildVectEltTy == TruncVecEltTy) {
8343       // Now we only need to compute the offset of the truncated elements.
8344       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8345       unsigned TruncVecNumElts = VT.getVectorNumElements();
8346       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8347
8348       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8349              "Invalid number of elements");
8350
8351       SmallVector<SDValue, 8> Opnds;
8352       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8353         Opnds.push_back(BuildVect.getOperand(i));
8354
8355       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8356     }
8357   }
8358
8359   // See if we can simplify the input to this truncate through knowledge that
8360   // only the low bits are being used.
8361   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8362   // Currently we only perform this optimization on scalars because vectors
8363   // may have different active low bits.
8364   if (!VT.isVector()) {
8365     if (SDValue Shorter =
8366             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
8367                                                      VT.getSizeInBits())))
8368       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8369   }
8370
8371   // fold (truncate (load x)) -> (smaller load x)
8372   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8373   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8374     if (SDValue Reduced = ReduceLoadWidth(N))
8375       return Reduced;
8376
8377     // Handle the case where the load remains an extending load even
8378     // after truncation.
8379     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8380       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8381       if (!LN0->isVolatile() &&
8382           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8383         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8384                                          VT, LN0->getChain(), LN0->getBasePtr(),
8385                                          LN0->getMemoryVT(),
8386                                          LN0->getMemOperand());
8387         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8388         return NewLoad;
8389       }
8390     }
8391   }
8392
8393   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8394   // where ... are all 'undef'.
8395   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8396     SmallVector<EVT, 8> VTs;
8397     SDValue V;
8398     unsigned Idx = 0;
8399     unsigned NumDefs = 0;
8400
8401     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8402       SDValue X = N0.getOperand(i);
8403       if (!X.isUndef()) {
8404         V = X;
8405         Idx = i;
8406         NumDefs++;
8407       }
8408       // Stop if more than one members are non-undef.
8409       if (NumDefs > 1)
8410         break;
8411       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8412                                      VT.getVectorElementType(),
8413                                      X.getValueType().getVectorNumElements()));
8414     }
8415
8416     if (NumDefs == 0)
8417       return DAG.getUNDEF(VT);
8418
8419     if (NumDefs == 1) {
8420       assert(V.getNode() && "The single defined operand is empty!");
8421       SmallVector<SDValue, 8> Opnds;
8422       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8423         if (i != Idx) {
8424           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8425           continue;
8426         }
8427         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8428         AddToWorklist(NV.getNode());
8429         Opnds.push_back(NV);
8430       }
8431       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8432     }
8433   }
8434
8435   // Fold truncate of a bitcast of a vector to an extract of the low vector
8436   // element.
8437   //
8438   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
8439   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8440     SDValue VecSrc = N0.getOperand(0);
8441     EVT SrcVT = VecSrc.getValueType();
8442     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8443         (!LegalOperations ||
8444          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8445       SDLoc SL(N);
8446
8447       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8448       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8449                          VecSrc, DAG.getConstant(0, SL, IdxVT));
8450     }
8451   }
8452
8453   // Simplify the operands using demanded-bits information.
8454   if (!VT.isVector() &&
8455       SimplifyDemandedBits(SDValue(N, 0)))
8456     return SDValue(N, 0);
8457
8458   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8459   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8460   // When the adde's carry is not used.
8461   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8462       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8463       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8464     SDLoc SL(N);
8465     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8466     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8467     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8468     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8469   }
8470
8471   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8472     return NewVSel;
8473
8474   return SDValue();
8475 }
8476
8477 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8478   SDValue Elt = N->getOperand(i);
8479   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8480     return Elt.getNode();
8481   return Elt.getOperand(Elt.getResNo()).getNode();
8482 }
8483
8484 /// build_pair (load, load) -> load
8485 /// if load locations are consecutive.
8486 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8487   assert(N->getOpcode() == ISD::BUILD_PAIR);
8488
8489   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8490   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8491   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8492       LD1->getAddressSpace() != LD2->getAddressSpace())
8493     return SDValue();
8494   EVT LD1VT = LD1->getValueType(0);
8495   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8496   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8497       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8498     unsigned Align = LD1->getAlignment();
8499     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8500         VT.getTypeForEVT(*DAG.getContext()));
8501
8502     if (NewAlign <= Align &&
8503         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8504       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8505                          LD1->getPointerInfo(), Align);
8506   }
8507
8508   return SDValue();
8509 }
8510
8511 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8512   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8513   // and Lo parts; on big-endian machines it doesn't.
8514   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8515 }
8516
8517 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8518                                     const TargetLowering &TLI) {
8519   // If this is not a bitcast to an FP type or if the target doesn't have
8520   // IEEE754-compliant FP logic, we're done.
8521   EVT VT = N->getValueType(0);
8522   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8523     return SDValue();
8524
8525   // TODO: Use splat values for the constant-checking below and remove this
8526   // restriction.
8527   SDValue N0 = N->getOperand(0);
8528   EVT SourceVT = N0.getValueType();
8529   if (SourceVT.isVector())
8530     return SDValue();
8531
8532   unsigned FPOpcode;
8533   APInt SignMask;
8534   switch (N0.getOpcode()) {
8535   case ISD::AND:
8536     FPOpcode = ISD::FABS;
8537     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8538     break;
8539   case ISD::XOR:
8540     FPOpcode = ISD::FNEG;
8541     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8542     break;
8543   // TODO: ISD::OR --> ISD::FNABS?
8544   default:
8545     return SDValue();
8546   }
8547
8548   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8549   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8550   SDValue LogicOp0 = N0.getOperand(0);
8551   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8552   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8553       LogicOp0.getOpcode() == ISD::BITCAST &&
8554       LogicOp0->getOperand(0).getValueType() == VT)
8555     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8556
8557   return SDValue();
8558 }
8559
8560 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8561   SDValue N0 = N->getOperand(0);
8562   EVT VT = N->getValueType(0);
8563
8564   if (N0.isUndef())
8565     return DAG.getUNDEF(VT);
8566
8567   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8568   // Only do this before legalize, since afterward the target may be depending
8569   // on the bitconvert.
8570   // First check to see if this is all constant.
8571   if (!LegalTypes &&
8572       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8573       VT.isVector()) {
8574     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8575
8576     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8577     assert(!DestEltVT.isVector() &&
8578            "Element type of vector ValueType must not be vector!");
8579     if (isSimple)
8580       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8581   }
8582
8583   // If the input is a constant, let getNode fold it.
8584   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8585     // If we can't allow illegal operations, we need to check that this is just
8586     // a fp -> int or int -> conversion and that the resulting operation will
8587     // be legal.
8588     if (!LegalOperations ||
8589         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8590          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8591         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8592          TLI.isOperationLegal(ISD::Constant, VT)))
8593       return DAG.getBitcast(VT, N0);
8594   }
8595
8596   // (conv (conv x, t1), t2) -> (conv x, t2)
8597   if (N0.getOpcode() == ISD::BITCAST)
8598     return DAG.getBitcast(VT, N0.getOperand(0));
8599
8600   // fold (conv (load x)) -> (load (conv*)x)
8601   // If the resultant load doesn't need a higher alignment than the original!
8602   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8603       // Do not change the width of a volatile load.
8604       !cast<LoadSDNode>(N0)->isVolatile() &&
8605       // Do not remove the cast if the types differ in endian layout.
8606       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8607           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8608       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8609       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8610     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8611     unsigned OrigAlign = LN0->getAlignment();
8612
8613     bool Fast = false;
8614     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8615                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8616         Fast) {
8617       SDValue Load =
8618           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8619                       LN0->getPointerInfo(), OrigAlign,
8620                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8621       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8622       return Load;
8623     }
8624   }
8625
8626   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8627     return V;
8628
8629   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8630   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8631   //
8632   // For ppc_fp128:
8633   // fold (bitcast (fneg x)) ->
8634   //     flipbit = signbit
8635   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8636   //
8637   // fold (bitcast (fabs x)) ->
8638   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8639   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8640   // This often reduces constant pool loads.
8641   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8642        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8643       N0.getNode()->hasOneUse() && VT.isInteger() &&
8644       !VT.isVector() && !N0.getValueType().isVector()) {
8645     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8646     AddToWorklist(NewConv.getNode());
8647
8648     SDLoc DL(N);
8649     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8650       assert(VT.getSizeInBits() == 128);
8651       SDValue SignBit = DAG.getConstant(
8652           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8653       SDValue FlipBit;
8654       if (N0.getOpcode() == ISD::FNEG) {
8655         FlipBit = SignBit;
8656         AddToWorklist(FlipBit.getNode());
8657       } else {
8658         assert(N0.getOpcode() == ISD::FABS);
8659         SDValue Hi =
8660             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8661                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8662                                               SDLoc(NewConv)));
8663         AddToWorklist(Hi.getNode());
8664         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8665         AddToWorklist(FlipBit.getNode());
8666       }
8667       SDValue FlipBits =
8668           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8669       AddToWorklist(FlipBits.getNode());
8670       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8671     }
8672     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8673     if (N0.getOpcode() == ISD::FNEG)
8674       return DAG.getNode(ISD::XOR, DL, VT,
8675                          NewConv, DAG.getConstant(SignBit, DL, VT));
8676     assert(N0.getOpcode() == ISD::FABS);
8677     return DAG.getNode(ISD::AND, DL, VT,
8678                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8679   }
8680
8681   // fold (bitconvert (fcopysign cst, x)) ->
8682   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8683   // Note that we don't handle (copysign x, cst) because this can always be
8684   // folded to an fneg or fabs.
8685   //
8686   // For ppc_fp128:
8687   // fold (bitcast (fcopysign cst, x)) ->
8688   //     flipbit = (and (extract_element
8689   //                     (xor (bitcast cst), (bitcast x)), 0),
8690   //                    signbit)
8691   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8692   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8693       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8694       VT.isInteger() && !VT.isVector()) {
8695     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8696     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8697     if (isTypeLegal(IntXVT)) {
8698       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8699       AddToWorklist(X.getNode());
8700
8701       // If X has a different width than the result/lhs, sext it or truncate it.
8702       unsigned VTWidth = VT.getSizeInBits();
8703       if (OrigXWidth < VTWidth) {
8704         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8705         AddToWorklist(X.getNode());
8706       } else if (OrigXWidth > VTWidth) {
8707         // To get the sign bit in the right place, we have to shift it right
8708         // before truncating.
8709         SDLoc DL(X);
8710         X = DAG.getNode(ISD::SRL, DL,
8711                         X.getValueType(), X,
8712                         DAG.getConstant(OrigXWidth-VTWidth, DL,
8713                                         X.getValueType()));
8714         AddToWorklist(X.getNode());
8715         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8716         AddToWorklist(X.getNode());
8717       }
8718
8719       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8720         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8721         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8722         AddToWorklist(Cst.getNode());
8723         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8724         AddToWorklist(X.getNode());
8725         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8726         AddToWorklist(XorResult.getNode());
8727         SDValue XorResult64 = DAG.getNode(
8728             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8729             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8730                                   SDLoc(XorResult)));
8731         AddToWorklist(XorResult64.getNode());
8732         SDValue FlipBit =
8733             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8734                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8735         AddToWorklist(FlipBit.getNode());
8736         SDValue FlipBits =
8737             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8738         AddToWorklist(FlipBits.getNode());
8739         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8740       }
8741       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8742       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8743                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
8744       AddToWorklist(X.getNode());
8745
8746       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8747       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8748                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8749       AddToWorklist(Cst.getNode());
8750
8751       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8752     }
8753   }
8754
8755   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8756   if (N0.getOpcode() == ISD::BUILD_PAIR)
8757     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8758       return CombineLD;
8759
8760   // Remove double bitcasts from shuffles - this is often a legacy of
8761   // XformToShuffleWithZero being used to combine bitmaskings (of
8762   // float vectors bitcast to integer vectors) into shuffles.
8763   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8764   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8765       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8766       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8767       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8768     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8769
8770     // If operands are a bitcast, peek through if it casts the original VT.
8771     // If operands are a constant, just bitcast back to original VT.
8772     auto PeekThroughBitcast = [&](SDValue Op) {
8773       if (Op.getOpcode() == ISD::BITCAST &&
8774           Op.getOperand(0).getValueType() == VT)
8775         return SDValue(Op.getOperand(0));
8776       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8777           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8778         return DAG.getBitcast(VT, Op);
8779       return SDValue();
8780     };
8781
8782     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8783     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8784     if (!(SV0 && SV1))
8785       return SDValue();
8786
8787     int MaskScale =
8788         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8789     SmallVector<int, 8> NewMask;
8790     for (int M : SVN->getMask())
8791       for (int i = 0; i != MaskScale; ++i)
8792         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8793
8794     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8795     if (!LegalMask) {
8796       std::swap(SV0, SV1);
8797       ShuffleVectorSDNode::commuteMask(NewMask);
8798       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8799     }
8800
8801     if (LegalMask)
8802       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8803   }
8804
8805   return SDValue();
8806 }
8807
8808 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8809   EVT VT = N->getValueType(0);
8810   return CombineConsecutiveLoads(N, VT);
8811 }
8812
8813 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8814 /// operands. DstEltVT indicates the destination element value type.
8815 SDValue DAGCombiner::
8816 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8817   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8818
8819   // If this is already the right type, we're done.
8820   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8821
8822   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8823   unsigned DstBitSize = DstEltVT.getSizeInBits();
8824
8825   // If this is a conversion of N elements of one type to N elements of another
8826   // type, convert each element.  This handles FP<->INT cases.
8827   if (SrcBitSize == DstBitSize) {
8828     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8829                               BV->getValueType(0).getVectorNumElements());
8830
8831     // Due to the FP element handling below calling this routine recursively,
8832     // we can end up with a scalar-to-vector node here.
8833     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8834       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8835                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8836
8837     SmallVector<SDValue, 8> Ops;
8838     for (SDValue Op : BV->op_values()) {
8839       // If the vector element type is not legal, the BUILD_VECTOR operands
8840       // are promoted and implicitly truncated.  Make that explicit here.
8841       if (Op.getValueType() != SrcEltVT)
8842         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8843       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8844       AddToWorklist(Ops.back().getNode());
8845     }
8846     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8847   }
8848
8849   // Otherwise, we're growing or shrinking the elements.  To avoid having to
8850   // handle annoying details of growing/shrinking FP values, we convert them to
8851   // int first.
8852   if (SrcEltVT.isFloatingPoint()) {
8853     // Convert the input float vector to a int vector where the elements are the
8854     // same sizes.
8855     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8856     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8857     SrcEltVT = IntVT;
8858   }
8859
8860   // Now we know the input is an integer vector.  If the output is a FP type,
8861   // convert to integer first, then to FP of the right size.
8862   if (DstEltVT.isFloatingPoint()) {
8863     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8864     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8865
8866     // Next, convert to FP elements of the same size.
8867     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8868   }
8869
8870   SDLoc DL(BV);
8871
8872   // Okay, we know the src/dst types are both integers of differing types.
8873   // Handling growing first.
8874   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8875   if (SrcBitSize < DstBitSize) {
8876     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8877
8878     SmallVector<SDValue, 8> Ops;
8879     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8880          i += NumInputsPerOutput) {
8881       bool isLE = DAG.getDataLayout().isLittleEndian();
8882       APInt NewBits = APInt(DstBitSize, 0);
8883       bool EltIsUndef = true;
8884       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8885         // Shift the previously computed bits over.
8886         NewBits <<= SrcBitSize;
8887         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8888         if (Op.isUndef()) continue;
8889         EltIsUndef = false;
8890
8891         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8892                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
8893       }
8894
8895       if (EltIsUndef)
8896         Ops.push_back(DAG.getUNDEF(DstEltVT));
8897       else
8898         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8899     }
8900
8901     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8902     return DAG.getBuildVector(VT, DL, Ops);
8903   }
8904
8905   // Finally, this must be the case where we are shrinking elements: each input
8906   // turns into multiple outputs.
8907   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8908   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8909                             NumOutputsPerInput*BV->getNumOperands());
8910   SmallVector<SDValue, 8> Ops;
8911
8912   for (const SDValue &Op : BV->op_values()) {
8913     if (Op.isUndef()) {
8914       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8915       continue;
8916     }
8917
8918     APInt OpVal = cast<ConstantSDNode>(Op)->
8919                   getAPIntValue().zextOrTrunc(SrcBitSize);
8920
8921     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8922       APInt ThisVal = OpVal.trunc(DstBitSize);
8923       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8924       OpVal.lshrInPlace(DstBitSize);
8925     }
8926
8927     // For big endian targets, swap the order of the pieces of each element.
8928     if (DAG.getDataLayout().isBigEndian())
8929       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8930   }
8931
8932   return DAG.getBuildVector(VT, DL, Ops);
8933 }
8934
8935 static bool isContractable(SDNode *N) {
8936   SDNodeFlags F = N->getFlags();
8937   return F.hasAllowContract() || F.hasUnsafeAlgebra();
8938 }
8939
8940 /// Try to perform FMA combining on a given FADD node.
8941 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8942   SDValue N0 = N->getOperand(0);
8943   SDValue N1 = N->getOperand(1);
8944   EVT VT = N->getValueType(0);
8945   SDLoc SL(N);
8946
8947   const TargetOptions &Options = DAG.getTarget().Options;
8948
8949   // Floating-point multiply-add with intermediate rounding.
8950   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8951
8952   // Floating-point multiply-add without intermediate rounding.
8953   bool HasFMA =
8954       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8955       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8956
8957   // No valid opcode, do not combine.
8958   if (!HasFMAD && !HasFMA)
8959     return SDValue();
8960
8961   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8962                               Options.UnsafeFPMath || HasFMAD);
8963   // If the addition is not contractable, do not combine.
8964   if (!AllowFusionGlobally && !isContractable(N))
8965     return SDValue();
8966
8967   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8968   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8969     return SDValue();
8970
8971   // Always prefer FMAD to FMA for precision.
8972   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8973   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8974   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8975
8976   // Is the node an FMUL and contractable either due to global flags or
8977   // SDNodeFlags.
8978   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8979     if (N.getOpcode() != ISD::FMUL)
8980       return false;
8981     return AllowFusionGlobally || isContractable(N.getNode());
8982   };
8983   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8984   // prefer to fold the multiply with fewer uses.
8985   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
8986     if (N0.getNode()->use_size() > N1.getNode()->use_size())
8987       std::swap(N0, N1);
8988   }
8989
8990   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8991   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8992     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8993                        N0.getOperand(0), N0.getOperand(1), N1);
8994   }
8995
8996   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8997   // Note: Commutes FADD operands.
8998   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
8999     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9000                        N1.getOperand(0), N1.getOperand(1), N0);
9001   }
9002
9003   // Look through FP_EXTEND nodes to do more combining.
9004   if (LookThroughFPExt) {
9005     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
9006     if (N0.getOpcode() == ISD::FP_EXTEND) {
9007       SDValue N00 = N0.getOperand(0);
9008       if (isContractableFMUL(N00))
9009         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9010                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9011                                        N00.getOperand(0)),
9012                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9013                                        N00.getOperand(1)), N1);
9014     }
9015
9016     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
9017     // Note: Commutes FADD operands.
9018     if (N1.getOpcode() == ISD::FP_EXTEND) {
9019       SDValue N10 = N1.getOperand(0);
9020       if (isContractableFMUL(N10))
9021         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9022                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9023                                        N10.getOperand(0)),
9024                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9025                                        N10.getOperand(1)), N0);
9026     }
9027   }
9028
9029   // More folding opportunities when target permits.
9030   if (Aggressive) {
9031     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9032     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9033     // are currently only supported on binary nodes.
9034     if (Options.UnsafeFPMath &&
9035         N0.getOpcode() == PreferredFusedOpcode &&
9036         N0.getOperand(2).getOpcode() == ISD::FMUL &&
9037         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9038       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9039                          N0.getOperand(0), N0.getOperand(1),
9040                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9041                                      N0.getOperand(2).getOperand(0),
9042                                      N0.getOperand(2).getOperand(1),
9043                                      N1));
9044     }
9045
9046     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9047     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9048     // are currently only supported on binary nodes.
9049     if (Options.UnsafeFPMath &&
9050         N1->getOpcode() == PreferredFusedOpcode &&
9051         N1.getOperand(2).getOpcode() == ISD::FMUL &&
9052         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9053       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9054                          N1.getOperand(0), N1.getOperand(1),
9055                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9056                                      N1.getOperand(2).getOperand(0),
9057                                      N1.getOperand(2).getOperand(1),
9058                                      N0));
9059     }
9060
9061     if (LookThroughFPExt) {
9062       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9063       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
9064       auto FoldFAddFMAFPExtFMul = [&] (
9065           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9066         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9067                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9068                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9069                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9070                                        Z));
9071       };
9072       if (N0.getOpcode() == PreferredFusedOpcode) {
9073         SDValue N02 = N0.getOperand(2);
9074         if (N02.getOpcode() == ISD::FP_EXTEND) {
9075           SDValue N020 = N02.getOperand(0);
9076           if (isContractableFMUL(N020))
9077             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9078                                         N020.getOperand(0), N020.getOperand(1),
9079                                         N1);
9080         }
9081       }
9082
9083       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9084       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9085       // FIXME: This turns two single-precision and one double-precision
9086       // operation into two double-precision operations, which might not be
9087       // interesting for all targets, especially GPUs.
9088       auto FoldFAddFPExtFMAFMul = [&] (
9089           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9090         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9091                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9092                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9093                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9094                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9095                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9096                                        Z));
9097       };
9098       if (N0.getOpcode() == ISD::FP_EXTEND) {
9099         SDValue N00 = N0.getOperand(0);
9100         if (N00.getOpcode() == PreferredFusedOpcode) {
9101           SDValue N002 = N00.getOperand(2);
9102           if (isContractableFMUL(N002))
9103             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9104                                         N002.getOperand(0), N002.getOperand(1),
9105                                         N1);
9106         }
9107       }
9108
9109       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9110       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9111       if (N1.getOpcode() == PreferredFusedOpcode) {
9112         SDValue N12 = N1.getOperand(2);
9113         if (N12.getOpcode() == ISD::FP_EXTEND) {
9114           SDValue N120 = N12.getOperand(0);
9115           if (isContractableFMUL(N120))
9116             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9117                                         N120.getOperand(0), N120.getOperand(1),
9118                                         N0);
9119         }
9120       }
9121
9122       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9123       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9124       // FIXME: This turns two single-precision and one double-precision
9125       // operation into two double-precision operations, which might not be
9126       // interesting for all targets, especially GPUs.
9127       if (N1.getOpcode() == ISD::FP_EXTEND) {
9128         SDValue N10 = N1.getOperand(0);
9129         if (N10.getOpcode() == PreferredFusedOpcode) {
9130           SDValue N102 = N10.getOperand(2);
9131           if (isContractableFMUL(N102))
9132             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9133                                         N102.getOperand(0), N102.getOperand(1),
9134                                         N0);
9135         }
9136       }
9137     }
9138   }
9139
9140   return SDValue();
9141 }
9142
9143 /// Try to perform FMA combining on a given FSUB node.
9144 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9145   SDValue N0 = N->getOperand(0);
9146   SDValue N1 = N->getOperand(1);
9147   EVT VT = N->getValueType(0);
9148   SDLoc SL(N);
9149
9150   const TargetOptions &Options = DAG.getTarget().Options;
9151   // Floating-point multiply-add with intermediate rounding.
9152   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9153
9154   // Floating-point multiply-add without intermediate rounding.
9155   bool HasFMA =
9156       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9157       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9158
9159   // No valid opcode, do not combine.
9160   if (!HasFMAD && !HasFMA)
9161     return SDValue();
9162
9163   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9164                               Options.UnsafeFPMath || HasFMAD);
9165   // If the subtraction is not contractable, do not combine.
9166   if (!AllowFusionGlobally && !isContractable(N))
9167     return SDValue();
9168
9169   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9170   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9171     return SDValue();
9172
9173   // Always prefer FMAD to FMA for precision.
9174   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9175   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9176   bool LookThroughFPExt = TLI.isFPExtFree(VT);
9177
9178   // Is the node an FMUL and contractable either due to global flags or
9179   // SDNodeFlags.
9180   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9181     if (N.getOpcode() != ISD::FMUL)
9182       return false;
9183     return AllowFusionGlobally || isContractable(N.getNode());
9184   };
9185
9186   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9187   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9188     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9189                        N0.getOperand(0), N0.getOperand(1),
9190                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9191   }
9192
9193   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9194   // Note: Commutes FSUB operands.
9195   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9196     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9197                        DAG.getNode(ISD::FNEG, SL, VT,
9198                                    N1.getOperand(0)),
9199                        N1.getOperand(1), N0);
9200
9201   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9202   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9203       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9204     SDValue N00 = N0.getOperand(0).getOperand(0);
9205     SDValue N01 = N0.getOperand(0).getOperand(1);
9206     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9207                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9208                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9209   }
9210
9211   // Look through FP_EXTEND nodes to do more combining.
9212   if (LookThroughFPExt) {
9213     // fold (fsub (fpext (fmul x, y)), z)
9214     //   -> (fma (fpext x), (fpext y), (fneg z))
9215     if (N0.getOpcode() == ISD::FP_EXTEND) {
9216       SDValue N00 = N0.getOperand(0);
9217       if (isContractableFMUL(N00))
9218         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9219                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9220                                        N00.getOperand(0)),
9221                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9222                                        N00.getOperand(1)),
9223                            DAG.getNode(ISD::FNEG, SL, VT, N1));
9224     }
9225
9226     // fold (fsub x, (fpext (fmul y, z)))
9227     //   -> (fma (fneg (fpext y)), (fpext z), x)
9228     // Note: Commutes FSUB operands.
9229     if (N1.getOpcode() == ISD::FP_EXTEND) {
9230       SDValue N10 = N1.getOperand(0);
9231       if (isContractableFMUL(N10))
9232         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9233                            DAG.getNode(ISD::FNEG, SL, VT,
9234                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9235                                                    N10.getOperand(0))),
9236                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9237                                        N10.getOperand(1)),
9238                            N0);
9239     }
9240
9241     // fold (fsub (fpext (fneg (fmul, x, y))), z)
9242     //   -> (fneg (fma (fpext x), (fpext y), z))
9243     // Note: This could be removed with appropriate canonicalization of the
9244     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9245     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9246     // from implementing the canonicalization in visitFSUB.
9247     if (N0.getOpcode() == ISD::FP_EXTEND) {
9248       SDValue N00 = N0.getOperand(0);
9249       if (N00.getOpcode() == ISD::FNEG) {
9250         SDValue N000 = N00.getOperand(0);
9251         if (isContractableFMUL(N000)) {
9252           return DAG.getNode(ISD::FNEG, SL, VT,
9253                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9254                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9255                                                      N000.getOperand(0)),
9256                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9257                                                      N000.getOperand(1)),
9258                                          N1));
9259         }
9260       }
9261     }
9262
9263     // fold (fsub (fneg (fpext (fmul, x, y))), z)
9264     //   -> (fneg (fma (fpext x)), (fpext y), z)
9265     // Note: This could be removed with appropriate canonicalization of the
9266     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9267     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9268     // from implementing the canonicalization in visitFSUB.
9269     if (N0.getOpcode() == ISD::FNEG) {
9270       SDValue N00 = N0.getOperand(0);
9271       if (N00.getOpcode() == ISD::FP_EXTEND) {
9272         SDValue N000 = N00.getOperand(0);
9273         if (isContractableFMUL(N000)) {
9274           return DAG.getNode(ISD::FNEG, SL, VT,
9275                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9276                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9277                                                      N000.getOperand(0)),
9278                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9279                                                      N000.getOperand(1)),
9280                                          N1));
9281         }
9282       }
9283     }
9284
9285   }
9286
9287   // More folding opportunities when target permits.
9288   if (Aggressive) {
9289     // fold (fsub (fma x, y, (fmul u, v)), z)
9290     //   -> (fma x, y (fma u, v, (fneg z)))
9291     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9292     // are currently only supported on binary nodes.
9293     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9294         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9295         N0.getOperand(2)->hasOneUse()) {
9296       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9297                          N0.getOperand(0), N0.getOperand(1),
9298                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9299                                      N0.getOperand(2).getOperand(0),
9300                                      N0.getOperand(2).getOperand(1),
9301                                      DAG.getNode(ISD::FNEG, SL, VT,
9302                                                  N1)));
9303     }
9304
9305     // fold (fsub x, (fma y, z, (fmul u, v)))
9306     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9307     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9308     // are currently only supported on binary nodes.
9309     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9310         isContractableFMUL(N1.getOperand(2))) {
9311       SDValue N20 = N1.getOperand(2).getOperand(0);
9312       SDValue N21 = N1.getOperand(2).getOperand(1);
9313       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9314                          DAG.getNode(ISD::FNEG, SL, VT,
9315                                      N1.getOperand(0)),
9316                          N1.getOperand(1),
9317                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9318                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9319
9320                                      N21, N0));
9321     }
9322
9323     if (LookThroughFPExt) {
9324       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9325       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9326       if (N0.getOpcode() == PreferredFusedOpcode) {
9327         SDValue N02 = N0.getOperand(2);
9328         if (N02.getOpcode() == ISD::FP_EXTEND) {
9329           SDValue N020 = N02.getOperand(0);
9330           if (isContractableFMUL(N020))
9331             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9332                                N0.getOperand(0), N0.getOperand(1),
9333                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9334                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9335                                                        N020.getOperand(0)),
9336                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9337                                                        N020.getOperand(1)),
9338                                            DAG.getNode(ISD::FNEG, SL, VT,
9339                                                        N1)));
9340         }
9341       }
9342
9343       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9344       //   -> (fma (fpext x), (fpext y),
9345       //           (fma (fpext u), (fpext v), (fneg z)))
9346       // FIXME: This turns two single-precision and one double-precision
9347       // operation into two double-precision operations, which might not be
9348       // interesting for all targets, especially GPUs.
9349       if (N0.getOpcode() == ISD::FP_EXTEND) {
9350         SDValue N00 = N0.getOperand(0);
9351         if (N00.getOpcode() == PreferredFusedOpcode) {
9352           SDValue N002 = N00.getOperand(2);
9353           if (isContractableFMUL(N002))
9354             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9355                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9356                                            N00.getOperand(0)),
9357                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9358                                            N00.getOperand(1)),
9359                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9360                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9361                                                        N002.getOperand(0)),
9362                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9363                                                        N002.getOperand(1)),
9364                                            DAG.getNode(ISD::FNEG, SL, VT,
9365                                                        N1)));
9366         }
9367       }
9368
9369       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9370       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9371       if (N1.getOpcode() == PreferredFusedOpcode &&
9372         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9373         SDValue N120 = N1.getOperand(2).getOperand(0);
9374         if (isContractableFMUL(N120)) {
9375           SDValue N1200 = N120.getOperand(0);
9376           SDValue N1201 = N120.getOperand(1);
9377           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9378                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9379                              N1.getOperand(1),
9380                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9381                                          DAG.getNode(ISD::FNEG, SL, VT,
9382                                              DAG.getNode(ISD::FP_EXTEND, SL,
9383                                                          VT, N1200)),
9384                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9385                                                      N1201),
9386                                          N0));
9387         }
9388       }
9389
9390       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9391       //   -> (fma (fneg (fpext y)), (fpext z),
9392       //           (fma (fneg (fpext u)), (fpext v), x))
9393       // FIXME: This turns two single-precision and one double-precision
9394       // operation into two double-precision operations, which might not be
9395       // interesting for all targets, especially GPUs.
9396       if (N1.getOpcode() == ISD::FP_EXTEND &&
9397         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9398         SDValue N100 = N1.getOperand(0).getOperand(0);
9399         SDValue N101 = N1.getOperand(0).getOperand(1);
9400         SDValue N102 = N1.getOperand(0).getOperand(2);
9401         if (isContractableFMUL(N102)) {
9402           SDValue N1020 = N102.getOperand(0);
9403           SDValue N1021 = N102.getOperand(1);
9404           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9405                              DAG.getNode(ISD::FNEG, SL, VT,
9406                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9407                                                      N100)),
9408                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9409                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9410                                          DAG.getNode(ISD::FNEG, SL, VT,
9411                                              DAG.getNode(ISD::FP_EXTEND, SL,
9412                                                          VT, N1020)),
9413                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9414                                                      N1021),
9415                                          N0));
9416         }
9417       }
9418     }
9419   }
9420
9421   return SDValue();
9422 }
9423
9424 /// Try to perform FMA combining on a given FMUL node based on the distributive
9425 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9426 /// subtraction instead of addition).
9427 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9428   SDValue N0 = N->getOperand(0);
9429   SDValue N1 = N->getOperand(1);
9430   EVT VT = N->getValueType(0);
9431   SDLoc SL(N);
9432
9433   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9434
9435   const TargetOptions &Options = DAG.getTarget().Options;
9436
9437   // The transforms below are incorrect when x == 0 and y == inf, because the
9438   // intermediate multiplication produces a nan.
9439   if (!Options.NoInfsFPMath)
9440     return SDValue();
9441
9442   // Floating-point multiply-add without intermediate rounding.
9443   bool HasFMA =
9444       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9445       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9446       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9447
9448   // Floating-point multiply-add with intermediate rounding. This can result
9449   // in a less precise result due to the changed rounding order.
9450   bool HasFMAD = Options.UnsafeFPMath &&
9451                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9452
9453   // No valid opcode, do not combine.
9454   if (!HasFMAD && !HasFMA)
9455     return SDValue();
9456
9457   // Always prefer FMAD to FMA for precision.
9458   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9459   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9460
9461   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9462   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9463   auto FuseFADD = [&](SDValue X, SDValue Y) {
9464     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9465       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9466       if (XC1 && XC1->isExactlyValue(+1.0))
9467         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9468       if (XC1 && XC1->isExactlyValue(-1.0))
9469         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9470                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9471     }
9472     return SDValue();
9473   };
9474
9475   if (SDValue FMA = FuseFADD(N0, N1))
9476     return FMA;
9477   if (SDValue FMA = FuseFADD(N1, N0))
9478     return FMA;
9479
9480   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9481   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9482   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9483   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9484   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9485     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9486       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9487       if (XC0 && XC0->isExactlyValue(+1.0))
9488         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9489                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9490                            Y);
9491       if (XC0 && XC0->isExactlyValue(-1.0))
9492         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9493                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9494                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9495
9496       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9497       if (XC1 && XC1->isExactlyValue(+1.0))
9498         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9499                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9500       if (XC1 && XC1->isExactlyValue(-1.0))
9501         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9502     }
9503     return SDValue();
9504   };
9505
9506   if (SDValue FMA = FuseFSUB(N0, N1))
9507     return FMA;
9508   if (SDValue FMA = FuseFSUB(N1, N0))
9509     return FMA;
9510
9511   return SDValue();
9512 }
9513
9514 static bool isFMulNegTwo(SDValue &N) {
9515   if (N.getOpcode() != ISD::FMUL)
9516     return false;
9517   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9518     return CFP->isExactlyValue(-2.0);
9519   return false;
9520 }
9521
9522 SDValue DAGCombiner::visitFADD(SDNode *N) {
9523   SDValue N0 = N->getOperand(0);
9524   SDValue N1 = N->getOperand(1);
9525   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9526   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9527   EVT VT = N->getValueType(0);
9528   SDLoc DL(N);
9529   const TargetOptions &Options = DAG.getTarget().Options;
9530   const SDNodeFlags Flags = N->getFlags();
9531
9532   // fold vector ops
9533   if (VT.isVector())
9534     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9535       return FoldedVOp;
9536
9537   // fold (fadd c1, c2) -> c1 + c2
9538   if (N0CFP && N1CFP)
9539     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9540
9541   // canonicalize constant to RHS
9542   if (N0CFP && !N1CFP)
9543     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9544
9545   if (SDValue NewSel = foldBinOpIntoSelect(N))
9546     return NewSel;
9547
9548   // fold (fadd A, (fneg B)) -> (fsub A, B)
9549   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9550       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9551     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9552                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9553
9554   // fold (fadd (fneg A), B) -> (fsub B, A)
9555   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9556       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9557     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9558                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9559
9560   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9561   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9562   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9563       (isFMulNegTwo(N1) && N1.hasOneUse())) {
9564     bool N1IsFMul = isFMulNegTwo(N1);
9565     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9566     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9567     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9568   }
9569
9570   // FIXME: Auto-upgrade the target/function-level option.
9571   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9572     // fold (fadd A, 0) -> A
9573     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9574       if (N1C->isZero())
9575         return N0;
9576   }
9577
9578   // If 'unsafe math' is enabled, fold lots of things.
9579   if (Options.UnsafeFPMath) {
9580     // No FP constant should be created after legalization as Instruction
9581     // Selection pass has a hard time dealing with FP constants.
9582     bool AllowNewConst = (Level < AfterLegalizeDAG);
9583
9584     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9585     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9586         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9587       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9588                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9589                                      Flags),
9590                          Flags);
9591
9592     // If allowed, fold (fadd (fneg x), x) -> 0.0
9593     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9594       return DAG.getConstantFP(0.0, DL, VT);
9595
9596     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9597     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9598       return DAG.getConstantFP(0.0, DL, VT);
9599
9600     // We can fold chains of FADD's of the same value into multiplications.
9601     // This transform is not safe in general because we are reducing the number
9602     // of rounding steps.
9603     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9604       if (N0.getOpcode() == ISD::FMUL) {
9605         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9606         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9607
9608         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9609         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9610           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9611                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9612           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9613         }
9614
9615         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9616         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9617             N1.getOperand(0) == N1.getOperand(1) &&
9618             N0.getOperand(0) == N1.getOperand(0)) {
9619           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9620                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9621           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9622         }
9623       }
9624
9625       if (N1.getOpcode() == ISD::FMUL) {
9626         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9627         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9628
9629         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9630         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9631           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9632                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9633           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9634         }
9635
9636         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9637         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9638             N0.getOperand(0) == N0.getOperand(1) &&
9639             N1.getOperand(0) == N0.getOperand(0)) {
9640           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9641                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9642           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9643         }
9644       }
9645
9646       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9647         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9648         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9649         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9650             (N0.getOperand(0) == N1)) {
9651           return DAG.getNode(ISD::FMUL, DL, VT,
9652                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9653         }
9654       }
9655
9656       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9657         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9658         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9659         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9660             N1.getOperand(0) == N0) {
9661           return DAG.getNode(ISD::FMUL, DL, VT,
9662                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9663         }
9664       }
9665
9666       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9667       if (AllowNewConst &&
9668           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9669           N0.getOperand(0) == N0.getOperand(1) &&
9670           N1.getOperand(0) == N1.getOperand(1) &&
9671           N0.getOperand(0) == N1.getOperand(0)) {
9672         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9673                            DAG.getConstantFP(4.0, DL, VT), Flags);
9674       }
9675     }
9676   } // enable-unsafe-fp-math
9677
9678   // FADD -> FMA combines:
9679   if (SDValue Fused = visitFADDForFMACombine(N)) {
9680     AddToWorklist(Fused.getNode());
9681     return Fused;
9682   }
9683   return SDValue();
9684 }
9685
9686 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9687   SDValue N0 = N->getOperand(0);
9688   SDValue N1 = N->getOperand(1);
9689   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9690   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9691   EVT VT = N->getValueType(0);
9692   SDLoc DL(N);
9693   const TargetOptions &Options = DAG.getTarget().Options;
9694   const SDNodeFlags Flags = N->getFlags();
9695
9696   // fold vector ops
9697   if (VT.isVector())
9698     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9699       return FoldedVOp;
9700
9701   // fold (fsub c1, c2) -> c1-c2
9702   if (N0CFP && N1CFP)
9703     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9704
9705   if (SDValue NewSel = foldBinOpIntoSelect(N))
9706     return NewSel;
9707
9708   // fold (fsub A, (fneg B)) -> (fadd A, B)
9709   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9710     return DAG.getNode(ISD::FADD, DL, VT, N0,
9711                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9712
9713   // FIXME: Auto-upgrade the target/function-level option.
9714   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
9715     // (fsub 0, B) -> -B
9716     if (N0CFP && N0CFP->isZero()) {
9717       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9718         return GetNegatedExpression(N1, DAG, LegalOperations);
9719       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9720         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9721     }
9722   }
9723
9724   // If 'unsafe math' is enabled, fold lots of things.
9725   if (Options.UnsafeFPMath) {
9726     // (fsub A, 0) -> A
9727     if (N1CFP && N1CFP->isZero())
9728       return N0;
9729
9730     // (fsub x, x) -> 0.0
9731     if (N0 == N1)
9732       return DAG.getConstantFP(0.0f, DL, VT);
9733
9734     // (fsub x, (fadd x, y)) -> (fneg y)
9735     // (fsub x, (fadd y, x)) -> (fneg y)
9736     if (N1.getOpcode() == ISD::FADD) {
9737       SDValue N10 = N1->getOperand(0);
9738       SDValue N11 = N1->getOperand(1);
9739
9740       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9741         return GetNegatedExpression(N11, DAG, LegalOperations);
9742
9743       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9744         return GetNegatedExpression(N10, DAG, LegalOperations);
9745     }
9746   }
9747
9748   // FSUB -> FMA combines:
9749   if (SDValue Fused = visitFSUBForFMACombine(N)) {
9750     AddToWorklist(Fused.getNode());
9751     return Fused;
9752   }
9753
9754   return SDValue();
9755 }
9756
9757 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9758   SDValue N0 = N->getOperand(0);
9759   SDValue N1 = N->getOperand(1);
9760   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9761   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9762   EVT VT = N->getValueType(0);
9763   SDLoc DL(N);
9764   const TargetOptions &Options = DAG.getTarget().Options;
9765   const SDNodeFlags Flags = N->getFlags();
9766
9767   // fold vector ops
9768   if (VT.isVector()) {
9769     // This just handles C1 * C2 for vectors. Other vector folds are below.
9770     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9771       return FoldedVOp;
9772   }
9773
9774   // fold (fmul c1, c2) -> c1*c2
9775   if (N0CFP && N1CFP)
9776     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9777
9778   // canonicalize constant to RHS
9779   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9780      !isConstantFPBuildVectorOrConstantFP(N1))
9781     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9782
9783   // fold (fmul A, 1.0) -> A
9784   if (N1CFP && N1CFP->isExactlyValue(1.0))
9785     return N0;
9786
9787   if (SDValue NewSel = foldBinOpIntoSelect(N))
9788     return NewSel;
9789
9790   if (Options.UnsafeFPMath) {
9791     // fold (fmul A, 0) -> 0
9792     if (N1CFP && N1CFP->isZero())
9793       return N1;
9794
9795     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9796     if (N0.getOpcode() == ISD::FMUL) {
9797       // Fold scalars or any vector constants (not just splats).
9798       // This fold is done in general by InstCombine, but extra fmul insts
9799       // may have been generated during lowering.
9800       SDValue N00 = N0.getOperand(0);
9801       SDValue N01 = N0.getOperand(1);
9802       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9803       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9804       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9805
9806       // Check 1: Make sure that the first operand of the inner multiply is NOT
9807       // a constant. Otherwise, we may induce infinite looping.
9808       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9809         // Check 2: Make sure that the second operand of the inner multiply and
9810         // the second operand of the outer multiply are constants.
9811         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9812             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9813           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9814           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9815         }
9816       }
9817     }
9818
9819     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9820     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9821     // during an early run of DAGCombiner can prevent folding with fmuls
9822     // inserted during lowering.
9823     if (N0.getOpcode() == ISD::FADD &&
9824         (N0.getOperand(0) == N0.getOperand(1)) &&
9825         N0.hasOneUse()) {
9826       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9827       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9828       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9829     }
9830   }
9831
9832   // fold (fmul X, 2.0) -> (fadd X, X)
9833   if (N1CFP && N1CFP->isExactlyValue(+2.0))
9834     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9835
9836   // fold (fmul X, -1.0) -> (fneg X)
9837   if (N1CFP && N1CFP->isExactlyValue(-1.0))
9838     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9839       return DAG.getNode(ISD::FNEG, DL, VT, N0);
9840
9841   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9842   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9843     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9844       // Both can be negated for free, check to see if at least one is cheaper
9845       // negated.
9846       if (LHSNeg == 2 || RHSNeg == 2)
9847         return DAG.getNode(ISD::FMUL, DL, VT,
9848                            GetNegatedExpression(N0, DAG, LegalOperations),
9849                            GetNegatedExpression(N1, DAG, LegalOperations),
9850                            Flags);
9851     }
9852   }
9853
9854   // FMUL -> FMA combines:
9855   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9856     AddToWorklist(Fused.getNode());
9857     return Fused;
9858   }
9859
9860   return SDValue();
9861 }
9862
9863 SDValue DAGCombiner::visitFMA(SDNode *N) {
9864   SDValue N0 = N->getOperand(0);
9865   SDValue N1 = N->getOperand(1);
9866   SDValue N2 = N->getOperand(2);
9867   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9868   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9869   EVT VT = N->getValueType(0);
9870   SDLoc DL(N);
9871   const TargetOptions &Options = DAG.getTarget().Options;
9872
9873   // Constant fold FMA.
9874   if (isa<ConstantFPSDNode>(N0) &&
9875       isa<ConstantFPSDNode>(N1) &&
9876       isa<ConstantFPSDNode>(N2)) {
9877     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9878   }
9879
9880   if (Options.UnsafeFPMath) {
9881     if (N0CFP && N0CFP->isZero())
9882       return N2;
9883     if (N1CFP && N1CFP->isZero())
9884       return N2;
9885   }
9886   // TODO: The FMA node should have flags that propagate to these nodes.
9887   if (N0CFP && N0CFP->isExactlyValue(1.0))
9888     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9889   if (N1CFP && N1CFP->isExactlyValue(1.0))
9890     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9891
9892   // Canonicalize (fma c, x, y) -> (fma x, c, y)
9893   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9894      !isConstantFPBuildVectorOrConstantFP(N1))
9895     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9896
9897   // TODO: FMA nodes should have flags that propagate to the created nodes.
9898   // For now, create a Flags object for use with all unsafe math transforms.
9899   SDNodeFlags Flags;
9900   Flags.setUnsafeAlgebra(true);
9901
9902   if (Options.UnsafeFPMath) {
9903     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9904     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9905         isConstantFPBuildVectorOrConstantFP(N1) &&
9906         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9907       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9908                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9909                                      Flags), Flags);
9910     }
9911
9912     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9913     if (N0.getOpcode() == ISD::FMUL &&
9914         isConstantFPBuildVectorOrConstantFP(N1) &&
9915         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9916       return DAG.getNode(ISD::FMA, DL, VT,
9917                          N0.getOperand(0),
9918                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9919                                      Flags),
9920                          N2);
9921     }
9922   }
9923
9924   // (fma x, 1, y) -> (fadd x, y)
9925   // (fma x, -1, y) -> (fadd (fneg x), y)
9926   if (N1CFP) {
9927     if (N1CFP->isExactlyValue(1.0))
9928       // TODO: The FMA node should have flags that propagate to this node.
9929       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9930
9931     if (N1CFP->isExactlyValue(-1.0) &&
9932         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9933       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9934       AddToWorklist(RHSNeg.getNode());
9935       // TODO: The FMA node should have flags that propagate to this node.
9936       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9937     }
9938   }
9939
9940   if (Options.UnsafeFPMath) {
9941     // (fma x, c, x) -> (fmul x, (c+1))
9942     if (N1CFP && N0 == N2) {
9943       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9944                          DAG.getNode(ISD::FADD, DL, VT, N1,
9945                                      DAG.getConstantFP(1.0, DL, VT), Flags),
9946                          Flags);
9947     }
9948
9949     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9950     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9951       return DAG.getNode(ISD::FMUL, DL, VT, N0,
9952                          DAG.getNode(ISD::FADD, DL, VT, N1,
9953                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
9954                          Flags);
9955     }
9956   }
9957
9958   return SDValue();
9959 }
9960
9961 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9962 // reciprocal.
9963 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9964 // Notice that this is not always beneficial. One reason is different targets
9965 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9966 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9967 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9968 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9969   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9970   const SDNodeFlags Flags = N->getFlags();
9971   if (!UnsafeMath && !Flags.hasAllowReciprocal())
9972     return SDValue();
9973
9974   // Skip if current node is a reciprocal.
9975   SDValue N0 = N->getOperand(0);
9976   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9977   if (N0CFP && N0CFP->isExactlyValue(1.0))
9978     return SDValue();
9979
9980   // Exit early if the target does not want this transform or if there can't
9981   // possibly be enough uses of the divisor to make the transform worthwhile.
9982   SDValue N1 = N->getOperand(1);
9983   unsigned MinUses = TLI.combineRepeatedFPDivisors();
9984   if (!MinUses || N1->use_size() < MinUses)
9985     return SDValue();
9986
9987   // Find all FDIV users of the same divisor.
9988   // Use a set because duplicates may be present in the user list.
9989   SetVector<SDNode *> Users;
9990   for (auto *U : N1->uses()) {
9991     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
9992       // This division is eligible for optimization only if global unsafe math
9993       // is enabled or if this division allows reciprocal formation.
9994       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
9995         Users.insert(U);
9996     }
9997   }
9998
9999   // Now that we have the actual number of divisor uses, make sure it meets
10000   // the minimum threshold specified by the target.
10001   if (Users.size() < MinUses)
10002     return SDValue();
10003
10004   EVT VT = N->getValueType(0);
10005   SDLoc DL(N);
10006   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10007   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10008
10009   // Dividend / Divisor -> Dividend * Reciprocal
10010   for (auto *U : Users) {
10011     SDValue Dividend = U->getOperand(0);
10012     if (Dividend != FPOne) {
10013       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10014                                     Reciprocal, Flags);
10015       CombineTo(U, NewNode);
10016     } else if (U != Reciprocal.getNode()) {
10017       // In the absence of fast-math-flags, this user node is always the
10018       // same node as Reciprocal, but with FMF they may be different nodes.
10019       CombineTo(U, Reciprocal);
10020     }
10021   }
10022   return SDValue(N, 0);  // N was replaced.
10023 }
10024
10025 SDValue DAGCombiner::visitFDIV(SDNode *N) {
10026   SDValue N0 = N->getOperand(0);
10027   SDValue N1 = N->getOperand(1);
10028   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10029   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10030   EVT VT = N->getValueType(0);
10031   SDLoc DL(N);
10032   const TargetOptions &Options = DAG.getTarget().Options;
10033   SDNodeFlags Flags = N->getFlags();
10034
10035   // fold vector ops
10036   if (VT.isVector())
10037     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10038       return FoldedVOp;
10039
10040   // fold (fdiv c1, c2) -> c1/c2
10041   if (N0CFP && N1CFP)
10042     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10043
10044   if (SDValue NewSel = foldBinOpIntoSelect(N))
10045     return NewSel;
10046
10047   if (Options.UnsafeFPMath) {
10048     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10049     if (N1CFP) {
10050       // Compute the reciprocal 1.0 / c2.
10051       const APFloat &N1APF = N1CFP->getValueAPF();
10052       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10053       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10054       // Only do the transform if the reciprocal is a legal fp immediate that
10055       // isn't too nasty (eg NaN, denormal, ...).
10056       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10057           (!LegalOperations ||
10058            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10059            // backend)... we should handle this gracefully after Legalize.
10060            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
10061            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
10062            TLI.isFPImmLegal(Recip, VT)))
10063         return DAG.getNode(ISD::FMUL, DL, VT, N0,
10064                            DAG.getConstantFP(Recip, DL, VT), Flags);
10065     }
10066
10067     // If this FDIV is part of a reciprocal square root, it may be folded
10068     // into a target-specific square root estimate instruction.
10069     if (N1.getOpcode() == ISD::FSQRT) {
10070       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10071         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10072       }
10073     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10074                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10075       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10076                                           Flags)) {
10077         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10078         AddToWorklist(RV.getNode());
10079         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10080       }
10081     } else if (N1.getOpcode() == ISD::FP_ROUND &&
10082                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10083       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10084                                           Flags)) {
10085         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10086         AddToWorklist(RV.getNode());
10087         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10088       }
10089     } else if (N1.getOpcode() == ISD::FMUL) {
10090       // Look through an FMUL. Even though this won't remove the FDIV directly,
10091       // it's still worthwhile to get rid of the FSQRT if possible.
10092       SDValue SqrtOp;
10093       SDValue OtherOp;
10094       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10095         SqrtOp = N1.getOperand(0);
10096         OtherOp = N1.getOperand(1);
10097       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10098         SqrtOp = N1.getOperand(1);
10099         OtherOp = N1.getOperand(0);
10100       }
10101       if (SqrtOp.getNode()) {
10102         // We found a FSQRT, so try to make this fold:
10103         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10104         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10105           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10106           AddToWorklist(RV.getNode());
10107           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10108         }
10109       }
10110     }
10111
10112     // Fold into a reciprocal estimate and multiply instead of a real divide.
10113     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10114       AddToWorklist(RV.getNode());
10115       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10116     }
10117   }
10118
10119   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10120   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10121     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10122       // Both can be negated for free, check to see if at least one is cheaper
10123       // negated.
10124       if (LHSNeg == 2 || RHSNeg == 2)
10125         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10126                            GetNegatedExpression(N0, DAG, LegalOperations),
10127                            GetNegatedExpression(N1, DAG, LegalOperations),
10128                            Flags);
10129     }
10130   }
10131
10132   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10133     return CombineRepeatedDivisors;
10134
10135   return SDValue();
10136 }
10137
10138 SDValue DAGCombiner::visitFREM(SDNode *N) {
10139   SDValue N0 = N->getOperand(0);
10140   SDValue N1 = N->getOperand(1);
10141   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10142   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10143   EVT VT = N->getValueType(0);
10144
10145   // fold (frem c1, c2) -> fmod(c1,c2)
10146   if (N0CFP && N1CFP)
10147     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10148
10149   if (SDValue NewSel = foldBinOpIntoSelect(N))
10150     return NewSel;
10151
10152   return SDValue();
10153 }
10154
10155 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10156   if (!DAG.getTarget().Options.UnsafeFPMath)
10157     return SDValue();
10158
10159   SDValue N0 = N->getOperand(0);
10160   if (TLI.isFsqrtCheap(N0, DAG))
10161     return SDValue();
10162
10163   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10164   // For now, create a Flags object for use with all unsafe math transforms.
10165   SDNodeFlags Flags;
10166   Flags.setUnsafeAlgebra(true);
10167   return buildSqrtEstimate(N0, Flags);
10168 }
10169
10170 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10171 /// copysign(x, fp_round(y)) -> copysign(x, y)
10172 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10173   SDValue N1 = N->getOperand(1);
10174   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10175        N1.getOpcode() == ISD::FP_ROUND)) {
10176     // Do not optimize out type conversion of f128 type yet.
10177     // For some targets like x86_64, configuration is changed to keep one f128
10178     // value in one SSE register, but instruction selection cannot handle
10179     // FCOPYSIGN on SSE registers yet.
10180     EVT N1VT = N1->getValueType(0);
10181     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10182     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10183   }
10184   return false;
10185 }
10186
10187 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10188   SDValue N0 = N->getOperand(0);
10189   SDValue N1 = N->getOperand(1);
10190   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10191   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10192   EVT VT = N->getValueType(0);
10193
10194   if (N0CFP && N1CFP) // Constant fold
10195     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10196
10197   if (N1CFP) {
10198     const APFloat &V = N1CFP->getValueAPF();
10199     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10200     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10201     if (!V.isNegative()) {
10202       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10203         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10204     } else {
10205       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10206         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10207                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10208     }
10209   }
10210
10211   // copysign(fabs(x), y) -> copysign(x, y)
10212   // copysign(fneg(x), y) -> copysign(x, y)
10213   // copysign(copysign(x,z), y) -> copysign(x, y)
10214   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10215       N0.getOpcode() == ISD::FCOPYSIGN)
10216     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10217
10218   // copysign(x, abs(y)) -> abs(x)
10219   if (N1.getOpcode() == ISD::FABS)
10220     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10221
10222   // copysign(x, copysign(y,z)) -> copysign(x, z)
10223   if (N1.getOpcode() == ISD::FCOPYSIGN)
10224     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10225
10226   // copysign(x, fp_extend(y)) -> copysign(x, y)
10227   // copysign(x, fp_round(y)) -> copysign(x, y)
10228   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10229     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10230
10231   return SDValue();
10232 }
10233
10234 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10235   SDValue N0 = N->getOperand(0);
10236   EVT VT = N->getValueType(0);
10237   EVT OpVT = N0.getValueType();
10238
10239   // fold (sint_to_fp c1) -> c1fp
10240   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10241       // ...but only if the target supports immediate floating-point values
10242       (!LegalOperations ||
10243        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10244     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10245
10246   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10247   // but UINT_TO_FP is legal on this target, try to convert.
10248   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10249       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10250     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10251     if (DAG.SignBitIsZero(N0))
10252       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10253   }
10254
10255   // The next optimizations are desirable only if SELECT_CC can be lowered.
10256   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10257     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10258     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10259         !VT.isVector() &&
10260         (!LegalOperations ||
10261          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10262       SDLoc DL(N);
10263       SDValue Ops[] =
10264         { N0.getOperand(0), N0.getOperand(1),
10265           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10266           N0.getOperand(2) };
10267       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10268     }
10269
10270     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10271     //      (select_cc x, y, 1.0, 0.0,, cc)
10272     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10273         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10274         (!LegalOperations ||
10275          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10276       SDLoc DL(N);
10277       SDValue Ops[] =
10278         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10279           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10280           N0.getOperand(0).getOperand(2) };
10281       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10282     }
10283   }
10284
10285   return SDValue();
10286 }
10287
10288 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10289   SDValue N0 = N->getOperand(0);
10290   EVT VT = N->getValueType(0);
10291   EVT OpVT = N0.getValueType();
10292
10293   // fold (uint_to_fp c1) -> c1fp
10294   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10295       // ...but only if the target supports immediate floating-point values
10296       (!LegalOperations ||
10297        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10298     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10299
10300   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10301   // but SINT_TO_FP is legal on this target, try to convert.
10302   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10303       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10304     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10305     if (DAG.SignBitIsZero(N0))
10306       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10307   }
10308
10309   // The next optimizations are desirable only if SELECT_CC can be lowered.
10310   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10311     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10312
10313     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10314         (!LegalOperations ||
10315          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10316       SDLoc DL(N);
10317       SDValue Ops[] =
10318         { N0.getOperand(0), N0.getOperand(1),
10319           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10320           N0.getOperand(2) };
10321       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10322     }
10323   }
10324
10325   return SDValue();
10326 }
10327
10328 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10329 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10330   SDValue N0 = N->getOperand(0);
10331   EVT VT = N->getValueType(0);
10332
10333   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10334     return SDValue();
10335
10336   SDValue Src = N0.getOperand(0);
10337   EVT SrcVT = Src.getValueType();
10338   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10339   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10340
10341   // We can safely assume the conversion won't overflow the output range,
10342   // because (for example) (uint8_t)18293.f is undefined behavior.
10343
10344   // Since we can assume the conversion won't overflow, our decision as to
10345   // whether the input will fit in the float should depend on the minimum
10346   // of the input range and output range.
10347
10348   // This means this is also safe for a signed input and unsigned output, since
10349   // a negative input would lead to undefined behavior.
10350   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10351   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10352   unsigned ActualSize = std::min(InputSize, OutputSize);
10353   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10354
10355   // We can only fold away the float conversion if the input range can be
10356   // represented exactly in the float range.
10357   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10358     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10359       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10360                                                        : ISD::ZERO_EXTEND;
10361       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10362     }
10363     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10364       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10365     return DAG.getBitcast(VT, Src);
10366   }
10367   return SDValue();
10368 }
10369
10370 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10371   SDValue N0 = N->getOperand(0);
10372   EVT VT = N->getValueType(0);
10373
10374   // fold (fp_to_sint c1fp) -> c1
10375   if (isConstantFPBuildVectorOrConstantFP(N0))
10376     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10377
10378   return FoldIntToFPToInt(N, DAG);
10379 }
10380
10381 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10382   SDValue N0 = N->getOperand(0);
10383   EVT VT = N->getValueType(0);
10384
10385   // fold (fp_to_uint c1fp) -> c1
10386   if (isConstantFPBuildVectorOrConstantFP(N0))
10387     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10388
10389   return FoldIntToFPToInt(N, DAG);
10390 }
10391
10392 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10393   SDValue N0 = N->getOperand(0);
10394   SDValue N1 = N->getOperand(1);
10395   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10396   EVT VT = N->getValueType(0);
10397
10398   // fold (fp_round c1fp) -> c1fp
10399   if (N0CFP)
10400     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10401
10402   // fold (fp_round (fp_extend x)) -> x
10403   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10404     return N0.getOperand(0);
10405
10406   // fold (fp_round (fp_round x)) -> (fp_round x)
10407   if (N0.getOpcode() == ISD::FP_ROUND) {
10408     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10409     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10410
10411     // Skip this folding if it results in an fp_round from f80 to f16.
10412     //
10413     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10414     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10415     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10416     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10417     // x86.
10418     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10419       return SDValue();
10420
10421     // If the first fp_round isn't a value preserving truncation, it might
10422     // introduce a tie in the second fp_round, that wouldn't occur in the
10423     // single-step fp_round we want to fold to.
10424     // In other words, double rounding isn't the same as rounding.
10425     // Also, this is a value preserving truncation iff both fp_round's are.
10426     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10427       SDLoc DL(N);
10428       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10429                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10430     }
10431   }
10432
10433   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10434   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10435     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10436                               N0.getOperand(0), N1);
10437     AddToWorklist(Tmp.getNode());
10438     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10439                        Tmp, N0.getOperand(1));
10440   }
10441
10442   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10443     return NewVSel;
10444
10445   return SDValue();
10446 }
10447
10448 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10449   SDValue N0 = N->getOperand(0);
10450   EVT VT = N->getValueType(0);
10451   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10452   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10453
10454   // fold (fp_round_inreg c1fp) -> c1fp
10455   if (N0CFP && isTypeLegal(EVT)) {
10456     SDLoc DL(N);
10457     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10458     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10459   }
10460
10461   return SDValue();
10462 }
10463
10464 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10465   SDValue N0 = N->getOperand(0);
10466   EVT VT = N->getValueType(0);
10467
10468   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10469   if (N->hasOneUse() &&
10470       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10471     return SDValue();
10472
10473   // fold (fp_extend c1fp) -> c1fp
10474   if (isConstantFPBuildVectorOrConstantFP(N0))
10475     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10476
10477   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10478   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10479       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10480     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10481
10482   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10483   // value of X.
10484   if (N0.getOpcode() == ISD::FP_ROUND
10485       && N0.getConstantOperandVal(1) == 1) {
10486     SDValue In = N0.getOperand(0);
10487     if (In.getValueType() == VT) return In;
10488     if (VT.bitsLT(In.getValueType()))
10489       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10490                          In, N0.getOperand(1));
10491     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10492   }
10493
10494   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10495   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10496        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10497     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10498     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10499                                      LN0->getChain(),
10500                                      LN0->getBasePtr(), N0.getValueType(),
10501                                      LN0->getMemOperand());
10502     CombineTo(N, ExtLoad);
10503     CombineTo(N0.getNode(),
10504               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10505                           N0.getValueType(), ExtLoad,
10506                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10507               ExtLoad.getValue(1));
10508     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10509   }
10510
10511   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10512     return NewVSel;
10513
10514   return SDValue();
10515 }
10516
10517 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10518   SDValue N0 = N->getOperand(0);
10519   EVT VT = N->getValueType(0);
10520
10521   // fold (fceil c1) -> fceil(c1)
10522   if (isConstantFPBuildVectorOrConstantFP(N0))
10523     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10524
10525   return SDValue();
10526 }
10527
10528 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10529   SDValue N0 = N->getOperand(0);
10530   EVT VT = N->getValueType(0);
10531
10532   // fold (ftrunc c1) -> ftrunc(c1)
10533   if (isConstantFPBuildVectorOrConstantFP(N0))
10534     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10535
10536   return SDValue();
10537 }
10538
10539 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10540   SDValue N0 = N->getOperand(0);
10541   EVT VT = N->getValueType(0);
10542
10543   // fold (ffloor c1) -> ffloor(c1)
10544   if (isConstantFPBuildVectorOrConstantFP(N0))
10545     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10546
10547   return SDValue();
10548 }
10549
10550 // FIXME: FNEG and FABS have a lot in common; refactor.
10551 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10552   SDValue N0 = N->getOperand(0);
10553   EVT VT = N->getValueType(0);
10554
10555   // Constant fold FNEG.
10556   if (isConstantFPBuildVectorOrConstantFP(N0))
10557     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10558
10559   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10560                          &DAG.getTarget().Options))
10561     return GetNegatedExpression(N0, DAG, LegalOperations);
10562
10563   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10564   // constant pool values.
10565   if (!TLI.isFNegFree(VT) &&
10566       N0.getOpcode() == ISD::BITCAST &&
10567       N0.getNode()->hasOneUse()) {
10568     SDValue Int = N0.getOperand(0);
10569     EVT IntVT = Int.getValueType();
10570     if (IntVT.isInteger() && !IntVT.isVector()) {
10571       APInt SignMask;
10572       if (N0.getValueType().isVector()) {
10573         // For a vector, get a mask such as 0x80... per scalar element
10574         // and splat it.
10575         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10576         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10577       } else {
10578         // For a scalar, just generate 0x80...
10579         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10580       }
10581       SDLoc DL0(N0);
10582       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10583                         DAG.getConstant(SignMask, DL0, IntVT));
10584       AddToWorklist(Int.getNode());
10585       return DAG.getBitcast(VT, Int);
10586     }
10587   }
10588
10589   // (fneg (fmul c, x)) -> (fmul -c, x)
10590   if (N0.getOpcode() == ISD::FMUL &&
10591       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10592     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10593     if (CFP1) {
10594       APFloat CVal = CFP1->getValueAPF();
10595       CVal.changeSign();
10596       if (Level >= AfterLegalizeDAG &&
10597           (TLI.isFPImmLegal(CVal, VT) ||
10598            TLI.isOperationLegal(ISD::ConstantFP, VT)))
10599         return DAG.getNode(
10600             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10601             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10602             N0->getFlags());
10603     }
10604   }
10605
10606   return SDValue();
10607 }
10608
10609 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10610   SDValue N0 = N->getOperand(0);
10611   SDValue N1 = N->getOperand(1);
10612   EVT VT = N->getValueType(0);
10613   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10614   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10615
10616   if (N0CFP && N1CFP) {
10617     const APFloat &C0 = N0CFP->getValueAPF();
10618     const APFloat &C1 = N1CFP->getValueAPF();
10619     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10620   }
10621
10622   // Canonicalize to constant on RHS.
10623   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10624      !isConstantFPBuildVectorOrConstantFP(N1))
10625     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10626
10627   return SDValue();
10628 }
10629
10630 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10631   SDValue N0 = N->getOperand(0);
10632   SDValue N1 = N->getOperand(1);
10633   EVT VT = N->getValueType(0);
10634   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10635   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10636
10637   if (N0CFP && N1CFP) {
10638     const APFloat &C0 = N0CFP->getValueAPF();
10639     const APFloat &C1 = N1CFP->getValueAPF();
10640     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10641   }
10642
10643   // Canonicalize to constant on RHS.
10644   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10645      !isConstantFPBuildVectorOrConstantFP(N1))
10646     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10647
10648   return SDValue();
10649 }
10650
10651 SDValue DAGCombiner::visitFABS(SDNode *N) {
10652   SDValue N0 = N->getOperand(0);
10653   EVT VT = N->getValueType(0);
10654
10655   // fold (fabs c1) -> fabs(c1)
10656   if (isConstantFPBuildVectorOrConstantFP(N0))
10657     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10658
10659   // fold (fabs (fabs x)) -> (fabs x)
10660   if (N0.getOpcode() == ISD::FABS)
10661     return N->getOperand(0);
10662
10663   // fold (fabs (fneg x)) -> (fabs x)
10664   // fold (fabs (fcopysign x, y)) -> (fabs x)
10665   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10666     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10667
10668   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10669   // constant pool values.
10670   if (!TLI.isFAbsFree(VT) &&
10671       N0.getOpcode() == ISD::BITCAST &&
10672       N0.getNode()->hasOneUse()) {
10673     SDValue Int = N0.getOperand(0);
10674     EVT IntVT = Int.getValueType();
10675     if (IntVT.isInteger() && !IntVT.isVector()) {
10676       APInt SignMask;
10677       if (N0.getValueType().isVector()) {
10678         // For a vector, get a mask such as 0x7f... per scalar element
10679         // and splat it.
10680         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10681         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10682       } else {
10683         // For a scalar, just generate 0x7f...
10684         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10685       }
10686       SDLoc DL(N0);
10687       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10688                         DAG.getConstant(SignMask, DL, IntVT));
10689       AddToWorklist(Int.getNode());
10690       return DAG.getBitcast(N->getValueType(0), Int);
10691     }
10692   }
10693
10694   return SDValue();
10695 }
10696
10697 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10698   SDValue Chain = N->getOperand(0);
10699   SDValue N1 = N->getOperand(1);
10700   SDValue N2 = N->getOperand(2);
10701
10702   // If N is a constant we could fold this into a fallthrough or unconditional
10703   // branch. However that doesn't happen very often in normal code, because
10704   // Instcombine/SimplifyCFG should have handled the available opportunities.
10705   // If we did this folding here, it would be necessary to update the
10706   // MachineBasicBlock CFG, which is awkward.
10707
10708   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10709   // on the target.
10710   if (N1.getOpcode() == ISD::SETCC &&
10711       TLI.isOperationLegalOrCustom(ISD::BR_CC,
10712                                    N1.getOperand(0).getValueType())) {
10713     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10714                        Chain, N1.getOperand(2),
10715                        N1.getOperand(0), N1.getOperand(1), N2);
10716   }
10717
10718   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10719       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10720        (N1.getOperand(0).hasOneUse() &&
10721         N1.getOperand(0).getOpcode() == ISD::SRL))) {
10722     SDNode *Trunc = nullptr;
10723     if (N1.getOpcode() == ISD::TRUNCATE) {
10724       // Look pass the truncate.
10725       Trunc = N1.getNode();
10726       N1 = N1.getOperand(0);
10727     }
10728
10729     // Match this pattern so that we can generate simpler code:
10730     //
10731     //   %a = ...
10732     //   %b = and i32 %a, 2
10733     //   %c = srl i32 %b, 1
10734     //   brcond i32 %c ...
10735     //
10736     // into
10737     //
10738     //   %a = ...
10739     //   %b = and i32 %a, 2
10740     //   %c = setcc eq %b, 0
10741     //   brcond %c ...
10742     //
10743     // This applies only when the AND constant value has one bit set and the
10744     // SRL constant is equal to the log2 of the AND constant. The back-end is
10745     // smart enough to convert the result into a TEST/JMP sequence.
10746     SDValue Op0 = N1.getOperand(0);
10747     SDValue Op1 = N1.getOperand(1);
10748
10749     if (Op0.getOpcode() == ISD::AND &&
10750         Op1.getOpcode() == ISD::Constant) {
10751       SDValue AndOp1 = Op0.getOperand(1);
10752
10753       if (AndOp1.getOpcode() == ISD::Constant) {
10754         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10755
10756         if (AndConst.isPowerOf2() &&
10757             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10758           SDLoc DL(N);
10759           SDValue SetCC =
10760             DAG.getSetCC(DL,
10761                          getSetCCResultType(Op0.getValueType()),
10762                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10763                          ISD::SETNE);
10764
10765           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10766                                           MVT::Other, Chain, SetCC, N2);
10767           // Don't add the new BRCond into the worklist or else SimplifySelectCC
10768           // will convert it back to (X & C1) >> C2.
10769           CombineTo(N, NewBRCond, false);
10770           // Truncate is dead.
10771           if (Trunc)
10772             deleteAndRecombine(Trunc);
10773           // Replace the uses of SRL with SETCC
10774           WorklistRemover DeadNodes(*this);
10775           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10776           deleteAndRecombine(N1.getNode());
10777           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10778         }
10779       }
10780     }
10781
10782     if (Trunc)
10783       // Restore N1 if the above transformation doesn't match.
10784       N1 = N->getOperand(1);
10785   }
10786
10787   // Transform br(xor(x, y)) -> br(x != y)
10788   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10789   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10790     SDNode *TheXor = N1.getNode();
10791     SDValue Op0 = TheXor->getOperand(0);
10792     SDValue Op1 = TheXor->getOperand(1);
10793     if (Op0.getOpcode() == Op1.getOpcode()) {
10794       // Avoid missing important xor optimizations.
10795       if (SDValue Tmp = visitXOR(TheXor)) {
10796         if (Tmp.getNode() != TheXor) {
10797           DEBUG(dbgs() << "\nReplacing.8 ";
10798                 TheXor->dump(&DAG);
10799                 dbgs() << "\nWith: ";
10800                 Tmp.getNode()->dump(&DAG);
10801                 dbgs() << '\n');
10802           WorklistRemover DeadNodes(*this);
10803           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10804           deleteAndRecombine(TheXor);
10805           return DAG.getNode(ISD::BRCOND, SDLoc(N),
10806                              MVT::Other, Chain, Tmp, N2);
10807         }
10808
10809         // visitXOR has changed XOR's operands or replaced the XOR completely,
10810         // bail out.
10811         return SDValue(N, 0);
10812       }
10813     }
10814
10815     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10816       bool Equal = false;
10817       if (isOneConstant(Op0) && Op0.hasOneUse() &&
10818           Op0.getOpcode() == ISD::XOR) {
10819         TheXor = Op0.getNode();
10820         Equal = true;
10821       }
10822
10823       EVT SetCCVT = N1.getValueType();
10824       if (LegalTypes)
10825         SetCCVT = getSetCCResultType(SetCCVT);
10826       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10827                                    SetCCVT,
10828                                    Op0, Op1,
10829                                    Equal ? ISD::SETEQ : ISD::SETNE);
10830       // Replace the uses of XOR with SETCC
10831       WorklistRemover DeadNodes(*this);
10832       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10833       deleteAndRecombine(N1.getNode());
10834       return DAG.getNode(ISD::BRCOND, SDLoc(N),
10835                          MVT::Other, Chain, SetCC, N2);
10836     }
10837   }
10838
10839   return SDValue();
10840 }
10841
10842 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10843 //
10844 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10845   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10846   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10847
10848   // If N is a constant we could fold this into a fallthrough or unconditional
10849   // branch. However that doesn't happen very often in normal code, because
10850   // Instcombine/SimplifyCFG should have handled the available opportunities.
10851   // If we did this folding here, it would be necessary to update the
10852   // MachineBasicBlock CFG, which is awkward.
10853
10854   // Use SimplifySetCC to simplify SETCC's.
10855   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10856                                CondLHS, CondRHS, CC->get(), SDLoc(N),
10857                                false);
10858   if (Simp.getNode()) AddToWorklist(Simp.getNode());
10859
10860   // fold to a simpler setcc
10861   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10862     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10863                        N->getOperand(0), Simp.getOperand(2),
10864                        Simp.getOperand(0), Simp.getOperand(1),
10865                        N->getOperand(4));
10866
10867   return SDValue();
10868 }
10869
10870 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10871 /// and that N may be folded in the load / store addressing mode.
10872 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10873                                     SelectionDAG &DAG,
10874                                     const TargetLowering &TLI) {
10875   EVT VT;
10876   unsigned AS;
10877
10878   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
10879     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10880       return false;
10881     VT = LD->getMemoryVT();
10882     AS = LD->getAddressSpace();
10883   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
10884     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10885       return false;
10886     VT = ST->getMemoryVT();
10887     AS = ST->getAddressSpace();
10888   } else
10889     return false;
10890
10891   TargetLowering::AddrMode AM;
10892   if (N->getOpcode() == ISD::ADD) {
10893     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10894     if (Offset)
10895       // [reg +/- imm]
10896       AM.BaseOffs = Offset->getSExtValue();
10897     else
10898       // [reg +/- reg]
10899       AM.Scale = 1;
10900   } else if (N->getOpcode() == ISD::SUB) {
10901     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10902     if (Offset)
10903       // [reg +/- imm]
10904       AM.BaseOffs = -Offset->getSExtValue();
10905     else
10906       // [reg +/- reg]
10907       AM.Scale = 1;
10908   } else
10909     return false;
10910
10911   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10912                                    VT.getTypeForEVT(*DAG.getContext()), AS);
10913 }
10914
10915 /// Try turning a load/store into a pre-indexed load/store when the base
10916 /// pointer is an add or subtract and it has other uses besides the load/store.
10917 /// After the transformation, the new indexed load/store has effectively folded
10918 /// the add/subtract in and all of its other uses are redirected to the
10919 /// new load/store.
10920 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10921   if (Level < AfterLegalizeDAG)
10922     return false;
10923
10924   bool isLoad = true;
10925   SDValue Ptr;
10926   EVT VT;
10927   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10928     if (LD->isIndexed())
10929       return false;
10930     VT = LD->getMemoryVT();
10931     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10932         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10933       return false;
10934     Ptr = LD->getBasePtr();
10935   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10936     if (ST->isIndexed())
10937       return false;
10938     VT = ST->getMemoryVT();
10939     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10940         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10941       return false;
10942     Ptr = ST->getBasePtr();
10943     isLoad = false;
10944   } else {
10945     return false;
10946   }
10947
10948   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10949   // out.  There is no reason to make this a preinc/predec.
10950   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10951       Ptr.getNode()->hasOneUse())
10952     return false;
10953
10954   // Ask the target to do addressing mode selection.
10955   SDValue BasePtr;
10956   SDValue Offset;
10957   ISD::MemIndexedMode AM = ISD::UNINDEXED;
10958   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10959     return false;
10960
10961   // Backends without true r+i pre-indexed forms may need to pass a
10962   // constant base with a variable offset so that constant coercion
10963   // will work with the patterns in canonical form.
10964   bool Swapped = false;
10965   if (isa<ConstantSDNode>(BasePtr)) {
10966     std::swap(BasePtr, Offset);
10967     Swapped = true;
10968   }
10969
10970   // Don't create a indexed load / store with zero offset.
10971   if (isNullConstant(Offset))
10972     return false;
10973
10974   // Try turning it into a pre-indexed load / store except when:
10975   // 1) The new base ptr is a frame index.
10976   // 2) If N is a store and the new base ptr is either the same as or is a
10977   //    predecessor of the value being stored.
10978   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10979   //    that would create a cycle.
10980   // 4) All uses are load / store ops that use it as old base ptr.
10981
10982   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
10983   // (plus the implicit offset) to a register to preinc anyway.
10984   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10985     return false;
10986
10987   // Check #2.
10988   if (!isLoad) {
10989     SDValue Val = cast<StoreSDNode>(N)->getValue();
10990     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
10991       return false;
10992   }
10993
10994   // Caches for hasPredecessorHelper.
10995   SmallPtrSet<const SDNode *, 32> Visited;
10996   SmallVector<const SDNode *, 16> Worklist;
10997   Worklist.push_back(N);
10998
10999   // If the offset is a constant, there may be other adds of constants that
11000   // can be folded with this one. We should do this to avoid having to keep
11001   // a copy of the original base pointer.
11002   SmallVector<SDNode *, 16> OtherUses;
11003   if (isa<ConstantSDNode>(Offset))
11004     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11005                               UE = BasePtr.getNode()->use_end();
11006          UI != UE; ++UI) {
11007       SDUse &Use = UI.getUse();
11008       // Skip the use that is Ptr and uses of other results from BasePtr's
11009       // node (important for nodes that return multiple results).
11010       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11011         continue;
11012
11013       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11014         continue;
11015
11016       if (Use.getUser()->getOpcode() != ISD::ADD &&
11017           Use.getUser()->getOpcode() != ISD::SUB) {
11018         OtherUses.clear();
11019         break;
11020       }
11021
11022       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11023       if (!isa<ConstantSDNode>(Op1)) {
11024         OtherUses.clear();
11025         break;
11026       }
11027
11028       // FIXME: In some cases, we can be smarter about this.
11029       if (Op1.getValueType() != Offset.getValueType()) {
11030         OtherUses.clear();
11031         break;
11032       }
11033
11034       OtherUses.push_back(Use.getUser());
11035     }
11036
11037   if (Swapped)
11038     std::swap(BasePtr, Offset);
11039
11040   // Now check for #3 and #4.
11041   bool RealUse = false;
11042
11043   for (SDNode *Use : Ptr.getNode()->uses()) {
11044     if (Use == N)
11045       continue;
11046     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11047       return false;
11048
11049     // If Ptr may be folded in addressing mode of other use, then it's
11050     // not profitable to do this transformation.
11051     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11052       RealUse = true;
11053   }
11054
11055   if (!RealUse)
11056     return false;
11057
11058   SDValue Result;
11059   if (isLoad)
11060     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11061                                 BasePtr, Offset, AM);
11062   else
11063     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11064                                  BasePtr, Offset, AM);
11065   ++PreIndexedNodes;
11066   ++NodesCombined;
11067   DEBUG(dbgs() << "\nReplacing.4 ";
11068         N->dump(&DAG);
11069         dbgs() << "\nWith: ";
11070         Result.getNode()->dump(&DAG);
11071         dbgs() << '\n');
11072   WorklistRemover DeadNodes(*this);
11073   if (isLoad) {
11074     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11075     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11076   } else {
11077     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11078   }
11079
11080   // Finally, since the node is now dead, remove it from the graph.
11081   deleteAndRecombine(N);
11082
11083   if (Swapped)
11084     std::swap(BasePtr, Offset);
11085
11086   // Replace other uses of BasePtr that can be updated to use Ptr
11087   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11088     unsigned OffsetIdx = 1;
11089     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11090       OffsetIdx = 0;
11091     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11092            BasePtr.getNode() && "Expected BasePtr operand");
11093
11094     // We need to replace ptr0 in the following expression:
11095     //   x0 * offset0 + y0 * ptr0 = t0
11096     // knowing that
11097     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11098     //
11099     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11100     // indexed load/store and the expresion that needs to be re-written.
11101     //
11102     // Therefore, we have:
11103     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11104
11105     ConstantSDNode *CN =
11106       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11107     int X0, X1, Y0, Y1;
11108     const APInt &Offset0 = CN->getAPIntValue();
11109     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11110
11111     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11112     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11113     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11114     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11115
11116     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11117
11118     APInt CNV = Offset0;
11119     if (X0 < 0) CNV = -CNV;
11120     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11121     else CNV = CNV - Offset1;
11122
11123     SDLoc DL(OtherUses[i]);
11124
11125     // We can now generate the new expression.
11126     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11127     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11128
11129     SDValue NewUse = DAG.getNode(Opcode,
11130                                  DL,
11131                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11132     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11133     deleteAndRecombine(OtherUses[i]);
11134   }
11135
11136   // Replace the uses of Ptr with uses of the updated base value.
11137   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11138   deleteAndRecombine(Ptr.getNode());
11139
11140   return true;
11141 }
11142
11143 /// Try to combine a load/store with a add/sub of the base pointer node into a
11144 /// post-indexed load/store. The transformation folded the add/subtract into the
11145 /// new indexed load/store effectively and all of its uses are redirected to the
11146 /// new load/store.
11147 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11148   if (Level < AfterLegalizeDAG)
11149     return false;
11150
11151   bool isLoad = true;
11152   SDValue Ptr;
11153   EVT VT;
11154   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11155     if (LD->isIndexed())
11156       return false;
11157     VT = LD->getMemoryVT();
11158     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11159         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11160       return false;
11161     Ptr = LD->getBasePtr();
11162   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11163     if (ST->isIndexed())
11164       return false;
11165     VT = ST->getMemoryVT();
11166     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11167         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11168       return false;
11169     Ptr = ST->getBasePtr();
11170     isLoad = false;
11171   } else {
11172     return false;
11173   }
11174
11175   if (Ptr.getNode()->hasOneUse())
11176     return false;
11177
11178   for (SDNode *Op : Ptr.getNode()->uses()) {
11179     if (Op == N ||
11180         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11181       continue;
11182
11183     SDValue BasePtr;
11184     SDValue Offset;
11185     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11186     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11187       // Don't create a indexed load / store with zero offset.
11188       if (isNullConstant(Offset))
11189         continue;
11190
11191       // Try turning it into a post-indexed load / store except when
11192       // 1) All uses are load / store ops that use it as base ptr (and
11193       //    it may be folded as addressing mmode).
11194       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11195       //    nor a successor of N. Otherwise, if Op is folded that would
11196       //    create a cycle.
11197
11198       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11199         continue;
11200
11201       // Check for #1.
11202       bool TryNext = false;
11203       for (SDNode *Use : BasePtr.getNode()->uses()) {
11204         if (Use == Ptr.getNode())
11205           continue;
11206
11207         // If all the uses are load / store addresses, then don't do the
11208         // transformation.
11209         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11210           bool RealUse = false;
11211           for (SDNode *UseUse : Use->uses()) {
11212             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11213               RealUse = true;
11214           }
11215
11216           if (!RealUse) {
11217             TryNext = true;
11218             break;
11219           }
11220         }
11221       }
11222
11223       if (TryNext)
11224         continue;
11225
11226       // Check for #2
11227       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11228         SDValue Result = isLoad
11229           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11230                                BasePtr, Offset, AM)
11231           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11232                                 BasePtr, Offset, AM);
11233         ++PostIndexedNodes;
11234         ++NodesCombined;
11235         DEBUG(dbgs() << "\nReplacing.5 ";
11236               N->dump(&DAG);
11237               dbgs() << "\nWith: ";
11238               Result.getNode()->dump(&DAG);
11239               dbgs() << '\n');
11240         WorklistRemover DeadNodes(*this);
11241         if (isLoad) {
11242           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11243           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11244         } else {
11245           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11246         }
11247
11248         // Finally, since the node is now dead, remove it from the graph.
11249         deleteAndRecombine(N);
11250
11251         // Replace the uses of Use with uses of the updated base value.
11252         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11253                                       Result.getValue(isLoad ? 1 : 0));
11254         deleteAndRecombine(Op);
11255         return true;
11256       }
11257     }
11258   }
11259
11260   return false;
11261 }
11262
11263 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11264 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11265   ISD::MemIndexedMode AM = LD->getAddressingMode();
11266   assert(AM != ISD::UNINDEXED);
11267   SDValue BP = LD->getOperand(1);
11268   SDValue Inc = LD->getOperand(2);
11269
11270   // Some backends use TargetConstants for load offsets, but don't expect
11271   // TargetConstants in general ADD nodes. We can convert these constants into
11272   // regular Constants (if the constant is not opaque).
11273   assert((Inc.getOpcode() != ISD::TargetConstant ||
11274           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11275          "Cannot split out indexing using opaque target constants");
11276   if (Inc.getOpcode() == ISD::TargetConstant) {
11277     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11278     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11279                           ConstInc->getValueType(0));
11280   }
11281
11282   unsigned Opc =
11283       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11284   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11285 }
11286
11287 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11288   LoadSDNode *LD  = cast<LoadSDNode>(N);
11289   SDValue Chain = LD->getChain();
11290   SDValue Ptr   = LD->getBasePtr();
11291
11292   // If load is not volatile and there are no uses of the loaded value (and
11293   // the updated indexed value in case of indexed loads), change uses of the
11294   // chain value into uses of the chain input (i.e. delete the dead load).
11295   if (!LD->isVolatile()) {
11296     if (N->getValueType(1) == MVT::Other) {
11297       // Unindexed loads.
11298       if (!N->hasAnyUseOfValue(0)) {
11299         // It's not safe to use the two value CombineTo variant here. e.g.
11300         // v1, chain2 = load chain1, loc
11301         // v2, chain3 = load chain2, loc
11302         // v3         = add v2, c
11303         // Now we replace use of chain2 with chain1.  This makes the second load
11304         // isomorphic to the one we are deleting, and thus makes this load live.
11305         DEBUG(dbgs() << "\nReplacing.6 ";
11306               N->dump(&DAG);
11307               dbgs() << "\nWith chain: ";
11308               Chain.getNode()->dump(&DAG);
11309               dbgs() << "\n");
11310         WorklistRemover DeadNodes(*this);
11311         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11312         AddUsersToWorklist(Chain.getNode());
11313         if (N->use_empty())
11314           deleteAndRecombine(N);
11315
11316         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11317       }
11318     } else {
11319       // Indexed loads.
11320       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11321
11322       // If this load has an opaque TargetConstant offset, then we cannot split
11323       // the indexing into an add/sub directly (that TargetConstant may not be
11324       // valid for a different type of node, and we cannot convert an opaque
11325       // target constant into a regular constant).
11326       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11327                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11328
11329       if (!N->hasAnyUseOfValue(0) &&
11330           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11331         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11332         SDValue Index;
11333         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11334           Index = SplitIndexingFromLoad(LD);
11335           // Try to fold the base pointer arithmetic into subsequent loads and
11336           // stores.
11337           AddUsersToWorklist(N);
11338         } else
11339           Index = DAG.getUNDEF(N->getValueType(1));
11340         DEBUG(dbgs() << "\nReplacing.7 ";
11341               N->dump(&DAG);
11342               dbgs() << "\nWith: ";
11343               Undef.getNode()->dump(&DAG);
11344               dbgs() << " and 2 other values\n");
11345         WorklistRemover DeadNodes(*this);
11346         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11347         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11348         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11349         deleteAndRecombine(N);
11350         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11351       }
11352     }
11353   }
11354
11355   // If this load is directly stored, replace the load value with the stored
11356   // value.
11357   // TODO: Handle store large -> read small portion.
11358   // TODO: Handle TRUNCSTORE/LOADEXT
11359   if (OptLevel != CodeGenOpt::None &&
11360       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11361     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11362       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11363       if (PrevST->getBasePtr() == Ptr &&
11364           PrevST->getValue().getValueType() == N->getValueType(0))
11365         return CombineTo(N, PrevST->getOperand(1), Chain);
11366     }
11367   }
11368
11369   // Try to infer better alignment information than the load already has.
11370   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11371     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11372       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11373         SDValue NewLoad = DAG.getExtLoad(
11374             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11375             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11376             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11377         if (NewLoad.getNode() != N)
11378           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11379       }
11380     }
11381   }
11382
11383   if (LD->isUnindexed()) {
11384     // Walk up chain skipping non-aliasing memory nodes.
11385     SDValue BetterChain = FindBetterChain(N, Chain);
11386
11387     // If there is a better chain.
11388     if (Chain != BetterChain) {
11389       SDValue ReplLoad;
11390
11391       // Replace the chain to void dependency.
11392       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11393         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11394                                BetterChain, Ptr, LD->getMemOperand());
11395       } else {
11396         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11397                                   LD->getValueType(0),
11398                                   BetterChain, Ptr, LD->getMemoryVT(),
11399                                   LD->getMemOperand());
11400       }
11401
11402       // Create token factor to keep old chain connected.
11403       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11404                                   MVT::Other, Chain, ReplLoad.getValue(1));
11405
11406       // Make sure the new and old chains are cleaned up.
11407       AddToWorklist(Token.getNode());
11408
11409       // Replace uses with load result and token factor. Don't add users
11410       // to work list.
11411       return CombineTo(N, ReplLoad.getValue(0), Token, false);
11412     }
11413   }
11414
11415   // Try transforming N to an indexed load.
11416   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11417     return SDValue(N, 0);
11418
11419   // Try to slice up N to more direct loads if the slices are mapped to
11420   // different register banks or pairing can take place.
11421   if (SliceUpLoad(N))
11422     return SDValue(N, 0);
11423
11424   return SDValue();
11425 }
11426
11427 namespace {
11428 /// \brief Helper structure used to slice a load in smaller loads.
11429 /// Basically a slice is obtained from the following sequence:
11430 /// Origin = load Ty1, Base
11431 /// Shift = srl Ty1 Origin, CstTy Amount
11432 /// Inst = trunc Shift to Ty2
11433 ///
11434 /// Then, it will be rewriten into:
11435 /// Slice = load SliceTy, Base + SliceOffset
11436 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11437 ///
11438 /// SliceTy is deduced from the number of bits that are actually used to
11439 /// build Inst.
11440 struct LoadedSlice {
11441   /// \brief Helper structure used to compute the cost of a slice.
11442   struct Cost {
11443     /// Are we optimizing for code size.
11444     bool ForCodeSize;
11445     /// Various cost.
11446     unsigned Loads;
11447     unsigned Truncates;
11448     unsigned CrossRegisterBanksCopies;
11449     unsigned ZExts;
11450     unsigned Shift;
11451
11452     Cost(bool ForCodeSize = false)
11453         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11454           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11455
11456     /// \brief Get the cost of one isolated slice.
11457     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11458         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11459           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11460       EVT TruncType = LS.Inst->getValueType(0);
11461       EVT LoadedType = LS.getLoadedType();
11462       if (TruncType != LoadedType &&
11463           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11464         ZExts = 1;
11465     }
11466
11467     /// \brief Account for slicing gain in the current cost.
11468     /// Slicing provide a few gains like removing a shift or a
11469     /// truncate. This method allows to grow the cost of the original
11470     /// load with the gain from this slice.
11471     void addSliceGain(const LoadedSlice &LS) {
11472       // Each slice saves a truncate.
11473       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11474       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11475                               LS.Inst->getValueType(0)))
11476         ++Truncates;
11477       // If there is a shift amount, this slice gets rid of it.
11478       if (LS.Shift)
11479         ++Shift;
11480       // If this slice can merge a cross register bank copy, account for it.
11481       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11482         ++CrossRegisterBanksCopies;
11483     }
11484
11485     Cost &operator+=(const Cost &RHS) {
11486       Loads += RHS.Loads;
11487       Truncates += RHS.Truncates;
11488       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11489       ZExts += RHS.ZExts;
11490       Shift += RHS.Shift;
11491       return *this;
11492     }
11493
11494     bool operator==(const Cost &RHS) const {
11495       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11496              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11497              ZExts == RHS.ZExts && Shift == RHS.Shift;
11498     }
11499
11500     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11501
11502     bool operator<(const Cost &RHS) const {
11503       // Assume cross register banks copies are as expensive as loads.
11504       // FIXME: Do we want some more target hooks?
11505       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11506       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11507       // Unless we are optimizing for code size, consider the
11508       // expensive operation first.
11509       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11510         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11511       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11512              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11513     }
11514
11515     bool operator>(const Cost &RHS) const { return RHS < *this; }
11516
11517     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11518
11519     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11520   };
11521   // The last instruction that represent the slice. This should be a
11522   // truncate instruction.
11523   SDNode *Inst;
11524   // The original load instruction.
11525   LoadSDNode *Origin;
11526   // The right shift amount in bits from the original load.
11527   unsigned Shift;
11528   // The DAG from which Origin came from.
11529   // This is used to get some contextual information about legal types, etc.
11530   SelectionDAG *DAG;
11531
11532   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11533               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11534       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11535
11536   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11537   /// \return Result is \p BitWidth and has used bits set to 1 and
11538   ///         not used bits set to 0.
11539   APInt getUsedBits() const {
11540     // Reproduce the trunc(lshr) sequence:
11541     // - Start from the truncated value.
11542     // - Zero extend to the desired bit width.
11543     // - Shift left.
11544     assert(Origin && "No original load to compare against.");
11545     unsigned BitWidth = Origin->getValueSizeInBits(0);
11546     assert(Inst && "This slice is not bound to an instruction");
11547     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11548            "Extracted slice is bigger than the whole type!");
11549     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11550     UsedBits.setAllBits();
11551     UsedBits = UsedBits.zext(BitWidth);
11552     UsedBits <<= Shift;
11553     return UsedBits;
11554   }
11555
11556   /// \brief Get the size of the slice to be loaded in bytes.
11557   unsigned getLoadedSize() const {
11558     unsigned SliceSize = getUsedBits().countPopulation();
11559     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11560     return SliceSize / 8;
11561   }
11562
11563   /// \brief Get the type that will be loaded for this slice.
11564   /// Note: This may not be the final type for the slice.
11565   EVT getLoadedType() const {
11566     assert(DAG && "Missing context");
11567     LLVMContext &Ctxt = *DAG->getContext();
11568     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11569   }
11570
11571   /// \brief Get the alignment of the load used for this slice.
11572   unsigned getAlignment() const {
11573     unsigned Alignment = Origin->getAlignment();
11574     unsigned Offset = getOffsetFromBase();
11575     if (Offset != 0)
11576       Alignment = MinAlign(Alignment, Alignment + Offset);
11577     return Alignment;
11578   }
11579
11580   /// \brief Check if this slice can be rewritten with legal operations.
11581   bool isLegal() const {
11582     // An invalid slice is not legal.
11583     if (!Origin || !Inst || !DAG)
11584       return false;
11585
11586     // Offsets are for indexed load only, we do not handle that.
11587     if (!Origin->getOffset().isUndef())
11588       return false;
11589
11590     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11591
11592     // Check that the type is legal.
11593     EVT SliceType = getLoadedType();
11594     if (!TLI.isTypeLegal(SliceType))
11595       return false;
11596
11597     // Check that the load is legal for this type.
11598     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11599       return false;
11600
11601     // Check that the offset can be computed.
11602     // 1. Check its type.
11603     EVT PtrType = Origin->getBasePtr().getValueType();
11604     if (PtrType == MVT::Untyped || PtrType.isExtended())
11605       return false;
11606
11607     // 2. Check that it fits in the immediate.
11608     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11609       return false;
11610
11611     // 3. Check that the computation is legal.
11612     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11613       return false;
11614
11615     // Check that the zext is legal if it needs one.
11616     EVT TruncateType = Inst->getValueType(0);
11617     if (TruncateType != SliceType &&
11618         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11619       return false;
11620
11621     return true;
11622   }
11623
11624   /// \brief Get the offset in bytes of this slice in the original chunk of
11625   /// bits.
11626   /// \pre DAG != nullptr.
11627   uint64_t getOffsetFromBase() const {
11628     assert(DAG && "Missing context.");
11629     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11630     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11631     uint64_t Offset = Shift / 8;
11632     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11633     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11634            "The size of the original loaded type is not a multiple of a"
11635            " byte.");
11636     // If Offset is bigger than TySizeInBytes, it means we are loading all
11637     // zeros. This should have been optimized before in the process.
11638     assert(TySizeInBytes > Offset &&
11639            "Invalid shift amount for given loaded size");
11640     if (IsBigEndian)
11641       Offset = TySizeInBytes - Offset - getLoadedSize();
11642     return Offset;
11643   }
11644
11645   /// \brief Generate the sequence of instructions to load the slice
11646   /// represented by this object and redirect the uses of this slice to
11647   /// this new sequence of instructions.
11648   /// \pre this->Inst && this->Origin are valid Instructions and this
11649   /// object passed the legal check: LoadedSlice::isLegal returned true.
11650   /// \return The last instruction of the sequence used to load the slice.
11651   SDValue loadSlice() const {
11652     assert(Inst && Origin && "Unable to replace a non-existing slice.");
11653     const SDValue &OldBaseAddr = Origin->getBasePtr();
11654     SDValue BaseAddr = OldBaseAddr;
11655     // Get the offset in that chunk of bytes w.r.t. the endianness.
11656     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11657     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11658     if (Offset) {
11659       // BaseAddr = BaseAddr + Offset.
11660       EVT ArithType = BaseAddr.getValueType();
11661       SDLoc DL(Origin);
11662       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11663                               DAG->getConstant(Offset, DL, ArithType));
11664     }
11665
11666     // Create the type of the loaded slice according to its size.
11667     EVT SliceType = getLoadedType();
11668
11669     // Create the load for the slice.
11670     SDValue LastInst =
11671         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11672                      Origin->getPointerInfo().getWithOffset(Offset),
11673                      getAlignment(), Origin->getMemOperand()->getFlags());
11674     // If the final type is not the same as the loaded type, this means that
11675     // we have to pad with zero. Create a zero extend for that.
11676     EVT FinalType = Inst->getValueType(0);
11677     if (SliceType != FinalType)
11678       LastInst =
11679           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11680     return LastInst;
11681   }
11682
11683   /// \brief Check if this slice can be merged with an expensive cross register
11684   /// bank copy. E.g.,
11685   /// i = load i32
11686   /// f = bitcast i32 i to float
11687   bool canMergeExpensiveCrossRegisterBankCopy() const {
11688     if (!Inst || !Inst->hasOneUse())
11689       return false;
11690     SDNode *Use = *Inst->use_begin();
11691     if (Use->getOpcode() != ISD::BITCAST)
11692       return false;
11693     assert(DAG && "Missing context");
11694     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11695     EVT ResVT = Use->getValueType(0);
11696     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11697     const TargetRegisterClass *ArgRC =
11698         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11699     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11700       return false;
11701
11702     // At this point, we know that we perform a cross-register-bank copy.
11703     // Check if it is expensive.
11704     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11705     // Assume bitcasts are cheap, unless both register classes do not
11706     // explicitly share a common sub class.
11707     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11708       return false;
11709
11710     // Check if it will be merged with the load.
11711     // 1. Check the alignment constraint.
11712     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11713         ResVT.getTypeForEVT(*DAG->getContext()));
11714
11715     if (RequiredAlignment > getAlignment())
11716       return false;
11717
11718     // 2. Check that the load is a legal operation for that type.
11719     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11720       return false;
11721
11722     // 3. Check that we do not have a zext in the way.
11723     if (Inst->getValueType(0) != getLoadedType())
11724       return false;
11725
11726     return true;
11727   }
11728 };
11729 }
11730
11731 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11732 /// \p UsedBits looks like 0..0 1..1 0..0.
11733 static bool areUsedBitsDense(const APInt &UsedBits) {
11734   // If all the bits are one, this is dense!
11735   if (UsedBits.isAllOnesValue())
11736     return true;
11737
11738   // Get rid of the unused bits on the right.
11739   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11740   // Get rid of the unused bits on the left.
11741   if (NarrowedUsedBits.countLeadingZeros())
11742     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11743   // Check that the chunk of bits is completely used.
11744   return NarrowedUsedBits.isAllOnesValue();
11745 }
11746
11747 /// \brief Check whether or not \p First and \p Second are next to each other
11748 /// in memory. This means that there is no hole between the bits loaded
11749 /// by \p First and the bits loaded by \p Second.
11750 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11751                                      const LoadedSlice &Second) {
11752   assert(First.Origin == Second.Origin && First.Origin &&
11753          "Unable to match different memory origins.");
11754   APInt UsedBits = First.getUsedBits();
11755   assert((UsedBits & Second.getUsedBits()) == 0 &&
11756          "Slices are not supposed to overlap.");
11757   UsedBits |= Second.getUsedBits();
11758   return areUsedBitsDense(UsedBits);
11759 }
11760
11761 /// \brief Adjust the \p GlobalLSCost according to the target
11762 /// paring capabilities and the layout of the slices.
11763 /// \pre \p GlobalLSCost should account for at least as many loads as
11764 /// there is in the slices in \p LoadedSlices.
11765 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11766                                  LoadedSlice::Cost &GlobalLSCost) {
11767   unsigned NumberOfSlices = LoadedSlices.size();
11768   // If there is less than 2 elements, no pairing is possible.
11769   if (NumberOfSlices < 2)
11770     return;
11771
11772   // Sort the slices so that elements that are likely to be next to each
11773   // other in memory are next to each other in the list.
11774   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11775             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11776     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11777     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11778   });
11779   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11780   // First (resp. Second) is the first (resp. Second) potentially candidate
11781   // to be placed in a paired load.
11782   const LoadedSlice *First = nullptr;
11783   const LoadedSlice *Second = nullptr;
11784   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11785                 // Set the beginning of the pair.
11786                                                            First = Second) {
11787
11788     Second = &LoadedSlices[CurrSlice];
11789
11790     // If First is NULL, it means we start a new pair.
11791     // Get to the next slice.
11792     if (!First)
11793       continue;
11794
11795     EVT LoadedType = First->getLoadedType();
11796
11797     // If the types of the slices are different, we cannot pair them.
11798     if (LoadedType != Second->getLoadedType())
11799       continue;
11800
11801     // Check if the target supplies paired loads for this type.
11802     unsigned RequiredAlignment = 0;
11803     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11804       // move to the next pair, this type is hopeless.
11805       Second = nullptr;
11806       continue;
11807     }
11808     // Check if we meet the alignment requirement.
11809     if (RequiredAlignment > First->getAlignment())
11810       continue;
11811
11812     // Check that both loads are next to each other in memory.
11813     if (!areSlicesNextToEachOther(*First, *Second))
11814       continue;
11815
11816     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11817     --GlobalLSCost.Loads;
11818     // Move to the next pair.
11819     Second = nullptr;
11820   }
11821 }
11822
11823 /// \brief Check the profitability of all involved LoadedSlice.
11824 /// Currently, it is considered profitable if there is exactly two
11825 /// involved slices (1) which are (2) next to each other in memory, and
11826 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11827 ///
11828 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11829 /// the elements themselves.
11830 ///
11831 /// FIXME: When the cost model will be mature enough, we can relax
11832 /// constraints (1) and (2).
11833 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11834                                 const APInt &UsedBits, bool ForCodeSize) {
11835   unsigned NumberOfSlices = LoadedSlices.size();
11836   if (StressLoadSlicing)
11837     return NumberOfSlices > 1;
11838
11839   // Check (1).
11840   if (NumberOfSlices != 2)
11841     return false;
11842
11843   // Check (2).
11844   if (!areUsedBitsDense(UsedBits))
11845     return false;
11846
11847   // Check (3).
11848   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11849   // The original code has one big load.
11850   OrigCost.Loads = 1;
11851   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11852     const LoadedSlice &LS = LoadedSlices[CurrSlice];
11853     // Accumulate the cost of all the slices.
11854     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11855     GlobalSlicingCost += SliceCost;
11856
11857     // Account as cost in the original configuration the gain obtained
11858     // with the current slices.
11859     OrigCost.addSliceGain(LS);
11860   }
11861
11862   // If the target supports paired load, adjust the cost accordingly.
11863   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11864   return OrigCost > GlobalSlicingCost;
11865 }
11866
11867 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11868 /// operations, split it in the various pieces being extracted.
11869 ///
11870 /// This sort of thing is introduced by SROA.
11871 /// This slicing takes care not to insert overlapping loads.
11872 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11873 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11874   if (Level < AfterLegalizeDAG)
11875     return false;
11876
11877   LoadSDNode *LD = cast<LoadSDNode>(N);
11878   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11879       !LD->getValueType(0).isInteger())
11880     return false;
11881
11882   // Keep track of already used bits to detect overlapping values.
11883   // In that case, we will just abort the transformation.
11884   APInt UsedBits(LD->getValueSizeInBits(0), 0);
11885
11886   SmallVector<LoadedSlice, 4> LoadedSlices;
11887
11888   // Check if this load is used as several smaller chunks of bits.
11889   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11890   // of computation for each trunc.
11891   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11892        UI != UIEnd; ++UI) {
11893     // Skip the uses of the chain.
11894     if (UI.getUse().getResNo() != 0)
11895       continue;
11896
11897     SDNode *User = *UI;
11898     unsigned Shift = 0;
11899
11900     // Check if this is a trunc(lshr).
11901     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11902         isa<ConstantSDNode>(User->getOperand(1))) {
11903       Shift = User->getConstantOperandVal(1);
11904       User = *User->use_begin();
11905     }
11906
11907     // At this point, User is a Truncate, iff we encountered, trunc or
11908     // trunc(lshr).
11909     if (User->getOpcode() != ISD::TRUNCATE)
11910       return false;
11911
11912     // The width of the type must be a power of 2 and greater than 8-bits.
11913     // Otherwise the load cannot be represented in LLVM IR.
11914     // Moreover, if we shifted with a non-8-bits multiple, the slice
11915     // will be across several bytes. We do not support that.
11916     unsigned Width = User->getValueSizeInBits(0);
11917     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11918       return 0;
11919
11920     // Build the slice for this chain of computations.
11921     LoadedSlice LS(User, LD, Shift, &DAG);
11922     APInt CurrentUsedBits = LS.getUsedBits();
11923
11924     // Check if this slice overlaps with another.
11925     if ((CurrentUsedBits & UsedBits) != 0)
11926       return false;
11927     // Update the bits used globally.
11928     UsedBits |= CurrentUsedBits;
11929
11930     // Check if the new slice would be legal.
11931     if (!LS.isLegal())
11932       return false;
11933
11934     // Record the slice.
11935     LoadedSlices.push_back(LS);
11936   }
11937
11938   // Abort slicing if it does not seem to be profitable.
11939   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11940     return false;
11941
11942   ++SlicedLoads;
11943
11944   // Rewrite each chain to use an independent load.
11945   // By construction, each chain can be represented by a unique load.
11946
11947   // Prepare the argument for the new token factor for all the slices.
11948   SmallVector<SDValue, 8> ArgChains;
11949   for (SmallVectorImpl<LoadedSlice>::const_iterator
11950            LSIt = LoadedSlices.begin(),
11951            LSItEnd = LoadedSlices.end();
11952        LSIt != LSItEnd; ++LSIt) {
11953     SDValue SliceInst = LSIt->loadSlice();
11954     CombineTo(LSIt->Inst, SliceInst, true);
11955     if (SliceInst.getOpcode() != ISD::LOAD)
11956       SliceInst = SliceInst.getOperand(0);
11957     assert(SliceInst->getOpcode() == ISD::LOAD &&
11958            "It takes more than a zext to get to the loaded slice!!");
11959     ArgChains.push_back(SliceInst.getValue(1));
11960   }
11961
11962   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11963                               ArgChains);
11964   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11965   AddToWorklist(Chain.getNode());
11966   return true;
11967 }
11968
11969 /// Check to see if V is (and load (ptr), imm), where the load is having
11970 /// specific bytes cleared out.  If so, return the byte size being masked out
11971 /// and the shift amount.
11972 static std::pair<unsigned, unsigned>
11973 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11974   std::pair<unsigned, unsigned> Result(0, 0);
11975
11976   // Check for the structure we're looking for.
11977   if (V->getOpcode() != ISD::AND ||
11978       !isa<ConstantSDNode>(V->getOperand(1)) ||
11979       !ISD::isNormalLoad(V->getOperand(0).getNode()))
11980     return Result;
11981
11982   // Check the chain and pointer.
11983   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11984   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
11985
11986   // The store should be chained directly to the load or be an operand of a
11987   // tokenfactor.
11988   if (LD == Chain.getNode())
11989     ; // ok.
11990   else if (Chain->getOpcode() != ISD::TokenFactor)
11991     return Result; // Fail.
11992   else {
11993     bool isOk = false;
11994     for (const SDValue &ChainOp : Chain->op_values())
11995       if (ChainOp.getNode() == LD) {
11996         isOk = true;
11997         break;
11998       }
11999     if (!isOk) return Result;
12000   }
12001
12002   // This only handles simple types.
12003   if (V.getValueType() != MVT::i16 &&
12004       V.getValueType() != MVT::i32 &&
12005       V.getValueType() != MVT::i64)
12006     return Result;
12007
12008   // Check the constant mask.  Invert it so that the bits being masked out are
12009   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
12010   // follow the sign bit for uniformity.
12011   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12012   unsigned NotMaskLZ = countLeadingZeros(NotMask);
12013   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
12014   unsigned NotMaskTZ = countTrailingZeros(NotMask);
12015   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
12016   if (NotMaskLZ == 64) return Result;  // All zero mask.
12017
12018   // See if we have a continuous run of bits.  If so, we have 0*1+0*
12019   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12020     return Result;
12021
12022   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12023   if (V.getValueType() != MVT::i64 && NotMaskLZ)
12024     NotMaskLZ -= 64-V.getValueSizeInBits();
12025
12026   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12027   switch (MaskedBytes) {
12028   case 1:
12029   case 2:
12030   case 4: break;
12031   default: return Result; // All one mask, or 5-byte mask.
12032   }
12033
12034   // Verify that the first bit starts at a multiple of mask so that the access
12035   // is aligned the same as the access width.
12036   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12037
12038   Result.first = MaskedBytes;
12039   Result.second = NotMaskTZ/8;
12040   return Result;
12041 }
12042
12043
12044 /// Check to see if IVal is something that provides a value as specified by
12045 /// MaskInfo. If so, replace the specified store with a narrower store of
12046 /// truncated IVal.
12047 static SDNode *
12048 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12049                                 SDValue IVal, StoreSDNode *St,
12050                                 DAGCombiner *DC) {
12051   unsigned NumBytes = MaskInfo.first;
12052   unsigned ByteShift = MaskInfo.second;
12053   SelectionDAG &DAG = DC->getDAG();
12054
12055   // Check to see if IVal is all zeros in the part being masked in by the 'or'
12056   // that uses this.  If not, this is not a replacement.
12057   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12058                                   ByteShift*8, (ByteShift+NumBytes)*8);
12059   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12060
12061   // Check that it is legal on the target to do this.  It is legal if the new
12062   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12063   // legalization.
12064   MVT VT = MVT::getIntegerVT(NumBytes*8);
12065   if (!DC->isTypeLegal(VT))
12066     return nullptr;
12067
12068   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
12069   // shifted by ByteShift and truncated down to NumBytes.
12070   if (ByteShift) {
12071     SDLoc DL(IVal);
12072     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12073                        DAG.getConstant(ByteShift*8, DL,
12074                                     DC->getShiftAmountTy(IVal.getValueType())));
12075   }
12076
12077   // Figure out the offset for the store and the alignment of the access.
12078   unsigned StOffset;
12079   unsigned NewAlign = St->getAlignment();
12080
12081   if (DAG.getDataLayout().isLittleEndian())
12082     StOffset = ByteShift;
12083   else
12084     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12085
12086   SDValue Ptr = St->getBasePtr();
12087   if (StOffset) {
12088     SDLoc DL(IVal);
12089     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12090                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12091     NewAlign = MinAlign(NewAlign, StOffset);
12092   }
12093
12094   // Truncate down to the new size.
12095   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12096
12097   ++OpsNarrowed;
12098   return DAG
12099       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12100                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12101       .getNode();
12102 }
12103
12104
12105 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12106 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12107 /// narrowing the load and store if it would end up being a win for performance
12108 /// or code size.
12109 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12110   StoreSDNode *ST  = cast<StoreSDNode>(N);
12111   if (ST->isVolatile())
12112     return SDValue();
12113
12114   SDValue Chain = ST->getChain();
12115   SDValue Value = ST->getValue();
12116   SDValue Ptr   = ST->getBasePtr();
12117   EVT VT = Value.getValueType();
12118
12119   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12120     return SDValue();
12121
12122   unsigned Opc = Value.getOpcode();
12123
12124   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12125   // is a byte mask indicating a consecutive number of bytes, check to see if
12126   // Y is known to provide just those bytes.  If so, we try to replace the
12127   // load + replace + store sequence with a single (narrower) store, which makes
12128   // the load dead.
12129   if (Opc == ISD::OR) {
12130     std::pair<unsigned, unsigned> MaskedLoad;
12131     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12132     if (MaskedLoad.first)
12133       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12134                                                   Value.getOperand(1), ST,this))
12135         return SDValue(NewST, 0);
12136
12137     // Or is commutative, so try swapping X and Y.
12138     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12139     if (MaskedLoad.first)
12140       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12141                                                   Value.getOperand(0), ST,this))
12142         return SDValue(NewST, 0);
12143   }
12144
12145   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12146       Value.getOperand(1).getOpcode() != ISD::Constant)
12147     return SDValue();
12148
12149   SDValue N0 = Value.getOperand(0);
12150   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12151       Chain == SDValue(N0.getNode(), 1)) {
12152     LoadSDNode *LD = cast<LoadSDNode>(N0);
12153     if (LD->getBasePtr() != Ptr ||
12154         LD->getPointerInfo().getAddrSpace() !=
12155         ST->getPointerInfo().getAddrSpace())
12156       return SDValue();
12157
12158     // Find the type to narrow it the load / op / store to.
12159     SDValue N1 = Value.getOperand(1);
12160     unsigned BitWidth = N1.getValueSizeInBits();
12161     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12162     if (Opc == ISD::AND)
12163       Imm ^= APInt::getAllOnesValue(BitWidth);
12164     if (Imm == 0 || Imm.isAllOnesValue())
12165       return SDValue();
12166     unsigned ShAmt = Imm.countTrailingZeros();
12167     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12168     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12169     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12170     // The narrowing should be profitable, the load/store operation should be
12171     // legal (or custom) and the store size should be equal to the NewVT width.
12172     while (NewBW < BitWidth &&
12173            (NewVT.getStoreSizeInBits() != NewBW ||
12174             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12175             !TLI.isNarrowingProfitable(VT, NewVT))) {
12176       NewBW = NextPowerOf2(NewBW);
12177       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12178     }
12179     if (NewBW >= BitWidth)
12180       return SDValue();
12181
12182     // If the lsb changed does not start at the type bitwidth boundary,
12183     // start at the previous one.
12184     if (ShAmt % NewBW)
12185       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12186     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12187                                    std::min(BitWidth, ShAmt + NewBW));
12188     if ((Imm & Mask) == Imm) {
12189       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12190       if (Opc == ISD::AND)
12191         NewImm ^= APInt::getAllOnesValue(NewBW);
12192       uint64_t PtrOff = ShAmt / 8;
12193       // For big endian targets, we need to adjust the offset to the pointer to
12194       // load the correct bytes.
12195       if (DAG.getDataLayout().isBigEndian())
12196         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12197
12198       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12199       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12200       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12201         return SDValue();
12202
12203       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12204                                    Ptr.getValueType(), Ptr,
12205                                    DAG.getConstant(PtrOff, SDLoc(LD),
12206                                                    Ptr.getValueType()));
12207       SDValue NewLD =
12208           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12209                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12210                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12211       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12212                                    DAG.getConstant(NewImm, SDLoc(Value),
12213                                                    NewVT));
12214       SDValue NewST =
12215           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12216                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12217
12218       AddToWorklist(NewPtr.getNode());
12219       AddToWorklist(NewLD.getNode());
12220       AddToWorklist(NewVal.getNode());
12221       WorklistRemover DeadNodes(*this);
12222       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12223       ++OpsNarrowed;
12224       return NewST;
12225     }
12226   }
12227
12228   return SDValue();
12229 }
12230
12231 /// For a given floating point load / store pair, if the load value isn't used
12232 /// by any other operations, then consider transforming the pair to integer
12233 /// load / store operations if the target deems the transformation profitable.
12234 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12235   StoreSDNode *ST  = cast<StoreSDNode>(N);
12236   SDValue Chain = ST->getChain();
12237   SDValue Value = ST->getValue();
12238   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12239       Value.hasOneUse() &&
12240       Chain == SDValue(Value.getNode(), 1)) {
12241     LoadSDNode *LD = cast<LoadSDNode>(Value);
12242     EVT VT = LD->getMemoryVT();
12243     if (!VT.isFloatingPoint() ||
12244         VT != ST->getMemoryVT() ||
12245         LD->isNonTemporal() ||
12246         ST->isNonTemporal() ||
12247         LD->getPointerInfo().getAddrSpace() != 0 ||
12248         ST->getPointerInfo().getAddrSpace() != 0)
12249       return SDValue();
12250
12251     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12252     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12253         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12254         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12255         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12256       return SDValue();
12257
12258     unsigned LDAlign = LD->getAlignment();
12259     unsigned STAlign = ST->getAlignment();
12260     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12261     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12262     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12263       return SDValue();
12264
12265     SDValue NewLD =
12266         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12267                     LD->getPointerInfo(), LDAlign);
12268
12269     SDValue NewST =
12270         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12271                      ST->getPointerInfo(), STAlign);
12272
12273     AddToWorklist(NewLD.getNode());
12274     AddToWorklist(NewST.getNode());
12275     WorklistRemover DeadNodes(*this);
12276     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12277     ++LdStFP2Int;
12278     return NewST;
12279   }
12280
12281   return SDValue();
12282 }
12283
12284 // This is a helper function for visitMUL to check the profitability
12285 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12286 // MulNode is the original multiply, AddNode is (add x, c1),
12287 // and ConstNode is c2.
12288 //
12289 // If the (add x, c1) has multiple uses, we could increase
12290 // the number of adds if we make this transformation.
12291 // It would only be worth doing this if we can remove a
12292 // multiply in the process. Check for that here.
12293 // To illustrate:
12294 //     (A + c1) * c3
12295 //     (A + c2) * c3
12296 // We're checking for cases where we have common "c3 * A" expressions.
12297 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12298                                               SDValue &AddNode,
12299                                               SDValue &ConstNode) {
12300   APInt Val;
12301
12302   // If the add only has one use, this would be OK to do.
12303   if (AddNode.getNode()->hasOneUse())
12304     return true;
12305
12306   // Walk all the users of the constant with which we're multiplying.
12307   for (SDNode *Use : ConstNode->uses()) {
12308
12309     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12310       continue;
12311
12312     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12313       SDNode *OtherOp;
12314       SDNode *MulVar = AddNode.getOperand(0).getNode();
12315
12316       // OtherOp is what we're multiplying against the constant.
12317       if (Use->getOperand(0) == ConstNode)
12318         OtherOp = Use->getOperand(1).getNode();
12319       else
12320         OtherOp = Use->getOperand(0).getNode();
12321
12322       // Check to see if multiply is with the same operand of our "add".
12323       //
12324       //     ConstNode  = CONST
12325       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12326       //     ...
12327       //     AddNode  = (A + c1)  <-- MulVar is A.
12328       //         = AddNode * ConstNode   <-- current visiting instruction.
12329       //
12330       // If we make this transformation, we will have a common
12331       // multiply (ConstNode * A) that we can save.
12332       if (OtherOp == MulVar)
12333         return true;
12334
12335       // Now check to see if a future expansion will give us a common
12336       // multiply.
12337       //
12338       //     ConstNode  = CONST
12339       //     AddNode    = (A + c1)
12340       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12341       //     ...
12342       //     OtherOp = (A + c2)
12343       //     Use     = OtherOp * ConstNode <-- visiting Use.
12344       //
12345       // If we make this transformation, we will have a common
12346       // multiply (CONST * A) after we also do the same transformation
12347       // to the "t2" instruction.
12348       if (OtherOp->getOpcode() == ISD::ADD &&
12349           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12350           OtherOp->getOperand(0).getNode() == MulVar)
12351         return true;
12352     }
12353   }
12354
12355   // Didn't find a case where this would be profitable.
12356   return false;
12357 }
12358
12359 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12360                                          unsigned NumStores) {
12361   SmallVector<SDValue, 8> Chains;
12362   SmallPtrSet<const SDNode *, 8> Visited;
12363   SDLoc StoreDL(StoreNodes[0].MemNode);
12364
12365   for (unsigned i = 0; i < NumStores; ++i) {
12366     Visited.insert(StoreNodes[i].MemNode);
12367   }
12368
12369   // don't include nodes that are children
12370   for (unsigned i = 0; i < NumStores; ++i) {
12371     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12372       Chains.push_back(StoreNodes[i].MemNode->getChain());
12373   }
12374
12375   assert(Chains.size() > 0 && "Chain should have generated a chain");
12376   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12377 }
12378
12379 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12380                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
12381                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
12382   // Make sure we have something to merge.
12383   if (NumStores < 2)
12384     return false;
12385
12386   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12387
12388   // The latest Node in the DAG.
12389   SDLoc DL(StoreNodes[0].MemNode);
12390
12391   SDValue StoredVal;
12392   if (UseVector) {
12393     bool IsVec = MemVT.isVector();
12394     unsigned Elts = NumStores;
12395     if (IsVec) {
12396       // When merging vector stores, get the total number of elements.
12397       Elts *= MemVT.getVectorNumElements();
12398     }
12399     // Get the type for the merged vector store.
12400     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12401     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
12402
12403     if (IsConstantSrc) {
12404       SmallVector<SDValue, 8> BuildVector;
12405       for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
12406         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12407         SDValue Val = St->getValue();
12408         if (MemVT.getScalarType().isInteger())
12409           if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
12410             Val = DAG.getConstant(
12411                 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
12412                 SDLoc(CFP), MemVT);
12413         BuildVector.push_back(Val);
12414       }
12415       StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
12416     } else {
12417       SmallVector<SDValue, 8> Ops;
12418       for (unsigned i = 0; i < NumStores; ++i) {
12419         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12420         SDValue Val = St->getValue();
12421         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
12422         if (Val.getValueType() != MemVT)
12423           return false;
12424         Ops.push_back(Val);
12425       }
12426
12427       // Build the extracted vector elements back into a vector.
12428       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
12429                               DL, Ty, Ops);    }
12430   } else {
12431     // We should always use a vector store when merging extracted vector
12432     // elements, so this path implies a store of constants.
12433     assert(IsConstantSrc && "Merged vector elements should use vector store");
12434
12435     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12436     APInt StoreInt(SizeInBits, 0);
12437
12438     // Construct a single integer constant which is made of the smaller
12439     // constant inputs.
12440     bool IsLE = DAG.getDataLayout().isLittleEndian();
12441     for (unsigned i = 0; i < NumStores; ++i) {
12442       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12443       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12444
12445       SDValue Val = St->getValue();
12446       StoreInt <<= ElementSizeBytes * 8;
12447       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12448         StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits);
12449       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12450         StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits);
12451       } else {
12452         llvm_unreachable("Invalid constant element type");
12453       }
12454     }
12455
12456     // Create the new Load and Store operations.
12457     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12458     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12459   }
12460
12461   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12462   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12463   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
12464                                   FirstInChain->getBasePtr(),
12465                                   FirstInChain->getPointerInfo(),
12466                                   FirstInChain->getAlignment());
12467
12468   // Replace all merged stores with the new store.
12469   for (unsigned i = 0; i < NumStores; ++i)
12470     CombineTo(StoreNodes[i].MemNode, NewStore);
12471
12472   AddToWorklist(NewChain.getNode());
12473   return true;
12474 }
12475
12476 void DAGCombiner::getStoreMergeCandidates(
12477     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12478   // This holds the base pointer, index, and the offset in bytes from the base
12479   // pointer.
12480   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12481   EVT MemVT = St->getMemoryVT();
12482
12483   // We must have a base and an offset.
12484   if (!BasePtr.Base.getNode())
12485     return;
12486
12487   // Do not handle stores to undef base pointers.
12488   if (BasePtr.Base.isUndef())
12489     return;
12490
12491   bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
12492   bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
12493                        isa<ConstantFPSDNode>(St->getValue());
12494   bool IsExtractVecSrc =
12495       (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12496        St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
12497   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr) -> bool {
12498     if (Other->isVolatile() || Other->isIndexed())
12499       return false;
12500     // We can merge constant floats to equivalent integers
12501     if (Other->getMemoryVT() != MemVT)
12502       if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) &&
12503             isa<ConstantFPSDNode>(Other->getValue())))
12504         return false;
12505     if (IsLoadSrc)
12506       if (!isa<LoadSDNode>(Other->getValue()))
12507         return false;
12508     if (IsConstantSrc)
12509       if (!(isa<ConstantSDNode>(Other->getValue()) ||
12510             isa<ConstantFPSDNode>(Other->getValue())))
12511         return false;
12512     if (IsExtractVecSrc)
12513       if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12514             Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR))
12515         return false;
12516     Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12517     return (Ptr.equalBaseIndex(BasePtr));
12518   };
12519   // We looking for a root node which is an ancestor to all mergable
12520   // stores. We search up through a load, to our root and then down
12521   // through all children. For instance we will find Store{1,2,3} if
12522   // St is Store1, Store2. or Store3 where the root is not a load
12523   // which always true for nonvolatile ops. TODO: Expand
12524   // the search to find all valid candidates through multiple layers of loads.
12525   //
12526   // Root
12527   // |-------|-------|
12528   // Load    Load    Store3
12529   // |       |
12530   // Store1   Store2
12531   //
12532   // FIXME: We should be able to climb and
12533   // descend TokenFactors to find candidates as well.
12534
12535   SDNode *RootNode = (St->getChain()).getNode();
12536
12537   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12538     RootNode = Ldn->getChain().getNode();
12539     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12540       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12541         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12542           if (I2.getOperandNo() == 0)
12543             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12544               BaseIndexOffset Ptr;
12545               if (CandidateMatch(OtherST, Ptr))
12546                 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12547             }
12548   } else
12549     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12550       if (I.getOperandNo() == 0)
12551         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12552           BaseIndexOffset Ptr;
12553           if (CandidateMatch(OtherST, Ptr))
12554             StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12555         }
12556 }
12557
12558 // We need to check that merging these stores does not cause a loop
12559 // in the DAG. Any store candidate may depend on another candidate
12560 // indirectly through its operand (we already consider dependencies
12561 // through the chain). Check in parallel by searching up from
12562 // non-chain operands of candidates.
12563 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12564     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12565   SmallPtrSet<const SDNode *, 16> Visited;
12566   SmallVector<const SDNode *, 8> Worklist;
12567   // search ops of store candidates
12568   for (unsigned i = 0; i < NumStores; ++i) {
12569     SDNode *n = StoreNodes[i].MemNode;
12570     // Potential loops may happen only through non-chain operands
12571     for (unsigned j = 1; j < n->getNumOperands(); ++j)
12572       Worklist.push_back(n->getOperand(j).getNode());
12573   }
12574   // search through DAG. We can stop early if we find a storenode
12575   for (unsigned i = 0; i < NumStores; ++i) {
12576     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12577       return false;
12578   }
12579   return true;
12580 }
12581
12582 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12583   if (OptLevel == CodeGenOpt::None)
12584     return false;
12585
12586   EVT MemVT = St->getMemoryVT();
12587   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12588
12589   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12590     return false;
12591
12592   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12593       Attribute::NoImplicitFloat);
12594
12595   // This function cannot currently deal with non-byte-sized memory sizes.
12596   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12597     return false;
12598
12599   if (!MemVT.isSimple())
12600     return false;
12601
12602   // Perform an early exit check. Do not bother looking at stored values that
12603   // are not constants, loads, or extracted vector elements.
12604   SDValue StoredVal = St->getValue();
12605   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12606   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12607                        isa<ConstantFPSDNode>(StoredVal);
12608   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12609                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12610
12611   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12612     return false;
12613
12614   // Don't merge vectors into wider vectors if the source data comes from loads.
12615   // TODO: This restriction can be lifted by using logic similar to the
12616   // ExtractVecSrc case.
12617   if (MemVT.isVector() && IsLoadSrc)
12618     return false;
12619
12620   SmallVector<MemOpLink, 8> StoreNodes;
12621   // Find potential store merge candidates by searching through chain sub-DAG
12622   getStoreMergeCandidates(St, StoreNodes);
12623
12624   // Check if there is anything to merge.
12625   if (StoreNodes.size() < 2)
12626     return false;
12627
12628   // Sort the memory operands according to their distance from the
12629   // base pointer.
12630   std::sort(StoreNodes.begin(), StoreNodes.end(),
12631             [](MemOpLink LHS, MemOpLink RHS) {
12632               return LHS.OffsetFromBase < RHS.OffsetFromBase;
12633             });
12634
12635   // Store Merge attempts to merge the lowest stores. This generally
12636   // works out as if successful, as the remaining stores are checked
12637   // after the first collection of stores is merged. However, in the
12638   // case that a non-mergeable store is found first, e.g., {p[-2],
12639   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12640   // mergeable cases. To prevent this, we prune such stores from the
12641   // front of StoreNodes here.
12642
12643   bool RV = false;
12644   while (StoreNodes.size() > 1) {
12645     unsigned StartIdx = 0;
12646     while ((StartIdx + 1 < StoreNodes.size()) &&
12647            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12648                StoreNodes[StartIdx + 1].OffsetFromBase)
12649       ++StartIdx;
12650
12651     // Bail if we don't have enough candidates to merge.
12652     if (StartIdx + 1 >= StoreNodes.size())
12653       return RV;
12654
12655     if (StartIdx)
12656       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12657
12658     // Scan the memory operations on the chain and find the first
12659     // non-consecutive store memory address.
12660     unsigned NumConsecutiveStores = 1;
12661     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12662     // Check that the addresses are consecutive starting from the second
12663     // element in the list of stores.
12664     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12665       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12666       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12667         break;
12668       NumConsecutiveStores = i + 1;
12669     }
12670
12671     if (NumConsecutiveStores < 2) {
12672       StoreNodes.erase(StoreNodes.begin(),
12673                        StoreNodes.begin() + NumConsecutiveStores);
12674       continue;
12675     }
12676
12677     // Check that we can merge these candidates without causing a cycle
12678     if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
12679                                                   NumConsecutiveStores)) {
12680       StoreNodes.erase(StoreNodes.begin(),
12681                        StoreNodes.begin() + NumConsecutiveStores);
12682       continue;
12683     }
12684
12685     // The node with the lowest store address.
12686     LLVMContext &Context = *DAG.getContext();
12687     const DataLayout &DL = DAG.getDataLayout();
12688
12689     // Store the constants into memory as one consecutive store.
12690     if (IsConstantSrc) {
12691       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12692       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12693       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12694       unsigned LastLegalType = 0;
12695       unsigned LastLegalVectorType = 0;
12696       bool NonZero = false;
12697       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12698         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12699         SDValue StoredVal = ST->getValue();
12700
12701         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12702           NonZero |= !C->isNullValue();
12703         } else if (ConstantFPSDNode *C =
12704                        dyn_cast<ConstantFPSDNode>(StoredVal)) {
12705           NonZero |= !C->getConstantFPValue()->isNullValue();
12706         } else {
12707           // Non-constant.
12708           break;
12709         }
12710
12711         // Find a legal type for the constant store.
12712         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12713         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12714         bool IsFast = false;
12715         if (TLI.isTypeLegal(StoreTy) &&
12716             TLI.canMergeStoresTo(FirstStoreAS, StoreTy) &&
12717             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12718                                    FirstStoreAlign, &IsFast) &&
12719             IsFast) {
12720           LastLegalType = i + 1;
12721           // Or check whether a truncstore is legal.
12722         } else if (!LegalTypes &&
12723                    TLI.getTypeAction(Context, StoreTy) ==
12724                    TargetLowering::TypePromoteInteger) {
12725           EVT LegalizedStoredValueTy =
12726               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12727           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12728               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy) &&
12729               TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12730                                      FirstStoreAS, FirstStoreAlign, &IsFast) &&
12731               IsFast) {
12732             LastLegalType = i + 1;
12733           }
12734         }
12735
12736         // We only use vectors if the constant is known to be zero or the target
12737         // allows it and the function is not marked with the noimplicitfloat
12738         // attribute.
12739         if ((!NonZero ||
12740              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12741             !NoVectors) {
12742           // Find a legal type for the vector store.
12743           EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1);
12744           if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(FirstStoreAS, Ty) &&
12745               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12746                                      FirstStoreAlign, &IsFast) &&
12747               IsFast)
12748             LastLegalVectorType = i + 1;
12749         }
12750       }
12751
12752       // Check if we found a legal integer type that creates a meaningful merge.
12753       if (LastLegalType < 2 && LastLegalVectorType < 2) {
12754         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12755         continue;
12756       }
12757
12758       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12759       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12760
12761       bool Merged = MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
12762                                                     true, UseVector);
12763       if (!Merged) {
12764         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12765         continue;
12766       }
12767       // Remove merged stores for next iteration.
12768       RV = true;
12769       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12770       continue;
12771     }
12772
12773     // When extracting multiple vector elements, try to store them
12774     // in one vector store rather than a sequence of scalar stores.
12775     if (IsExtractVecSrc) {
12776       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12777       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12778       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12779       unsigned NumStoresToMerge = 1;
12780       bool IsVec = MemVT.isVector();
12781       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12782         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12783         unsigned StoreValOpcode = St->getValue().getOpcode();
12784         // This restriction could be loosened.
12785         // Bail out if any stored values are not elements extracted from a
12786         // vector. It should be possible to handle mixed sources, but load
12787         // sources need more careful handling (see the block of code below that
12788         // handles consecutive loads).
12789         if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12790             StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12791           return RV;
12792
12793         // Find a legal type for the vector store.
12794         unsigned Elts = i + 1;
12795         if (IsVec) {
12796           // When merging vector stores, get the total number of elements.
12797           Elts *= MemVT.getVectorNumElements();
12798         }
12799         EVT Ty =
12800             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12801         bool IsFast;
12802         if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(FirstStoreAS, Ty) &&
12803             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12804                                    FirstStoreAlign, &IsFast) &&
12805             IsFast)
12806           NumStoresToMerge = i + 1;
12807       }
12808
12809       bool Merged = MergeStoresOfConstantsOrVecElts(
12810           StoreNodes, MemVT, NumStoresToMerge, false, true);
12811       if (!Merged) {
12812         StoreNodes.erase(StoreNodes.begin(),
12813                          StoreNodes.begin() + NumStoresToMerge);
12814         continue;
12815       }
12816       // Remove merged stores for next iteration.
12817       StoreNodes.erase(StoreNodes.begin(),
12818                        StoreNodes.begin() + NumStoresToMerge);
12819       RV = true;
12820       continue;
12821     }
12822
12823     // Below we handle the case of multiple consecutive stores that
12824     // come from multiple consecutive loads. We merge them into a single
12825     // wide load and a single wide store.
12826
12827     // Look for load nodes which are used by the stored values.
12828     SmallVector<MemOpLink, 8> LoadNodes;
12829
12830     // Find acceptable loads. Loads need to have the same chain (token factor),
12831     // must not be zext, volatile, indexed, and they must be consecutive.
12832     BaseIndexOffset LdBasePtr;
12833     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12834       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12835       LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12836       if (!Ld)
12837         break;
12838
12839       // Loads must only have one use.
12840       if (!Ld->hasNUsesOfValue(1, 0))
12841         break;
12842
12843       // The memory operands must not be volatile.
12844       if (Ld->isVolatile() || Ld->isIndexed())
12845         break;
12846
12847       // We do not accept ext loads.
12848       if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12849         break;
12850
12851       // The stored memory type must be the same.
12852       if (Ld->getMemoryVT() != MemVT)
12853         break;
12854
12855       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12856       // If this is not the first ptr that we check.
12857       if (LdBasePtr.Base.getNode()) {
12858         // The base ptr must be the same.
12859         if (!LdPtr.equalBaseIndex(LdBasePtr))
12860           break;
12861       } else {
12862         // Check that all other base pointers are the same as this one.
12863         LdBasePtr = LdPtr;
12864       }
12865
12866       // We found a potential memory operand to merge.
12867       LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset));
12868     }
12869
12870     if (LoadNodes.size() < 2) {
12871       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12872       continue;
12873     }
12874
12875     // If we have load/store pair instructions and we only have two values,
12876     // don't bother merging.
12877     unsigned RequiredAlignment;
12878     if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12879         StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
12880       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
12881       continue;
12882     }
12883     LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12884     unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12885     unsigned FirstStoreAlign = FirstInChain->getAlignment();
12886     LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12887     unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12888     unsigned FirstLoadAlign = FirstLoad->getAlignment();
12889
12890     // Scan the memory operations on the chain and find the first
12891     // non-consecutive load memory address. These variables hold the index in
12892     // the store node array.
12893     unsigned LastConsecutiveLoad = 0;
12894     // This variable refers to the size and not index in the array.
12895     unsigned LastLegalVectorType = 0;
12896     unsigned LastLegalIntegerType = 0;
12897     StartAddress = LoadNodes[0].OffsetFromBase;
12898     SDValue FirstChain = FirstLoad->getChain();
12899     for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12900       // All loads must share the same chain.
12901       if (LoadNodes[i].MemNode->getChain() != FirstChain)
12902         break;
12903
12904       int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12905       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12906         break;
12907       LastConsecutiveLoad = i;
12908       // Find a legal type for the vector store.
12909       EVT StoreTy = EVT::getVectorVT(Context, MemVT, i + 1);
12910       bool IsFastSt, IsFastLd;
12911       if (TLI.isTypeLegal(StoreTy) &&
12912           TLI.canMergeStoresTo(FirstStoreAS, StoreTy) &&
12913           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12914                                  FirstStoreAlign, &IsFastSt) &&
12915           IsFastSt &&
12916           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12917                                  FirstLoadAlign, &IsFastLd) &&
12918           IsFastLd) {
12919         LastLegalVectorType = i + 1;
12920       }
12921
12922       // Find a legal type for the integer store.
12923       unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12924       StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12925       if (TLI.isTypeLegal(StoreTy) &&
12926           TLI.canMergeStoresTo(FirstStoreAS, StoreTy) &&
12927           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12928                                  FirstStoreAlign, &IsFastSt) &&
12929           IsFastSt &&
12930           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12931                                  FirstLoadAlign, &IsFastLd) &&
12932           IsFastLd)
12933         LastLegalIntegerType = i + 1;
12934       // Or check whether a truncstore and extload is legal.
12935       else if (TLI.getTypeAction(Context, StoreTy) ==
12936                TargetLowering::TypePromoteInteger) {
12937         EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
12938         if (!LegalTypes &&
12939             TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12940             TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy) &&
12941             TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
12942                                StoreTy) &&
12943             TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
12944                                StoreTy) &&
12945             TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12946             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12947                                    FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
12948             IsFastSt &&
12949             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12950                                    FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
12951             IsFastLd)
12952           LastLegalIntegerType = i + 1;
12953       }
12954     }
12955
12956     // Only use vector types if the vector type is larger than the integer type.
12957     // If they are the same, use integers.
12958     bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
12959     unsigned LastLegalType =
12960         std::max(LastLegalVectorType, LastLegalIntegerType);
12961
12962     // We add +1 here because the LastXXX variables refer to location while
12963     // the NumElem refers to array/index size.
12964     unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
12965     NumElem = std::min(LastLegalType, NumElem);
12966
12967     if (NumElem < 2) {
12968       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12969       continue;
12970     }
12971
12972     // Find if it is better to use vectors or integers to load and store
12973     // to memory.
12974     EVT JointMemOpVT;
12975     if (UseVectorTy) {
12976       JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12977     } else {
12978       unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12979       JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12980     }
12981
12982     SDLoc LoadDL(LoadNodes[0].MemNode);
12983     SDLoc StoreDL(StoreNodes[0].MemNode);
12984
12985     // The merged loads are required to have the same incoming chain, so
12986     // using the first's chain is acceptable.
12987     SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12988                                   FirstLoad->getBasePtr(),
12989                                   FirstLoad->getPointerInfo(), FirstLoadAlign);
12990
12991     SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
12992
12993     AddToWorklist(NewStoreChain.getNode());
12994
12995     SDValue NewStore = DAG.getStore(
12996         NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12997         FirstInChain->getPointerInfo(), FirstStoreAlign);
12998
12999     // Transfer chain users from old loads to the new load.
13000     for (unsigned i = 0; i < NumElem; ++i) {
13001       LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13002       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13003                                     SDValue(NewLoad.getNode(), 1));
13004     }
13005
13006     // Replace the all stores with the new store.
13007     for (unsigned i = 0; i < NumElem; ++i)
13008       CombineTo(StoreNodes[i].MemNode, NewStore);
13009     RV = true;
13010     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13011     continue;
13012   }
13013   return RV;
13014 }
13015
13016 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13017   SDLoc SL(ST);
13018   SDValue ReplStore;
13019
13020   // Replace the chain to avoid dependency.
13021   if (ST->isTruncatingStore()) {
13022     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13023                                   ST->getBasePtr(), ST->getMemoryVT(),
13024                                   ST->getMemOperand());
13025   } else {
13026     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13027                              ST->getMemOperand());
13028   }
13029
13030   // Create token to keep both nodes around.
13031   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13032                               MVT::Other, ST->getChain(), ReplStore);
13033
13034   // Make sure the new and old chains are cleaned up.
13035   AddToWorklist(Token.getNode());
13036
13037   // Don't add users to work list.
13038   return CombineTo(ST, Token, false);
13039 }
13040
13041 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13042   SDValue Value = ST->getValue();
13043   if (Value.getOpcode() == ISD::TargetConstantFP)
13044     return SDValue();
13045
13046   SDLoc DL(ST);
13047
13048   SDValue Chain = ST->getChain();
13049   SDValue Ptr = ST->getBasePtr();
13050
13051   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13052
13053   // NOTE: If the original store is volatile, this transform must not increase
13054   // the number of stores.  For example, on x86-32 an f64 can be stored in one
13055   // processor operation but an i64 (which is not legal) requires two.  So the
13056   // transform should not be done in this case.
13057
13058   SDValue Tmp;
13059   switch (CFP->getSimpleValueType(0).SimpleTy) {
13060   default:
13061     llvm_unreachable("Unknown FP type");
13062   case MVT::f16:    // We don't do this for these yet.
13063   case MVT::f80:
13064   case MVT::f128:
13065   case MVT::ppcf128:
13066     return SDValue();
13067   case MVT::f32:
13068     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13069         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13070       ;
13071       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13072                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13073                             MVT::i32);
13074       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13075     }
13076
13077     return SDValue();
13078   case MVT::f64:
13079     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13080          !ST->isVolatile()) ||
13081         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13082       ;
13083       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13084                             getZExtValue(), SDLoc(CFP), MVT::i64);
13085       return DAG.getStore(Chain, DL, Tmp,
13086                           Ptr, ST->getMemOperand());
13087     }
13088
13089     if (!ST->isVolatile() &&
13090         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13091       // Many FP stores are not made apparent until after legalize, e.g. for
13092       // argument passing.  Since this is so common, custom legalize the
13093       // 64-bit integer store into two 32-bit stores.
13094       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13095       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13096       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13097       if (DAG.getDataLayout().isBigEndian())
13098         std::swap(Lo, Hi);
13099
13100       unsigned Alignment = ST->getAlignment();
13101       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13102       AAMDNodes AAInfo = ST->getAAInfo();
13103
13104       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13105                                  ST->getAlignment(), MMOFlags, AAInfo);
13106       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13107                         DAG.getConstant(4, DL, Ptr.getValueType()));
13108       Alignment = MinAlign(Alignment, 4U);
13109       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13110                                  ST->getPointerInfo().getWithOffset(4),
13111                                  Alignment, MMOFlags, AAInfo);
13112       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13113                          St0, St1);
13114     }
13115
13116     return SDValue();
13117   }
13118 }
13119
13120 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13121   StoreSDNode *ST  = cast<StoreSDNode>(N);
13122   SDValue Chain = ST->getChain();
13123   SDValue Value = ST->getValue();
13124   SDValue Ptr   = ST->getBasePtr();
13125
13126   // If this is a store of a bit convert, store the input value if the
13127   // resultant store does not need a higher alignment than the original.
13128   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13129       ST->isUnindexed()) {
13130     EVT SVT = Value.getOperand(0).getValueType();
13131     if (((!LegalOperations && !ST->isVolatile()) ||
13132          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13133         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13134       unsigned OrigAlign = ST->getAlignment();
13135       bool Fast = false;
13136       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13137                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13138           Fast) {
13139         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13140                             ST->getPointerInfo(), OrigAlign,
13141                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13142       }
13143     }
13144   }
13145
13146   // Turn 'store undef, Ptr' -> nothing.
13147   if (Value.isUndef() && ST->isUnindexed())
13148     return Chain;
13149
13150   // Try to infer better alignment information than the store already has.
13151   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13152     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13153       if (Align > ST->getAlignment()) {
13154         SDValue NewStore =
13155             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13156                               ST->getMemoryVT(), Align,
13157                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13158         if (NewStore.getNode() != N)
13159           return CombineTo(ST, NewStore, true);
13160       }
13161     }
13162   }
13163
13164   // Try transforming a pair floating point load / store ops to integer
13165   // load / store ops.
13166   if (SDValue NewST = TransformFPLoadStorePair(N))
13167     return NewST;
13168
13169   if (ST->isUnindexed()) {
13170     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13171     // adjacent stores.
13172     if (findBetterNeighborChains(ST)) {
13173       // replaceStoreChain uses CombineTo, which handled all of the worklist
13174       // manipulation. Return the original node to not do anything else.
13175       return SDValue(ST, 0);
13176     }
13177     Chain = ST->getChain();
13178   }
13179
13180   // Try transforming N to an indexed store.
13181   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13182     return SDValue(N, 0);
13183
13184   // FIXME: is there such a thing as a truncating indexed store?
13185   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13186       Value.getValueType().isInteger()) {
13187     // See if we can simplify the input to this truncstore with knowledge that
13188     // only the low bits are being used.  For example:
13189     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13190     SDValue Shorter = GetDemandedBits(
13191         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13192                                     ST->getMemoryVT().getScalarSizeInBits()));
13193     AddToWorklist(Value.getNode());
13194     if (Shorter.getNode())
13195       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13196                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13197
13198     // Otherwise, see if we can simplify the operation with
13199     // SimplifyDemandedBits, which only works if the value has a single use.
13200     if (SimplifyDemandedBits(
13201             Value,
13202             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13203                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13204       // Re-visit the store if anything changed and the store hasn't been merged
13205       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13206       // node back to the worklist if necessary, but we also need to re-visit
13207       // the Store node itself.
13208       if (N->getOpcode() != ISD::DELETED_NODE)
13209         AddToWorklist(N);
13210       return SDValue(N, 0);
13211     }
13212   }
13213
13214   // If this is a load followed by a store to the same location, then the store
13215   // is dead/noop.
13216   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13217     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13218         ST->isUnindexed() && !ST->isVolatile() &&
13219         // There can't be any side effects between the load and store, such as
13220         // a call or store.
13221         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13222       // The store is dead, remove it.
13223       return Chain;
13224     }
13225   }
13226
13227   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13228     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13229         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13230         ST->getMemoryVT() == ST1->getMemoryVT()) {
13231       // If this is a store followed by a store with the same value to the same
13232       // location, then the store is dead/noop.
13233       if (ST1->getValue() == Value) {
13234         // The store is dead, remove it.
13235         return Chain;
13236       }
13237
13238       // If this is a store who's preceeding store to the same location
13239       // and no one other node is chained to that store we can effectively
13240       // drop the store. Do not remove stores to undef as they may be used as
13241       // data sinks.
13242       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13243           !ST1->getBasePtr().isUndef()) {
13244         // ST1 is fully overwritten and can be elided. Combine with it's chain
13245         // value.
13246         CombineTo(ST1, ST1->getChain());
13247         return SDValue();
13248       }
13249     }
13250   }
13251
13252   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13253   // truncating store.  We can do this even if this is already a truncstore.
13254   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13255       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13256       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13257                             ST->getMemoryVT())) {
13258     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13259                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
13260   }
13261
13262   // Only perform this optimization before the types are legal, because we
13263   // don't want to perform this optimization on every DAGCombine invocation.
13264   if (!LegalTypes) {
13265     for (;;) {
13266       // There can be multiple store sequences on the same chain.
13267       // Keep trying to merge store sequences until we are unable to do so
13268       // or until we merge the last store on the chain.
13269       bool Changed = MergeConsecutiveStores(ST);
13270       if (!Changed) break;
13271       // Return N as merge only uses CombineTo and no worklist clean
13272       // up is necessary.
13273       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13274         return SDValue(N, 0);
13275     }
13276   }
13277
13278   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13279   //
13280   // Make sure to do this only after attempting to merge stores in order to
13281   //  avoid changing the types of some subset of stores due to visit order,
13282   //  preventing their merging.
13283   if (isa<ConstantFPSDNode>(ST->getValue())) {
13284     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13285       return NewSt;
13286   }
13287
13288   if (SDValue NewSt = splitMergedValStore(ST))
13289     return NewSt;
13290
13291   return ReduceLoadOpStoreWidth(N);
13292 }
13293
13294 /// For the instruction sequence of store below, F and I values
13295 /// are bundled together as an i64 value before being stored into memory.
13296 /// Sometimes it is more efficent to generate separate stores for F and I,
13297 /// which can remove the bitwise instructions or sink them to colder places.
13298 ///
13299 ///   (store (or (zext (bitcast F to i32) to i64),
13300 ///              (shl (zext I to i64), 32)), addr)  -->
13301 ///   (store F, addr) and (store I, addr+4)
13302 ///
13303 /// Similarly, splitting for other merged store can also be beneficial, like:
13304 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13305 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13306 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13307 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13308 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13309 ///
13310 /// We allow each target to determine specifically which kind of splitting is
13311 /// supported.
13312 ///
13313 /// The store patterns are commonly seen from the simple code snippet below
13314 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13315 ///   void goo(const std::pair<int, float> &);
13316 ///   hoo() {
13317 ///     ...
13318 ///     goo(std::make_pair(tmp, ftmp));
13319 ///     ...
13320 ///   }
13321 ///
13322 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13323   if (OptLevel == CodeGenOpt::None)
13324     return SDValue();
13325
13326   SDValue Val = ST->getValue();
13327   SDLoc DL(ST);
13328
13329   // Match OR operand.
13330   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13331     return SDValue();
13332
13333   // Match SHL operand and get Lower and Higher parts of Val.
13334   SDValue Op1 = Val.getOperand(0);
13335   SDValue Op2 = Val.getOperand(1);
13336   SDValue Lo, Hi;
13337   if (Op1.getOpcode() != ISD::SHL) {
13338     std::swap(Op1, Op2);
13339     if (Op1.getOpcode() != ISD::SHL)
13340       return SDValue();
13341   }
13342   Lo = Op2;
13343   Hi = Op1.getOperand(0);
13344   if (!Op1.hasOneUse())
13345     return SDValue();
13346
13347   // Match shift amount to HalfValBitSize.
13348   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13349   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13350   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13351     return SDValue();
13352
13353   // Lo and Hi are zero-extended from int with size less equal than 32
13354   // to i64.
13355   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13356       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13357       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13358       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13359       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13360       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13361     return SDValue();
13362
13363   // Use the EVT of low and high parts before bitcast as the input
13364   // of target query.
13365   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13366                   ? Lo.getOperand(0).getValueType()
13367                   : Lo.getValueType();
13368   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13369                    ? Hi.getOperand(0).getValueType()
13370                    : Hi.getValueType();
13371   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13372     return SDValue();
13373
13374   // Start to split store.
13375   unsigned Alignment = ST->getAlignment();
13376   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13377   AAMDNodes AAInfo = ST->getAAInfo();
13378
13379   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13380   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13381   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13382   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13383
13384   SDValue Chain = ST->getChain();
13385   SDValue Ptr = ST->getBasePtr();
13386   // Lower value store.
13387   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13388                              ST->getAlignment(), MMOFlags, AAInfo);
13389   Ptr =
13390       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13391                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13392   // Higher value store.
13393   SDValue St1 =
13394       DAG.getStore(St0, DL, Hi, Ptr,
13395                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13396                    Alignment / 2, MMOFlags, AAInfo);
13397   return St1;
13398 }
13399
13400 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13401   SDValue InVec = N->getOperand(0);
13402   SDValue InVal = N->getOperand(1);
13403   SDValue EltNo = N->getOperand(2);
13404   SDLoc DL(N);
13405
13406   // If the inserted element is an UNDEF, just use the input vector.
13407   if (InVal.isUndef())
13408     return InVec;
13409
13410   EVT VT = InVec.getValueType();
13411
13412   // Check that we know which element is being inserted
13413   if (!isa<ConstantSDNode>(EltNo))
13414     return SDValue();
13415   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13416
13417   // Canonicalize insert_vector_elt dag nodes.
13418   // Example:
13419   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13420   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13421   //
13422   // Do this only if the child insert_vector node has one use; also
13423   // do this only if indices are both constants and Idx1 < Idx0.
13424   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13425       && isa<ConstantSDNode>(InVec.getOperand(2))) {
13426     unsigned OtherElt = InVec.getConstantOperandVal(2);
13427     if (Elt < OtherElt) {
13428       // Swap nodes.
13429       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13430                                   InVec.getOperand(0), InVal, EltNo);
13431       AddToWorklist(NewOp.getNode());
13432       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13433                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13434     }
13435   }
13436
13437   // If we can't generate a legal BUILD_VECTOR, exit
13438   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13439     return SDValue();
13440
13441   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13442   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
13443   // vector elements.
13444   SmallVector<SDValue, 8> Ops;
13445   // Do not combine these two vectors if the output vector will not replace
13446   // the input vector.
13447   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13448     Ops.append(InVec.getNode()->op_begin(),
13449                InVec.getNode()->op_end());
13450   } else if (InVec.isUndef()) {
13451     unsigned NElts = VT.getVectorNumElements();
13452     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13453   } else {
13454     return SDValue();
13455   }
13456
13457   // Insert the element
13458   if (Elt < Ops.size()) {
13459     // All the operands of BUILD_VECTOR must have the same type;
13460     // we enforce that here.
13461     EVT OpVT = Ops[0].getValueType();
13462     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13463   }
13464
13465   // Return the new vector
13466   return DAG.getBuildVector(VT, DL, Ops);
13467 }
13468
13469 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13470     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13471   assert(!OriginalLoad->isVolatile());
13472
13473   EVT ResultVT = EVE->getValueType(0);
13474   EVT VecEltVT = InVecVT.getVectorElementType();
13475   unsigned Align = OriginalLoad->getAlignment();
13476   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13477       VecEltVT.getTypeForEVT(*DAG.getContext()));
13478
13479   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13480     return SDValue();
13481
13482   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13483     ISD::NON_EXTLOAD : ISD::EXTLOAD;
13484   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13485     return SDValue();
13486
13487   Align = NewAlign;
13488
13489   SDValue NewPtr = OriginalLoad->getBasePtr();
13490   SDValue Offset;
13491   EVT PtrType = NewPtr.getValueType();
13492   MachinePointerInfo MPI;
13493   SDLoc DL(EVE);
13494   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13495     int Elt = ConstEltNo->getZExtValue();
13496     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13497     Offset = DAG.getConstant(PtrOff, DL, PtrType);
13498     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13499   } else {
13500     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13501     Offset = DAG.getNode(
13502         ISD::MUL, DL, PtrType, Offset,
13503         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13504     MPI = OriginalLoad->getPointerInfo();
13505   }
13506   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13507
13508   // The replacement we need to do here is a little tricky: we need to
13509   // replace an extractelement of a load with a load.
13510   // Use ReplaceAllUsesOfValuesWith to do the replacement.
13511   // Note that this replacement assumes that the extractvalue is the only
13512   // use of the load; that's okay because we don't want to perform this
13513   // transformation in other cases anyway.
13514   SDValue Load;
13515   SDValue Chain;
13516   if (ResultVT.bitsGT(VecEltVT)) {
13517     // If the result type of vextract is wider than the load, then issue an
13518     // extending load instead.
13519     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13520                                                   VecEltVT)
13521                                    ? ISD::ZEXTLOAD
13522                                    : ISD::EXTLOAD;
13523     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13524                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13525                           Align, OriginalLoad->getMemOperand()->getFlags(),
13526                           OriginalLoad->getAAInfo());
13527     Chain = Load.getValue(1);
13528   } else {
13529     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13530                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13531                        OriginalLoad->getAAInfo());
13532     Chain = Load.getValue(1);
13533     if (ResultVT.bitsLT(VecEltVT))
13534       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13535     else
13536       Load = DAG.getBitcast(ResultVT, Load);
13537   }
13538   WorklistRemover DeadNodes(*this);
13539   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13540   SDValue To[] = { Load, Chain };
13541   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13542   // Since we're explicitly calling ReplaceAllUses, add the new node to the
13543   // worklist explicitly as well.
13544   AddToWorklist(Load.getNode());
13545   AddUsersToWorklist(Load.getNode()); // Add users too
13546   // Make sure to revisit this node to clean it up; it will usually be dead.
13547   AddToWorklist(EVE);
13548   ++OpsNarrowed;
13549   return SDValue(EVE, 0);
13550 }
13551
13552 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13553   // (vextract (scalar_to_vector val, 0) -> val
13554   SDValue InVec = N->getOperand(0);
13555   EVT VT = InVec.getValueType();
13556   EVT NVT = N->getValueType(0);
13557
13558   if (InVec.isUndef())
13559     return DAG.getUNDEF(NVT);
13560
13561   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13562     // Check if the result type doesn't match the inserted element type. A
13563     // SCALAR_TO_VECTOR may truncate the inserted element and the
13564     // EXTRACT_VECTOR_ELT may widen the extracted vector.
13565     SDValue InOp = InVec.getOperand(0);
13566     if (InOp.getValueType() != NVT) {
13567       assert(InOp.getValueType().isInteger() && NVT.isInteger());
13568       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13569     }
13570     return InOp;
13571   }
13572
13573   SDValue EltNo = N->getOperand(1);
13574   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13575
13576   // extract_vector_elt (build_vector x, y), 1 -> y
13577   if (ConstEltNo &&
13578       InVec.getOpcode() == ISD::BUILD_VECTOR &&
13579       TLI.isTypeLegal(VT) &&
13580       (InVec.hasOneUse() ||
13581        TLI.aggressivelyPreferBuildVectorSources(VT))) {
13582     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13583     EVT InEltVT = Elt.getValueType();
13584
13585     // Sometimes build_vector's scalar input types do not match result type.
13586     if (NVT == InEltVT)
13587       return Elt;
13588
13589     // TODO: It may be useful to truncate if free if the build_vector implicitly
13590     // converts.
13591   }
13592
13593   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
13594   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13595       ConstEltNo->isNullValue() && VT.isInteger()) {
13596     SDValue BCSrc = InVec.getOperand(0);
13597     if (BCSrc.getValueType().isScalarInteger())
13598       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13599   }
13600
13601   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13602   //
13603   // This only really matters if the index is non-constant since other combines
13604   // on the constant elements already work.
13605   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13606       EltNo == InVec.getOperand(2)) {
13607     SDValue Elt = InVec.getOperand(1);
13608     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13609   }
13610
13611   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13612   // We only perform this optimization before the op legalization phase because
13613   // we may introduce new vector instructions which are not backed by TD
13614   // patterns. For example on AVX, extracting elements from a wide vector
13615   // without using extract_subvector. However, if we can find an underlying
13616   // scalar value, then we can always use that.
13617   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13618     int NumElem = VT.getVectorNumElements();
13619     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13620     // Find the new index to extract from.
13621     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13622
13623     // Extracting an undef index is undef.
13624     if (OrigElt == -1)
13625       return DAG.getUNDEF(NVT);
13626
13627     // Select the right vector half to extract from.
13628     SDValue SVInVec;
13629     if (OrigElt < NumElem) {
13630       SVInVec = InVec->getOperand(0);
13631     } else {
13632       SVInVec = InVec->getOperand(1);
13633       OrigElt -= NumElem;
13634     }
13635
13636     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13637       SDValue InOp = SVInVec.getOperand(OrigElt);
13638       if (InOp.getValueType() != NVT) {
13639         assert(InOp.getValueType().isInteger() && NVT.isInteger());
13640         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13641       }
13642
13643       return InOp;
13644     }
13645
13646     // FIXME: We should handle recursing on other vector shuffles and
13647     // scalar_to_vector here as well.
13648
13649     if (!LegalOperations) {
13650       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13651       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13652                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13653     }
13654   }
13655
13656   bool BCNumEltsChanged = false;
13657   EVT ExtVT = VT.getVectorElementType();
13658   EVT LVT = ExtVT;
13659
13660   // If the result of load has to be truncated, then it's not necessarily
13661   // profitable.
13662   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13663     return SDValue();
13664
13665   if (InVec.getOpcode() == ISD::BITCAST) {
13666     // Don't duplicate a load with other uses.
13667     if (!InVec.hasOneUse())
13668       return SDValue();
13669
13670     EVT BCVT = InVec.getOperand(0).getValueType();
13671     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13672       return SDValue();
13673     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13674       BCNumEltsChanged = true;
13675     InVec = InVec.getOperand(0);
13676     ExtVT = BCVT.getVectorElementType();
13677   }
13678
13679   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13680   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13681       ISD::isNormalLoad(InVec.getNode()) &&
13682       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13683     SDValue Index = N->getOperand(1);
13684     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13685       if (!OrigLoad->isVolatile()) {
13686         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13687                                                              OrigLoad);
13688       }
13689     }
13690   }
13691
13692   // Perform only after legalization to ensure build_vector / vector_shuffle
13693   // optimizations have already been done.
13694   if (!LegalOperations) return SDValue();
13695
13696   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13697   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13698   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13699
13700   if (ConstEltNo) {
13701     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13702
13703     LoadSDNode *LN0 = nullptr;
13704     const ShuffleVectorSDNode *SVN = nullptr;
13705     if (ISD::isNormalLoad(InVec.getNode())) {
13706       LN0 = cast<LoadSDNode>(InVec);
13707     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13708                InVec.getOperand(0).getValueType() == ExtVT &&
13709                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13710       // Don't duplicate a load with other uses.
13711       if (!InVec.hasOneUse())
13712         return SDValue();
13713
13714       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13715     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13716       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13717       // =>
13718       // (load $addr+1*size)
13719
13720       // Don't duplicate a load with other uses.
13721       if (!InVec.hasOneUse())
13722         return SDValue();
13723
13724       // If the bit convert changed the number of elements, it is unsafe
13725       // to examine the mask.
13726       if (BCNumEltsChanged)
13727         return SDValue();
13728
13729       // Select the input vector, guarding against out of range extract vector.
13730       unsigned NumElems = VT.getVectorNumElements();
13731       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13732       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13733
13734       if (InVec.getOpcode() == ISD::BITCAST) {
13735         // Don't duplicate a load with other uses.
13736         if (!InVec.hasOneUse())
13737           return SDValue();
13738
13739         InVec = InVec.getOperand(0);
13740       }
13741       if (ISD::isNormalLoad(InVec.getNode())) {
13742         LN0 = cast<LoadSDNode>(InVec);
13743         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13744         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13745       }
13746     }
13747
13748     // Make sure we found a non-volatile load and the extractelement is
13749     // the only use.
13750     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13751       return SDValue();
13752
13753     // If Idx was -1 above, Elt is going to be -1, so just return undef.
13754     if (Elt == -1)
13755       return DAG.getUNDEF(LVT);
13756
13757     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13758   }
13759
13760   return SDValue();
13761 }
13762
13763 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13764 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13765   // We perform this optimization post type-legalization because
13766   // the type-legalizer often scalarizes integer-promoted vectors.
13767   // Performing this optimization before may create bit-casts which
13768   // will be type-legalized to complex code sequences.
13769   // We perform this optimization only before the operation legalizer because we
13770   // may introduce illegal operations.
13771   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13772     return SDValue();
13773
13774   unsigned NumInScalars = N->getNumOperands();
13775   SDLoc DL(N);
13776   EVT VT = N->getValueType(0);
13777
13778   // Check to see if this is a BUILD_VECTOR of a bunch of values
13779   // which come from any_extend or zero_extend nodes. If so, we can create
13780   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13781   // optimizations. We do not handle sign-extend because we can't fill the sign
13782   // using shuffles.
13783   EVT SourceType = MVT::Other;
13784   bool AllAnyExt = true;
13785
13786   for (unsigned i = 0; i != NumInScalars; ++i) {
13787     SDValue In = N->getOperand(i);
13788     // Ignore undef inputs.
13789     if (In.isUndef()) continue;
13790
13791     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
13792     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13793
13794     // Abort if the element is not an extension.
13795     if (!ZeroExt && !AnyExt) {
13796       SourceType = MVT::Other;
13797       break;
13798     }
13799
13800     // The input is a ZeroExt or AnyExt. Check the original type.
13801     EVT InTy = In.getOperand(0).getValueType();
13802
13803     // Check that all of the widened source types are the same.
13804     if (SourceType == MVT::Other)
13805       // First time.
13806       SourceType = InTy;
13807     else if (InTy != SourceType) {
13808       // Multiple income types. Abort.
13809       SourceType = MVT::Other;
13810       break;
13811     }
13812
13813     // Check if all of the extends are ANY_EXTENDs.
13814     AllAnyExt &= AnyExt;
13815   }
13816
13817   // In order to have valid types, all of the inputs must be extended from the
13818   // same source type and all of the inputs must be any or zero extend.
13819   // Scalar sizes must be a power of two.
13820   EVT OutScalarTy = VT.getScalarType();
13821   bool ValidTypes = SourceType != MVT::Other &&
13822                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13823                  isPowerOf2_32(SourceType.getSizeInBits());
13824
13825   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13826   // turn into a single shuffle instruction.
13827   if (!ValidTypes)
13828     return SDValue();
13829
13830   bool isLE = DAG.getDataLayout().isLittleEndian();
13831   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13832   assert(ElemRatio > 1 && "Invalid element size ratio");
13833   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13834                                DAG.getConstant(0, DL, SourceType);
13835
13836   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13837   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13838
13839   // Populate the new build_vector
13840   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13841     SDValue Cast = N->getOperand(i);
13842     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13843             Cast.getOpcode() == ISD::ZERO_EXTEND ||
13844             Cast.isUndef()) && "Invalid cast opcode");
13845     SDValue In;
13846     if (Cast.isUndef())
13847       In = DAG.getUNDEF(SourceType);
13848     else
13849       In = Cast->getOperand(0);
13850     unsigned Index = isLE ? (i * ElemRatio) :
13851                             (i * ElemRatio + (ElemRatio - 1));
13852
13853     assert(Index < Ops.size() && "Invalid index");
13854     Ops[Index] = In;
13855   }
13856
13857   // The type of the new BUILD_VECTOR node.
13858   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13859   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13860          "Invalid vector size");
13861   // Check if the new vector type is legal.
13862   if (!isTypeLegal(VecVT)) return SDValue();
13863
13864   // Make the new BUILD_VECTOR.
13865   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13866
13867   // The new BUILD_VECTOR node has the potential to be further optimized.
13868   AddToWorklist(BV.getNode());
13869   // Bitcast to the desired type.
13870   return DAG.getBitcast(VT, BV);
13871 }
13872
13873 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13874   EVT VT = N->getValueType(0);
13875
13876   unsigned NumInScalars = N->getNumOperands();
13877   SDLoc DL(N);
13878
13879   EVT SrcVT = MVT::Other;
13880   unsigned Opcode = ISD::DELETED_NODE;
13881   unsigned NumDefs = 0;
13882
13883   for (unsigned i = 0; i != NumInScalars; ++i) {
13884     SDValue In = N->getOperand(i);
13885     unsigned Opc = In.getOpcode();
13886
13887     if (Opc == ISD::UNDEF)
13888       continue;
13889
13890     // If all scalar values are floats and converted from integers.
13891     if (Opcode == ISD::DELETED_NODE &&
13892         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13893       Opcode = Opc;
13894     }
13895
13896     if (Opc != Opcode)
13897       return SDValue();
13898
13899     EVT InVT = In.getOperand(0).getValueType();
13900
13901     // If all scalar values are typed differently, bail out. It's chosen to
13902     // simplify BUILD_VECTOR of integer types.
13903     if (SrcVT == MVT::Other)
13904       SrcVT = InVT;
13905     if (SrcVT != InVT)
13906       return SDValue();
13907     NumDefs++;
13908   }
13909
13910   // If the vector has just one element defined, it's not worth to fold it into
13911   // a vectorized one.
13912   if (NumDefs < 2)
13913     return SDValue();
13914
13915   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
13916          && "Should only handle conversion from integer to float.");
13917   assert(SrcVT != MVT::Other && "Cannot determine source type!");
13918
13919   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
13920
13921   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
13922     return SDValue();
13923
13924   // Just because the floating-point vector type is legal does not necessarily
13925   // mean that the corresponding integer vector type is.
13926   if (!isTypeLegal(NVT))
13927     return SDValue();
13928
13929   SmallVector<SDValue, 8> Opnds;
13930   for (unsigned i = 0; i != NumInScalars; ++i) {
13931     SDValue In = N->getOperand(i);
13932
13933     if (In.isUndef())
13934       Opnds.push_back(DAG.getUNDEF(SrcVT));
13935     else
13936       Opnds.push_back(In.getOperand(0));
13937   }
13938   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
13939   AddToWorklist(BV.getNode());
13940
13941   return DAG.getNode(Opcode, DL, VT, BV);
13942 }
13943
13944 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
13945                                            ArrayRef<int> VectorMask,
13946                                            SDValue VecIn1, SDValue VecIn2,
13947                                            unsigned LeftIdx) {
13948   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13949   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
13950
13951   EVT VT = N->getValueType(0);
13952   EVT InVT1 = VecIn1.getValueType();
13953   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
13954
13955   unsigned Vec2Offset = InVT1.getVectorNumElements();
13956   unsigned NumElems = VT.getVectorNumElements();
13957   unsigned ShuffleNumElems = NumElems;
13958
13959   // We can't generate a shuffle node with mismatched input and output types.
13960   // Try to make the types match the type of the output.
13961   if (InVT1 != VT || InVT2 != VT) {
13962     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13963       // If the output vector length is a multiple of both input lengths,
13964       // we can concatenate them and pad the rest with undefs.
13965       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13966       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13967       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13968       ConcatOps[0] = VecIn1;
13969       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13970       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13971       VecIn2 = SDValue();
13972     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13973       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13974         return SDValue();
13975
13976       if (!VecIn2.getNode()) {
13977         // If we only have one input vector, and it's twice the size of the
13978         // output, split it in two.
13979         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13980                              DAG.getConstant(NumElems, DL, IdxTy));
13981         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13982         // Since we now have shorter input vectors, adjust the offset of the
13983         // second vector's start.
13984         Vec2Offset = NumElems;
13985       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13986         // VecIn1 is wider than the output, and we have another, possibly
13987         // smaller input. Pad the smaller input with undefs, shuffle at the
13988         // input vector width, and extract the output.
13989         // The shuffle type is different than VT, so check legality again.
13990         if (LegalOperations &&
13991             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13992           return SDValue();
13993
13994         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
13995         // lower it back into a BUILD_VECTOR. So if the inserted type is
13996         // illegal, don't even try.
13997         if (InVT1 != InVT2) {
13998           if (!TLI.isTypeLegal(InVT2))
13999             return SDValue();
14000           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14001                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14002         }
14003         ShuffleNumElems = NumElems * 2;
14004       } else {
14005         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14006         // than VecIn1. We can't handle this for now - this case will disappear
14007         // when we start sorting the vectors by type.
14008         return SDValue();
14009       }
14010     } else {
14011       // TODO: Support cases where the length mismatch isn't exactly by a
14012       // factor of 2.
14013       // TODO: Move this check upwards, so that if we have bad type
14014       // mismatches, we don't create any DAG nodes.
14015       return SDValue();
14016     }
14017   }
14018
14019   // Initialize mask to undef.
14020   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14021
14022   // Only need to run up to the number of elements actually used, not the
14023   // total number of elements in the shuffle - if we are shuffling a wider
14024   // vector, the high lanes should be set to undef.
14025   for (unsigned i = 0; i != NumElems; ++i) {
14026     if (VectorMask[i] <= 0)
14027       continue;
14028
14029     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14030     if (VectorMask[i] == (int)LeftIdx) {
14031       Mask[i] = ExtIndex;
14032     } else if (VectorMask[i] == (int)LeftIdx + 1) {
14033       Mask[i] = Vec2Offset + ExtIndex;
14034     }
14035   }
14036
14037   // The type the input vectors may have changed above.
14038   InVT1 = VecIn1.getValueType();
14039
14040   // If we already have a VecIn2, it should have the same type as VecIn1.
14041   // If we don't, get an undef/zero vector of the appropriate type.
14042   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14043   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
14044
14045   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14046   if (ShuffleNumElems > NumElems)
14047     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14048
14049   return Shuffle;
14050 }
14051
14052 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14053 // operations. If the types of the vectors we're extracting from allow it,
14054 // turn this into a vector_shuffle node.
14055 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14056   SDLoc DL(N);
14057   EVT VT = N->getValueType(0);
14058
14059   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14060   if (!isTypeLegal(VT))
14061     return SDValue();
14062
14063   // May only combine to shuffle after legalize if shuffle is legal.
14064   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14065     return SDValue();
14066
14067   bool UsesZeroVector = false;
14068   unsigned NumElems = N->getNumOperands();
14069
14070   // Record, for each element of the newly built vector, which input vector
14071   // that element comes from. -1 stands for undef, 0 for the zero vector,
14072   // and positive values for the input vectors.
14073   // VectorMask maps each element to its vector number, and VecIn maps vector
14074   // numbers to their initial SDValues.
14075
14076   SmallVector<int, 8> VectorMask(NumElems, -1);
14077   SmallVector<SDValue, 8> VecIn;
14078   VecIn.push_back(SDValue());
14079
14080   for (unsigned i = 0; i != NumElems; ++i) {
14081     SDValue Op = N->getOperand(i);
14082
14083     if (Op.isUndef())
14084       continue;
14085
14086     // See if we can use a blend with a zero vector.
14087     // TODO: Should we generalize this to a blend with an arbitrary constant
14088     // vector?
14089     if (isNullConstant(Op) || isNullFPConstant(Op)) {
14090       UsesZeroVector = true;
14091       VectorMask[i] = 0;
14092       continue;
14093     }
14094
14095     // Not an undef or zero. If the input is something other than an
14096     // EXTRACT_VECTOR_ELT with a constant index, bail out.
14097     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14098         !isa<ConstantSDNode>(Op.getOperand(1)))
14099       return SDValue();
14100
14101     SDValue ExtractedFromVec = Op.getOperand(0);
14102
14103     // All inputs must have the same element type as the output.
14104     if (VT.getVectorElementType() !=
14105         ExtractedFromVec.getValueType().getVectorElementType())
14106       return SDValue();
14107
14108     // Have we seen this input vector before?
14109     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14110     // a map back from SDValues to numbers isn't worth it.
14111     unsigned Idx = std::distance(
14112         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14113     if (Idx == VecIn.size())
14114       VecIn.push_back(ExtractedFromVec);
14115
14116     VectorMask[i] = Idx;
14117   }
14118
14119   // If we didn't find at least one input vector, bail out.
14120   if (VecIn.size() < 2)
14121     return SDValue();
14122
14123   // TODO: We want to sort the vectors by descending length, so that adjacent
14124   // pairs have similar length, and the longer vector is always first in the
14125   // pair.
14126
14127   // TODO: Should this fire if some of the input vectors has illegal type (like
14128   // it does now), or should we let legalization run its course first?
14129
14130   // Shuffle phase:
14131   // Take pairs of vectors, and shuffle them so that the result has elements
14132   // from these vectors in the correct places.
14133   // For example, given:
14134   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14135   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14136   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14137   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14138   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14139   // We will generate:
14140   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14141   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14142   SmallVector<SDValue, 4> Shuffles;
14143   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14144     unsigned LeftIdx = 2 * In + 1;
14145     SDValue VecLeft = VecIn[LeftIdx];
14146     SDValue VecRight =
14147         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14148
14149     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14150                                                 VecRight, LeftIdx))
14151       Shuffles.push_back(Shuffle);
14152     else
14153       return SDValue();
14154   }
14155
14156   // If we need the zero vector as an "ingredient" in the blend tree, add it
14157   // to the list of shuffles.
14158   if (UsesZeroVector)
14159     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14160                                       : DAG.getConstantFP(0.0, DL, VT));
14161
14162   // If we only have one shuffle, we're done.
14163   if (Shuffles.size() == 1)
14164     return Shuffles[0];
14165
14166   // Update the vector mask to point to the post-shuffle vectors.
14167   for (int &Vec : VectorMask)
14168     if (Vec == 0)
14169       Vec = Shuffles.size() - 1;
14170     else
14171       Vec = (Vec - 1) / 2;
14172
14173   // More than one shuffle. Generate a binary tree of blends, e.g. if from
14174   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14175   // generate:
14176   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14177   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14178   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14179   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14180   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14181   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14182   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14183
14184   // Make sure the initial size of the shuffle list is even.
14185   if (Shuffles.size() % 2)
14186     Shuffles.push_back(DAG.getUNDEF(VT));
14187
14188   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14189     if (CurSize % 2) {
14190       Shuffles[CurSize] = DAG.getUNDEF(VT);
14191       CurSize++;
14192     }
14193     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14194       int Left = 2 * In;
14195       int Right = 2 * In + 1;
14196       SmallVector<int, 8> Mask(NumElems, -1);
14197       for (unsigned i = 0; i != NumElems; ++i) {
14198         if (VectorMask[i] == Left) {
14199           Mask[i] = i;
14200           VectorMask[i] = In;
14201         } else if (VectorMask[i] == Right) {
14202           Mask[i] = i + NumElems;
14203           VectorMask[i] = In;
14204         }
14205       }
14206
14207       Shuffles[In] =
14208           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14209     }
14210   }
14211
14212   return Shuffles[0];
14213 }
14214
14215 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14216   EVT VT = N->getValueType(0);
14217
14218   // A vector built entirely of undefs is undef.
14219   if (ISD::allOperandsUndef(N))
14220     return DAG.getUNDEF(VT);
14221
14222   // Check if we can express BUILD VECTOR via subvector extract.
14223   if (!LegalTypes && (N->getNumOperands() > 1)) {
14224     SDValue Op0 = N->getOperand(0);
14225     auto checkElem = [&](SDValue Op) -> uint64_t {
14226       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14227           (Op0.getOperand(0) == Op.getOperand(0)))
14228         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14229           return CNode->getZExtValue();
14230       return -1;
14231     };
14232
14233     int Offset = checkElem(Op0);
14234     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14235       if (Offset + i != checkElem(N->getOperand(i))) {
14236         Offset = -1;
14237         break;
14238       }
14239     }
14240
14241     if ((Offset == 0) &&
14242         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14243       return Op0.getOperand(0);
14244     if ((Offset != -1) &&
14245         ((Offset % N->getValueType(0).getVectorNumElements()) ==
14246          0)) // IDX must be multiple of output size.
14247       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14248                          Op0.getOperand(0), Op0.getOperand(1));
14249   }
14250
14251   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14252     return V;
14253
14254   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14255     return V;
14256
14257   if (SDValue V = reduceBuildVecToShuffle(N))
14258     return V;
14259
14260   return SDValue();
14261 }
14262
14263 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14265   EVT OpVT = N->getOperand(0).getValueType();
14266
14267   // If the operands are legal vectors, leave them alone.
14268   if (TLI.isTypeLegal(OpVT))
14269     return SDValue();
14270
14271   SDLoc DL(N);
14272   EVT VT = N->getValueType(0);
14273   SmallVector<SDValue, 8> Ops;
14274
14275   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14276   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14277
14278   // Keep track of what we encounter.
14279   bool AnyInteger = false;
14280   bool AnyFP = false;
14281   for (const SDValue &Op : N->ops()) {
14282     if (ISD::BITCAST == Op.getOpcode() &&
14283         !Op.getOperand(0).getValueType().isVector())
14284       Ops.push_back(Op.getOperand(0));
14285     else if (ISD::UNDEF == Op.getOpcode())
14286       Ops.push_back(ScalarUndef);
14287     else
14288       return SDValue();
14289
14290     // Note whether we encounter an integer or floating point scalar.
14291     // If it's neither, bail out, it could be something weird like x86mmx.
14292     EVT LastOpVT = Ops.back().getValueType();
14293     if (LastOpVT.isFloatingPoint())
14294       AnyFP = true;
14295     else if (LastOpVT.isInteger())
14296       AnyInteger = true;
14297     else
14298       return SDValue();
14299   }
14300
14301   // If any of the operands is a floating point scalar bitcast to a vector,
14302   // use floating point types throughout, and bitcast everything.
14303   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14304   if (AnyFP) {
14305     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14306     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14307     if (AnyInteger) {
14308       for (SDValue &Op : Ops) {
14309         if (Op.getValueType() == SVT)
14310           continue;
14311         if (Op.isUndef())
14312           Op = ScalarUndef;
14313         else
14314           Op = DAG.getBitcast(SVT, Op);
14315       }
14316     }
14317   }
14318
14319   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14320                                VT.getSizeInBits() / SVT.getSizeInBits());
14321   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14322 }
14323
14324 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14325 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14326 // most two distinct vectors the same size as the result, attempt to turn this
14327 // into a legal shuffle.
14328 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14329   EVT VT = N->getValueType(0);
14330   EVT OpVT = N->getOperand(0).getValueType();
14331   int NumElts = VT.getVectorNumElements();
14332   int NumOpElts = OpVT.getVectorNumElements();
14333
14334   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14335   SmallVector<int, 8> Mask;
14336
14337   for (SDValue Op : N->ops()) {
14338     // Peek through any bitcast.
14339     while (Op.getOpcode() == ISD::BITCAST)
14340       Op = Op.getOperand(0);
14341
14342     // UNDEF nodes convert to UNDEF shuffle mask values.
14343     if (Op.isUndef()) {
14344       Mask.append((unsigned)NumOpElts, -1);
14345       continue;
14346     }
14347
14348     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14349       return SDValue();
14350
14351     // What vector are we extracting the subvector from and at what index?
14352     SDValue ExtVec = Op.getOperand(0);
14353
14354     // We want the EVT of the original extraction to correctly scale the
14355     // extraction index.
14356     EVT ExtVT = ExtVec.getValueType();
14357
14358     // Peek through any bitcast.
14359     while (ExtVec.getOpcode() == ISD::BITCAST)
14360       ExtVec = ExtVec.getOperand(0);
14361
14362     // UNDEF nodes convert to UNDEF shuffle mask values.
14363     if (ExtVec.isUndef()) {
14364       Mask.append((unsigned)NumOpElts, -1);
14365       continue;
14366     }
14367
14368     if (!isa<ConstantSDNode>(Op.getOperand(1)))
14369       return SDValue();
14370     int ExtIdx = Op.getConstantOperandVal(1);
14371
14372     // Ensure that we are extracting a subvector from a vector the same
14373     // size as the result.
14374     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14375       return SDValue();
14376
14377     // Scale the subvector index to account for any bitcast.
14378     int NumExtElts = ExtVT.getVectorNumElements();
14379     if (0 == (NumExtElts % NumElts))
14380       ExtIdx /= (NumExtElts / NumElts);
14381     else if (0 == (NumElts % NumExtElts))
14382       ExtIdx *= (NumElts / NumExtElts);
14383     else
14384       return SDValue();
14385
14386     // At most we can reference 2 inputs in the final shuffle.
14387     if (SV0.isUndef() || SV0 == ExtVec) {
14388       SV0 = ExtVec;
14389       for (int i = 0; i != NumOpElts; ++i)
14390         Mask.push_back(i + ExtIdx);
14391     } else if (SV1.isUndef() || SV1 == ExtVec) {
14392       SV1 = ExtVec;
14393       for (int i = 0; i != NumOpElts; ++i)
14394         Mask.push_back(i + ExtIdx + NumElts);
14395     } else {
14396       return SDValue();
14397     }
14398   }
14399
14400   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14401     return SDValue();
14402
14403   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14404                               DAG.getBitcast(VT, SV1), Mask);
14405 }
14406
14407 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14408   // If we only have one input vector, we don't need to do any concatenation.
14409   if (N->getNumOperands() == 1)
14410     return N->getOperand(0);
14411
14412   // Check if all of the operands are undefs.
14413   EVT VT = N->getValueType(0);
14414   if (ISD::allOperandsUndef(N))
14415     return DAG.getUNDEF(VT);
14416
14417   // Optimize concat_vectors where all but the first of the vectors are undef.
14418   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14419         return Op.isUndef();
14420       })) {
14421     SDValue In = N->getOperand(0);
14422     assert(In.getValueType().isVector() && "Must concat vectors");
14423
14424     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14425     if (In->getOpcode() == ISD::BITCAST &&
14426         !In->getOperand(0)->getValueType(0).isVector()) {
14427       SDValue Scalar = In->getOperand(0);
14428
14429       // If the bitcast type isn't legal, it might be a trunc of a legal type;
14430       // look through the trunc so we can still do the transform:
14431       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14432       if (Scalar->getOpcode() == ISD::TRUNCATE &&
14433           !TLI.isTypeLegal(Scalar.getValueType()) &&
14434           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14435         Scalar = Scalar->getOperand(0);
14436
14437       EVT SclTy = Scalar->getValueType(0);
14438
14439       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14440         return SDValue();
14441
14442       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14443       if (VNTNumElms < 2)
14444         return SDValue();
14445
14446       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14447       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14448         return SDValue();
14449
14450       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14451       return DAG.getBitcast(VT, Res);
14452     }
14453   }
14454
14455   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14456   // We have already tested above for an UNDEF only concatenation.
14457   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14458   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14459   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14460     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14461   };
14462   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14463     SmallVector<SDValue, 8> Opnds;
14464     EVT SVT = VT.getScalarType();
14465
14466     EVT MinVT = SVT;
14467     if (!SVT.isFloatingPoint()) {
14468       // If BUILD_VECTOR are from built from integer, they may have different
14469       // operand types. Get the smallest type and truncate all operands to it.
14470       bool FoundMinVT = false;
14471       for (const SDValue &Op : N->ops())
14472         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14473           EVT OpSVT = Op.getOperand(0)->getValueType(0);
14474           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14475           FoundMinVT = true;
14476         }
14477       assert(FoundMinVT && "Concat vector type mismatch");
14478     }
14479
14480     for (const SDValue &Op : N->ops()) {
14481       EVT OpVT = Op.getValueType();
14482       unsigned NumElts = OpVT.getVectorNumElements();
14483
14484       if (ISD::UNDEF == Op.getOpcode())
14485         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14486
14487       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14488         if (SVT.isFloatingPoint()) {
14489           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14490           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14491         } else {
14492           for (unsigned i = 0; i != NumElts; ++i)
14493             Opnds.push_back(
14494                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14495         }
14496       }
14497     }
14498
14499     assert(VT.getVectorNumElements() == Opnds.size() &&
14500            "Concat vector type mismatch");
14501     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14502   }
14503
14504   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14505   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14506     return V;
14507
14508   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14509   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14510     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14511       return V;
14512
14513   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14514   // nodes often generate nop CONCAT_VECTOR nodes.
14515   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14516   // place the incoming vectors at the exact same location.
14517   SDValue SingleSource = SDValue();
14518   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14519
14520   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14521     SDValue Op = N->getOperand(i);
14522
14523     if (Op.isUndef())
14524       continue;
14525
14526     // Check if this is the identity extract:
14527     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14528       return SDValue();
14529
14530     // Find the single incoming vector for the extract_subvector.
14531     if (SingleSource.getNode()) {
14532       if (Op.getOperand(0) != SingleSource)
14533         return SDValue();
14534     } else {
14535       SingleSource = Op.getOperand(0);
14536
14537       // Check the source type is the same as the type of the result.
14538       // If not, this concat may extend the vector, so we can not
14539       // optimize it away.
14540       if (SingleSource.getValueType() != N->getValueType(0))
14541         return SDValue();
14542     }
14543
14544     unsigned IdentityIndex = i * PartNumElem;
14545     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14546     // The extract index must be constant.
14547     if (!CS)
14548       return SDValue();
14549
14550     // Check that we are reading from the identity index.
14551     if (CS->getZExtValue() != IdentityIndex)
14552       return SDValue();
14553   }
14554
14555   if (SingleSource.getNode())
14556     return SingleSource;
14557
14558   return SDValue();
14559 }
14560
14561 /// If we are extracting a subvector produced by a wide binary operator with at
14562 /// at least one operand that was the result of a vector concatenation, then try
14563 /// to use the narrow vector operands directly to avoid the concatenation and
14564 /// extraction.
14565 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
14566   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
14567   // some of these bailouts with other transforms.
14568
14569   // The extract index must be a constant, so we can map it to a concat operand.
14570   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14571   if (!ExtractIndex)
14572     return SDValue();
14573
14574   // Only handle the case where we are doubling and then halving. A larger ratio
14575   // may require more than two narrow binops to replace the wide binop.
14576   EVT VT = Extract->getValueType(0);
14577   unsigned NumElems = VT.getVectorNumElements();
14578   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
14579          "Extract index is not a multiple of the vector length.");
14580   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
14581     return SDValue();
14582
14583   // We are looking for an optionally bitcasted wide vector binary operator
14584   // feeding an extract subvector.
14585   SDValue BinOp = Extract->getOperand(0);
14586   if (BinOp.getOpcode() == ISD::BITCAST)
14587     BinOp = BinOp.getOperand(0);
14588
14589   // TODO: The motivating case for this transform is an x86 AVX1 target. That
14590   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
14591   // flavors, but no other 256-bit integer support. This could be extended to
14592   // handle any binop, but that may require fixing/adding other folds to avoid
14593   // codegen regressions.
14594   unsigned BOpcode = BinOp.getOpcode();
14595   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
14596     return SDValue();
14597
14598   // The binop must be a vector type, so we can chop it in half.
14599   EVT WideBVT = BinOp.getValueType();
14600   if (!WideBVT.isVector())
14601     return SDValue();
14602
14603   // Bail out if the target does not support a narrower version of the binop.
14604   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
14605                                    WideBVT.getVectorNumElements() / 2);
14606   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14607   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
14608     return SDValue();
14609
14610   // Peek through bitcasts of the binary operator operands if needed.
14611   SDValue LHS = BinOp.getOperand(0);
14612   if (LHS.getOpcode() == ISD::BITCAST)
14613     LHS = LHS.getOperand(0);
14614
14615   SDValue RHS = BinOp.getOperand(1);
14616   if (RHS.getOpcode() == ISD::BITCAST)
14617     RHS = RHS.getOperand(0);
14618
14619   // We need at least one concatenation operation of a binop operand to make
14620   // this transform worthwhile. The concat must double the input vector sizes.
14621   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
14622   bool ConcatL =
14623       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
14624   bool ConcatR =
14625       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
14626   if (!ConcatL && !ConcatR)
14627     return SDValue();
14628
14629   // If one of the binop operands was not the result of a concat, we must
14630   // extract a half-sized operand for our new narrow binop. We can't just reuse
14631   // the original extract index operand because we may have bitcasted.
14632   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
14633   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
14634   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
14635   SDLoc DL(Extract);
14636
14637   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
14638   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
14639   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
14640   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
14641                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14642                                     BinOp.getOperand(0),
14643                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14644
14645   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
14646                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14647                                     BinOp.getOperand(1),
14648                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14649
14650   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
14651   return DAG.getBitcast(VT, NarrowBinOp);
14652 }
14653
14654 /// If we are extracting a subvector from a wide vector load, convert to a
14655 /// narrow load to eliminate the extraction:
14656 /// (extract_subvector (load wide vector)) --> (load narrow vector)
14657 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
14658   // TODO: Add support for big-endian. The offset calculation must be adjusted.
14659   if (DAG.getDataLayout().isBigEndian())
14660     return SDValue();
14661
14662   // TODO: The one-use check is overly conservative. Check the cost of the
14663   // extract instead or remove that condition entirely.
14664   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
14665   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14666   if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
14667       !ExtIdx)
14668     return SDValue();
14669
14670   // The narrow load will be offset from the base address of the old load if
14671   // we are extracting from something besides index 0 (little-endian).
14672   EVT VT = Extract->getValueType(0);
14673   SDLoc DL(Extract);
14674   SDValue BaseAddr = Ld->getOperand(1);
14675   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
14676
14677   // TODO: Use "BaseIndexOffset" to make this more effective.
14678   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
14679   MachineFunction &MF = DAG.getMachineFunction();
14680   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
14681                                                    VT.getStoreSize());
14682   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
14683
14684   // The new load must have the same position as the old load in terms of memory
14685   // dependency. Create a TokenFactor for Ld and NewLd and update uses of Ld's
14686   // output chain to use that TokenFactor.
14687   // TODO: This code is based on a similar sequence in x86 lowering. It should
14688   // be moved to a helper function, so it can be shared and reused.
14689   if (Ld->hasAnyUseOfValue(1)) {
14690     SDValue OldChain = SDValue(Ld, 1);
14691     SDValue NewChain = SDValue(NewLd.getNode(), 1);
14692     SDValue TokenFactor = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14693                                       OldChain, NewChain);
14694     DAG.ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
14695     DAG.UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
14696   }
14697
14698   return NewLd;
14699 }
14700
14701 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
14702   EVT NVT = N->getValueType(0);
14703   SDValue V = N->getOperand(0);
14704
14705   // Extract from UNDEF is UNDEF.
14706   if (V.isUndef())
14707     return DAG.getUNDEF(NVT);
14708
14709   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
14710     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
14711       return NarrowLoad;
14712
14713   // Combine:
14714   //    (extract_subvec (concat V1, V2, ...), i)
14715   // Into:
14716   //    Vi if possible
14717   // Only operand 0 is checked as 'concat' assumes all inputs of the same
14718   // type.
14719   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
14720       isa<ConstantSDNode>(N->getOperand(1)) &&
14721       V->getOperand(0).getValueType() == NVT) {
14722     unsigned Idx = N->getConstantOperandVal(1);
14723     unsigned NumElems = NVT.getVectorNumElements();
14724     assert((Idx % NumElems) == 0 &&
14725            "IDX in concat is not a multiple of the result vector length.");
14726     return V->getOperand(Idx / NumElems);
14727   }
14728
14729   // Skip bitcasting
14730   if (V->getOpcode() == ISD::BITCAST)
14731     V = V.getOperand(0);
14732
14733   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
14734     // Handle only simple case where vector being inserted and vector
14735     // being extracted are of same size.
14736     EVT SmallVT = V->getOperand(1).getValueType();
14737     if (!NVT.bitsEq(SmallVT))
14738       return SDValue();
14739
14740     // Only handle cases where both indexes are constants.
14741     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
14742     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
14743
14744     if (InsIdx && ExtIdx) {
14745       // Combine:
14746       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
14747       // Into:
14748       //    indices are equal or bit offsets are equal => V1
14749       //    otherwise => (extract_subvec V1, ExtIdx)
14750       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
14751           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
14752         return DAG.getBitcast(NVT, V->getOperand(1));
14753       return DAG.getNode(
14754           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
14755           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
14756           N->getOperand(1));
14757     }
14758   }
14759
14760   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
14761     return NarrowBOp;
14762
14763   return SDValue();
14764 }
14765
14766 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
14767                                                  SDValue V, SelectionDAG &DAG) {
14768   SDLoc DL(V);
14769   EVT VT = V.getValueType();
14770
14771   switch (V.getOpcode()) {
14772   default:
14773     return V;
14774
14775   case ISD::CONCAT_VECTORS: {
14776     EVT OpVT = V->getOperand(0).getValueType();
14777     int OpSize = OpVT.getVectorNumElements();
14778     SmallBitVector OpUsedElements(OpSize, false);
14779     bool FoundSimplification = false;
14780     SmallVector<SDValue, 4> NewOps;
14781     NewOps.reserve(V->getNumOperands());
14782     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
14783       SDValue Op = V->getOperand(i);
14784       bool OpUsed = false;
14785       for (int j = 0; j < OpSize; ++j)
14786         if (UsedElements[i * OpSize + j]) {
14787           OpUsedElements[j] = true;
14788           OpUsed = true;
14789         }
14790       NewOps.push_back(
14791           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
14792                  : DAG.getUNDEF(OpVT));
14793       FoundSimplification |= Op == NewOps.back();
14794       OpUsedElements.reset();
14795     }
14796     if (FoundSimplification)
14797       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
14798     return V;
14799   }
14800
14801   case ISD::INSERT_SUBVECTOR: {
14802     SDValue BaseV = V->getOperand(0);
14803     SDValue SubV = V->getOperand(1);
14804     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
14805     if (!IdxN)
14806       return V;
14807
14808     int SubSize = SubV.getValueType().getVectorNumElements();
14809     int Idx = IdxN->getZExtValue();
14810     bool SubVectorUsed = false;
14811     SmallBitVector SubUsedElements(SubSize, false);
14812     for (int i = 0; i < SubSize; ++i)
14813       if (UsedElements[i + Idx]) {
14814         SubVectorUsed = true;
14815         SubUsedElements[i] = true;
14816         UsedElements[i + Idx] = false;
14817       }
14818
14819     // Now recurse on both the base and sub vectors.
14820     SDValue SimplifiedSubV =
14821         SubVectorUsed
14822             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14823             : DAG.getUNDEF(SubV.getValueType());
14824     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14825     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14826       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14827                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14828     return V;
14829   }
14830   }
14831 }
14832
14833 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14834                                        SDValue N1, SelectionDAG &DAG) {
14835   EVT VT = SVN->getValueType(0);
14836   int NumElts = VT.getVectorNumElements();
14837   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
14838   for (int M : SVN->getMask())
14839     if (M >= 0 && M < NumElts)
14840       N0UsedElements[M] = true;
14841     else if (M >= NumElts)
14842       N1UsedElements[M - NumElts] = true;
14843
14844   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
14845   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
14846   if (S0 == N0 && S1 == N1)
14847     return SDValue();
14848
14849   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
14850 }
14851
14852 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
14853 // or turn a shuffle of a single concat into simpler shuffle then concat.
14854 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
14855   EVT VT = N->getValueType(0);
14856   unsigned NumElts = VT.getVectorNumElements();
14857
14858   SDValue N0 = N->getOperand(0);
14859   SDValue N1 = N->getOperand(1);
14860   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14861
14862   SmallVector<SDValue, 4> Ops;
14863   EVT ConcatVT = N0.getOperand(0).getValueType();
14864   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
14865   unsigned NumConcats = NumElts / NumElemsPerConcat;
14866
14867   // Special case: shuffle(concat(A,B)) can be more efficiently represented
14868   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
14869   // half vector elements.
14870   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
14871       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
14872                   SVN->getMask().end(), [](int i) { return i == -1; })) {
14873     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
14874                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
14875     N1 = DAG.getUNDEF(ConcatVT);
14876     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
14877   }
14878
14879   // Look at every vector that's inserted. We're looking for exact
14880   // subvector-sized copies from a concatenated vector
14881   for (unsigned I = 0; I != NumConcats; ++I) {
14882     // Make sure we're dealing with a copy.
14883     unsigned Begin = I * NumElemsPerConcat;
14884     bool AllUndef = true, NoUndef = true;
14885     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
14886       if (SVN->getMaskElt(J) >= 0)
14887         AllUndef = false;
14888       else
14889         NoUndef = false;
14890     }
14891
14892     if (NoUndef) {
14893       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
14894         return SDValue();
14895
14896       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
14897         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
14898           return SDValue();
14899
14900       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
14901       if (FirstElt < N0.getNumOperands())
14902         Ops.push_back(N0.getOperand(FirstElt));
14903       else
14904         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
14905
14906     } else if (AllUndef) {
14907       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
14908     } else { // Mixed with general masks and undefs, can't do optimization.
14909       return SDValue();
14910     }
14911   }
14912
14913   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
14914 }
14915
14916 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14917 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14918 //
14919 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
14920 // a simplification in some sense, but it isn't appropriate in general: some
14921 // BUILD_VECTORs are substantially cheaper than others. The general case
14922 // of a BUILD_VECTOR requires inserting each element individually (or
14923 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
14924 // all constants is a single constant pool load.  A BUILD_VECTOR where each
14925 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
14926 // are undef lowers to a small number of element insertions.
14927 //
14928 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
14929 // We don't fold shuffles where one side is a non-zero constant, and we don't
14930 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
14931 // non-constant operands. This seems to work out reasonably well in practice.
14932 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
14933                                        SelectionDAG &DAG,
14934                                        const TargetLowering &TLI) {
14935   EVT VT = SVN->getValueType(0);
14936   unsigned NumElts = VT.getVectorNumElements();
14937   SDValue N0 = SVN->getOperand(0);
14938   SDValue N1 = SVN->getOperand(1);
14939
14940   if (!N0->hasOneUse() || !N1->hasOneUse())
14941     return SDValue();
14942   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
14943   // discussed above.
14944   if (!N1.isUndef()) {
14945     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
14946     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
14947     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
14948       return SDValue();
14949     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
14950       return SDValue();
14951   }
14952
14953   SmallVector<SDValue, 8> Ops;
14954   SmallSet<SDValue, 16> DuplicateOps;
14955   for (int M : SVN->getMask()) {
14956     SDValue Op = DAG.getUNDEF(VT.getScalarType());
14957     if (M >= 0) {
14958       int Idx = M < (int)NumElts ? M : M - NumElts;
14959       SDValue &S = (M < (int)NumElts ? N0 : N1);
14960       if (S.getOpcode() == ISD::BUILD_VECTOR) {
14961         Op = S.getOperand(Idx);
14962       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14963         if (Idx == 0)
14964           Op = S.getOperand(0);
14965       } else {
14966         // Operand can't be combined - bail out.
14967         return SDValue();
14968       }
14969     }
14970
14971     // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
14972     // fine, but it's likely to generate low-quality code if the target can't
14973     // reconstruct an appropriate shuffle.
14974     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
14975       if (!DuplicateOps.insert(Op).second)
14976         return SDValue();
14977
14978     Ops.push_back(Op);
14979   }
14980   // BUILD_VECTOR requires all inputs to be of the same type, find the
14981   // maximum type and extend them all.
14982   EVT SVT = VT.getScalarType();
14983   if (SVT.isInteger())
14984     for (SDValue &Op : Ops)
14985       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
14986   if (SVT != VT.getScalarType())
14987     for (SDValue &Op : Ops)
14988       Op = TLI.isZExtFree(Op.getValueType(), SVT)
14989                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
14990                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
14991   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
14992 }
14993
14994 // Match shuffles that can be converted to any_vector_extend_in_reg.
14995 // This is often generated during legalization.
14996 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
14997 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
14998 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
14999                                             SelectionDAG &DAG,
15000                                             const TargetLowering &TLI,
15001                                             bool LegalOperations) {
15002   EVT VT = SVN->getValueType(0);
15003   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15004
15005   // TODO Add support for big-endian when we have a test case.
15006   if (!VT.isInteger() || IsBigEndian)
15007     return SDValue();
15008
15009   unsigned NumElts = VT.getVectorNumElements();
15010   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15011   ArrayRef<int> Mask = SVN->getMask();
15012   SDValue N0 = SVN->getOperand(0);
15013
15014   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15015   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15016     for (unsigned i = 0; i != NumElts; ++i) {
15017       if (Mask[i] < 0)
15018         continue;
15019       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15020         continue;
15021       return false;
15022     }
15023     return true;
15024   };
15025
15026   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15027   // power-of-2 extensions as they are the most likely.
15028   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15029     if (!isAnyExtend(Scale))
15030       continue;
15031
15032     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15033     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15034     if (!LegalOperations ||
15035         TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15036       return DAG.getBitcast(VT,
15037                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15038   }
15039
15040   return SDValue();
15041 }
15042
15043 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15044 // each source element of a large type into the lowest elements of a smaller
15045 // destination type. This is often generated during legalization.
15046 // If the source node itself was a '*_extend_vector_inreg' node then we should
15047 // then be able to remove it.
15048 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15049                                         SelectionDAG &DAG) {
15050   EVT VT = SVN->getValueType(0);
15051   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15052
15053   // TODO Add support for big-endian when we have a test case.
15054   if (!VT.isInteger() || IsBigEndian)
15055     return SDValue();
15056
15057   SDValue N0 = SVN->getOperand(0);
15058   while (N0.getOpcode() == ISD::BITCAST)
15059     N0 = N0.getOperand(0);
15060
15061   unsigned Opcode = N0.getOpcode();
15062   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15063       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15064       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15065     return SDValue();
15066
15067   SDValue N00 = N0.getOperand(0);
15068   ArrayRef<int> Mask = SVN->getMask();
15069   unsigned NumElts = VT.getVectorNumElements();
15070   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15071   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15072
15073   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15074   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15075   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15076   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15077     for (unsigned i = 0; i != NumElts; ++i) {
15078       if (Mask[i] < 0)
15079         continue;
15080       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15081         continue;
15082       return false;
15083     }
15084     return true;
15085   };
15086
15087   // At the moment we just handle the case where we've truncated back to the
15088   // same size as before the extension.
15089   // TODO: handle more extension/truncation cases as cases arise.
15090   if (EltSizeInBits != ExtSrcSizeInBits)
15091     return SDValue();
15092
15093   // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for
15094   // power-of-2 truncations as they are the most likely.
15095   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2)
15096     if (isTruncate(Scale))
15097       return DAG.getBitcast(VT, N00);
15098
15099   return SDValue();
15100 }
15101
15102 // Combine shuffles of splat-shuffles of the form:
15103 // shuffle (shuffle V, undef, splat-mask), undef, M
15104 // If splat-mask contains undef elements, we need to be careful about
15105 // introducing undef's in the folded mask which are not the result of composing
15106 // the masks of the shuffles.
15107 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15108                                      ShuffleVectorSDNode *Splat,
15109                                      SelectionDAG &DAG) {
15110   ArrayRef<int> SplatMask = Splat->getMask();
15111   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
15112
15113   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15114   // every undef mask element in the splat-shuffle has a corresponding undef
15115   // element in the user-shuffle's mask or if the composition of mask elements
15116   // would result in undef.
15117   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15118   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15119   //   In this case it is not legal to simplify to the splat-shuffle because we
15120   //   may be exposing the users of the shuffle an undef element at index 1
15121   //   which was not there before the combine.
15122   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15123   //   In this case the composition of masks yields SplatMask, so it's ok to
15124   //   simplify to the splat-shuffle.
15125   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15126   //   In this case the composed mask includes all undef elements of SplatMask
15127   //   and in addition sets element zero to undef. It is safe to simplify to
15128   //   the splat-shuffle.
15129   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15130                                        ArrayRef<int> SplatMask) {
15131     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15132       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15133           SplatMask[UserMask[i]] != -1)
15134         return false;
15135     return true;
15136   };
15137   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15138     return SDValue(Splat, 0);
15139
15140   // Create a new shuffle with a mask that is composed of the two shuffles'
15141   // masks.
15142   SmallVector<int, 32> NewMask;
15143   for (int Idx : UserMask)
15144     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15145
15146   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15147                               Splat->getOperand(0), Splat->getOperand(1),
15148                               NewMask);
15149 }
15150
15151 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
15152   EVT VT = N->getValueType(0);
15153   unsigned NumElts = VT.getVectorNumElements();
15154
15155   SDValue N0 = N->getOperand(0);
15156   SDValue N1 = N->getOperand(1);
15157
15158   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
15159
15160   // Canonicalize shuffle undef, undef -> undef
15161   if (N0.isUndef() && N1.isUndef())
15162     return DAG.getUNDEF(VT);
15163
15164   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15165
15166   // Canonicalize shuffle v, v -> v, undef
15167   if (N0 == N1) {
15168     SmallVector<int, 8> NewMask;
15169     for (unsigned i = 0; i != NumElts; ++i) {
15170       int Idx = SVN->getMaskElt(i);
15171       if (Idx >= (int)NumElts) Idx -= NumElts;
15172       NewMask.push_back(Idx);
15173     }
15174     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
15175   }
15176
15177   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
15178   if (N0.isUndef())
15179     return DAG.getCommutedVectorShuffle(*SVN);
15180
15181   // Remove references to rhs if it is undef
15182   if (N1.isUndef()) {
15183     bool Changed = false;
15184     SmallVector<int, 8> NewMask;
15185     for (unsigned i = 0; i != NumElts; ++i) {
15186       int Idx = SVN->getMaskElt(i);
15187       if (Idx >= (int)NumElts) {
15188         Idx = -1;
15189         Changed = true;
15190       }
15191       NewMask.push_back(Idx);
15192     }
15193     if (Changed)
15194       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
15195   }
15196
15197   // A shuffle of a single vector that is a splat can always be folded.
15198   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
15199     if (N1->isUndef() && N0Shuf->isSplat())
15200       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
15201
15202   // If it is a splat, check if the argument vector is another splat or a
15203   // build_vector.
15204   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
15205     SDNode *V = N0.getNode();
15206
15207     // If this is a bit convert that changes the element type of the vector but
15208     // not the number of vector elements, look through it.  Be careful not to
15209     // look though conversions that change things like v4f32 to v2f64.
15210     if (V->getOpcode() == ISD::BITCAST) {
15211       SDValue ConvInput = V->getOperand(0);
15212       if (ConvInput.getValueType().isVector() &&
15213           ConvInput.getValueType().getVectorNumElements() == NumElts)
15214         V = ConvInput.getNode();
15215     }
15216
15217     if (V->getOpcode() == ISD::BUILD_VECTOR) {
15218       assert(V->getNumOperands() == NumElts &&
15219              "BUILD_VECTOR has wrong number of operands");
15220       SDValue Base;
15221       bool AllSame = true;
15222       for (unsigned i = 0; i != NumElts; ++i) {
15223         if (!V->getOperand(i).isUndef()) {
15224           Base = V->getOperand(i);
15225           break;
15226         }
15227       }
15228       // Splat of <u, u, u, u>, return <u, u, u, u>
15229       if (!Base.getNode())
15230         return N0;
15231       for (unsigned i = 0; i != NumElts; ++i) {
15232         if (V->getOperand(i) != Base) {
15233           AllSame = false;
15234           break;
15235         }
15236       }
15237       // Splat of <x, x, x, x>, return <x, x, x, x>
15238       if (AllSame)
15239         return N0;
15240
15241       // Canonicalize any other splat as a build_vector.
15242       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
15243       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
15244       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
15245
15246       // We may have jumped through bitcasts, so the type of the
15247       // BUILD_VECTOR may not match the type of the shuffle.
15248       if (V->getValueType(0) != VT)
15249         NewBV = DAG.getBitcast(VT, NewBV);
15250       return NewBV;
15251     }
15252   }
15253
15254   // There are various patterns used to build up a vector from smaller vectors,
15255   // subvectors, or elements. Scan chains of these and replace unused insertions
15256   // or components with undef.
15257   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
15258     return S;
15259
15260   // Match shuffles that can be converted to any_vector_extend_in_reg.
15261   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
15262     return V;
15263
15264   // Combine "truncate_vector_in_reg" style shuffles.
15265   if (SDValue V = combineTruncationShuffle(SVN, DAG))
15266     return V;
15267
15268   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
15269       Level < AfterLegalizeVectorOps &&
15270       (N1.isUndef() ||
15271       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
15272        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
15273     if (SDValue V = partitionShuffleOfConcats(N, DAG))
15274       return V;
15275   }
15276
15277   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15278   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15279   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15280     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
15281       return Res;
15282
15283   // If this shuffle only has a single input that is a bitcasted shuffle,
15284   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
15285   // back to their original types.
15286   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
15287       N1.isUndef() && Level < AfterLegalizeVectorOps &&
15288       TLI.isTypeLegal(VT)) {
15289
15290     // Peek through the bitcast only if there is one user.
15291     SDValue BC0 = N0;
15292     while (BC0.getOpcode() == ISD::BITCAST) {
15293       if (!BC0.hasOneUse())
15294         break;
15295       BC0 = BC0.getOperand(0);
15296     }
15297
15298     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
15299       if (Scale == 1)
15300         return SmallVector<int, 8>(Mask.begin(), Mask.end());
15301
15302       SmallVector<int, 8> NewMask;
15303       for (int M : Mask)
15304         for (int s = 0; s != Scale; ++s)
15305           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
15306       return NewMask;
15307     };
15308
15309     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
15310       EVT SVT = VT.getScalarType();
15311       EVT InnerVT = BC0->getValueType(0);
15312       EVT InnerSVT = InnerVT.getScalarType();
15313
15314       // Determine which shuffle works with the smaller scalar type.
15315       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
15316       EVT ScaleSVT = ScaleVT.getScalarType();
15317
15318       if (TLI.isTypeLegal(ScaleVT) &&
15319           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
15320           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
15321
15322         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15323         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15324
15325         // Scale the shuffle masks to the smaller scalar type.
15326         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
15327         SmallVector<int, 8> InnerMask =
15328             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
15329         SmallVector<int, 8> OuterMask =
15330             ScaleShuffleMask(SVN->getMask(), OuterScale);
15331
15332         // Merge the shuffle masks.
15333         SmallVector<int, 8> NewMask;
15334         for (int M : OuterMask)
15335           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
15336
15337         // Test for shuffle mask legality over both commutations.
15338         SDValue SV0 = BC0->getOperand(0);
15339         SDValue SV1 = BC0->getOperand(1);
15340         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15341         if (!LegalMask) {
15342           std::swap(SV0, SV1);
15343           ShuffleVectorSDNode::commuteMask(NewMask);
15344           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15345         }
15346
15347         if (LegalMask) {
15348           SV0 = DAG.getBitcast(ScaleVT, SV0);
15349           SV1 = DAG.getBitcast(ScaleVT, SV1);
15350           return DAG.getBitcast(
15351               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
15352         }
15353       }
15354     }
15355   }
15356
15357   // Canonicalize shuffles according to rules:
15358   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
15359   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
15360   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
15361   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
15362       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
15363       TLI.isTypeLegal(VT)) {
15364     // The incoming shuffle must be of the same type as the result of the
15365     // current shuffle.
15366     assert(N1->getOperand(0).getValueType() == VT &&
15367            "Shuffle types don't match");
15368
15369     SDValue SV0 = N1->getOperand(0);
15370     SDValue SV1 = N1->getOperand(1);
15371     bool HasSameOp0 = N0 == SV0;
15372     bool IsSV1Undef = SV1.isUndef();
15373     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
15374       // Commute the operands of this shuffle so that next rule
15375       // will trigger.
15376       return DAG.getCommutedVectorShuffle(*SVN);
15377   }
15378
15379   // Try to fold according to rules:
15380   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15381   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15382   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15383   // Don't try to fold shuffles with illegal type.
15384   // Only fold if this shuffle is the only user of the other shuffle.
15385   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
15386       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
15387     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
15388
15389     // Don't try to fold splats; they're likely to simplify somehow, or they
15390     // might be free.
15391     if (OtherSV->isSplat())
15392       return SDValue();
15393
15394     // The incoming shuffle must be of the same type as the result of the
15395     // current shuffle.
15396     assert(OtherSV->getOperand(0).getValueType() == VT &&
15397            "Shuffle types don't match");
15398
15399     SDValue SV0, SV1;
15400     SmallVector<int, 4> Mask;
15401     // Compute the combined shuffle mask for a shuffle with SV0 as the first
15402     // operand, and SV1 as the second operand.
15403     for (unsigned i = 0; i != NumElts; ++i) {
15404       int Idx = SVN->getMaskElt(i);
15405       if (Idx < 0) {
15406         // Propagate Undef.
15407         Mask.push_back(Idx);
15408         continue;
15409       }
15410
15411       SDValue CurrentVec;
15412       if (Idx < (int)NumElts) {
15413         // This shuffle index refers to the inner shuffle N0. Lookup the inner
15414         // shuffle mask to identify which vector is actually referenced.
15415         Idx = OtherSV->getMaskElt(Idx);
15416         if (Idx < 0) {
15417           // Propagate Undef.
15418           Mask.push_back(Idx);
15419           continue;
15420         }
15421
15422         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
15423                                            : OtherSV->getOperand(1);
15424       } else {
15425         // This shuffle index references an element within N1.
15426         CurrentVec = N1;
15427       }
15428
15429       // Simple case where 'CurrentVec' is UNDEF.
15430       if (CurrentVec.isUndef()) {
15431         Mask.push_back(-1);
15432         continue;
15433       }
15434
15435       // Canonicalize the shuffle index. We don't know yet if CurrentVec
15436       // will be the first or second operand of the combined shuffle.
15437       Idx = Idx % NumElts;
15438       if (!SV0.getNode() || SV0 == CurrentVec) {
15439         // Ok. CurrentVec is the left hand side.
15440         // Update the mask accordingly.
15441         SV0 = CurrentVec;
15442         Mask.push_back(Idx);
15443         continue;
15444       }
15445
15446       // Bail out if we cannot convert the shuffle pair into a single shuffle.
15447       if (SV1.getNode() && SV1 != CurrentVec)
15448         return SDValue();
15449
15450       // Ok. CurrentVec is the right hand side.
15451       // Update the mask accordingly.
15452       SV1 = CurrentVec;
15453       Mask.push_back(Idx + NumElts);
15454     }
15455
15456     // Check if all indices in Mask are Undef. In case, propagate Undef.
15457     bool isUndefMask = true;
15458     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
15459       isUndefMask &= Mask[i] < 0;
15460
15461     if (isUndefMask)
15462       return DAG.getUNDEF(VT);
15463
15464     if (!SV0.getNode())
15465       SV0 = DAG.getUNDEF(VT);
15466     if (!SV1.getNode())
15467       SV1 = DAG.getUNDEF(VT);
15468
15469     // Avoid introducing shuffles with illegal mask.
15470     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
15471       ShuffleVectorSDNode::commuteMask(Mask);
15472
15473       if (!TLI.isShuffleMaskLegal(Mask, VT))
15474         return SDValue();
15475
15476       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
15477       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
15478       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
15479       std::swap(SV0, SV1);
15480     }
15481
15482     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15483     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15484     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15485     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
15486   }
15487
15488   return SDValue();
15489 }
15490
15491 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
15492   SDValue InVal = N->getOperand(0);
15493   EVT VT = N->getValueType(0);
15494
15495   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
15496   // with a VECTOR_SHUFFLE.
15497   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15498     SDValue InVec = InVal->getOperand(0);
15499     SDValue EltNo = InVal->getOperand(1);
15500
15501     // FIXME: We could support implicit truncation if the shuffle can be
15502     // scaled to a smaller vector scalar type.
15503     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
15504     if (C0 && VT == InVec.getValueType() &&
15505         VT.getScalarType() == InVal.getValueType()) {
15506       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
15507       int Elt = C0->getZExtValue();
15508       NewMask[0] = Elt;
15509
15510       if (TLI.isShuffleMaskLegal(NewMask, VT))
15511         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
15512                                     NewMask);
15513     }
15514   }
15515
15516   return SDValue();
15517 }
15518
15519 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15520   EVT VT = N->getValueType(0);
15521   SDValue N0 = N->getOperand(0);
15522   SDValue N1 = N->getOperand(1);
15523   SDValue N2 = N->getOperand(2);
15524
15525   // If inserting an UNDEF, just return the original vector.
15526   if (N1.isUndef())
15527     return N0;
15528
15529   // If this is an insert of an extracted vector into an undef vector, we can
15530   // just use the input to the extract.
15531   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15532       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15533     return N1.getOperand(0);
15534
15535   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15536   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15537   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15538   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15539       N0.getOperand(1).getValueType() == N1.getValueType() &&
15540       N0.getOperand(2) == N2)
15541     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15542                        N1, N2);
15543
15544   if (!isa<ConstantSDNode>(N2))
15545     return SDValue();
15546
15547   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15548
15549   // Canonicalize insert_subvector dag nodes.
15550   // Example:
15551   // (insert_subvector (insert_subvector A, Idx0), Idx1)
15552   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15553   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15554       N1.getValueType() == N0.getOperand(1).getValueType() &&
15555       isa<ConstantSDNode>(N0.getOperand(2))) {
15556     unsigned OtherIdx = N0.getConstantOperandVal(2);
15557     if (InsIdx < OtherIdx) {
15558       // Swap nodes.
15559       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15560                                   N0.getOperand(0), N1, N2);
15561       AddToWorklist(NewOp.getNode());
15562       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15563                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15564     }
15565   }
15566
15567   // If the input vector is a concatenation, and the insert replaces
15568   // one of the pieces, we can optimize into a single concat_vectors.
15569   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15570       N0.getOperand(0).getValueType() == N1.getValueType()) {
15571     unsigned Factor = N1.getValueType().getVectorNumElements();
15572
15573     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15574     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15575
15576     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15577   }
15578
15579   return SDValue();
15580 }
15581
15582 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15583   SDValue N0 = N->getOperand(0);
15584
15585   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15586   if (N0->getOpcode() == ISD::FP16_TO_FP)
15587     return N0->getOperand(0);
15588
15589   return SDValue();
15590 }
15591
15592 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15593   SDValue N0 = N->getOperand(0);
15594
15595   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15596   if (N0->getOpcode() == ISD::AND) {
15597     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15598     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15599       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15600                          N0.getOperand(0));
15601     }
15602   }
15603
15604   return SDValue();
15605 }
15606
15607 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
15608 /// with the destination vector and a zero vector.
15609 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
15610 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
15611 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
15612   EVT VT = N->getValueType(0);
15613   SDValue LHS = N->getOperand(0);
15614   SDValue RHS = N->getOperand(1);
15615   SDLoc DL(N);
15616
15617   // Make sure we're not running after operation legalization where it
15618   // may have custom lowered the vector shuffles.
15619   if (LegalOperations)
15620     return SDValue();
15621
15622   if (N->getOpcode() != ISD::AND)
15623     return SDValue();
15624
15625   if (RHS.getOpcode() == ISD::BITCAST)
15626     RHS = RHS.getOperand(0);
15627
15628   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
15629     return SDValue();
15630
15631   EVT RVT = RHS.getValueType();
15632   unsigned NumElts = RHS.getNumOperands();
15633
15634   // Attempt to create a valid clear mask, splitting the mask into
15635   // sub elements and checking to see if each is
15636   // all zeros or all ones - suitable for shuffle masking.
15637   auto BuildClearMask = [&](int Split) {
15638     int NumSubElts = NumElts * Split;
15639     int NumSubBits = RVT.getScalarSizeInBits() / Split;
15640
15641     SmallVector<int, 8> Indices;
15642     for (int i = 0; i != NumSubElts; ++i) {
15643       int EltIdx = i / Split;
15644       int SubIdx = i % Split;
15645       SDValue Elt = RHS.getOperand(EltIdx);
15646       if (Elt.isUndef()) {
15647         Indices.push_back(-1);
15648         continue;
15649       }
15650
15651       APInt Bits;
15652       if (isa<ConstantSDNode>(Elt))
15653         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
15654       else if (isa<ConstantFPSDNode>(Elt))
15655         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
15656       else
15657         return SDValue();
15658
15659       // Extract the sub element from the constant bit mask.
15660       if (DAG.getDataLayout().isBigEndian()) {
15661         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
15662       } else {
15663         Bits.lshrInPlace(SubIdx * NumSubBits);
15664       }
15665
15666       if (Split > 1)
15667         Bits = Bits.trunc(NumSubBits);
15668
15669       if (Bits.isAllOnesValue())
15670         Indices.push_back(i);
15671       else if (Bits == 0)
15672         Indices.push_back(i + NumSubElts);
15673       else
15674         return SDValue();
15675     }
15676
15677     // Let's see if the target supports this vector_shuffle.
15678     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
15679     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
15680     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
15681       return SDValue();
15682
15683     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
15684     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
15685                                                    DAG.getBitcast(ClearVT, LHS),
15686                                                    Zero, Indices));
15687   };
15688
15689   // Determine maximum split level (byte level masking).
15690   int MaxSplit = 1;
15691   if (RVT.getScalarSizeInBits() % 8 == 0)
15692     MaxSplit = RVT.getScalarSizeInBits() / 8;
15693
15694   for (int Split = 1; Split <= MaxSplit; ++Split)
15695     if (RVT.getScalarSizeInBits() % Split == 0)
15696       if (SDValue S = BuildClearMask(Split))
15697         return S;
15698
15699   return SDValue();
15700 }
15701
15702 /// Visit a binary vector operation, like ADD.
15703 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
15704   assert(N->getValueType(0).isVector() &&
15705          "SimplifyVBinOp only works on vectors!");
15706
15707   SDValue LHS = N->getOperand(0);
15708   SDValue RHS = N->getOperand(1);
15709   SDValue Ops[] = {LHS, RHS};
15710
15711   // See if we can constant fold the vector operation.
15712   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
15713           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
15714     return Fold;
15715
15716   // Try to convert a constant mask AND into a shuffle clear mask.
15717   if (SDValue Shuffle = XformToShuffleWithZero(N))
15718     return Shuffle;
15719
15720   // Type legalization might introduce new shuffles in the DAG.
15721   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
15722   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
15723   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
15724       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
15725       LHS.getOperand(1).isUndef() &&
15726       RHS.getOperand(1).isUndef()) {
15727     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
15728     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
15729
15730     if (SVN0->getMask().equals(SVN1->getMask())) {
15731       EVT VT = N->getValueType(0);
15732       SDValue UndefVector = LHS.getOperand(1);
15733       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
15734                                      LHS.getOperand(0), RHS.getOperand(0),
15735                                      N->getFlags());
15736       AddUsersToWorklist(N);
15737       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
15738                                   SVN0->getMask());
15739     }
15740   }
15741
15742   return SDValue();
15743 }
15744
15745 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
15746                                     SDValue N2) {
15747   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
15748
15749   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
15750                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
15751
15752   // If we got a simplified select_cc node back from SimplifySelectCC, then
15753   // break it down into a new SETCC node, and a new SELECT node, and then return
15754   // the SELECT node, since we were called with a SELECT node.
15755   if (SCC.getNode()) {
15756     // Check to see if we got a select_cc back (to turn into setcc/select).
15757     // Otherwise, just return whatever node we got back, like fabs.
15758     if (SCC.getOpcode() == ISD::SELECT_CC) {
15759       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
15760                                   N0.getValueType(),
15761                                   SCC.getOperand(0), SCC.getOperand(1),
15762                                   SCC.getOperand(4));
15763       AddToWorklist(SETCC.getNode());
15764       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
15765                            SCC.getOperand(2), SCC.getOperand(3));
15766     }
15767
15768     return SCC;
15769   }
15770   return SDValue();
15771 }
15772
15773 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
15774 /// being selected between, see if we can simplify the select.  Callers of this
15775 /// should assume that TheSelect is deleted if this returns true.  As such, they
15776 /// should return the appropriate thing (e.g. the node) back to the top-level of
15777 /// the DAG combiner loop to avoid it being looked at.
15778 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
15779                                     SDValue RHS) {
15780
15781   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15782   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
15783   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
15784     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
15785       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
15786       SDValue Sqrt = RHS;
15787       ISD::CondCode CC;
15788       SDValue CmpLHS;
15789       const ConstantFPSDNode *Zero = nullptr;
15790
15791       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
15792         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
15793         CmpLHS = TheSelect->getOperand(0);
15794         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
15795       } else {
15796         // SELECT or VSELECT
15797         SDValue Cmp = TheSelect->getOperand(0);
15798         if (Cmp.getOpcode() == ISD::SETCC) {
15799           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
15800           CmpLHS = Cmp.getOperand(0);
15801           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
15802         }
15803       }
15804       if (Zero && Zero->isZero() &&
15805           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
15806           CC == ISD::SETULT || CC == ISD::SETLT)) {
15807         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15808         CombineTo(TheSelect, Sqrt);
15809         return true;
15810       }
15811     }
15812   }
15813   // Cannot simplify select with vector condition
15814   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
15815
15816   // If this is a select from two identical things, try to pull the operation
15817   // through the select.
15818   if (LHS.getOpcode() != RHS.getOpcode() ||
15819       !LHS.hasOneUse() || !RHS.hasOneUse())
15820     return false;
15821
15822   // If this is a load and the token chain is identical, replace the select
15823   // of two loads with a load through a select of the address to load from.
15824   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
15825   // constants have been dropped into the constant pool.
15826   if (LHS.getOpcode() == ISD::LOAD) {
15827     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
15828     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
15829
15830     // Token chains must be identical.
15831     if (LHS.getOperand(0) != RHS.getOperand(0) ||
15832         // Do not let this transformation reduce the number of volatile loads.
15833         LLD->isVolatile() || RLD->isVolatile() ||
15834         // FIXME: If either is a pre/post inc/dec load,
15835         // we'd need to split out the address adjustment.
15836         LLD->isIndexed() || RLD->isIndexed() ||
15837         // If this is an EXTLOAD, the VT's must match.
15838         LLD->getMemoryVT() != RLD->getMemoryVT() ||
15839         // If this is an EXTLOAD, the kind of extension must match.
15840         (LLD->getExtensionType() != RLD->getExtensionType() &&
15841          // The only exception is if one of the extensions is anyext.
15842          LLD->getExtensionType() != ISD::EXTLOAD &&
15843          RLD->getExtensionType() != ISD::EXTLOAD) ||
15844         // FIXME: this discards src value information.  This is
15845         // over-conservative. It would be beneficial to be able to remember
15846         // both potential memory locations.  Since we are discarding
15847         // src value info, don't do the transformation if the memory
15848         // locations are not in the default address space.
15849         LLD->getPointerInfo().getAddrSpace() != 0 ||
15850         RLD->getPointerInfo().getAddrSpace() != 0 ||
15851         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
15852                                       LLD->getBasePtr().getValueType()))
15853       return false;
15854
15855     // Check that the select condition doesn't reach either load.  If so,
15856     // folding this will induce a cycle into the DAG.  If not, this is safe to
15857     // xform, so create a select of the addresses.
15858     SDValue Addr;
15859     if (TheSelect->getOpcode() == ISD::SELECT) {
15860       SDNode *CondNode = TheSelect->getOperand(0).getNode();
15861       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
15862           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
15863         return false;
15864       // The loads must not depend on one another.
15865       if (LLD->isPredecessorOf(RLD) ||
15866           RLD->isPredecessorOf(LLD))
15867         return false;
15868       Addr = DAG.getSelect(SDLoc(TheSelect),
15869                            LLD->getBasePtr().getValueType(),
15870                            TheSelect->getOperand(0), LLD->getBasePtr(),
15871                            RLD->getBasePtr());
15872     } else {  // Otherwise SELECT_CC
15873       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
15874       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
15875
15876       if ((LLD->hasAnyUseOfValue(1) &&
15877            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
15878           (RLD->hasAnyUseOfValue(1) &&
15879            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
15880         return false;
15881
15882       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
15883                          LLD->getBasePtr().getValueType(),
15884                          TheSelect->getOperand(0),
15885                          TheSelect->getOperand(1),
15886                          LLD->getBasePtr(), RLD->getBasePtr(),
15887                          TheSelect->getOperand(4));
15888     }
15889
15890     SDValue Load;
15891     // It is safe to replace the two loads if they have different alignments,
15892     // but the new load must be the minimum (most restrictive) alignment of the
15893     // inputs.
15894     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
15895     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
15896     if (!RLD->isInvariant())
15897       MMOFlags &= ~MachineMemOperand::MOInvariant;
15898     if (!RLD->isDereferenceable())
15899       MMOFlags &= ~MachineMemOperand::MODereferenceable;
15900     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
15901       // FIXME: Discards pointer and AA info.
15902       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
15903                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
15904                          MMOFlags);
15905     } else {
15906       // FIXME: Discards pointer and AA info.
15907       Load = DAG.getExtLoad(
15908           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
15909                                                   : LLD->getExtensionType(),
15910           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
15911           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
15912     }
15913
15914     // Users of the select now use the result of the load.
15915     CombineTo(TheSelect, Load);
15916
15917     // Users of the old loads now use the new load's chain.  We know the
15918     // old-load value is dead now.
15919     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
15920     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
15921     return true;
15922   }
15923
15924   return false;
15925 }
15926
15927 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
15928 /// bitwise 'and'.
15929 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
15930                                             SDValue N1, SDValue N2, SDValue N3,
15931                                             ISD::CondCode CC) {
15932   // If this is a select where the false operand is zero and the compare is a
15933   // check of the sign bit, see if we can perform the "gzip trick":
15934   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
15935   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
15936   EVT XType = N0.getValueType();
15937   EVT AType = N2.getValueType();
15938   if (!isNullConstant(N3) || !XType.bitsGE(AType))
15939     return SDValue();
15940
15941   // If the comparison is testing for a positive value, we have to invert
15942   // the sign bit mask, so only do that transform if the target has a bitwise
15943   // 'and not' instruction (the invert is free).
15944   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
15945     // (X > -1) ? A : 0
15946     // (X >  0) ? X : 0 <-- This is canonical signed max.
15947     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
15948       return SDValue();
15949   } else if (CC == ISD::SETLT) {
15950     // (X <  0) ? A : 0
15951     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
15952     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
15953       return SDValue();
15954   } else {
15955     return SDValue();
15956   }
15957
15958   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
15959   // constant.
15960   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
15961   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15962   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
15963     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
15964     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
15965     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
15966     AddToWorklist(Shift.getNode());
15967
15968     if (XType.bitsGT(AType)) {
15969       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15970       AddToWorklist(Shift.getNode());
15971     }
15972
15973     if (CC == ISD::SETGT)
15974       Shift = DAG.getNOT(DL, Shift, AType);
15975
15976     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15977   }
15978
15979   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
15980   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
15981   AddToWorklist(Shift.getNode());
15982
15983   if (XType.bitsGT(AType)) {
15984     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15985     AddToWorklist(Shift.getNode());
15986   }
15987
15988   if (CC == ISD::SETGT)
15989     Shift = DAG.getNOT(DL, Shift, AType);
15990
15991   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15992 }
15993
15994 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
15995 /// where 'cond' is the comparison specified by CC.
15996 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
15997                                       SDValue N2, SDValue N3, ISD::CondCode CC,
15998                                       bool NotExtCompare) {
15999   // (x ? y : y) -> y.
16000   if (N2 == N3) return N2;
16001
16002   EVT VT = N2.getValueType();
16003   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
16004   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16005
16006   // Determine if the condition we're dealing with is constant
16007   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
16008                               N0, N1, CC, DL, false);
16009   if (SCC.getNode()) AddToWorklist(SCC.getNode());
16010
16011   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
16012     // fold select_cc true, x, y -> x
16013     // fold select_cc false, x, y -> y
16014     return !SCCC->isNullValue() ? N2 : N3;
16015   }
16016
16017   // Check to see if we can simplify the select into an fabs node
16018   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
16019     // Allow either -0.0 or 0.0
16020     if (CFP->isZero()) {
16021       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
16022       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
16023           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
16024           N2 == N3.getOperand(0))
16025         return DAG.getNode(ISD::FABS, DL, VT, N0);
16026
16027       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
16028       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
16029           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
16030           N2.getOperand(0) == N3)
16031         return DAG.getNode(ISD::FABS, DL, VT, N3);
16032     }
16033   }
16034
16035   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
16036   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
16037   // in it.  This is a win when the constant is not otherwise available because
16038   // it replaces two constant pool loads with one.  We only do this if the FP
16039   // type is known to be legal, because if it isn't, then we are before legalize
16040   // types an we want the other legalization to happen first (e.g. to avoid
16041   // messing with soft float) and if the ConstantFP is not legal, because if
16042   // it is legal, we may not need to store the FP constant in a constant pool.
16043   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
16044     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
16045       if (TLI.isTypeLegal(N2.getValueType()) &&
16046           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
16047                TargetLowering::Legal &&
16048            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
16049            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
16050           // If both constants have multiple uses, then we won't need to do an
16051           // extra load, they are likely around in registers for other users.
16052           (TV->hasOneUse() || FV->hasOneUse())) {
16053         Constant *Elts[] = {
16054           const_cast<ConstantFP*>(FV->getConstantFPValue()),
16055           const_cast<ConstantFP*>(TV->getConstantFPValue())
16056         };
16057         Type *FPTy = Elts[0]->getType();
16058         const DataLayout &TD = DAG.getDataLayout();
16059
16060         // Create a ConstantArray of the two constants.
16061         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
16062         SDValue CPIdx =
16063             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
16064                                 TD.getPrefTypeAlignment(FPTy));
16065         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
16066
16067         // Get the offsets to the 0 and 1 element of the array so that we can
16068         // select between them.
16069         SDValue Zero = DAG.getIntPtrConstant(0, DL);
16070         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
16071         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
16072
16073         SDValue Cond = DAG.getSetCC(DL,
16074                                     getSetCCResultType(N0.getValueType()),
16075                                     N0, N1, CC);
16076         AddToWorklist(Cond.getNode());
16077         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
16078                                           Cond, One, Zero);
16079         AddToWorklist(CstOffset.getNode());
16080         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
16081                             CstOffset);
16082         AddToWorklist(CPIdx.getNode());
16083         return DAG.getLoad(
16084             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
16085             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
16086             Alignment);
16087       }
16088     }
16089
16090   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
16091     return V;
16092
16093   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
16094   // where y is has a single bit set.
16095   // A plaintext description would be, we can turn the SELECT_CC into an AND
16096   // when the condition can be materialized as an all-ones register.  Any
16097   // single bit-test can be materialized as an all-ones register with
16098   // shift-left and shift-right-arith.
16099   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
16100       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
16101     SDValue AndLHS = N0->getOperand(0);
16102     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
16103     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
16104       // Shift the tested bit over the sign bit.
16105       const APInt &AndMask = ConstAndRHS->getAPIntValue();
16106       SDValue ShlAmt =
16107         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
16108                         getShiftAmountTy(AndLHS.getValueType()));
16109       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
16110
16111       // Now arithmetic right shift it all the way over, so the result is either
16112       // all-ones, or zero.
16113       SDValue ShrAmt =
16114         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
16115                         getShiftAmountTy(Shl.getValueType()));
16116       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
16117
16118       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
16119     }
16120   }
16121
16122   // fold select C, 16, 0 -> shl C, 4
16123   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
16124       TLI.getBooleanContents(N0.getValueType()) ==
16125           TargetLowering::ZeroOrOneBooleanContent) {
16126
16127     // If the caller doesn't want us to simplify this into a zext of a compare,
16128     // don't do it.
16129     if (NotExtCompare && N2C->isOne())
16130       return SDValue();
16131
16132     // Get a SetCC of the condition
16133     // NOTE: Don't create a SETCC if it's not legal on this target.
16134     if (!LegalOperations ||
16135         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
16136       SDValue Temp, SCC;
16137       // cast from setcc result type to select result type
16138       if (LegalTypes) {
16139         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
16140                             N0, N1, CC);
16141         if (N2.getValueType().bitsLT(SCC.getValueType()))
16142           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
16143                                         N2.getValueType());
16144         else
16145           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16146                              N2.getValueType(), SCC);
16147       } else {
16148         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
16149         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16150                            N2.getValueType(), SCC);
16151       }
16152
16153       AddToWorklist(SCC.getNode());
16154       AddToWorklist(Temp.getNode());
16155
16156       if (N2C->isOne())
16157         return Temp;
16158
16159       // shl setcc result by log2 n2c
16160       return DAG.getNode(
16161           ISD::SHL, DL, N2.getValueType(), Temp,
16162           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
16163                           getShiftAmountTy(Temp.getValueType())));
16164     }
16165   }
16166
16167   // Check to see if this is an integer abs.
16168   // select_cc setg[te] X,  0,  X, -X ->
16169   // select_cc setgt    X, -1,  X, -X ->
16170   // select_cc setl[te] X,  0, -X,  X ->
16171   // select_cc setlt    X,  1, -X,  X ->
16172   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
16173   if (N1C) {
16174     ConstantSDNode *SubC = nullptr;
16175     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
16176          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
16177         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
16178       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
16179     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
16180               (N1C->isOne() && CC == ISD::SETLT)) &&
16181              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
16182       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
16183
16184     EVT XType = N0.getValueType();
16185     if (SubC && SubC->isNullValue() && XType.isInteger()) {
16186       SDLoc DL(N0);
16187       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
16188                                   N0,
16189                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
16190                                          getShiftAmountTy(N0.getValueType())));
16191       SDValue Add = DAG.getNode(ISD::ADD, DL,
16192                                 XType, N0, Shift);
16193       AddToWorklist(Shift.getNode());
16194       AddToWorklist(Add.getNode());
16195       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
16196     }
16197   }
16198
16199   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
16200   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
16201   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
16202   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
16203   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
16204   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
16205   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
16206   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
16207   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
16208     SDValue ValueOnZero = N2;
16209     SDValue Count = N3;
16210     // If the condition is NE instead of E, swap the operands.
16211     if (CC == ISD::SETNE)
16212       std::swap(ValueOnZero, Count);
16213     // Check if the value on zero is a constant equal to the bits in the type.
16214     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
16215       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
16216         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
16217         // legal, combine to just cttz.
16218         if ((Count.getOpcode() == ISD::CTTZ ||
16219              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
16220             N0 == Count.getOperand(0) &&
16221             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
16222           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
16223         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
16224         // legal, combine to just ctlz.
16225         if ((Count.getOpcode() == ISD::CTLZ ||
16226              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
16227             N0 == Count.getOperand(0) &&
16228             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
16229           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
16230       }
16231     }
16232   }
16233
16234   return SDValue();
16235 }
16236
16237 /// This is a stub for TargetLowering::SimplifySetCC.
16238 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
16239                                    ISD::CondCode Cond, const SDLoc &DL,
16240                                    bool foldBooleans) {
16241   TargetLowering::DAGCombinerInfo
16242     DagCombineInfo(DAG, Level, false, this);
16243   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
16244 }
16245
16246 /// Given an ISD::SDIV node expressing a divide by constant, return
16247 /// a DAG expression to select that will generate the same value by multiplying
16248 /// by a magic number.
16249 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16250 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
16251   // when optimising for minimum size, we don't want to expand a div to a mul
16252   // and a shift.
16253   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16254     return SDValue();
16255
16256   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16257   if (!C)
16258     return SDValue();
16259
16260   // Avoid division by zero.
16261   if (C->isNullValue())
16262     return SDValue();
16263
16264   std::vector<SDNode*> Built;
16265   SDValue S =
16266       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16267
16268   for (SDNode *N : Built)
16269     AddToWorklist(N);
16270   return S;
16271 }
16272
16273 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
16274 /// DAG expression that will generate the same value by right shifting.
16275 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
16276   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16277   if (!C)
16278     return SDValue();
16279
16280   // Avoid division by zero.
16281   if (C->isNullValue())
16282     return SDValue();
16283
16284   std::vector<SDNode *> Built;
16285   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
16286
16287   for (SDNode *N : Built)
16288     AddToWorklist(N);
16289   return S;
16290 }
16291
16292 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
16293 /// expression that will generate the same value by multiplying by a magic
16294 /// number.
16295 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16296 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
16297   // when optimising for minimum size, we don't want to expand a div to a mul
16298   // and a shift.
16299   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16300     return SDValue();
16301
16302   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16303   if (!C)
16304     return SDValue();
16305
16306   // Avoid division by zero.
16307   if (C->isNullValue())
16308     return SDValue();
16309
16310   std::vector<SDNode*> Built;
16311   SDValue S =
16312       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16313
16314   for (SDNode *N : Built)
16315     AddToWorklist(N);
16316   return S;
16317 }
16318
16319 /// Determines the LogBase2 value for a non-null input value using the
16320 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
16321 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
16322   EVT VT = V.getValueType();
16323   unsigned EltBits = VT.getScalarSizeInBits();
16324   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
16325   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
16326   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
16327   return LogBase2;
16328 }
16329
16330 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16331 /// For the reciprocal, we need to find the zero of the function:
16332 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
16333 ///     =>
16334 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
16335 ///     does not require additional intermediate precision]
16336 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
16337   if (Level >= AfterLegalizeDAG)
16338     return SDValue();
16339
16340   // TODO: Handle half and/or extended types?
16341   EVT VT = Op.getValueType();
16342   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16343     return SDValue();
16344
16345   // If estimates are explicitly disabled for this function, we're done.
16346   MachineFunction &MF = DAG.getMachineFunction();
16347   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
16348   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16349     return SDValue();
16350
16351   // Estimates may be explicitly enabled for this type with a custom number of
16352   // refinement steps.
16353   int Iterations = TLI.getDivRefinementSteps(VT, MF);
16354   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
16355     AddToWorklist(Est.getNode());
16356
16357     if (Iterations) {
16358       EVT VT = Op.getValueType();
16359       SDLoc DL(Op);
16360       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
16361
16362       // Newton iterations: Est = Est + Est (1 - Arg * Est)
16363       for (int i = 0; i < Iterations; ++i) {
16364         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
16365         AddToWorklist(NewEst.getNode());
16366
16367         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
16368         AddToWorklist(NewEst.getNode());
16369
16370         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16371         AddToWorklist(NewEst.getNode());
16372
16373         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
16374         AddToWorklist(Est.getNode());
16375       }
16376     }
16377     return Est;
16378   }
16379
16380   return SDValue();
16381 }
16382
16383 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16384 /// For the reciprocal sqrt, we need to find the zero of the function:
16385 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16386 ///     =>
16387 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
16388 /// As a result, we precompute A/2 prior to the iteration loop.
16389 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
16390                                          unsigned Iterations,
16391                                          SDNodeFlags Flags, bool Reciprocal) {
16392   EVT VT = Arg.getValueType();
16393   SDLoc DL(Arg);
16394   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
16395
16396   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
16397   // this entire sequence requires only one FP constant.
16398   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
16399   AddToWorklist(HalfArg.getNode());
16400
16401   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
16402   AddToWorklist(HalfArg.getNode());
16403
16404   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
16405   for (unsigned i = 0; i < Iterations; ++i) {
16406     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
16407     AddToWorklist(NewEst.getNode());
16408
16409     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
16410     AddToWorklist(NewEst.getNode());
16411
16412     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
16413     AddToWorklist(NewEst.getNode());
16414
16415     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16416     AddToWorklist(Est.getNode());
16417   }
16418
16419   // If non-reciprocal square root is requested, multiply the result by Arg.
16420   if (!Reciprocal) {
16421     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
16422     AddToWorklist(Est.getNode());
16423   }
16424
16425   return Est;
16426 }
16427
16428 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16429 /// For the reciprocal sqrt, we need to find the zero of the function:
16430 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16431 ///     =>
16432 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
16433 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
16434                                          unsigned Iterations,
16435                                          SDNodeFlags Flags, bool Reciprocal) {
16436   EVT VT = Arg.getValueType();
16437   SDLoc DL(Arg);
16438   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
16439   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
16440
16441   // This routine must enter the loop below to work correctly
16442   // when (Reciprocal == false).
16443   assert(Iterations > 0);
16444
16445   // Newton iterations for reciprocal square root:
16446   // E = (E * -0.5) * ((A * E) * E + -3.0)
16447   for (unsigned i = 0; i < Iterations; ++i) {
16448     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
16449     AddToWorklist(AE.getNode());
16450
16451     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
16452     AddToWorklist(AEE.getNode());
16453
16454     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
16455     AddToWorklist(RHS.getNode());
16456
16457     // When calculating a square root at the last iteration build:
16458     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
16459     // (notice a common subexpression)
16460     SDValue LHS;
16461     if (Reciprocal || (i + 1) < Iterations) {
16462       // RSQRT: LHS = (E * -0.5)
16463       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
16464     } else {
16465       // SQRT: LHS = (A * E) * -0.5
16466       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
16467     }
16468     AddToWorklist(LHS.getNode());
16469
16470     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
16471     AddToWorklist(Est.getNode());
16472   }
16473
16474   return Est;
16475 }
16476
16477 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
16478 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
16479 /// Op can be zero.
16480 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
16481                                            bool Reciprocal) {
16482   if (Level >= AfterLegalizeDAG)
16483     return SDValue();
16484
16485   // TODO: Handle half and/or extended types?
16486   EVT VT = Op.getValueType();
16487   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16488     return SDValue();
16489
16490   // If estimates are explicitly disabled for this function, we're done.
16491   MachineFunction &MF = DAG.getMachineFunction();
16492   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
16493   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16494     return SDValue();
16495
16496   // Estimates may be explicitly enabled for this type with a custom number of
16497   // refinement steps.
16498   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
16499
16500   bool UseOneConstNR = false;
16501   if (SDValue Est =
16502       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
16503                           Reciprocal)) {
16504     AddToWorklist(Est.getNode());
16505
16506     if (Iterations) {
16507       Est = UseOneConstNR
16508             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16509             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16510
16511       if (!Reciprocal) {
16512         // Unfortunately, Est is now NaN if the input was exactly 0.0.
16513         // Select out this case and force the answer to 0.0.
16514         EVT VT = Op.getValueType();
16515         SDLoc DL(Op);
16516
16517         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16518         EVT CCVT = getSetCCResultType(VT);
16519         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16520         AddToWorklist(ZeroCmp.getNode());
16521
16522         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16523                           ZeroCmp, FPZero, Est);
16524         AddToWorklist(Est.getNode());
16525       }
16526     }
16527     return Est;
16528   }
16529
16530   return SDValue();
16531 }
16532
16533 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16534   return buildSqrtEstimateImpl(Op, Flags, true);
16535 }
16536
16537 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16538   return buildSqrtEstimateImpl(Op, Flags, false);
16539 }
16540
16541 /// Return true if base is a frame index, which is known not to alias with
16542 /// anything but itself.  Provides base object and offset as results.
16543 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16544                            const GlobalValue *&GV, const void *&CV) {
16545   // Assume it is a primitive operation.
16546   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16547
16548   // If it's an adding a simple constant then integrate the offset.
16549   if (Base.getOpcode() == ISD::ADD) {
16550     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16551       Base = Base.getOperand(0);
16552       Offset += C->getSExtValue();
16553     }
16554   }
16555
16556   // Return the underlying GlobalValue, and update the Offset.  Return false
16557   // for GlobalAddressSDNode since the same GlobalAddress may be represented
16558   // by multiple nodes with different offsets.
16559   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16560     GV = G->getGlobal();
16561     Offset += G->getOffset();
16562     return false;
16563   }
16564
16565   // Return the underlying Constant value, and update the Offset.  Return false
16566   // for ConstantSDNodes since the same constant pool entry may be represented
16567   // by multiple nodes with different offsets.
16568   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16569     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16570                                          : (const void *)C->getConstVal();
16571     Offset += C->getOffset();
16572     return false;
16573   }
16574   // If it's any of the following then it can't alias with anything but itself.
16575   return isa<FrameIndexSDNode>(Base);
16576 }
16577
16578 /// Return true if there is any possibility that the two addresses overlap.
16579 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16580   // If they are the same then they must be aliases.
16581   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16582
16583   // If they are both volatile then they cannot be reordered.
16584   if (Op0->isVolatile() && Op1->isVolatile()) return true;
16585
16586   // If one operation reads from invariant memory, and the other may store, they
16587   // cannot alias. These should really be checking the equivalent of mayWrite,
16588   // but it only matters for memory nodes other than load /store.
16589   if (Op0->isInvariant() && Op1->writeMem())
16590     return false;
16591
16592   if (Op1->isInvariant() && Op0->writeMem())
16593     return false;
16594
16595   unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16596   unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16597
16598   // Check for BaseIndexOffset matching.
16599   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
16600   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
16601   if (BasePtr0.equalBaseIndex(BasePtr1))
16602     return !((BasePtr0.Offset + NumBytes0 <= BasePtr1.Offset) ||
16603              (BasePtr1.Offset + NumBytes1 <= BasePtr0.Offset));
16604
16605   // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
16606   // modified to use BaseIndexOffset.
16607
16608   // Gather base node and offset information.
16609   SDValue Base0, Base1;
16610   int64_t Offset0, Offset1;
16611   const GlobalValue *GV0, *GV1;
16612   const void *CV0, *CV1;
16613   bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
16614                                       Base0, Offset0, GV0, CV0);
16615   bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
16616                                       Base1, Offset1, GV1, CV1);
16617
16618   // If they have the same base address, then check to see if they overlap.
16619   if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
16620     return !((Offset0 + NumBytes0) <= Offset1 ||
16621              (Offset1 + NumBytes1) <= Offset0);
16622
16623   // It is possible for different frame indices to alias each other, mostly
16624   // when tail call optimization reuses return address slots for arguments.
16625   // To catch this case, look up the actual index of frame indices to compute
16626   // the real alias relationship.
16627   if (IsFrameIndex0 && IsFrameIndex1) {
16628     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16629     Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
16630     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
16631     return !((Offset0 + NumBytes0) <= Offset1 ||
16632              (Offset1 + NumBytes1) <= Offset0);
16633   }
16634
16635   // Otherwise, if we know what the bases are, and they aren't identical, then
16636   // we know they cannot alias.
16637   if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
16638     return false;
16639
16640   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
16641   // compared to the size and offset of the access, we may be able to prove they
16642   // do not alias. This check is conservative for now to catch cases created by
16643   // splitting vector types.
16644   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
16645   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
16646   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
16647   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
16648   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
16649       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
16650     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
16651     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
16652
16653     // There is no overlap between these relatively aligned accesses of similar
16654     // size. Return no alias.
16655     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
16656         (OffAlign1 + NumBytes1) <= OffAlign0)
16657       return false;
16658   }
16659
16660   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
16661                    ? CombinerGlobalAA
16662                    : DAG.getSubtarget().useAA();
16663 #ifndef NDEBUG
16664   if (CombinerAAOnlyFunc.getNumOccurrences() &&
16665       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
16666     UseAA = false;
16667 #endif
16668
16669   if (UseAA && AA &&
16670       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
16671     // Use alias analysis information.
16672     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
16673     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
16674     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
16675     AliasResult AAResult =
16676         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
16677                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
16678                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
16679                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
16680     if (AAResult == NoAlias)
16681       return false;
16682   }
16683
16684   // Otherwise we have to assume they alias.
16685   return true;
16686 }
16687
16688 /// Walk up chain skipping non-aliasing memory nodes,
16689 /// looking for aliasing nodes and adding them to the Aliases vector.
16690 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
16691                                    SmallVectorImpl<SDValue> &Aliases) {
16692   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
16693   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
16694
16695   // Get alias information for node.
16696   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
16697
16698   // Starting off.
16699   Chains.push_back(OriginalChain);
16700   unsigned Depth = 0;
16701
16702   // Look at each chain and determine if it is an alias.  If so, add it to the
16703   // aliases list.  If not, then continue up the chain looking for the next
16704   // candidate.
16705   while (!Chains.empty()) {
16706     SDValue Chain = Chains.pop_back_val();
16707
16708     // For TokenFactor nodes, look at each operand and only continue up the
16709     // chain until we reach the depth limit.
16710     //
16711     // FIXME: The depth check could be made to return the last non-aliasing
16712     // chain we found before we hit a tokenfactor rather than the original
16713     // chain.
16714     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
16715       Aliases.clear();
16716       Aliases.push_back(OriginalChain);
16717       return;
16718     }
16719
16720     // Don't bother if we've been before.
16721     if (!Visited.insert(Chain.getNode()).second)
16722       continue;
16723
16724     switch (Chain.getOpcode()) {
16725     case ISD::EntryToken:
16726       // Entry token is ideal chain operand, but handled in FindBetterChain.
16727       break;
16728
16729     case ISD::LOAD:
16730     case ISD::STORE: {
16731       // Get alias information for Chain.
16732       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
16733           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
16734
16735       // If chain is alias then stop here.
16736       if (!(IsLoad && IsOpLoad) &&
16737           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
16738         Aliases.push_back(Chain);
16739       } else {
16740         // Look further up the chain.
16741         Chains.push_back(Chain.getOperand(0));
16742         ++Depth;
16743       }
16744       break;
16745     }
16746
16747     case ISD::TokenFactor:
16748       // We have to check each of the operands of the token factor for "small"
16749       // token factors, so we queue them up.  Adding the operands to the queue
16750       // (stack) in reverse order maintains the original order and increases the
16751       // likelihood that getNode will find a matching token factor (CSE.)
16752       if (Chain.getNumOperands() > 16) {
16753         Aliases.push_back(Chain);
16754         break;
16755       }
16756       for (unsigned n = Chain.getNumOperands(); n;)
16757         Chains.push_back(Chain.getOperand(--n));
16758       ++Depth;
16759       break;
16760
16761     case ISD::CopyFromReg:
16762       // Forward past CopyFromReg.
16763       Chains.push_back(Chain.getOperand(0));
16764       ++Depth;
16765       break;
16766
16767     default:
16768       // For all other instructions we will just have to take what we can get.
16769       Aliases.push_back(Chain);
16770       break;
16771     }
16772   }
16773 }
16774
16775 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
16776 /// (aliasing node.)
16777 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
16778   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
16779
16780   // Accumulate all the aliases to this node.
16781   GatherAllAliases(N, OldChain, Aliases);
16782
16783   // If no operands then chain to entry token.
16784   if (Aliases.size() == 0)
16785     return DAG.getEntryNode();
16786
16787   // If a single operand then chain to it.  We don't need to revisit it.
16788   if (Aliases.size() == 1)
16789     return Aliases[0];
16790
16791   // Construct a custom tailored token factor.
16792   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
16793 }
16794
16795 // This function tries to collect a bunch of potentially interesting
16796 // nodes to improve the chains of, all at once. This might seem
16797 // redundant, as this function gets called when visiting every store
16798 // node, so why not let the work be done on each store as it's visited?
16799 //
16800 // I believe this is mainly important because MergeConsecutiveStores
16801 // is unable to deal with merging stores of different sizes, so unless
16802 // we improve the chains of all the potential candidates up-front
16803 // before running MergeConsecutiveStores, it might only see some of
16804 // the nodes that will eventually be candidates, and then not be able
16805 // to go from a partially-merged state to the desired final
16806 // fully-merged state.
16807 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
16808   // This holds the base pointer, index, and the offset in bytes from the base
16809   // pointer.
16810   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
16811
16812   // We must have a base and an offset.
16813   if (!BasePtr.Base.getNode())
16814     return false;
16815
16816   // Do not handle stores to undef base pointers.
16817   if (BasePtr.Base.isUndef())
16818     return false;
16819
16820   SmallVector<StoreSDNode *, 8> ChainedStores;
16821   ChainedStores.push_back(St);
16822
16823   // Walk up the chain and look for nodes with offsets from the same
16824   // base pointer. Stop when reaching an instruction with a different kind
16825   // or instruction which has a different base pointer.
16826   StoreSDNode *Index = St;
16827   while (Index) {
16828     // If the chain has more than one use, then we can't reorder the mem ops.
16829     if (Index != St && !SDValue(Index, 0)->hasOneUse())
16830       break;
16831
16832     if (Index->isVolatile() || Index->isIndexed())
16833       break;
16834
16835     // Find the base pointer and offset for this memory node.
16836     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
16837
16838     // Check that the base pointer is the same as the original one.
16839     if (!Ptr.equalBaseIndex(BasePtr))
16840       break;
16841
16842     // Walk up the chain to find the next store node, ignoring any
16843     // intermediate loads. Any other kind of node will halt the loop.
16844     SDNode *NextInChain = Index->getChain().getNode();
16845     while (true) {
16846       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
16847         // We found a store node. Use it for the next iteration.
16848         if (STn->isVolatile() || STn->isIndexed()) {
16849           Index = nullptr;
16850           break;
16851         }
16852         ChainedStores.push_back(STn);
16853         Index = STn;
16854         break;
16855       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
16856         NextInChain = Ldn->getChain().getNode();
16857         continue;
16858       } else {
16859         Index = nullptr;
16860         break;
16861       }
16862     } // end while
16863   }
16864
16865   // At this point, ChainedStores lists all of the Store nodes
16866   // reachable by iterating up through chain nodes matching the above
16867   // conditions.  For each such store identified, try to find an
16868   // earlier chain to attach the store to which won't violate the
16869   // required ordering.
16870   bool MadeChangeToSt = false;
16871   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
16872
16873   for (StoreSDNode *ChainedStore : ChainedStores) {
16874     SDValue Chain = ChainedStore->getChain();
16875     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
16876
16877     if (Chain != BetterChain) {
16878       if (ChainedStore == St)
16879         MadeChangeToSt = true;
16880       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
16881     }
16882   }
16883
16884   // Do all replacements after finding the replacements to make to avoid making
16885   // the chains more complicated by introducing new TokenFactors.
16886   for (auto Replacement : BetterChains)
16887     replaceStoreChain(Replacement.first, Replacement.second);
16888
16889   return MadeChangeToSt;
16890 }
16891
16892 /// This is the entry point for the file.
16893 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
16894                            CodeGenOpt::Level OptLevel) {
16895   /// This is the main entry point to this class.
16896   DAGCombiner(*this, AA, OptLevel).Run(Level);
16897 }