1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 #include <algorithm>
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "dagcombine"
45 
46 STATISTIC(NodesCombined   , "Number of dag nodes combined");
47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
49 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
50 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
51 STATISTIC(SlicedLoads, "Number of load sliced");
52 
53 namespace {
54   static cl::opt<bool>
55     CombinerAA("combiner-alias-analysis", cl::Hidden,
56                cl::desc("Enable DAG combiner alias-analysis heuristics"));
57 
58   static cl::opt<bool>
59     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60                cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 
62   static cl::opt<bool>
63     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
64                cl::desc("Enable DAG combiner's use of TBAA"));
65 
66 #ifndef NDEBUG
67   static cl::opt<std::string>
68     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
69                cl::desc("Only use DAG-combiner alias analysis in this"
70                         " function"));
71 #endif
72 
73   /// Hidden option to stress test load slicing, i.e., when this option
74   /// is enabled, load slicing bypasses most of its profitability guards.
75   static cl::opt<bool>
76   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
77                     cl::desc("Bypass the profitability model of load "
78                              "slicing"),
79                     cl::init(false));
80 
81   static cl::opt<bool>
82     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
83                       cl::desc("DAG combiner may split indexing from loads"));
84 
85 //------------------------------ DAGCombiner ---------------------------------//
86 
87   class DAGCombiner {
88     SelectionDAG &DAG;
89     const TargetLowering &TLI;
90     CombineLevel Level;
91     CodeGenOpt::Level OptLevel;
92     bool LegalOperations;
93     bool LegalTypes;
94     bool ForCodeSize;
95 
96     /// \brief Worklist of all of the nodes that need to be simplified.
97     ///
98     /// This must behave as a stack -- new nodes to process are pushed onto the
99     /// back and when processing we pop off of the back.
100     ///
101     /// The worklist will not contain duplicates but may contain null entries
102     /// due to nodes being deleted from the underlying DAG.
103     SmallVector<SDNode *, 64> Worklist;
104 
105     /// \brief Mapping from an SDNode to its position on the worklist.
106     ///
107     /// This is used to find and remove nodes from the worklist (by nulling
108     /// them) when they are deleted from the underlying DAG. It relies on
109     /// stable indices of nodes within the worklist.
110     DenseMap<SDNode *, unsigned> WorklistMap;
111 
112     /// \brief Set of nodes which have been combined (at least once).
113     ///
114     /// This is used to allow us to reliably add any operands of a DAG node
115     /// which have not yet been combined to the worklist.
116     SmallPtrSet<SDNode *, 32> CombinedNodes;
117 
118     // AA - Used for DAG load/store alias analysis.
119     AliasAnalysis &AA;
120 
121     /// When an instruction is simplified, add all users of the instruction to
122     /// the work lists because they might get more simplified now.
123     void AddUsersToWorklist(SDNode *N) {
124       for (SDNode *Node : N->uses())
125         AddToWorklist(Node);
126     }
127 
128     /// Call the node-specific routine that folds each particular type of node.
129     SDValue visit(SDNode *N);
130 
131   public:
132     /// Add to the worklist making sure its instance is at the back (next to be
133     /// processed.)
134     void AddToWorklist(SDNode *N) {
135       // Skip handle nodes as they can't usefully be combined and confuse the
136       // zero-use deletion strategy.
137       if (N->getOpcode() == ISD::HANDLENODE)
138         return;
139 
140       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
141         Worklist.push_back(N);
142     }
143 
144     /// Remove all instances of N from the worklist.
145     void removeFromWorklist(SDNode *N) {
146       CombinedNodes.erase(N);
147 
148       auto It = WorklistMap.find(N);
149       if (It == WorklistMap.end())
150         return; // Not in the worklist.
151 
152       // Null out the entry rather than erasing it to avoid a linear operation.
153       Worklist[It->second] = nullptr;
154       WorklistMap.erase(It);
155     }
156 
157     void deleteAndRecombine(SDNode *N);
158     bool recursivelyDeleteUnusedNodes(SDNode *N);
159 
160     /// Replaces all uses of the results of one DAG node with new values.
161     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162                       bool AddTo = true);
163 
164     /// Replaces all uses of the results of one DAG node with new values.
165     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
166       return CombineTo(N, &Res, 1, AddTo);
167     }
168 
169     /// Replaces all uses of the results of one DAG node with new values.
170     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
171                       bool AddTo = true) {
172       SDValue To[] = { Res0, Res1 };
173       return CombineTo(N, To, 2, AddTo);
174     }
175 
176     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
177 
178   private:
179 
180     /// Check the specified integer node value to see if it can be simplified or
181     /// if things it uses can be simplified by bit propagation.
182     /// If so, return true.
183     bool SimplifyDemandedBits(SDValue Op) {
184       unsigned BitWidth = Op.getScalarValueSizeInBits();
185       APInt Demanded = APInt::getAllOnesValue(BitWidth);
186       return SimplifyDemandedBits(Op, Demanded);
187     }
188 
189     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
190 
191     bool CombineToPreIndexedLoadStore(SDNode *N);
192     bool CombineToPostIndexedLoadStore(SDNode *N);
193     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
194     bool SliceUpLoad(SDNode *N);
195 
196     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
197     ///   load.
198     ///
199     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
200     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
201     /// \param EltNo index of the vector element to load.
202     /// \param OriginalLoad load that EVE came from to be replaced.
203     /// \returns EVE on success SDValue() on failure.
204     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
205         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
206     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
207     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
208     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
210     SDValue PromoteIntBinOp(SDValue Op);
211     SDValue PromoteIntShiftOp(SDValue Op);
212     SDValue PromoteExtend(SDValue Op);
213     bool PromoteLoad(SDValue Op);
214 
215     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
216                          SDValue ExtLoad, const SDLoc &DL,
217                          ISD::NodeType ExtType);
218 
219     /// Call the node-specific routine that knows how to fold each
220     /// particular type of node. If that doesn't do anything, try the
221     /// target-specific DAG combines.
222     SDValue combine(SDNode *N);
223 
224     // Visitation implementation - Implement dag node combining for different
225     // node types.  The semantics are as follows:
226     // Return Value:
227     //   SDValue.getNode() == 0 - No change was made
228     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
229     //   otherwise              - N should be replaced by the returned Operand.
230     //
231     SDValue visitTokenFactor(SDNode *N);
232     SDValue visitMERGE_VALUES(SDNode *N);
233     SDValue visitADD(SDNode *N);
234     SDValue visitSUB(SDNode *N);
235     SDValue visitADDC(SDNode *N);
236     SDValue visitSUBC(SDNode *N);
237     SDValue visitADDE(SDNode *N);
238     SDValue visitSUBE(SDNode *N);
239     SDValue visitMUL(SDNode *N);
240     SDValue useDivRem(SDNode *N);
241     SDValue visitSDIV(SDNode *N);
242     SDValue visitUDIV(SDNode *N);
243     SDValue visitREM(SDNode *N);
244     SDValue visitMULHU(SDNode *N);
245     SDValue visitMULHS(SDNode *N);
246     SDValue visitSMUL_LOHI(SDNode *N);
247     SDValue visitUMUL_LOHI(SDNode *N);
248     SDValue visitSMULO(SDNode *N);
249     SDValue visitUMULO(SDNode *N);
250     SDValue visitIMINMAX(SDNode *N);
251     SDValue visitAND(SDNode *N);
252     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitOR(SDNode *N);
254     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
255     SDValue visitXOR(SDNode *N);
256     SDValue SimplifyVBinOp(SDNode *N);
257     SDValue visitSHL(SDNode *N);
258     SDValue visitSRA(SDNode *N);
259     SDValue visitSRL(SDNode *N);
260     SDValue visitRotate(SDNode *N);
261     SDValue visitBSWAP(SDNode *N);
262     SDValue visitBITREVERSE(SDNode *N);
263     SDValue visitCTLZ(SDNode *N);
264     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
265     SDValue visitCTTZ(SDNode *N);
266     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
267     SDValue visitCTPOP(SDNode *N);
268     SDValue visitSELECT(SDNode *N);
269     SDValue visitVSELECT(SDNode *N);
270     SDValue visitSELECT_CC(SDNode *N);
271     SDValue visitSETCC(SDNode *N);
272     SDValue visitSETCCE(SDNode *N);
273     SDValue visitSIGN_EXTEND(SDNode *N);
274     SDValue visitZERO_EXTEND(SDNode *N);
275     SDValue visitANY_EXTEND(SDNode *N);
276     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
277     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
278     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
279     SDValue visitTRUNCATE(SDNode *N);
280     SDValue visitBITCAST(SDNode *N);
281     SDValue visitBUILD_PAIR(SDNode *N);
282     SDValue visitFADD(SDNode *N);
283     SDValue visitFSUB(SDNode *N);
284     SDValue visitFMUL(SDNode *N);
285     SDValue visitFMA(SDNode *N);
286     SDValue visitFDIV(SDNode *N);
287     SDValue visitFREM(SDNode *N);
288     SDValue visitFSQRT(SDNode *N);
289     SDValue visitFCOPYSIGN(SDNode *N);
290     SDValue visitSINT_TO_FP(SDNode *N);
291     SDValue visitUINT_TO_FP(SDNode *N);
292     SDValue visitFP_TO_SINT(SDNode *N);
293     SDValue visitFP_TO_UINT(SDNode *N);
294     SDValue visitFP_ROUND(SDNode *N);
295     SDValue visitFP_ROUND_INREG(SDNode *N);
296     SDValue visitFP_EXTEND(SDNode *N);
297     SDValue visitFNEG(SDNode *N);
298     SDValue visitFABS(SDNode *N);
299     SDValue visitFCEIL(SDNode *N);
300     SDValue visitFTRUNC(SDNode *N);
301     SDValue visitFFLOOR(SDNode *N);
302     SDValue visitFMINNUM(SDNode *N);
303     SDValue visitFMAXNUM(SDNode *N);
304     SDValue visitBRCOND(SDNode *N);
305     SDValue visitBR_CC(SDNode *N);
306     SDValue visitLOAD(SDNode *N);
307 
308     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
309     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
310 
311     SDValue visitSTORE(SDNode *N);
312     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
313     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
314     SDValue visitBUILD_VECTOR(SDNode *N);
315     SDValue visitCONCAT_VECTORS(SDNode *N);
316     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
317     SDValue visitVECTOR_SHUFFLE(SDNode *N);
318     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
319     SDValue visitINSERT_SUBVECTOR(SDNode *N);
320     SDValue visitMLOAD(SDNode *N);
321     SDValue visitMSTORE(SDNode *N);
322     SDValue visitMGATHER(SDNode *N);
323     SDValue visitMSCATTER(SDNode *N);
324     SDValue visitFP_TO_FP16(SDNode *N);
325     SDValue visitFP16_TO_FP(SDNode *N);
326 
327     SDValue visitFADDForFMACombine(SDNode *N);
328     SDValue visitFSUBForFMACombine(SDNode *N);
329     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
330 
331     SDValue XformToShuffleWithZero(SDNode *N);
332     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
333                            SDValue RHS);
334 
335     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
336 
337     SDValue foldSelectOfConstants(SDNode *N);
338     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
339     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
340     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
341     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
342                              SDValue N2, SDValue N3, ISD::CondCode CC,
343                              bool NotExtCompare = false);
344     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
345                                    SDValue N2, SDValue N3, ISD::CondCode CC);
346     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
347                           const SDLoc &DL, bool foldBooleans = true);
348 
349     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
350                            SDValue &CC) const;
351     bool isOneUseSetCC(SDValue N) const;
352 
353     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
354                                          unsigned HiOp);
355     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
356     SDValue CombineExtLoad(SDNode *N);
357     SDValue combineRepeatedFPDivisors(SDNode *N);
358     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
359     SDValue BuildSDIV(SDNode *N);
360     SDValue BuildSDIVPow2(SDNode *N);
361     SDValue BuildUDIV(SDNode *N);
362     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
363     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
364     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
365     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
366     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
367                                 SDNodeFlags *Flags, bool Reciprocal);
368     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
369                                 SDNodeFlags *Flags, bool Reciprocal);
370     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
371                                bool DemandHighBits = true);
372     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
373     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
374                               SDValue InnerPos, SDValue InnerNeg,
375                               unsigned PosOpcode, unsigned NegOpcode,
376                               const SDLoc &DL);
377     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
378     SDValue ReduceLoadWidth(SDNode *N);
379     SDValue ReduceLoadOpStoreWidth(SDNode *N);
380     SDValue splitMergedValStore(StoreSDNode *ST);
381     SDValue TransformFPLoadStorePair(SDNode *N);
382     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
383     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
384     SDValue reduceBuildVecToShuffle(SDNode *N);
385     SDValue createBuildVecShuffle(SDLoc DL, SDNode *N, ArrayRef<int> VectorMask,
386                                   SDValue VecIn1, SDValue VecIn2,
387                                   unsigned LeftIdx);
388 
389     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
390 
391     /// Walk up chain skipping non-aliasing memory nodes,
392     /// looking for aliasing nodes and adding them to the Aliases vector.
393     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
394                           SmallVectorImpl<SDValue> &Aliases);
395 
396     /// Return true if there is any possibility that the two addresses overlap.
397     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
398 
399     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
400     /// chain (aliasing node.)
401     SDValue FindBetterChain(SDNode *N, SDValue Chain);
402 
403     /// Try to replace a store and any possibly adjacent stores on
404     /// consecutive chains with better chains. Return true only if St is
405     /// replaced.
406     ///
407     /// Notice that other chains may still be replaced even if the function
408     /// returns false.
409     bool findBetterNeighborChains(StoreSDNode *St);
410 
411     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
412     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
413 
414     /// Holds a pointer to an LSBaseSDNode as well as information on where it
415     /// is located in a sequence of memory operations connected by a chain.
416     struct MemOpLink {
417       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
418       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
419       // Ptr to the mem node.
420       LSBaseSDNode *MemNode;
421       // Offset from the base ptr.
422       int64_t OffsetFromBase;
423       // What is the sequence number of this mem node.
424       // Lowest mem operand in the DAG starts at zero.
425       unsigned SequenceNum;
426     };
427 
428     /// This is a helper function for visitMUL to check the profitability
429     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
430     /// MulNode is the original multiply, AddNode is (add x, c1),
431     /// and ConstNode is c2.
432     bool isMulAddWithConstProfitable(SDNode *MulNode,
433                                      SDValue &AddNode,
434                                      SDValue &ConstNode);
435 
436     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
437     /// constant build_vector of the stored constant values in Stores.
438     SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL,
439                                          ArrayRef<MemOpLink> Stores,
440                                          SmallVectorImpl<SDValue> &Chains,
441                                          EVT Ty) const;
442 
443     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
444     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
445     /// the type of the loaded value to be extended.  LoadedVT returns the type
446     /// of the original loaded value.  NarrowLoad returns whether the load would
447     /// need to be narrowed in order to match.
448     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
449                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
450                           bool &NarrowLoad);
451 
452     /// This is a helper function for MergeConsecutiveStores. When the source
453     /// elements of the consecutive stores are all constants or all extracted
454     /// vector elements, try to merge them into one larger store.
455     /// \return number of stores that were merged into a merged store (always
456     /// a prefix of \p StoreNode).
457     bool MergeStoresOfConstantsOrVecElts(
458         SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
459         bool IsConstantSrc, bool UseVector);
460 
461     /// This is a helper function for MergeConsecutiveStores.
462     /// Stores that may be merged are placed in StoreNodes.
463     /// Loads that may alias with those stores are placed in AliasLoadNodes.
464     void getStoreMergeAndAliasCandidates(
465         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
466         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
467 
468     /// Helper function for MergeConsecutiveStores. Checks if
469     /// Candidate stores have indirect dependency through their
470     /// operands. \return True if safe to merge
471     bool checkMergeStoreCandidatesForDependencies(
472         SmallVectorImpl<MemOpLink> &StoreNodes);
473 
474     /// Merge consecutive store operations into a wide store.
475     /// This optimization uses wide integers or vectors when possible.
476     /// \return number of stores that were merged into a merged store (the
477     /// affected nodes are stored as a prefix in \p StoreNodes).
478     bool MergeConsecutiveStores(StoreSDNode *N,
479                                 SmallVectorImpl<MemOpLink> &StoreNodes);
480 
481     /// \brief Try to transform a truncation where C is a constant:
482     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
483     ///
484     /// \p N needs to be a truncation and its first operand an AND. Other
485     /// requirements are checked by the function (e.g. that trunc is
486     /// single-use) and if missed an empty SDValue is returned.
487     SDValue distributeTruncateThroughAnd(SDNode *N);
488 
489   public:
490     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
491         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
492           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
493       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
494     }
495 
496     /// Runs the dag combiner on all nodes in the work list
497     void Run(CombineLevel AtLevel);
498 
499     SelectionDAG &getDAG() const { return DAG; }
500 
501     /// Returns a type large enough to hold any valid shift amount - before type
502     /// legalization these can be huge.
503     EVT getShiftAmountTy(EVT LHSTy) {
504       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
505       if (LHSTy.isVector())
506         return LHSTy;
507       auto &DL = DAG.getDataLayout();
508       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
509                         : TLI.getPointerTy(DL);
510     }
511 
512     /// This method returns true if we are running before type legalization or
513     /// if the specified VT is legal.
514     bool isTypeLegal(const EVT &VT) {
515       if (!LegalTypes) return true;
516       return TLI.isTypeLegal(VT);
517     }
518 
519     /// Convenience wrapper around TargetLowering::getSetCCResultType
520     EVT getSetCCResultType(EVT VT) const {
521       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
522     }
523   };
524 }
525 
526 
527 namespace {
528 /// This class is a DAGUpdateListener that removes any deleted
529 /// nodes from the worklist.
530 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
531   DAGCombiner &DC;
532 public:
533   explicit WorklistRemover(DAGCombiner &dc)
534     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
535 
536   void NodeDeleted(SDNode *N, SDNode *E) override {
537     DC.removeFromWorklist(N);
538   }
539 };
540 }
541 
542 //===----------------------------------------------------------------------===//
543 //  TargetLowering::DAGCombinerInfo implementation
544 //===----------------------------------------------------------------------===//
545 
546 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
547   ((DAGCombiner*)DC)->AddToWorklist(N);
548 }
549 
550 SDValue TargetLowering::DAGCombinerInfo::
551 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
552   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
553 }
554 
555 SDValue TargetLowering::DAGCombinerInfo::
556 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
557   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
558 }
559 
560 
561 SDValue TargetLowering::DAGCombinerInfo::
562 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
563   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
564 }
565 
566 void TargetLowering::DAGCombinerInfo::
567 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
568   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
569 }
570 
571 //===----------------------------------------------------------------------===//
572 // Helper Functions
573 //===----------------------------------------------------------------------===//
574 
575 void DAGCombiner::deleteAndRecombine(SDNode *N) {
576   removeFromWorklist(N);
577 
578   // If the operands of this node are only used by the node, they will now be
579   // dead. Make sure to re-visit them and recursively delete dead nodes.
580   for (const SDValue &Op : N->ops())
581     // For an operand generating multiple values, one of the values may
582     // become dead allowing further simplification (e.g. split index
583     // arithmetic from an indexed load).
584     if (Op->hasOneUse() || Op->getNumValues() > 1)
585       AddToWorklist(Op.getNode());
586 
587   DAG.DeleteNode(N);
588 }
589 
590 /// Return 1 if we can compute the negated form of the specified expression for
591 /// the same cost as the expression itself, or 2 if we can compute the negated
592 /// form more cheaply than the expression itself.
593 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
594                                const TargetLowering &TLI,
595                                const TargetOptions *Options,
596                                unsigned Depth = 0) {
597   // fneg is removable even if it has multiple uses.
598   if (Op.getOpcode() == ISD::FNEG) return 2;
599 
600   // Don't allow anything with multiple uses.
601   if (!Op.hasOneUse()) return 0;
602 
603   // Don't recurse exponentially.
604   if (Depth > 6) return 0;
605 
606   switch (Op.getOpcode()) {
607   default: return false;
608   case ISD::ConstantFP:
609     // Don't invert constant FP values after legalize.  The negated constant
610     // isn't necessarily legal.
611     return LegalOperations ? 0 : 1;
612   case ISD::FADD:
613     // FIXME: determine better conditions for this xform.
614     if (!Options->UnsafeFPMath) return 0;
615 
616     // After operation legalization, it might not be legal to create new FSUBs.
617     if (LegalOperations &&
618         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
619       return 0;
620 
621     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
622     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
623                                     Options, Depth + 1))
624       return V;
625     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
626     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
627                               Depth + 1);
628   case ISD::FSUB:
629     // We can't turn -(A-B) into B-A when we honor signed zeros.
630     if (!Options->UnsafeFPMath && !Op.getNode()->getFlags()->hasNoSignedZeros())
631       return 0;
632 
633     // fold (fneg (fsub A, B)) -> (fsub B, A)
634     return 1;
635 
636   case ISD::FMUL:
637   case ISD::FDIV:
638     if (Options->HonorSignDependentRoundingFPMath()) return 0;
639 
640     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
641     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
642                                     Options, Depth + 1))
643       return V;
644 
645     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
646                               Depth + 1);
647 
648   case ISD::FP_EXTEND:
649   case ISD::FP_ROUND:
650   case ISD::FSIN:
651     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
652                               Depth + 1);
653   }
654 }
655 
656 /// If isNegatibleForFree returns true, return the newly negated expression.
657 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
658                                     bool LegalOperations, unsigned Depth = 0) {
659   const TargetOptions &Options = DAG.getTarget().Options;
660   // fneg is removable even if it has multiple uses.
661   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
662 
663   // Don't allow anything with multiple uses.
664   assert(Op.hasOneUse() && "Unknown reuse!");
665 
666   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
667 
668   const SDNodeFlags *Flags = Op.getNode()->getFlags();
669 
670   switch (Op.getOpcode()) {
671   default: llvm_unreachable("Unknown code");
672   case ISD::ConstantFP: {
673     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
674     V.changeSign();
675     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
676   }
677   case ISD::FADD:
678     // FIXME: determine better conditions for this xform.
679     assert(Options.UnsafeFPMath);
680 
681     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
682     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
683                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
684       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
685                          GetNegatedExpression(Op.getOperand(0), DAG,
686                                               LegalOperations, Depth+1),
687                          Op.getOperand(1), Flags);
688     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
689     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
690                        GetNegatedExpression(Op.getOperand(1), DAG,
691                                             LegalOperations, Depth+1),
692                        Op.getOperand(0), Flags);
693   case ISD::FSUB:
694     // fold (fneg (fsub 0, B)) -> B
695     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
696       if (N0CFP->isZero())
697         return Op.getOperand(1);
698 
699     // fold (fneg (fsub A, B)) -> (fsub B, A)
700     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
701                        Op.getOperand(1), Op.getOperand(0), Flags);
702 
703   case ISD::FMUL:
704   case ISD::FDIV:
705     assert(!Options.HonorSignDependentRoundingFPMath());
706 
707     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
708     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
709                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
710       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
711                          GetNegatedExpression(Op.getOperand(0), DAG,
712                                               LegalOperations, Depth+1),
713                          Op.getOperand(1), Flags);
714 
715     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
716     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
717                        Op.getOperand(0),
718                        GetNegatedExpression(Op.getOperand(1), DAG,
719                                             LegalOperations, Depth+1), Flags);
720 
721   case ISD::FP_EXTEND:
722   case ISD::FSIN:
723     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
724                        GetNegatedExpression(Op.getOperand(0), DAG,
725                                             LegalOperations, Depth+1));
726   case ISD::FP_ROUND:
727       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
728                          GetNegatedExpression(Op.getOperand(0), DAG,
729                                               LegalOperations, Depth+1),
730                          Op.getOperand(1));
731   }
732 }
733 
734 // APInts must be the same size for most operations, this helper
735 // function zero extends the shorter of the pair so that they match.
736 // We provide an Offset so that we can create bitwidths that won't overflow.
737 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
738   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
739   LHS = LHS.zextOrSelf(Bits);
740   RHS = RHS.zextOrSelf(Bits);
741 }
742 
743 // Return true if this node is a setcc, or is a select_cc
744 // that selects between the target values used for true and false, making it
745 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
746 // the appropriate nodes based on the type of node we are checking. This
747 // simplifies life a bit for the callers.
748 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
749                                     SDValue &CC) const {
750   if (N.getOpcode() == ISD::SETCC) {
751     LHS = N.getOperand(0);
752     RHS = N.getOperand(1);
753     CC  = N.getOperand(2);
754     return true;
755   }
756 
757   if (N.getOpcode() != ISD::SELECT_CC ||
758       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
759       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
760     return false;
761 
762   if (TLI.getBooleanContents(N.getValueType()) ==
763       TargetLowering::UndefinedBooleanContent)
764     return false;
765 
766   LHS = N.getOperand(0);
767   RHS = N.getOperand(1);
768   CC  = N.getOperand(4);
769   return true;
770 }
771 
772 /// Return true if this is a SetCC-equivalent operation with only one use.
773 /// If this is true, it allows the users to invert the operation for free when
774 /// it is profitable to do so.
775 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
776   SDValue N0, N1, N2;
777   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
778     return true;
779   return false;
780 }
781 
782 // \brief Returns the SDNode if it is a constant float BuildVector
783 // or constant float.
784 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
785   if (isa<ConstantFPSDNode>(N))
786     return N.getNode();
787   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
788     return N.getNode();
789   return nullptr;
790 }
791 
792 // Determines if it is a constant integer or a build vector of constant
793 // integers (and undefs).
794 // Do not permit build vector implicit truncation.
795 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
796   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
797     return !(Const->isOpaque() && NoOpaques);
798   if (N.getOpcode() != ISD::BUILD_VECTOR)
799     return false;
800   unsigned BitWidth = N.getScalarValueSizeInBits();
801   for (const SDValue &Op : N->op_values()) {
802     if (Op.isUndef())
803       continue;
804     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
805     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
806         (Const->isOpaque() && NoOpaques))
807       return false;
808   }
809   return true;
810 }
811 
812 // Determines if it is a constant null integer or a splatted vector of a
813 // constant null integer (with no undefs).
814 // Build vector implicit truncation is not an issue for null values.
815 static bool isNullConstantOrNullSplatConstant(SDValue N) {
816   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
817     return Splat->isNullValue();
818   return false;
819 }
820 
821 // Determines if it is a constant integer of one or a splatted vector of a
822 // constant integer of one (with no undefs).
823 // Do not permit build vector implicit truncation.
824 static bool isOneConstantOrOneSplatConstant(SDValue N) {
825   unsigned BitWidth = N.getScalarValueSizeInBits();
826   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
827     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
828   return false;
829 }
830 
831 // Determines if it is a constant integer of all ones or a splatted vector of a
832 // constant integer of all ones (with no undefs).
833 // Do not permit build vector implicit truncation.
834 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
835   unsigned BitWidth = N.getScalarValueSizeInBits();
836   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
837     return Splat->isAllOnesValue() &&
838            Splat->getAPIntValue().getBitWidth() == BitWidth;
839   return false;
840 }
841 
842 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
843 // undef's.
844 static bool isAnyConstantBuildVector(const SDNode *N) {
845   return ISD::isBuildVectorOfConstantSDNodes(N) ||
846          ISD::isBuildVectorOfConstantFPSDNodes(N);
847 }
848 
849 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
850                                     SDValue N1) {
851   EVT VT = N0.getValueType();
852   if (N0.getOpcode() == Opc) {
853     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
854       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
855         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
856         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
857           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
858         return SDValue();
859       }
860       if (N0.hasOneUse()) {
861         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
862         // use
863         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
864         if (!OpNode.getNode())
865           return SDValue();
866         AddToWorklist(OpNode.getNode());
867         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
868       }
869     }
870   }
871 
872   if (N1.getOpcode() == Opc) {
873     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
874       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
875         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
876         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
877           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
878         return SDValue();
879       }
880       if (N1.hasOneUse()) {
881         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
882         // use
883         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
884         if (!OpNode.getNode())
885           return SDValue();
886         AddToWorklist(OpNode.getNode());
887         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
888       }
889     }
890   }
891 
892   return SDValue();
893 }
894 
895 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
896                                bool AddTo) {
897   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
898   ++NodesCombined;
899   DEBUG(dbgs() << "\nReplacing.1 ";
900         N->dump(&DAG);
901         dbgs() << "\nWith: ";
902         To[0].getNode()->dump(&DAG);
903         dbgs() << " and " << NumTo-1 << " other values\n");
904   for (unsigned i = 0, e = NumTo; i != e; ++i)
905     assert((!To[i].getNode() ||
906             N->getValueType(i) == To[i].getValueType()) &&
907            "Cannot combine value to value of different type!");
908 
909   WorklistRemover DeadNodes(*this);
910   DAG.ReplaceAllUsesWith(N, To);
911   if (AddTo) {
912     // Push the new nodes and any users onto the worklist
913     for (unsigned i = 0, e = NumTo; i != e; ++i) {
914       if (To[i].getNode()) {
915         AddToWorklist(To[i].getNode());
916         AddUsersToWorklist(To[i].getNode());
917       }
918     }
919   }
920 
921   // Finally, if the node is now dead, remove it from the graph.  The node
922   // may not be dead if the replacement process recursively simplified to
923   // something else needing this node.
924   if (N->use_empty())
925     deleteAndRecombine(N);
926   return SDValue(N, 0);
927 }
928 
929 void DAGCombiner::
930 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
931   // Replace all uses.  If any nodes become isomorphic to other nodes and
932   // are deleted, make sure to remove them from our worklist.
933   WorklistRemover DeadNodes(*this);
934   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
935 
936   // Push the new node and any (possibly new) users onto the worklist.
937   AddToWorklist(TLO.New.getNode());
938   AddUsersToWorklist(TLO.New.getNode());
939 
940   // Finally, if the node is now dead, remove it from the graph.  The node
941   // may not be dead if the replacement process recursively simplified to
942   // something else needing this node.
943   if (TLO.Old.getNode()->use_empty())
944     deleteAndRecombine(TLO.Old.getNode());
945 }
946 
947 /// Check the specified integer node value to see if it can be simplified or if
948 /// things it uses can be simplified by bit propagation. If so, return true.
949 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
950   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
951   APInt KnownZero, KnownOne;
952   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
953     return false;
954 
955   // Revisit the node.
956   AddToWorklist(Op.getNode());
957 
958   // Replace the old value with the new one.
959   ++NodesCombined;
960   DEBUG(dbgs() << "\nReplacing.2 ";
961         TLO.Old.getNode()->dump(&DAG);
962         dbgs() << "\nWith: ";
963         TLO.New.getNode()->dump(&DAG);
964         dbgs() << '\n');
965 
966   CommitTargetLoweringOpt(TLO);
967   return true;
968 }
969 
970 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
971   SDLoc DL(Load);
972   EVT VT = Load->getValueType(0);
973   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
974 
975   DEBUG(dbgs() << "\nReplacing.9 ";
976         Load->dump(&DAG);
977         dbgs() << "\nWith: ";
978         Trunc.getNode()->dump(&DAG);
979         dbgs() << '\n');
980   WorklistRemover DeadNodes(*this);
981   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
982   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
983   deleteAndRecombine(Load);
984   AddToWorklist(Trunc.getNode());
985 }
986 
987 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
988   Replace = false;
989   SDLoc DL(Op);
990   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
991     LoadSDNode *LD = cast<LoadSDNode>(Op);
992     EVT MemVT = LD->getMemoryVT();
993     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
994       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
995                                                        : ISD::EXTLOAD)
996       : LD->getExtensionType();
997     Replace = true;
998     return DAG.getExtLoad(ExtType, DL, PVT,
999                           LD->getChain(), LD->getBasePtr(),
1000                           MemVT, LD->getMemOperand());
1001   }
1002 
1003   unsigned Opc = Op.getOpcode();
1004   switch (Opc) {
1005   default: break;
1006   case ISD::AssertSext:
1007     return DAG.getNode(ISD::AssertSext, DL, PVT,
1008                        SExtPromoteOperand(Op.getOperand(0), PVT),
1009                        Op.getOperand(1));
1010   case ISD::AssertZext:
1011     return DAG.getNode(ISD::AssertZext, DL, PVT,
1012                        ZExtPromoteOperand(Op.getOperand(0), PVT),
1013                        Op.getOperand(1));
1014   case ISD::Constant: {
1015     unsigned ExtOpc =
1016       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1017     return DAG.getNode(ExtOpc, DL, PVT, Op);
1018   }
1019   }
1020 
1021   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1022     return SDValue();
1023   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1024 }
1025 
1026 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1027   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1028     return SDValue();
1029   EVT OldVT = Op.getValueType();
1030   SDLoc DL(Op);
1031   bool Replace = false;
1032   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1033   if (!NewOp.getNode())
1034     return SDValue();
1035   AddToWorklist(NewOp.getNode());
1036 
1037   if (Replace)
1038     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1039   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1040                      DAG.getValueType(OldVT));
1041 }
1042 
1043 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1044   EVT OldVT = Op.getValueType();
1045   SDLoc DL(Op);
1046   bool Replace = false;
1047   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1048   if (!NewOp.getNode())
1049     return SDValue();
1050   AddToWorklist(NewOp.getNode());
1051 
1052   if (Replace)
1053     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1054   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1055 }
1056 
1057 /// Promote the specified integer binary operation if the target indicates it is
1058 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1059 /// i32 since i16 instructions are longer.
1060 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1061   if (!LegalOperations)
1062     return SDValue();
1063 
1064   EVT VT = Op.getValueType();
1065   if (VT.isVector() || !VT.isInteger())
1066     return SDValue();
1067 
1068   // If operation type is 'undesirable', e.g. i16 on x86, consider
1069   // promoting it.
1070   unsigned Opc = Op.getOpcode();
1071   if (TLI.isTypeDesirableForOp(Opc, VT))
1072     return SDValue();
1073 
1074   EVT PVT = VT;
1075   // Consult target whether it is a good idea to promote this operation and
1076   // what's the right type to promote it to.
1077   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1078     assert(PVT != VT && "Don't know what type to promote to!");
1079 
1080     bool Replace0 = false;
1081     SDValue N0 = Op.getOperand(0);
1082     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1083     if (!NN0.getNode())
1084       return SDValue();
1085 
1086     bool Replace1 = false;
1087     SDValue N1 = Op.getOperand(1);
1088     SDValue NN1;
1089     if (N0 == N1)
1090       NN1 = NN0;
1091     else {
1092       NN1 = PromoteOperand(N1, PVT, Replace1);
1093       if (!NN1.getNode())
1094         return SDValue();
1095     }
1096 
1097     AddToWorklist(NN0.getNode());
1098     if (NN1.getNode())
1099       AddToWorklist(NN1.getNode());
1100 
1101     if (Replace0)
1102       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1103     if (Replace1)
1104       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1105 
1106     DEBUG(dbgs() << "\nPromoting ";
1107           Op.getNode()->dump(&DAG));
1108     SDLoc DL(Op);
1109     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1110                        DAG.getNode(Opc, DL, PVT, NN0, NN1));
1111   }
1112   return SDValue();
1113 }
1114 
1115 /// Promote the specified integer shift operation if the target indicates it is
1116 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1117 /// i32 since i16 instructions are longer.
1118 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1119   if (!LegalOperations)
1120     return SDValue();
1121 
1122   EVT VT = Op.getValueType();
1123   if (VT.isVector() || !VT.isInteger())
1124     return SDValue();
1125 
1126   // If operation type is 'undesirable', e.g. i16 on x86, consider
1127   // promoting it.
1128   unsigned Opc = Op.getOpcode();
1129   if (TLI.isTypeDesirableForOp(Opc, VT))
1130     return SDValue();
1131 
1132   EVT PVT = VT;
1133   // Consult target whether it is a good idea to promote this operation and
1134   // what's the right type to promote it to.
1135   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1136     assert(PVT != VT && "Don't know what type to promote to!");
1137 
1138     bool Replace = false;
1139     SDValue N0 = Op.getOperand(0);
1140     if (Opc == ISD::SRA)
1141       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1142     else if (Opc == ISD::SRL)
1143       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1144     else
1145       N0 = PromoteOperand(N0, PVT, Replace);
1146     if (!N0.getNode())
1147       return SDValue();
1148 
1149     AddToWorklist(N0.getNode());
1150     if (Replace)
1151       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1152 
1153     DEBUG(dbgs() << "\nPromoting ";
1154           Op.getNode()->dump(&DAG));
1155     SDLoc DL(Op);
1156     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1157                        DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1)));
1158   }
1159   return SDValue();
1160 }
1161 
1162 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1163   if (!LegalOperations)
1164     return SDValue();
1165 
1166   EVT VT = Op.getValueType();
1167   if (VT.isVector() || !VT.isInteger())
1168     return SDValue();
1169 
1170   // If operation type is 'undesirable', e.g. i16 on x86, consider
1171   // promoting it.
1172   unsigned Opc = Op.getOpcode();
1173   if (TLI.isTypeDesirableForOp(Opc, VT))
1174     return SDValue();
1175 
1176   EVT PVT = VT;
1177   // Consult target whether it is a good idea to promote this operation and
1178   // what's the right type to promote it to.
1179   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1180     assert(PVT != VT && "Don't know what type to promote to!");
1181     // fold (aext (aext x)) -> (aext x)
1182     // fold (aext (zext x)) -> (zext x)
1183     // fold (aext (sext x)) -> (sext x)
1184     DEBUG(dbgs() << "\nPromoting ";
1185           Op.getNode()->dump(&DAG));
1186     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1187   }
1188   return SDValue();
1189 }
1190 
1191 bool DAGCombiner::PromoteLoad(SDValue Op) {
1192   if (!LegalOperations)
1193     return false;
1194 
1195   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1196     return false;
1197 
1198   EVT VT = Op.getValueType();
1199   if (VT.isVector() || !VT.isInteger())
1200     return false;
1201 
1202   // If operation type is 'undesirable', e.g. i16 on x86, consider
1203   // promoting it.
1204   unsigned Opc = Op.getOpcode();
1205   if (TLI.isTypeDesirableForOp(Opc, VT))
1206     return false;
1207 
1208   EVT PVT = VT;
1209   // Consult target whether it is a good idea to promote this operation and
1210   // what's the right type to promote it to.
1211   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1212     assert(PVT != VT && "Don't know what type to promote to!");
1213 
1214     SDLoc DL(Op);
1215     SDNode *N = Op.getNode();
1216     LoadSDNode *LD = cast<LoadSDNode>(N);
1217     EVT MemVT = LD->getMemoryVT();
1218     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1219       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1220                                                        : ISD::EXTLOAD)
1221       : LD->getExtensionType();
1222     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1223                                    LD->getChain(), LD->getBasePtr(),
1224                                    MemVT, LD->getMemOperand());
1225     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1226 
1227     DEBUG(dbgs() << "\nPromoting ";
1228           N->dump(&DAG);
1229           dbgs() << "\nTo: ";
1230           Result.getNode()->dump(&DAG);
1231           dbgs() << '\n');
1232     WorklistRemover DeadNodes(*this);
1233     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1234     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1235     deleteAndRecombine(N);
1236     AddToWorklist(Result.getNode());
1237     return true;
1238   }
1239   return false;
1240 }
1241 
1242 /// \brief Recursively delete a node which has no uses and any operands for
1243 /// which it is the only use.
1244 ///
1245 /// Note that this both deletes the nodes and removes them from the worklist.
1246 /// It also adds any nodes who have had a user deleted to the worklist as they
1247 /// may now have only one use and subject to other combines.
1248 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1249   if (!N->use_empty())
1250     return false;
1251 
1252   SmallSetVector<SDNode *, 16> Nodes;
1253   Nodes.insert(N);
1254   do {
1255     N = Nodes.pop_back_val();
1256     if (!N)
1257       continue;
1258 
1259     if (N->use_empty()) {
1260       for (const SDValue &ChildN : N->op_values())
1261         Nodes.insert(ChildN.getNode());
1262 
1263       removeFromWorklist(N);
1264       DAG.DeleteNode(N);
1265     } else {
1266       AddToWorklist(N);
1267     }
1268   } while (!Nodes.empty());
1269   return true;
1270 }
1271 
1272 //===----------------------------------------------------------------------===//
1273 //  Main DAG Combiner implementation
1274 //===----------------------------------------------------------------------===//
1275 
1276 void DAGCombiner::Run(CombineLevel AtLevel) {
1277   // set the instance variables, so that the various visit routines may use it.
1278   Level = AtLevel;
1279   LegalOperations = Level >= AfterLegalizeVectorOps;
1280   LegalTypes = Level >= AfterLegalizeTypes;
1281 
1282   // Add all the dag nodes to the worklist.
1283   for (SDNode &Node : DAG.allnodes())
1284     AddToWorklist(&Node);
1285 
1286   // Create a dummy node (which is not added to allnodes), that adds a reference
1287   // to the root node, preventing it from being deleted, and tracking any
1288   // changes of the root.
1289   HandleSDNode Dummy(DAG.getRoot());
1290 
1291   // While the worklist isn't empty, find a node and try to combine it.
1292   while (!WorklistMap.empty()) {
1293     SDNode *N;
1294     // The Worklist holds the SDNodes in order, but it may contain null entries.
1295     do {
1296       N = Worklist.pop_back_val();
1297     } while (!N);
1298 
1299     bool GoodWorklistEntry = WorklistMap.erase(N);
1300     (void)GoodWorklistEntry;
1301     assert(GoodWorklistEntry &&
1302            "Found a worklist entry without a corresponding map entry!");
1303 
1304     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1305     // N is deleted from the DAG, since they too may now be dead or may have a
1306     // reduced number of uses, allowing other xforms.
1307     if (recursivelyDeleteUnusedNodes(N))
1308       continue;
1309 
1310     WorklistRemover DeadNodes(*this);
1311 
1312     // If this combine is running after legalizing the DAG, re-legalize any
1313     // nodes pulled off the worklist.
1314     if (Level == AfterLegalizeDAG) {
1315       SmallSetVector<SDNode *, 16> UpdatedNodes;
1316       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1317 
1318       for (SDNode *LN : UpdatedNodes) {
1319         AddToWorklist(LN);
1320         AddUsersToWorklist(LN);
1321       }
1322       if (!NIsValid)
1323         continue;
1324     }
1325 
1326     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1327 
1328     // Add any operands of the new node which have not yet been combined to the
1329     // worklist as well. Because the worklist uniques things already, this
1330     // won't repeatedly process the same operand.
1331     CombinedNodes.insert(N);
1332     for (const SDValue &ChildN : N->op_values())
1333       if (!CombinedNodes.count(ChildN.getNode()))
1334         AddToWorklist(ChildN.getNode());
1335 
1336     SDValue RV = combine(N);
1337 
1338     if (!RV.getNode())
1339       continue;
1340 
1341     ++NodesCombined;
1342 
1343     // If we get back the same node we passed in, rather than a new node or
1344     // zero, we know that the node must have defined multiple values and
1345     // CombineTo was used.  Since CombineTo takes care of the worklist
1346     // mechanics for us, we have no work to do in this case.
1347     if (RV.getNode() == N)
1348       continue;
1349 
1350     assert(N->getOpcode() != ISD::DELETED_NODE &&
1351            RV.getOpcode() != ISD::DELETED_NODE &&
1352            "Node was deleted but visit returned new node!");
1353 
1354     DEBUG(dbgs() << " ... into: ";
1355           RV.getNode()->dump(&DAG));
1356 
1357     if (N->getNumValues() == RV.getNode()->getNumValues())
1358       DAG.ReplaceAllUsesWith(N, RV.getNode());
1359     else {
1360       assert(N->getValueType(0) == RV.getValueType() &&
1361              N->getNumValues() == 1 && "Type mismatch");
1362       SDValue OpV = RV;
1363       DAG.ReplaceAllUsesWith(N, &OpV);
1364     }
1365 
1366     // Push the new node and any users onto the worklist
1367     AddToWorklist(RV.getNode());
1368     AddUsersToWorklist(RV.getNode());
1369 
1370     // Finally, if the node is now dead, remove it from the graph.  The node
1371     // may not be dead if the replacement process recursively simplified to
1372     // something else needing this node. This will also take care of adding any
1373     // operands which have lost a user to the worklist.
1374     recursivelyDeleteUnusedNodes(N);
1375   }
1376 
1377   // If the root changed (e.g. it was a dead load, update the root).
1378   DAG.setRoot(Dummy.getValue());
1379   DAG.RemoveDeadNodes();
1380 }
1381 
1382 SDValue DAGCombiner::visit(SDNode *N) {
1383   switch (N->getOpcode()) {
1384   default: break;
1385   case ISD::TokenFactor:        return visitTokenFactor(N);
1386   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1387   case ISD::ADD:                return visitADD(N);
1388   case ISD::SUB:                return visitSUB(N);
1389   case ISD::ADDC:               return visitADDC(N);
1390   case ISD::SUBC:               return visitSUBC(N);
1391   case ISD::ADDE:               return visitADDE(N);
1392   case ISD::SUBE:               return visitSUBE(N);
1393   case ISD::MUL:                return visitMUL(N);
1394   case ISD::SDIV:               return visitSDIV(N);
1395   case ISD::UDIV:               return visitUDIV(N);
1396   case ISD::SREM:
1397   case ISD::UREM:               return visitREM(N);
1398   case ISD::MULHU:              return visitMULHU(N);
1399   case ISD::MULHS:              return visitMULHS(N);
1400   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1401   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1402   case ISD::SMULO:              return visitSMULO(N);
1403   case ISD::UMULO:              return visitUMULO(N);
1404   case ISD::SMIN:
1405   case ISD::SMAX:
1406   case ISD::UMIN:
1407   case ISD::UMAX:               return visitIMINMAX(N);
1408   case ISD::AND:                return visitAND(N);
1409   case ISD::OR:                 return visitOR(N);
1410   case ISD::XOR:                return visitXOR(N);
1411   case ISD::SHL:                return visitSHL(N);
1412   case ISD::SRA:                return visitSRA(N);
1413   case ISD::SRL:                return visitSRL(N);
1414   case ISD::ROTR:
1415   case ISD::ROTL:               return visitRotate(N);
1416   case ISD::BSWAP:              return visitBSWAP(N);
1417   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1418   case ISD::CTLZ:               return visitCTLZ(N);
1419   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1420   case ISD::CTTZ:               return visitCTTZ(N);
1421   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1422   case ISD::CTPOP:              return visitCTPOP(N);
1423   case ISD::SELECT:             return visitSELECT(N);
1424   case ISD::VSELECT:            return visitVSELECT(N);
1425   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1426   case ISD::SETCC:              return visitSETCC(N);
1427   case ISD::SETCCE:             return visitSETCCE(N);
1428   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1429   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1430   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1431   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1432   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1433   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1434   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1435   case ISD::BITCAST:            return visitBITCAST(N);
1436   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1437   case ISD::FADD:               return visitFADD(N);
1438   case ISD::FSUB:               return visitFSUB(N);
1439   case ISD::FMUL:               return visitFMUL(N);
1440   case ISD::FMA:                return visitFMA(N);
1441   case ISD::FDIV:               return visitFDIV(N);
1442   case ISD::FREM:               return visitFREM(N);
1443   case ISD::FSQRT:              return visitFSQRT(N);
1444   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1445   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1446   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1447   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1448   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1449   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1450   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1451   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1452   case ISD::FNEG:               return visitFNEG(N);
1453   case ISD::FABS:               return visitFABS(N);
1454   case ISD::FFLOOR:             return visitFFLOOR(N);
1455   case ISD::FMINNUM:            return visitFMINNUM(N);
1456   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1457   case ISD::FCEIL:              return visitFCEIL(N);
1458   case ISD::FTRUNC:             return visitFTRUNC(N);
1459   case ISD::BRCOND:             return visitBRCOND(N);
1460   case ISD::BR_CC:              return visitBR_CC(N);
1461   case ISD::LOAD:               return visitLOAD(N);
1462   case ISD::STORE:              return visitSTORE(N);
1463   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1464   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1465   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1466   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1467   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1468   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1469   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1470   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1471   case ISD::MGATHER:            return visitMGATHER(N);
1472   case ISD::MLOAD:              return visitMLOAD(N);
1473   case ISD::MSCATTER:           return visitMSCATTER(N);
1474   case ISD::MSTORE:             return visitMSTORE(N);
1475   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1476   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1477   }
1478   return SDValue();
1479 }
1480 
1481 SDValue DAGCombiner::combine(SDNode *N) {
1482   SDValue RV = visit(N);
1483 
1484   // If nothing happened, try a target-specific DAG combine.
1485   if (!RV.getNode()) {
1486     assert(N->getOpcode() != ISD::DELETED_NODE &&
1487            "Node was deleted but visit returned NULL!");
1488 
1489     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1490         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1491 
1492       // Expose the DAG combiner to the target combiner impls.
1493       TargetLowering::DAGCombinerInfo
1494         DagCombineInfo(DAG, Level, false, this);
1495 
1496       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1497     }
1498   }
1499 
1500   // If nothing happened still, try promoting the operation.
1501   if (!RV.getNode()) {
1502     switch (N->getOpcode()) {
1503     default: break;
1504     case ISD::ADD:
1505     case ISD::SUB:
1506     case ISD::MUL:
1507     case ISD::AND:
1508     case ISD::OR:
1509     case ISD::XOR:
1510       RV = PromoteIntBinOp(SDValue(N, 0));
1511       break;
1512     case ISD::SHL:
1513     case ISD::SRA:
1514     case ISD::SRL:
1515       RV = PromoteIntShiftOp(SDValue(N, 0));
1516       break;
1517     case ISD::SIGN_EXTEND:
1518     case ISD::ZERO_EXTEND:
1519     case ISD::ANY_EXTEND:
1520       RV = PromoteExtend(SDValue(N, 0));
1521       break;
1522     case ISD::LOAD:
1523       if (PromoteLoad(SDValue(N, 0)))
1524         RV = SDValue(N, 0);
1525       break;
1526     }
1527   }
1528 
1529   // If N is a commutative binary node, try commuting it to enable more
1530   // sdisel CSE.
1531   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1532       N->getNumValues() == 1) {
1533     SDValue N0 = N->getOperand(0);
1534     SDValue N1 = N->getOperand(1);
1535 
1536     // Constant operands are canonicalized to RHS.
1537     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1538       SDValue Ops[] = {N1, N0};
1539       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1540                                             N->getFlags());
1541       if (CSENode)
1542         return SDValue(CSENode, 0);
1543     }
1544   }
1545 
1546   return RV;
1547 }
1548 
1549 /// Given a node, return its input chain if it has one, otherwise return a null
1550 /// sd operand.
1551 static SDValue getInputChainForNode(SDNode *N) {
1552   if (unsigned NumOps = N->getNumOperands()) {
1553     if (N->getOperand(0).getValueType() == MVT::Other)
1554       return N->getOperand(0);
1555     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1556       return N->getOperand(NumOps-1);
1557     for (unsigned i = 1; i < NumOps-1; ++i)
1558       if (N->getOperand(i).getValueType() == MVT::Other)
1559         return N->getOperand(i);
1560   }
1561   return SDValue();
1562 }
1563 
1564 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1565   // If N has two operands, where one has an input chain equal to the other,
1566   // the 'other' chain is redundant.
1567   if (N->getNumOperands() == 2) {
1568     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1569       return N->getOperand(0);
1570     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1571       return N->getOperand(1);
1572   }
1573 
1574   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1575   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1576   SmallPtrSet<SDNode*, 16> SeenOps;
1577   bool Changed = false;             // If we should replace this token factor.
1578 
1579   // Start out with this token factor.
1580   TFs.push_back(N);
1581 
1582   // Iterate through token factors.  The TFs grows when new token factors are
1583   // encountered.
1584   for (unsigned i = 0; i < TFs.size(); ++i) {
1585     SDNode *TF = TFs[i];
1586 
1587     // Check each of the operands.
1588     for (const SDValue &Op : TF->op_values()) {
1589 
1590       switch (Op.getOpcode()) {
1591       case ISD::EntryToken:
1592         // Entry tokens don't need to be added to the list. They are
1593         // redundant.
1594         Changed = true;
1595         break;
1596 
1597       case ISD::TokenFactor:
1598         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1599           // Queue up for processing.
1600           TFs.push_back(Op.getNode());
1601           // Clean up in case the token factor is removed.
1602           AddToWorklist(Op.getNode());
1603           Changed = true;
1604           break;
1605         }
1606         LLVM_FALLTHROUGH;
1607 
1608       default:
1609         // Only add if it isn't already in the list.
1610         if (SeenOps.insert(Op.getNode()).second)
1611           Ops.push_back(Op);
1612         else
1613           Changed = true;
1614         break;
1615       }
1616     }
1617   }
1618 
1619   SDValue Result;
1620 
1621   // If we've changed things around then replace token factor.
1622   if (Changed) {
1623     if (Ops.empty()) {
1624       // The entry token is the only possible outcome.
1625       Result = DAG.getEntryNode();
1626     } else {
1627       // New and improved token factor.
1628       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1629     }
1630 
1631     // Add users to worklist if AA is enabled, since it may introduce
1632     // a lot of new chained token factors while removing memory deps.
1633     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1634       : DAG.getSubtarget().useAA();
1635     return CombineTo(N, Result, UseAA /*add to worklist*/);
1636   }
1637 
1638   return Result;
1639 }
1640 
1641 /// MERGE_VALUES can always be eliminated.
1642 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1643   WorklistRemover DeadNodes(*this);
1644   // Replacing results may cause a different MERGE_VALUES to suddenly
1645   // be CSE'd with N, and carry its uses with it. Iterate until no
1646   // uses remain, to ensure that the node can be safely deleted.
1647   // First add the users of this node to the work list so that they
1648   // can be tried again once they have new operands.
1649   AddUsersToWorklist(N);
1650   do {
1651     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1652       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1653   } while (!N->use_empty());
1654   deleteAndRecombine(N);
1655   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1656 }
1657 
1658 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1659 /// ConstantSDNode pointer else nullptr.
1660 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1661   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1662   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1663 }
1664 
1665 SDValue DAGCombiner::visitADD(SDNode *N) {
1666   SDValue N0 = N->getOperand(0);
1667   SDValue N1 = N->getOperand(1);
1668   EVT VT = N0.getValueType();
1669   SDLoc DL(N);
1670 
1671   // fold vector ops
1672   if (VT.isVector()) {
1673     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1674       return FoldedVOp;
1675 
1676     // fold (add x, 0) -> x, vector edition
1677     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1678       return N0;
1679     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1680       return N1;
1681   }
1682 
1683   // fold (add x, undef) -> undef
1684   if (N0.isUndef())
1685     return N0;
1686 
1687   if (N1.isUndef())
1688     return N1;
1689 
1690   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1691     // canonicalize constant to RHS
1692     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1693       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1694     // fold (add c1, c2) -> c1+c2
1695     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1696                                       N1.getNode());
1697   }
1698 
1699   // fold (add x, 0) -> x
1700   if (isNullConstant(N1))
1701     return N0;
1702 
1703   // fold ((c1-A)+c2) -> (c1+c2)-A
1704   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1705     if (N0.getOpcode() == ISD::SUB)
1706       if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1707         return DAG.getNode(ISD::SUB, DL, VT,
1708                            DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1709                            N0.getOperand(1));
1710       }
1711   }
1712 
1713   // reassociate add
1714   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1715     return RADD;
1716 
1717   // fold ((0-A) + B) -> B-A
1718   if (N0.getOpcode() == ISD::SUB &&
1719       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1720     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1721 
1722   // fold (A + (0-B)) -> A-B
1723   if (N1.getOpcode() == ISD::SUB &&
1724       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1725     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1726 
1727   // fold (A+(B-A)) -> B
1728   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1729     return N1.getOperand(0);
1730 
1731   // fold ((B-A)+A) -> B
1732   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1733     return N0.getOperand(0);
1734 
1735   // fold (A+(B-(A+C))) to (B-C)
1736   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1737       N0 == N1.getOperand(1).getOperand(0))
1738     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1739                        N1.getOperand(1).getOperand(1));
1740 
1741   // fold (A+(B-(C+A))) to (B-C)
1742   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1743       N0 == N1.getOperand(1).getOperand(1))
1744     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1745                        N1.getOperand(1).getOperand(0));
1746 
1747   // fold (A+((B-A)+or-C)) to (B+or-C)
1748   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1749       N1.getOperand(0).getOpcode() == ISD::SUB &&
1750       N0 == N1.getOperand(0).getOperand(1))
1751     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1752                        N1.getOperand(1));
1753 
1754   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1755   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1756     SDValue N00 = N0.getOperand(0);
1757     SDValue N01 = N0.getOperand(1);
1758     SDValue N10 = N1.getOperand(0);
1759     SDValue N11 = N1.getOperand(1);
1760 
1761     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1762       return DAG.getNode(ISD::SUB, DL, VT,
1763                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1764                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1765   }
1766 
1767   if (SimplifyDemandedBits(SDValue(N, 0)))
1768     return SDValue(N, 0);
1769 
1770   // fold (a+b) -> (a|b) iff a and b share no bits.
1771   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1772       VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1773     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1774 
1775   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1776   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1777       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1778     return DAG.getNode(ISD::SUB, DL, VT, N0,
1779                        DAG.getNode(ISD::SHL, DL, VT,
1780                                    N1.getOperand(0).getOperand(1),
1781                                    N1.getOperand(1)));
1782   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1783       isNullConstantOrNullSplatConstant(N0.getOperand(0).getOperand(0)))
1784     return DAG.getNode(ISD::SUB, DL, VT, N1,
1785                        DAG.getNode(ISD::SHL, DL, VT,
1786                                    N0.getOperand(0).getOperand(1),
1787                                    N0.getOperand(1)));
1788 
1789   if (N1.getOpcode() == ISD::AND) {
1790     SDValue AndOp0 = N1.getOperand(0);
1791     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1792     unsigned DestBits = VT.getScalarSizeInBits();
1793 
1794     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1795     // and similar xforms where the inner op is either ~0 or 0.
1796     if (NumSignBits == DestBits &&
1797         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1798       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1799   }
1800 
1801   // add (sext i1), X -> sub X, (zext i1)
1802   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1803       N0.getOperand(0).getValueType() == MVT::i1 &&
1804       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1805     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1806     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1807   }
1808 
1809   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1810   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1811     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1812     if (TN->getVT() == MVT::i1) {
1813       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1814                                  DAG.getConstant(1, DL, VT));
1815       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1816     }
1817   }
1818 
1819   return SDValue();
1820 }
1821 
1822 SDValue DAGCombiner::visitADDC(SDNode *N) {
1823   SDValue N0 = N->getOperand(0);
1824   SDValue N1 = N->getOperand(1);
1825   EVT VT = N0.getValueType();
1826 
1827   // If the flag result is dead, turn this into an ADD.
1828   if (!N->hasAnyUseOfValue(1))
1829     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1830                      DAG.getNode(ISD::CARRY_FALSE,
1831                                  SDLoc(N), MVT::Glue));
1832 
1833   // canonicalize constant to RHS.
1834   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1835   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1836   if (N0C && !N1C)
1837     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1838 
1839   // fold (addc x, 0) -> x + no carry out
1840   if (isNullConstant(N1))
1841     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1842                                         SDLoc(N), MVT::Glue));
1843 
1844   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1845   APInt LHSZero, LHSOne;
1846   APInt RHSZero, RHSOne;
1847   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1848 
1849   if (LHSZero.getBoolValue()) {
1850     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1851 
1852     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1853     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1854     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1855       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1856                        DAG.getNode(ISD::CARRY_FALSE,
1857                                    SDLoc(N), MVT::Glue));
1858   }
1859 
1860   return SDValue();
1861 }
1862 
1863 SDValue DAGCombiner::visitADDE(SDNode *N) {
1864   SDValue N0 = N->getOperand(0);
1865   SDValue N1 = N->getOperand(1);
1866   SDValue CarryIn = N->getOperand(2);
1867 
1868   // canonicalize constant to RHS
1869   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1870   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1871   if (N0C && !N1C)
1872     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1873                        N1, N0, CarryIn);
1874 
1875   // fold (adde x, y, false) -> (addc x, y)
1876   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1877     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1878 
1879   return SDValue();
1880 }
1881 
1882 // Since it may not be valid to emit a fold to zero for vector initializers
1883 // check if we can before folding.
1884 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
1885                              SelectionDAG &DAG, bool LegalOperations,
1886                              bool LegalTypes) {
1887   if (!VT.isVector())
1888     return DAG.getConstant(0, DL, VT);
1889   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1890     return DAG.getConstant(0, DL, VT);
1891   return SDValue();
1892 }
1893 
1894 SDValue DAGCombiner::visitSUB(SDNode *N) {
1895   SDValue N0 = N->getOperand(0);
1896   SDValue N1 = N->getOperand(1);
1897   EVT VT = N0.getValueType();
1898   SDLoc DL(N);
1899 
1900   // fold vector ops
1901   if (VT.isVector()) {
1902     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1903       return FoldedVOp;
1904 
1905     // fold (sub x, 0) -> x, vector edition
1906     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1907       return N0;
1908   }
1909 
1910   // fold (sub x, x) -> 0
1911   // FIXME: Refactor this and xor and other similar operations together.
1912   if (N0 == N1)
1913     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
1914   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1915       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1916     // fold (sub c1, c2) -> c1-c2
1917     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
1918                                       N1.getNode());
1919   }
1920 
1921   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1922 
1923   // fold (sub x, c) -> (add x, -c)
1924   if (N1C) {
1925     return DAG.getNode(ISD::ADD, DL, VT, N0,
1926                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1927   }
1928 
1929   if (isNullConstantOrNullSplatConstant(N0)) {
1930     unsigned BitWidth = VT.getScalarSizeInBits();
1931     // Right-shifting everything out but the sign bit followed by negation is
1932     // the same as flipping arithmetic/logical shift type without the negation:
1933     // -(X >>u 31) -> (X >>s 31)
1934     // -(X >>s 31) -> (X >>u 31)
1935     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
1936       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
1937       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
1938         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
1939         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
1940           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
1941       }
1942     }
1943 
1944     // 0 - X --> 0 if the sub is NUW.
1945     if (N->getFlags()->hasNoUnsignedWrap())
1946       return N0;
1947 
1948     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignBit(BitWidth))) {
1949       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
1950       // N1 must be 0 because negating the minimum signed value is undefined.
1951       if (N->getFlags()->hasNoSignedWrap())
1952         return N0;
1953 
1954       // 0 - X --> X if X is 0 or the minimum signed value.
1955       return N1;
1956     }
1957   }
1958 
1959   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1960   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
1961     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
1962 
1963   // fold A-(A-B) -> B
1964   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1965     return N1.getOperand(1);
1966 
1967   // fold (A+B)-A -> B
1968   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1969     return N0.getOperand(1);
1970 
1971   // fold (A+B)-B -> A
1972   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1973     return N0.getOperand(0);
1974 
1975   // fold C2-(A+C1) -> (C2-C1)-A
1976   if (N1.getOpcode() == ISD::ADD) {
1977     SDValue N11 = N1.getOperand(1);
1978     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
1979         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
1980       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
1981       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
1982     }
1983   }
1984 
1985   // fold ((A+(B+or-C))-B) -> A+or-C
1986   if (N0.getOpcode() == ISD::ADD &&
1987       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1988        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1989       N0.getOperand(1).getOperand(0) == N1)
1990     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
1991                        N0.getOperand(1).getOperand(1));
1992 
1993   // fold ((A+(C+B))-B) -> A+C
1994   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
1995       N0.getOperand(1).getOperand(1) == N1)
1996     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
1997                        N0.getOperand(1).getOperand(0));
1998 
1999   // fold ((A-(B-C))-C) -> A-B
2000   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2001       N0.getOperand(1).getOperand(1) == N1)
2002     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2003                        N0.getOperand(1).getOperand(0));
2004 
2005   // If either operand of a sub is undef, the result is undef
2006   if (N0.isUndef())
2007     return N0;
2008   if (N1.isUndef())
2009     return N1;
2010 
2011   // If the relocation model supports it, consider symbol offsets.
2012   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2013     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2014       // fold (sub Sym, c) -> Sym-c
2015       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2016         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2017                                     GA->getOffset() -
2018                                         (uint64_t)N1C->getSExtValue());
2019       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2020       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2021         if (GA->getGlobal() == GB->getGlobal())
2022           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2023                                  DL, VT);
2024     }
2025 
2026   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2027   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2028     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2029     if (TN->getVT() == MVT::i1) {
2030       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2031                                  DAG.getConstant(1, DL, VT));
2032       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2033     }
2034   }
2035 
2036   return SDValue();
2037 }
2038 
2039 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2040   SDValue N0 = N->getOperand(0);
2041   SDValue N1 = N->getOperand(1);
2042   EVT VT = N0.getValueType();
2043   SDLoc DL(N);
2044 
2045   // If the flag result is dead, turn this into an SUB.
2046   if (!N->hasAnyUseOfValue(1))
2047     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2048                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2049 
2050   // fold (subc x, x) -> 0 + no borrow
2051   if (N0 == N1)
2052     return CombineTo(N, DAG.getConstant(0, DL, VT),
2053                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2054 
2055   // fold (subc x, 0) -> x + no borrow
2056   if (isNullConstant(N1))
2057     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2058 
2059   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2060   if (isAllOnesConstant(N0))
2061     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2062                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2063 
2064   return SDValue();
2065 }
2066 
2067 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2068   SDValue N0 = N->getOperand(0);
2069   SDValue N1 = N->getOperand(1);
2070   SDValue CarryIn = N->getOperand(2);
2071 
2072   // fold (sube x, y, false) -> (subc x, y)
2073   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2074     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2075 
2076   return SDValue();
2077 }
2078 
2079 SDValue DAGCombiner::visitMUL(SDNode *N) {
2080   SDValue N0 = N->getOperand(0);
2081   SDValue N1 = N->getOperand(1);
2082   EVT VT = N0.getValueType();
2083 
2084   // fold (mul x, undef) -> 0
2085   if (N0.isUndef() || N1.isUndef())
2086     return DAG.getConstant(0, SDLoc(N), VT);
2087 
2088   bool N0IsConst = false;
2089   bool N1IsConst = false;
2090   bool N1IsOpaqueConst = false;
2091   bool N0IsOpaqueConst = false;
2092   APInt ConstValue0, ConstValue1;
2093   // fold vector ops
2094   if (VT.isVector()) {
2095     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2096       return FoldedVOp;
2097 
2098     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2099     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2100   } else {
2101     N0IsConst = isa<ConstantSDNode>(N0);
2102     if (N0IsConst) {
2103       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2104       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2105     }
2106     N1IsConst = isa<ConstantSDNode>(N1);
2107     if (N1IsConst) {
2108       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2109       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2110     }
2111   }
2112 
2113   // fold (mul c1, c2) -> c1*c2
2114   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2115     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2116                                       N0.getNode(), N1.getNode());
2117 
2118   // canonicalize constant to RHS (vector doesn't have to splat)
2119   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2120      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2121     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2122   // fold (mul x, 0) -> 0
2123   if (N1IsConst && ConstValue1 == 0)
2124     return N1;
2125   // We require a splat of the entire scalar bit width for non-contiguous
2126   // bit patterns.
2127   bool IsFullSplat =
2128     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2129   // fold (mul x, 1) -> x
2130   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2131     return N0;
2132   // fold (mul x, -1) -> 0-x
2133   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2134     SDLoc DL(N);
2135     return DAG.getNode(ISD::SUB, DL, VT,
2136                        DAG.getConstant(0, DL, VT), N0);
2137   }
2138   // fold (mul x, (1 << c)) -> x << c
2139   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2140       IsFullSplat) {
2141     SDLoc DL(N);
2142     return DAG.getNode(ISD::SHL, DL, VT, N0,
2143                        DAG.getConstant(ConstValue1.logBase2(), DL,
2144                                        getShiftAmountTy(N0.getValueType())));
2145   }
2146   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2147   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2148       IsFullSplat) {
2149     unsigned Log2Val = (-ConstValue1).logBase2();
2150     SDLoc DL(N);
2151     // FIXME: If the input is something that is easily negated (e.g. a
2152     // single-use add), we should put the negate there.
2153     return DAG.getNode(ISD::SUB, DL, VT,
2154                        DAG.getConstant(0, DL, VT),
2155                        DAG.getNode(ISD::SHL, DL, VT, N0,
2156                             DAG.getConstant(Log2Val, DL,
2157                                       getShiftAmountTy(N0.getValueType()))));
2158   }
2159 
2160   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2161   if (N0.getOpcode() == ISD::SHL &&
2162       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2163       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2164     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2165     if (isConstantOrConstantVector(C3))
2166       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2167   }
2168 
2169   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2170   // use.
2171   {
2172     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2173 
2174     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2175     if (N0.getOpcode() == ISD::SHL &&
2176         isConstantOrConstantVector(N0.getOperand(1)) &&
2177         N0.getNode()->hasOneUse()) {
2178       Sh = N0; Y = N1;
2179     } else if (N1.getOpcode() == ISD::SHL &&
2180                isConstantOrConstantVector(N1.getOperand(1)) &&
2181                N1.getNode()->hasOneUse()) {
2182       Sh = N1; Y = N0;
2183     }
2184 
2185     if (Sh.getNode()) {
2186       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2187       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2188     }
2189   }
2190 
2191   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2192   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2193       N0.getOpcode() == ISD::ADD &&
2194       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2195       isMulAddWithConstProfitable(N, N0, N1))
2196       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2197                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2198                                      N0.getOperand(0), N1),
2199                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2200                                      N0.getOperand(1), N1));
2201 
2202   // reassociate mul
2203   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2204     return RMUL;
2205 
2206   return SDValue();
2207 }
2208 
2209 /// Return true if divmod libcall is available.
2210 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2211                                      const TargetLowering &TLI) {
2212   RTLIB::Libcall LC;
2213   EVT NodeType = Node->getValueType(0);
2214   if (!NodeType.isSimple())
2215     return false;
2216   switch (NodeType.getSimpleVT().SimpleTy) {
2217   default: return false; // No libcall for vector types.
2218   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2219   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2220   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2221   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2222   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2223   }
2224 
2225   return TLI.getLibcallName(LC) != nullptr;
2226 }
2227 
2228 /// Issue divrem if both quotient and remainder are needed.
2229 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2230   if (Node->use_empty())
2231     return SDValue(); // This is a dead node, leave it alone.
2232 
2233   unsigned Opcode = Node->getOpcode();
2234   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2235   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2236 
2237   // DivMod lib calls can still work on non-legal types if using lib-calls.
2238   EVT VT = Node->getValueType(0);
2239   if (VT.isVector() || !VT.isInteger())
2240     return SDValue();
2241 
2242   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2243     return SDValue();
2244 
2245   // If DIVREM is going to get expanded into a libcall,
2246   // but there is no libcall available, then don't combine.
2247   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2248       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2249     return SDValue();
2250 
2251   // If div is legal, it's better to do the normal expansion
2252   unsigned OtherOpcode = 0;
2253   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2254     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2255     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2256       return SDValue();
2257   } else {
2258     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2259     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2260       return SDValue();
2261   }
2262 
2263   SDValue Op0 = Node->getOperand(0);
2264   SDValue Op1 = Node->getOperand(1);
2265   SDValue combined;
2266   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2267          UE = Op0.getNode()->use_end(); UI != UE;) {
2268     SDNode *User = *UI++;
2269     if (User == Node || User->use_empty())
2270       continue;
2271     // Convert the other matching node(s), too;
2272     // otherwise, the DIVREM may get target-legalized into something
2273     // target-specific that we won't be able to recognize.
2274     unsigned UserOpc = User->getOpcode();
2275     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2276         User->getOperand(0) == Op0 &&
2277         User->getOperand(1) == Op1) {
2278       if (!combined) {
2279         if (UserOpc == OtherOpcode) {
2280           SDVTList VTs = DAG.getVTList(VT, VT);
2281           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2282         } else if (UserOpc == DivRemOpc) {
2283           combined = SDValue(User, 0);
2284         } else {
2285           assert(UserOpc == Opcode);
2286           continue;
2287         }
2288       }
2289       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2290         CombineTo(User, combined);
2291       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2292         CombineTo(User, combined.getValue(1));
2293     }
2294   }
2295   return combined;
2296 }
2297 
2298 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2299   SDValue N0 = N->getOperand(0);
2300   SDValue N1 = N->getOperand(1);
2301   EVT VT = N->getValueType(0);
2302 
2303   // fold vector ops
2304   if (VT.isVector())
2305     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2306       return FoldedVOp;
2307 
2308   SDLoc DL(N);
2309 
2310   // fold (sdiv c1, c2) -> c1/c2
2311   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2312   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2313   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2314     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2315   // fold (sdiv X, 1) -> X
2316   if (N1C && N1C->isOne())
2317     return N0;
2318   // fold (sdiv X, -1) -> 0-X
2319   if (N1C && N1C->isAllOnesValue())
2320     return DAG.getNode(ISD::SUB, DL, VT,
2321                        DAG.getConstant(0, DL, VT), N0);
2322 
2323   // If we know the sign bits of both operands are zero, strength reduce to a
2324   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2325   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2326     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2327 
2328   // fold (sdiv X, pow2) -> simple ops after legalize
2329   // FIXME: We check for the exact bit here because the generic lowering gives
2330   // better results in that case. The target-specific lowering should learn how
2331   // to handle exact sdivs efficiently.
2332   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2333       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2334       (N1C->getAPIntValue().isPowerOf2() ||
2335        (-N1C->getAPIntValue()).isPowerOf2())) {
2336     // Target-specific implementation of sdiv x, pow2.
2337     if (SDValue Res = BuildSDIVPow2(N))
2338       return Res;
2339 
2340     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2341 
2342     // Splat the sign bit into the register
2343     SDValue SGN =
2344         DAG.getNode(ISD::SRA, DL, VT, N0,
2345                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2346                                     getShiftAmountTy(N0.getValueType())));
2347     AddToWorklist(SGN.getNode());
2348 
2349     // Add (N0 < 0) ? abs2 - 1 : 0;
2350     SDValue SRL =
2351         DAG.getNode(ISD::SRL, DL, VT, SGN,
2352                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2353                                     getShiftAmountTy(SGN.getValueType())));
2354     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2355     AddToWorklist(SRL.getNode());
2356     AddToWorklist(ADD.getNode());    // Divide by pow2
2357     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2358                   DAG.getConstant(lg2, DL,
2359                                   getShiftAmountTy(ADD.getValueType())));
2360 
2361     // If we're dividing by a positive value, we're done.  Otherwise, we must
2362     // negate the result.
2363     if (N1C->getAPIntValue().isNonNegative())
2364       return SRA;
2365 
2366     AddToWorklist(SRA.getNode());
2367     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2368   }
2369 
2370   // If integer divide is expensive and we satisfy the requirements, emit an
2371   // alternate sequence.  Targets may check function attributes for size/speed
2372   // trade-offs.
2373   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2374   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2375     if (SDValue Op = BuildSDIV(N))
2376       return Op;
2377 
2378   // sdiv, srem -> sdivrem
2379   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2380   // true.  Otherwise, we break the simplification logic in visitREM().
2381   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2382     if (SDValue DivRem = useDivRem(N))
2383         return DivRem;
2384 
2385   // undef / X -> 0
2386   if (N0.isUndef())
2387     return DAG.getConstant(0, DL, VT);
2388   // X / undef -> undef
2389   if (N1.isUndef())
2390     return N1;
2391 
2392   return SDValue();
2393 }
2394 
2395 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2396   SDValue N0 = N->getOperand(0);
2397   SDValue N1 = N->getOperand(1);
2398   EVT VT = N->getValueType(0);
2399 
2400   // fold vector ops
2401   if (VT.isVector())
2402     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2403       return FoldedVOp;
2404 
2405   SDLoc DL(N);
2406 
2407   // fold (udiv c1, c2) -> c1/c2
2408   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2409   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2410   if (N0C && N1C)
2411     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2412                                                     N0C, N1C))
2413       return Folded;
2414 
2415   // fold (udiv x, (1 << c)) -> x >>u c
2416   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2417     return DAG.getNode(ISD::SRL, DL, VT, N0,
2418                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2419                                        getShiftAmountTy(N0.getValueType())));
2420 
2421   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2422   if (N1.getOpcode() == ISD::SHL) {
2423     if (ConstantSDNode *SHC = isConstOrConstSplat(N1.getOperand(0))) {
2424       if (!SHC->isOpaque() && SHC->getAPIntValue().isPowerOf2()) {
2425         EVT ADDVT = N1.getOperand(1).getValueType();
2426         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2427                                   N1.getOperand(1),
2428                                   DAG.getConstant(SHC->getAPIntValue()
2429                                                                   .logBase2(),
2430                                                   DL, ADDVT));
2431         AddToWorklist(Add.getNode());
2432         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2433       }
2434     }
2435   }
2436 
2437   // fold (udiv x, c) -> alternate
2438   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2439   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2440     if (SDValue Op = BuildUDIV(N))
2441       return Op;
2442 
2443   // sdiv, srem -> sdivrem
2444   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2445   // true.  Otherwise, we break the simplification logic in visitREM().
2446   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2447     if (SDValue DivRem = useDivRem(N))
2448         return DivRem;
2449 
2450   // undef / X -> 0
2451   if (N0.isUndef())
2452     return DAG.getConstant(0, DL, VT);
2453   // X / undef -> undef
2454   if (N1.isUndef())
2455     return N1;
2456 
2457   return SDValue();
2458 }
2459 
2460 // handles ISD::SREM and ISD::UREM
2461 SDValue DAGCombiner::visitREM(SDNode *N) {
2462   unsigned Opcode = N->getOpcode();
2463   SDValue N0 = N->getOperand(0);
2464   SDValue N1 = N->getOperand(1);
2465   EVT VT = N->getValueType(0);
2466   bool isSigned = (Opcode == ISD::SREM);
2467   SDLoc DL(N);
2468 
2469   // fold (rem c1, c2) -> c1%c2
2470   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2471   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2472   if (N0C && N1C)
2473     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2474       return Folded;
2475 
2476   if (isSigned) {
2477     // If we know the sign bits of both operands are zero, strength reduce to a
2478     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2479     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2480       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2481   } else {
2482     // fold (urem x, pow2) -> (and x, pow2-1)
2483     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2484         N1C->getAPIntValue().isPowerOf2()) {
2485       return DAG.getNode(ISD::AND, DL, VT, N0,
2486                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2487     }
2488     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2489     if (N1.getOpcode() == ISD::SHL) {
2490       ConstantSDNode *SHC = isConstOrConstSplat(N1.getOperand(0));
2491       if (SHC && !SHC->isOpaque() && SHC->getAPIntValue().isPowerOf2()) {
2492         APInt NegOne = APInt::getAllOnesValue(VT.getScalarSizeInBits());
2493         SDValue Add =
2494             DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2495         AddToWorklist(Add.getNode());
2496         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2497       }
2498     }
2499   }
2500 
2501   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2502 
2503   // If X/C can be simplified by the division-by-constant logic, lower
2504   // X%C to the equivalent of X-X/C*C.
2505   // To avoid mangling nodes, this simplification requires that the combine()
2506   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2507   // against this by skipping the simplification if isIntDivCheap().  When
2508   // div is not cheap, combine will not return a DIVREM.  Regardless,
2509   // checking cheapness here makes sense since the simplification results in
2510   // fatter code.
2511   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2512     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2513     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2514     AddToWorklist(Div.getNode());
2515     SDValue OptimizedDiv = combine(Div.getNode());
2516     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2517       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2518              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2519       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2520       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2521       AddToWorklist(Mul.getNode());
2522       return Sub;
2523     }
2524   }
2525 
2526   // sdiv, srem -> sdivrem
2527   if (SDValue DivRem = useDivRem(N))
2528     return DivRem.getValue(1);
2529 
2530   // undef % X -> 0
2531   if (N0.isUndef())
2532     return DAG.getConstant(0, DL, VT);
2533   // X % undef -> undef
2534   if (N1.isUndef())
2535     return N1;
2536 
2537   return SDValue();
2538 }
2539 
2540 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2541   SDValue N0 = N->getOperand(0);
2542   SDValue N1 = N->getOperand(1);
2543   EVT VT = N->getValueType(0);
2544   SDLoc DL(N);
2545 
2546   // fold (mulhs x, 0) -> 0
2547   if (isNullConstant(N1))
2548     return N1;
2549   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2550   if (isOneConstant(N1)) {
2551     SDLoc DL(N);
2552     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2553                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2554                                        getShiftAmountTy(N0.getValueType())));
2555   }
2556   // fold (mulhs x, undef) -> 0
2557   if (N0.isUndef() || N1.isUndef())
2558     return DAG.getConstant(0, SDLoc(N), VT);
2559 
2560   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2561   // plus a shift.
2562   if (VT.isSimple() && !VT.isVector()) {
2563     MVT Simple = VT.getSimpleVT();
2564     unsigned SimpleSize = Simple.getSizeInBits();
2565     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2566     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2567       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2568       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2569       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2570       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2571             DAG.getConstant(SimpleSize, DL,
2572                             getShiftAmountTy(N1.getValueType())));
2573       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2574     }
2575   }
2576 
2577   return SDValue();
2578 }
2579 
2580 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2581   SDValue N0 = N->getOperand(0);
2582   SDValue N1 = N->getOperand(1);
2583   EVT VT = N->getValueType(0);
2584   SDLoc DL(N);
2585 
2586   // fold (mulhu x, 0) -> 0
2587   if (isNullConstant(N1))
2588     return N1;
2589   // fold (mulhu x, 1) -> 0
2590   if (isOneConstant(N1))
2591     return DAG.getConstant(0, DL, N0.getValueType());
2592   // fold (mulhu x, undef) -> 0
2593   if (N0.isUndef() || N1.isUndef())
2594     return DAG.getConstant(0, DL, VT);
2595 
2596   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2597   // plus a shift.
2598   if (VT.isSimple() && !VT.isVector()) {
2599     MVT Simple = VT.getSimpleVT();
2600     unsigned SimpleSize = Simple.getSizeInBits();
2601     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2602     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2603       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2604       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2605       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2606       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2607             DAG.getConstant(SimpleSize, DL,
2608                             getShiftAmountTy(N1.getValueType())));
2609       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2610     }
2611   }
2612 
2613   return SDValue();
2614 }
2615 
2616 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2617 /// give the opcodes for the two computations that are being performed. Return
2618 /// true if a simplification was made.
2619 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2620                                                 unsigned HiOp) {
2621   // If the high half is not needed, just compute the low half.
2622   bool HiExists = N->hasAnyUseOfValue(1);
2623   if (!HiExists &&
2624       (!LegalOperations ||
2625        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2626     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2627     return CombineTo(N, Res, Res);
2628   }
2629 
2630   // If the low half is not needed, just compute the high half.
2631   bool LoExists = N->hasAnyUseOfValue(0);
2632   if (!LoExists &&
2633       (!LegalOperations ||
2634        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2635     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2636     return CombineTo(N, Res, Res);
2637   }
2638 
2639   // If both halves are used, return as it is.
2640   if (LoExists && HiExists)
2641     return SDValue();
2642 
2643   // If the two computed results can be simplified separately, separate them.
2644   if (LoExists) {
2645     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2646     AddToWorklist(Lo.getNode());
2647     SDValue LoOpt = combine(Lo.getNode());
2648     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2649         (!LegalOperations ||
2650          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2651       return CombineTo(N, LoOpt, LoOpt);
2652   }
2653 
2654   if (HiExists) {
2655     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2656     AddToWorklist(Hi.getNode());
2657     SDValue HiOpt = combine(Hi.getNode());
2658     if (HiOpt.getNode() && HiOpt != Hi &&
2659         (!LegalOperations ||
2660          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2661       return CombineTo(N, HiOpt, HiOpt);
2662   }
2663 
2664   return SDValue();
2665 }
2666 
2667 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2668   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2669     return Res;
2670 
2671   EVT VT = N->getValueType(0);
2672   SDLoc DL(N);
2673 
2674   // If the type is twice as wide is legal, transform the mulhu to a wider
2675   // multiply plus a shift.
2676   if (VT.isSimple() && !VT.isVector()) {
2677     MVT Simple = VT.getSimpleVT();
2678     unsigned SimpleSize = Simple.getSizeInBits();
2679     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2680     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2681       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2682       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2683       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2684       // Compute the high part as N1.
2685       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2686             DAG.getConstant(SimpleSize, DL,
2687                             getShiftAmountTy(Lo.getValueType())));
2688       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2689       // Compute the low part as N0.
2690       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2691       return CombineTo(N, Lo, Hi);
2692     }
2693   }
2694 
2695   return SDValue();
2696 }
2697 
2698 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2699   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2700     return Res;
2701 
2702   EVT VT = N->getValueType(0);
2703   SDLoc DL(N);
2704 
2705   // If the type is twice as wide is legal, transform the mulhu to a wider
2706   // multiply plus a shift.
2707   if (VT.isSimple() && !VT.isVector()) {
2708     MVT Simple = VT.getSimpleVT();
2709     unsigned SimpleSize = Simple.getSizeInBits();
2710     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2711     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2712       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2713       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2714       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2715       // Compute the high part as N1.
2716       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2717             DAG.getConstant(SimpleSize, DL,
2718                             getShiftAmountTy(Lo.getValueType())));
2719       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2720       // Compute the low part as N0.
2721       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2722       return CombineTo(N, Lo, Hi);
2723     }
2724   }
2725 
2726   return SDValue();
2727 }
2728 
2729 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2730   // (smulo x, 2) -> (saddo x, x)
2731   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2732     if (C2->getAPIntValue() == 2)
2733       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2734                          N->getOperand(0), N->getOperand(0));
2735 
2736   return SDValue();
2737 }
2738 
2739 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2740   // (umulo x, 2) -> (uaddo x, x)
2741   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2742     if (C2->getAPIntValue() == 2)
2743       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2744                          N->getOperand(0), N->getOperand(0));
2745 
2746   return SDValue();
2747 }
2748 
2749 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2750   SDValue N0 = N->getOperand(0);
2751   SDValue N1 = N->getOperand(1);
2752   EVT VT = N0.getValueType();
2753 
2754   // fold vector ops
2755   if (VT.isVector())
2756     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2757       return FoldedVOp;
2758 
2759   // fold (add c1, c2) -> c1+c2
2760   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2761   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2762   if (N0C && N1C)
2763     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2764 
2765   // canonicalize constant to RHS
2766   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2767      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2768     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2769 
2770   return SDValue();
2771 }
2772 
2773 /// If this is a binary operator with two operands of the same opcode, try to
2774 /// simplify it.
2775 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2776   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2777   EVT VT = N0.getValueType();
2778   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2779 
2780   // Bail early if none of these transforms apply.
2781   if (N0.getNumOperands() == 0) return SDValue();
2782 
2783   // For each of OP in AND/OR/XOR:
2784   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2785   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2786   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2787   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2788   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2789   //
2790   // do not sink logical op inside of a vector extend, since it may combine
2791   // into a vsetcc.
2792   EVT Op0VT = N0.getOperand(0).getValueType();
2793   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2794        N0.getOpcode() == ISD::SIGN_EXTEND ||
2795        N0.getOpcode() == ISD::BSWAP ||
2796        // Avoid infinite looping with PromoteIntBinOp.
2797        (N0.getOpcode() == ISD::ANY_EXTEND &&
2798         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2799        (N0.getOpcode() == ISD::TRUNCATE &&
2800         (!TLI.isZExtFree(VT, Op0VT) ||
2801          !TLI.isTruncateFree(Op0VT, VT)) &&
2802         TLI.isTypeLegal(Op0VT))) &&
2803       !VT.isVector() &&
2804       Op0VT == N1.getOperand(0).getValueType() &&
2805       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2806     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2807                                  N0.getOperand(0).getValueType(),
2808                                  N0.getOperand(0), N1.getOperand(0));
2809     AddToWorklist(ORNode.getNode());
2810     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2811   }
2812 
2813   // For each of OP in SHL/SRL/SRA/AND...
2814   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2815   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2816   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2817   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2818        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2819       N0.getOperand(1) == N1.getOperand(1)) {
2820     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2821                                  N0.getOperand(0).getValueType(),
2822                                  N0.getOperand(0), N1.getOperand(0));
2823     AddToWorklist(ORNode.getNode());
2824     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2825                        ORNode, N0.getOperand(1));
2826   }
2827 
2828   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2829   // Only perform this optimization up until type legalization, before
2830   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2831   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2832   // we don't want to undo this promotion.
2833   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2834   // on scalars.
2835   if ((N0.getOpcode() == ISD::BITCAST ||
2836        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2837        Level <= AfterLegalizeTypes) {
2838     SDValue In0 = N0.getOperand(0);
2839     SDValue In1 = N1.getOperand(0);
2840     EVT In0Ty = In0.getValueType();
2841     EVT In1Ty = In1.getValueType();
2842     SDLoc DL(N);
2843     // If both incoming values are integers, and the original types are the
2844     // same.
2845     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2846       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2847       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2848       AddToWorklist(Op.getNode());
2849       return BC;
2850     }
2851   }
2852 
2853   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2854   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2855   // If both shuffles use the same mask, and both shuffle within a single
2856   // vector, then it is worthwhile to move the swizzle after the operation.
2857   // The type-legalizer generates this pattern when loading illegal
2858   // vector types from memory. In many cases this allows additional shuffle
2859   // optimizations.
2860   // There are other cases where moving the shuffle after the xor/and/or
2861   // is profitable even if shuffles don't perform a swizzle.
2862   // If both shuffles use the same mask, and both shuffles have the same first
2863   // or second operand, then it might still be profitable to move the shuffle
2864   // after the xor/and/or operation.
2865   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2866     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2867     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2868 
2869     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2870            "Inputs to shuffles are not the same type");
2871 
2872     // Check that both shuffles use the same mask. The masks are known to be of
2873     // the same length because the result vector type is the same.
2874     // Check also that shuffles have only one use to avoid introducing extra
2875     // instructions.
2876     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2877         SVN0->getMask().equals(SVN1->getMask())) {
2878       SDValue ShOp = N0->getOperand(1);
2879 
2880       // Don't try to fold this node if it requires introducing a
2881       // build vector of all zeros that might be illegal at this stage.
2882       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2883         if (!LegalTypes)
2884           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2885         else
2886           ShOp = SDValue();
2887       }
2888 
2889       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2890       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2891       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2892       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2893         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2894                                       N0->getOperand(0), N1->getOperand(0));
2895         AddToWorklist(NewNode.getNode());
2896         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2897                                     SVN0->getMask());
2898       }
2899 
2900       // Don't try to fold this node if it requires introducing a
2901       // build vector of all zeros that might be illegal at this stage.
2902       ShOp = N0->getOperand(0);
2903       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2904         if (!LegalTypes)
2905           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2906         else
2907           ShOp = SDValue();
2908       }
2909 
2910       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2911       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2912       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2913       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2914         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2915                                       N0->getOperand(1), N1->getOperand(1));
2916         AddToWorklist(NewNode.getNode());
2917         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2918                                     SVN0->getMask());
2919       }
2920     }
2921   }
2922 
2923   return SDValue();
2924 }
2925 
2926 /// This contains all DAGCombine rules which reduce two values combined by
2927 /// an And operation to a single value. This makes them reusable in the context
2928 /// of visitSELECT(). Rules involving constants are not included as
2929 /// visitSELECT() already handles those cases.
2930 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2931                                   SDNode *LocReference) {
2932   EVT VT = N1.getValueType();
2933 
2934   // fold (and x, undef) -> 0
2935   if (N0.isUndef() || N1.isUndef())
2936     return DAG.getConstant(0, SDLoc(LocReference), VT);
2937   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2938   SDValue LL, LR, RL, RR, CC0, CC1;
2939   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2940     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2941     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2942 
2943     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2944         LL.getValueType().isInteger()) {
2945       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2946       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2947         EVT CCVT = getSetCCResultType(LR.getValueType());
2948         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2949           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2950                                        LR.getValueType(), LL, RL);
2951           AddToWorklist(ORNode.getNode());
2952           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2953         }
2954       }
2955       if (isAllOnesConstant(LR)) {
2956         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2957         if (Op1 == ISD::SETEQ) {
2958           EVT CCVT = getSetCCResultType(LR.getValueType());
2959           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2960             SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2961                                           LR.getValueType(), LL, RL);
2962             AddToWorklist(ANDNode.getNode());
2963             return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2964           }
2965         }
2966         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2967         if (Op1 == ISD::SETGT) {
2968           EVT CCVT = getSetCCResultType(LR.getValueType());
2969           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2970             SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2971                                          LR.getValueType(), LL, RL);
2972             AddToWorklist(ORNode.getNode());
2973             return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2974           }
2975         }
2976       }
2977     }
2978     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2979     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2980         Op0 == Op1 && LL.getValueType().isInteger() &&
2981       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2982                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2983       EVT CCVT = getSetCCResultType(LL.getValueType());
2984       if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2985         SDLoc DL(N0);
2986         SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2987                                       LL, DAG.getConstant(1, DL,
2988                                                           LL.getValueType()));
2989         AddToWorklist(ADDNode.getNode());
2990         return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2991                             DAG.getConstant(2, DL, LL.getValueType()),
2992                             ISD::SETUGE);
2993       }
2994     }
2995     // canonicalize equivalent to ll == rl
2996     if (LL == RR && LR == RL) {
2997       Op1 = ISD::getSetCCSwappedOperands(Op1);
2998       std::swap(RL, RR);
2999     }
3000     if (LL == RL && LR == RR) {
3001       bool isInteger = LL.getValueType().isInteger();
3002       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
3003       if (Result != ISD::SETCC_INVALID &&
3004           (!LegalOperations ||
3005            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3006             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3007         EVT CCVT = getSetCCResultType(LL.getValueType());
3008         if (N0.getValueType() == CCVT ||
3009             (!LegalOperations && N0.getValueType() == MVT::i1))
3010           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3011                               LL, LR, Result);
3012       }
3013     }
3014   }
3015 
3016   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3017       VT.getSizeInBits() <= 64) {
3018     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3019       APInt ADDC = ADDI->getAPIntValue();
3020       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3021         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3022         // immediate for an add, but it is legal if its top c2 bits are set,
3023         // transform the ADD so the immediate doesn't need to be materialized
3024         // in a register.
3025         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3026           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3027                                              SRLI->getZExtValue());
3028           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3029             ADDC |= Mask;
3030             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3031               SDLoc DL(N0);
3032               SDValue NewAdd =
3033                 DAG.getNode(ISD::ADD, DL, VT,
3034                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3035               CombineTo(N0.getNode(), NewAdd);
3036               // Return N so it doesn't get rechecked!
3037               return SDValue(LocReference, 0);
3038             }
3039           }
3040         }
3041       }
3042     }
3043   }
3044 
3045   // Reduce bit extract of low half of an integer to the narrower type.
3046   // (and (srl i64:x, K), KMask) ->
3047   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3048   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3049     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3050       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3051         unsigned Size = VT.getSizeInBits();
3052         const APInt &AndMask = CAnd->getAPIntValue();
3053         unsigned ShiftBits = CShift->getZExtValue();
3054 
3055         // Bail out, this node will probably disappear anyway.
3056         if (ShiftBits == 0)
3057           return SDValue();
3058 
3059         unsigned MaskBits = AndMask.countTrailingOnes();
3060         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3061 
3062         if (APIntOps::isMask(AndMask) &&
3063             // Required bits must not span the two halves of the integer and
3064             // must fit in the half size type.
3065             (ShiftBits + MaskBits <= Size / 2) &&
3066             TLI.isNarrowingProfitable(VT, HalfVT) &&
3067             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3068             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3069             TLI.isTruncateFree(VT, HalfVT) &&
3070             TLI.isZExtFree(HalfVT, VT)) {
3071           // The isNarrowingProfitable is to avoid regressions on PPC and
3072           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3073           // on downstream users of this. Those patterns could probably be
3074           // extended to handle extensions mixed in.
3075 
3076           SDValue SL(N0);
3077           assert(MaskBits <= Size);
3078 
3079           // Extracting the highest bit of the low half.
3080           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3081           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3082                                       N0.getOperand(0));
3083 
3084           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3085           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3086           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3087           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3088           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3089         }
3090       }
3091     }
3092   }
3093 
3094   return SDValue();
3095 }
3096 
3097 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3098                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3099                                    bool &NarrowLoad) {
3100   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3101 
3102   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3103     return false;
3104 
3105   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3106   LoadedVT = LoadN->getMemoryVT();
3107 
3108   if (ExtVT == LoadedVT &&
3109       (!LegalOperations ||
3110        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3111     // ZEXTLOAD will match without needing to change the size of the value being
3112     // loaded.
3113     NarrowLoad = false;
3114     return true;
3115   }
3116 
3117   // Do not change the width of a volatile load.
3118   if (LoadN->isVolatile())
3119     return false;
3120 
3121   // Do not generate loads of non-round integer types since these can
3122   // be expensive (and would be wrong if the type is not byte sized).
3123   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3124     return false;
3125 
3126   if (LegalOperations &&
3127       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3128     return false;
3129 
3130   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3131     return false;
3132 
3133   NarrowLoad = true;
3134   return true;
3135 }
3136 
3137 SDValue DAGCombiner::visitAND(SDNode *N) {
3138   SDValue N0 = N->getOperand(0);
3139   SDValue N1 = N->getOperand(1);
3140   EVT VT = N1.getValueType();
3141 
3142   // x & x --> x
3143   if (N0 == N1)
3144     return N0;
3145 
3146   // fold vector ops
3147   if (VT.isVector()) {
3148     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3149       return FoldedVOp;
3150 
3151     // fold (and x, 0) -> 0, vector edition
3152     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3153       // do not return N0, because undef node may exist in N0
3154       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3155                              SDLoc(N), N0.getValueType());
3156     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3157       // do not return N1, because undef node may exist in N1
3158       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3159                              SDLoc(N), N1.getValueType());
3160 
3161     // fold (and x, -1) -> x, vector edition
3162     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3163       return N1;
3164     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3165       return N0;
3166   }
3167 
3168   // fold (and c1, c2) -> c1&c2
3169   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3170   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3171   if (N0C && N1C && !N1C->isOpaque())
3172     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3173   // canonicalize constant to RHS
3174   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3175      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3176     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3177   // fold (and x, -1) -> x
3178   if (isAllOnesConstant(N1))
3179     return N0;
3180   // if (and x, c) is known to be zero, return 0
3181   unsigned BitWidth = VT.getScalarSizeInBits();
3182   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3183                                    APInt::getAllOnesValue(BitWidth)))
3184     return DAG.getConstant(0, SDLoc(N), VT);
3185   // reassociate and
3186   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3187     return RAND;
3188   // fold (and (or x, C), D) -> D if (C & D) == D
3189   if (N1C && N0.getOpcode() == ISD::OR)
3190     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3191       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3192         return N1;
3193   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3194   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3195     SDValue N0Op0 = N0.getOperand(0);
3196     APInt Mask = ~N1C->getAPIntValue();
3197     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3198     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3199       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3200                                  N0.getValueType(), N0Op0);
3201 
3202       // Replace uses of the AND with uses of the Zero extend node.
3203       CombineTo(N, Zext);
3204 
3205       // We actually want to replace all uses of the any_extend with the
3206       // zero_extend, to avoid duplicating things.  This will later cause this
3207       // AND to be folded.
3208       CombineTo(N0.getNode(), Zext);
3209       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3210     }
3211   }
3212   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3213   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3214   // already be zero by virtue of the width of the base type of the load.
3215   //
3216   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3217   // more cases.
3218   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3219        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3220        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3221        N0.getOperand(0).getResNo() == 0) ||
3222       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3223     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3224                                          N0 : N0.getOperand(0) );
3225 
3226     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3227     // This can be a pure constant or a vector splat, in which case we treat the
3228     // vector as a scalar and use the splat value.
3229     APInt Constant = APInt::getNullValue(1);
3230     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3231       Constant = C->getAPIntValue();
3232     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3233       APInt SplatValue, SplatUndef;
3234       unsigned SplatBitSize;
3235       bool HasAnyUndefs;
3236       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3237                                              SplatBitSize, HasAnyUndefs);
3238       if (IsSplat) {
3239         // Undef bits can contribute to a possible optimisation if set, so
3240         // set them.
3241         SplatValue |= SplatUndef;
3242 
3243         // The splat value may be something like "0x00FFFFFF", which means 0 for
3244         // the first vector value and FF for the rest, repeating. We need a mask
3245         // that will apply equally to all members of the vector, so AND all the
3246         // lanes of the constant together.
3247         EVT VT = Vector->getValueType(0);
3248         unsigned BitWidth = VT.getScalarSizeInBits();
3249 
3250         // If the splat value has been compressed to a bitlength lower
3251         // than the size of the vector lane, we need to re-expand it to
3252         // the lane size.
3253         if (BitWidth > SplatBitSize)
3254           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3255                SplatBitSize < BitWidth;
3256                SplatBitSize = SplatBitSize * 2)
3257             SplatValue |= SplatValue.shl(SplatBitSize);
3258 
3259         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3260         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3261         if (SplatBitSize % BitWidth == 0) {
3262           Constant = APInt::getAllOnesValue(BitWidth);
3263           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3264             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3265         }
3266       }
3267     }
3268 
3269     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3270     // actually legal and isn't going to get expanded, else this is a false
3271     // optimisation.
3272     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3273                                                     Load->getValueType(0),
3274                                                     Load->getMemoryVT());
3275 
3276     // Resize the constant to the same size as the original memory access before
3277     // extension. If it is still the AllOnesValue then this AND is completely
3278     // unneeded.
3279     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3280 
3281     bool B;
3282     switch (Load->getExtensionType()) {
3283     default: B = false; break;
3284     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3285     case ISD::ZEXTLOAD:
3286     case ISD::NON_EXTLOAD: B = true; break;
3287     }
3288 
3289     if (B && Constant.isAllOnesValue()) {
3290       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3291       // preserve semantics once we get rid of the AND.
3292       SDValue NewLoad(Load, 0);
3293       if (Load->getExtensionType() == ISD::EXTLOAD) {
3294         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3295                               Load->getValueType(0), SDLoc(Load),
3296                               Load->getChain(), Load->getBasePtr(),
3297                               Load->getOffset(), Load->getMemoryVT(),
3298                               Load->getMemOperand());
3299         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3300         if (Load->getNumValues() == 3) {
3301           // PRE/POST_INC loads have 3 values.
3302           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3303                            NewLoad.getValue(2) };
3304           CombineTo(Load, To, 3, true);
3305         } else {
3306           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3307         }
3308       }
3309 
3310       // Fold the AND away, taking care not to fold to the old load node if we
3311       // replaced it.
3312       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3313 
3314       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3315     }
3316   }
3317 
3318   // fold (and (load x), 255) -> (zextload x, i8)
3319   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3320   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3321   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3322                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3323                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3324     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3325     LoadSDNode *LN0 = HasAnyExt
3326       ? cast<LoadSDNode>(N0.getOperand(0))
3327       : cast<LoadSDNode>(N0);
3328     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3329         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3330       auto NarrowLoad = false;
3331       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3332       EVT ExtVT, LoadedVT;
3333       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3334                            NarrowLoad)) {
3335         if (!NarrowLoad) {
3336           SDValue NewLoad =
3337             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3338                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3339                            LN0->getMemOperand());
3340           AddToWorklist(N);
3341           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3342           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3343         } else {
3344           EVT PtrType = LN0->getOperand(1).getValueType();
3345 
3346           unsigned Alignment = LN0->getAlignment();
3347           SDValue NewPtr = LN0->getBasePtr();
3348 
3349           // For big endian targets, we need to add an offset to the pointer
3350           // to load the correct bytes.  For little endian systems, we merely
3351           // need to read fewer bytes from the same pointer.
3352           if (DAG.getDataLayout().isBigEndian()) {
3353             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3354             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3355             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3356             SDLoc DL(LN0);
3357             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3358                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3359             Alignment = MinAlign(Alignment, PtrOff);
3360           }
3361 
3362           AddToWorklist(NewPtr.getNode());
3363 
3364           SDValue Load = DAG.getExtLoad(
3365               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3366               LN0->getPointerInfo(), ExtVT, Alignment,
3367               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3368           AddToWorklist(N);
3369           CombineTo(LN0, Load, Load.getValue(1));
3370           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3371         }
3372       }
3373     }
3374   }
3375 
3376   if (SDValue Combined = visitANDLike(N0, N1, N))
3377     return Combined;
3378 
3379   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3380   if (N0.getOpcode() == N1.getOpcode())
3381     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3382       return Tmp;
3383 
3384   // Masking the negated extension of a boolean is just the zero-extended
3385   // boolean:
3386   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3387   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3388   //
3389   // Note: the SimplifyDemandedBits fold below can make an information-losing
3390   // transform, and then we have no way to find this better fold.
3391   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3392     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3393     SDValue SubRHS = N0.getOperand(1);
3394     if (SubLHS && SubLHS->isNullValue()) {
3395       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3396           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3397         return SubRHS;
3398       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3399           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3400         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3401     }
3402   }
3403 
3404   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3405   // fold (and (sra)) -> (and (srl)) when possible.
3406   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
3407     return SDValue(N, 0);
3408 
3409   // fold (zext_inreg (extload x)) -> (zextload x)
3410   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3411     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3412     EVT MemVT = LN0->getMemoryVT();
3413     // If we zero all the possible extended bits, then we can turn this into
3414     // a zextload if we are running before legalize or the operation is legal.
3415     unsigned BitWidth = N1.getScalarValueSizeInBits();
3416     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3417                            BitWidth - MemVT.getScalarSizeInBits())) &&
3418         ((!LegalOperations && !LN0->isVolatile()) ||
3419          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3420       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3421                                        LN0->getChain(), LN0->getBasePtr(),
3422                                        MemVT, LN0->getMemOperand());
3423       AddToWorklist(N);
3424       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3425       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3426     }
3427   }
3428   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3429   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3430       N0.hasOneUse()) {
3431     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3432     EVT MemVT = LN0->getMemoryVT();
3433     // If we zero all the possible extended bits, then we can turn this into
3434     // a zextload if we are running before legalize or the operation is legal.
3435     unsigned BitWidth = N1.getScalarValueSizeInBits();
3436     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3437                            BitWidth - MemVT.getScalarSizeInBits())) &&
3438         ((!LegalOperations && !LN0->isVolatile()) ||
3439          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3440       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3441                                        LN0->getChain(), LN0->getBasePtr(),
3442                                        MemVT, LN0->getMemOperand());
3443       AddToWorklist(N);
3444       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3445       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3446     }
3447   }
3448   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3449   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3450     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3451                                            N0.getOperand(1), false))
3452       return BSwap;
3453   }
3454 
3455   return SDValue();
3456 }
3457 
3458 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3459 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3460                                         bool DemandHighBits) {
3461   if (!LegalOperations)
3462     return SDValue();
3463 
3464   EVT VT = N->getValueType(0);
3465   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3466     return SDValue();
3467   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3468     return SDValue();
3469 
3470   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3471   bool LookPassAnd0 = false;
3472   bool LookPassAnd1 = false;
3473   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3474       std::swap(N0, N1);
3475   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3476       std::swap(N0, N1);
3477   if (N0.getOpcode() == ISD::AND) {
3478     if (!N0.getNode()->hasOneUse())
3479       return SDValue();
3480     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3481     if (!N01C || N01C->getZExtValue() != 0xFF00)
3482       return SDValue();
3483     N0 = N0.getOperand(0);
3484     LookPassAnd0 = true;
3485   }
3486 
3487   if (N1.getOpcode() == ISD::AND) {
3488     if (!N1.getNode()->hasOneUse())
3489       return SDValue();
3490     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3491     if (!N11C || N11C->getZExtValue() != 0xFF)
3492       return SDValue();
3493     N1 = N1.getOperand(0);
3494     LookPassAnd1 = true;
3495   }
3496 
3497   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3498     std::swap(N0, N1);
3499   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3500     return SDValue();
3501   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3502     return SDValue();
3503 
3504   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3505   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3506   if (!N01C || !N11C)
3507     return SDValue();
3508   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3509     return SDValue();
3510 
3511   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3512   SDValue N00 = N0->getOperand(0);
3513   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3514     if (!N00.getNode()->hasOneUse())
3515       return SDValue();
3516     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3517     if (!N001C || N001C->getZExtValue() != 0xFF)
3518       return SDValue();
3519     N00 = N00.getOperand(0);
3520     LookPassAnd0 = true;
3521   }
3522 
3523   SDValue N10 = N1->getOperand(0);
3524   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3525     if (!N10.getNode()->hasOneUse())
3526       return SDValue();
3527     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3528     if (!N101C || N101C->getZExtValue() != 0xFF00)
3529       return SDValue();
3530     N10 = N10.getOperand(0);
3531     LookPassAnd1 = true;
3532   }
3533 
3534   if (N00 != N10)
3535     return SDValue();
3536 
3537   // Make sure everything beyond the low halfword gets set to zero since the SRL
3538   // 16 will clear the top bits.
3539   unsigned OpSizeInBits = VT.getSizeInBits();
3540   if (DemandHighBits && OpSizeInBits > 16) {
3541     // If the left-shift isn't masked out then the only way this is a bswap is
3542     // if all bits beyond the low 8 are 0. In that case the entire pattern
3543     // reduces to a left shift anyway: leave it for other parts of the combiner.
3544     if (!LookPassAnd0)
3545       return SDValue();
3546 
3547     // However, if the right shift isn't masked out then it might be because
3548     // it's not needed. See if we can spot that too.
3549     if (!LookPassAnd1 &&
3550         !DAG.MaskedValueIsZero(
3551             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3552       return SDValue();
3553   }
3554 
3555   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3556   if (OpSizeInBits > 16) {
3557     SDLoc DL(N);
3558     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3559                       DAG.getConstant(OpSizeInBits - 16, DL,
3560                                       getShiftAmountTy(VT)));
3561   }
3562   return Res;
3563 }
3564 
3565 /// Return true if the specified node is an element that makes up a 32-bit
3566 /// packed halfword byteswap.
3567 /// ((x & 0x000000ff) << 8) |
3568 /// ((x & 0x0000ff00) >> 8) |
3569 /// ((x & 0x00ff0000) << 8) |
3570 /// ((x & 0xff000000) >> 8)
3571 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3572   if (!N.getNode()->hasOneUse())
3573     return false;
3574 
3575   unsigned Opc = N.getOpcode();
3576   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3577     return false;
3578 
3579   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3580   if (!N1C)
3581     return false;
3582 
3583   unsigned Num;
3584   switch (N1C->getZExtValue()) {
3585   default:
3586     return false;
3587   case 0xFF:       Num = 0; break;
3588   case 0xFF00:     Num = 1; break;
3589   case 0xFF0000:   Num = 2; break;
3590   case 0xFF000000: Num = 3; break;
3591   }
3592 
3593   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3594   SDValue N0 = N.getOperand(0);
3595   if (Opc == ISD::AND) {
3596     if (Num == 0 || Num == 2) {
3597       // (x >> 8) & 0xff
3598       // (x >> 8) & 0xff0000
3599       if (N0.getOpcode() != ISD::SRL)
3600         return false;
3601       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3602       if (!C || C->getZExtValue() != 8)
3603         return false;
3604     } else {
3605       // (x << 8) & 0xff00
3606       // (x << 8) & 0xff000000
3607       if (N0.getOpcode() != ISD::SHL)
3608         return false;
3609       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3610       if (!C || C->getZExtValue() != 8)
3611         return false;
3612     }
3613   } else if (Opc == ISD::SHL) {
3614     // (x & 0xff) << 8
3615     // (x & 0xff0000) << 8
3616     if (Num != 0 && Num != 2)
3617       return false;
3618     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3619     if (!C || C->getZExtValue() != 8)
3620       return false;
3621   } else { // Opc == ISD::SRL
3622     // (x & 0xff00) >> 8
3623     // (x & 0xff000000) >> 8
3624     if (Num != 1 && Num != 3)
3625       return false;
3626     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3627     if (!C || C->getZExtValue() != 8)
3628       return false;
3629   }
3630 
3631   if (Parts[Num])
3632     return false;
3633 
3634   Parts[Num] = N0.getOperand(0).getNode();
3635   return true;
3636 }
3637 
3638 /// Match a 32-bit packed halfword bswap. That is
3639 /// ((x & 0x000000ff) << 8) |
3640 /// ((x & 0x0000ff00) >> 8) |
3641 /// ((x & 0x00ff0000) << 8) |
3642 /// ((x & 0xff000000) >> 8)
3643 /// => (rotl (bswap x), 16)
3644 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3645   if (!LegalOperations)
3646     return SDValue();
3647 
3648   EVT VT = N->getValueType(0);
3649   if (VT != MVT::i32)
3650     return SDValue();
3651   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3652     return SDValue();
3653 
3654   // Look for either
3655   // (or (or (and), (and)), (or (and), (and)))
3656   // (or (or (or (and), (and)), (and)), (and))
3657   if (N0.getOpcode() != ISD::OR)
3658     return SDValue();
3659   SDValue N00 = N0.getOperand(0);
3660   SDValue N01 = N0.getOperand(1);
3661   SDNode *Parts[4] = {};
3662 
3663   if (N1.getOpcode() == ISD::OR &&
3664       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3665     // (or (or (and), (and)), (or (and), (and)))
3666     SDValue N000 = N00.getOperand(0);
3667     if (!isBSwapHWordElement(N000, Parts))
3668       return SDValue();
3669 
3670     SDValue N001 = N00.getOperand(1);
3671     if (!isBSwapHWordElement(N001, Parts))
3672       return SDValue();
3673     SDValue N010 = N01.getOperand(0);
3674     if (!isBSwapHWordElement(N010, Parts))
3675       return SDValue();
3676     SDValue N011 = N01.getOperand(1);
3677     if (!isBSwapHWordElement(N011, Parts))
3678       return SDValue();
3679   } else {
3680     // (or (or (or (and), (and)), (and)), (and))
3681     if (!isBSwapHWordElement(N1, Parts))
3682       return SDValue();
3683     if (!isBSwapHWordElement(N01, Parts))
3684       return SDValue();
3685     if (N00.getOpcode() != ISD::OR)
3686       return SDValue();
3687     SDValue N000 = N00.getOperand(0);
3688     if (!isBSwapHWordElement(N000, Parts))
3689       return SDValue();
3690     SDValue N001 = N00.getOperand(1);
3691     if (!isBSwapHWordElement(N001, Parts))
3692       return SDValue();
3693   }
3694 
3695   // Make sure the parts are all coming from the same node.
3696   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3697     return SDValue();
3698 
3699   SDLoc DL(N);
3700   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3701                               SDValue(Parts[0], 0));
3702 
3703   // Result of the bswap should be rotated by 16. If it's not legal, then
3704   // do  (x << 16) | (x >> 16).
3705   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3706   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3707     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3708   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3709     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3710   return DAG.getNode(ISD::OR, DL, VT,
3711                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3712                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3713 }
3714 
3715 /// This contains all DAGCombine rules which reduce two values combined by
3716 /// an Or operation to a single value \see visitANDLike().
3717 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3718   EVT VT = N1.getValueType();
3719   // fold (or x, undef) -> -1
3720   if (!LegalOperations &&
3721       (N0.isUndef() || N1.isUndef())) {
3722     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3723     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3724                            SDLoc(LocReference), VT);
3725   }
3726   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3727   SDValue LL, LR, RL, RR, CC0, CC1;
3728   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3729     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3730     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3731 
3732     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3733       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3734       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3735       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3736         EVT CCVT = getSetCCResultType(LR.getValueType());
3737         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3738           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3739                                        LR.getValueType(), LL, RL);
3740           AddToWorklist(ORNode.getNode());
3741           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3742         }
3743       }
3744       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3745       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3746       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3747         EVT CCVT = getSetCCResultType(LR.getValueType());
3748         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3749           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3750                                         LR.getValueType(), LL, RL);
3751           AddToWorklist(ANDNode.getNode());
3752           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3753         }
3754       }
3755     }
3756     // canonicalize equivalent to ll == rl
3757     if (LL == RR && LR == RL) {
3758       Op1 = ISD::getSetCCSwappedOperands(Op1);
3759       std::swap(RL, RR);
3760     }
3761     if (LL == RL && LR == RR) {
3762       bool isInteger = LL.getValueType().isInteger();
3763       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3764       if (Result != ISD::SETCC_INVALID &&
3765           (!LegalOperations ||
3766            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3767             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3768         EVT CCVT = getSetCCResultType(LL.getValueType());
3769         if (N0.getValueType() == CCVT ||
3770             (!LegalOperations && N0.getValueType() == MVT::i1))
3771           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3772                               LL, LR, Result);
3773       }
3774     }
3775   }
3776 
3777   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3778   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3779       // Don't increase # computations.
3780       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3781     // We can only do this xform if we know that bits from X that are set in C2
3782     // but not in C1 are already zero.  Likewise for Y.
3783     if (const ConstantSDNode *N0O1C =
3784         getAsNonOpaqueConstant(N0.getOperand(1))) {
3785       if (const ConstantSDNode *N1O1C =
3786           getAsNonOpaqueConstant(N1.getOperand(1))) {
3787         // We can only do this xform if we know that bits from X that are set in
3788         // C2 but not in C1 are already zero.  Likewise for Y.
3789         const APInt &LHSMask = N0O1C->getAPIntValue();
3790         const APInt &RHSMask = N1O1C->getAPIntValue();
3791 
3792         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3793             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3794           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3795                                   N0.getOperand(0), N1.getOperand(0));
3796           SDLoc DL(LocReference);
3797           return DAG.getNode(ISD::AND, DL, VT, X,
3798                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3799         }
3800       }
3801     }
3802   }
3803 
3804   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3805   if (N0.getOpcode() == ISD::AND &&
3806       N1.getOpcode() == ISD::AND &&
3807       N0.getOperand(0) == N1.getOperand(0) &&
3808       // Don't increase # computations.
3809       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3810     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3811                             N0.getOperand(1), N1.getOperand(1));
3812     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3813   }
3814 
3815   return SDValue();
3816 }
3817 
3818 SDValue DAGCombiner::visitOR(SDNode *N) {
3819   SDValue N0 = N->getOperand(0);
3820   SDValue N1 = N->getOperand(1);
3821   EVT VT = N1.getValueType();
3822 
3823   // x | x --> x
3824   if (N0 == N1)
3825     return N0;
3826 
3827   // fold vector ops
3828   if (VT.isVector()) {
3829     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3830       return FoldedVOp;
3831 
3832     // fold (or x, 0) -> x, vector edition
3833     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3834       return N1;
3835     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3836       return N0;
3837 
3838     // fold (or x, -1) -> -1, vector edition
3839     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3840       // do not return N0, because undef node may exist in N0
3841       return DAG.getConstant(
3842           APInt::getAllOnesValue(N0.getScalarValueSizeInBits()), SDLoc(N),
3843           N0.getValueType());
3844     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3845       // do not return N1, because undef node may exist in N1
3846       return DAG.getConstant(
3847           APInt::getAllOnesValue(N1.getScalarValueSizeInBits()), SDLoc(N),
3848           N1.getValueType());
3849 
3850     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
3851     // Do this only if the resulting shuffle is legal.
3852     if (isa<ShuffleVectorSDNode>(N0) &&
3853         isa<ShuffleVectorSDNode>(N1) &&
3854         // Avoid folding a node with illegal type.
3855         TLI.isTypeLegal(VT)) {
3856       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
3857       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
3858       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
3859       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
3860       // Ensure both shuffles have a zero input.
3861       if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) {
3862         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
3863         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
3864         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3865         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3866         bool CanFold = true;
3867         int NumElts = VT.getVectorNumElements();
3868         SmallVector<int, 4> Mask(NumElts);
3869 
3870         for (int i = 0; i != NumElts; ++i) {
3871           int M0 = SV0->getMaskElt(i);
3872           int M1 = SV1->getMaskElt(i);
3873 
3874           // Determine if either index is pointing to a zero vector.
3875           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
3876           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
3877 
3878           // If one element is zero and the otherside is undef, keep undef.
3879           // This also handles the case that both are undef.
3880           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
3881             Mask[i] = -1;
3882             continue;
3883           }
3884 
3885           // Make sure only one of the elements is zero.
3886           if (M0Zero == M1Zero) {
3887             CanFold = false;
3888             break;
3889           }
3890 
3891           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
3892 
3893           // We have a zero and non-zero element. If the non-zero came from
3894           // SV0 make the index a LHS index. If it came from SV1, make it
3895           // a RHS index. We need to mod by NumElts because we don't care
3896           // which operand it came from in the original shuffles.
3897           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
3898         }
3899 
3900         if (CanFold) {
3901           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
3902           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
3903 
3904           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3905           if (!LegalMask) {
3906             std::swap(NewLHS, NewRHS);
3907             ShuffleVectorSDNode::commuteMask(Mask);
3908             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3909           }
3910 
3911           if (LegalMask)
3912             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
3913         }
3914       }
3915     }
3916   }
3917 
3918   // fold (or c1, c2) -> c1|c2
3919   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3920   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3921   if (N0C && N1C && !N1C->isOpaque())
3922     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3923   // canonicalize constant to RHS
3924   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3925      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3926     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3927   // fold (or x, 0) -> x
3928   if (isNullConstant(N1))
3929     return N0;
3930   // fold (or x, -1) -> -1
3931   if (isAllOnesConstant(N1))
3932     return N1;
3933   // fold (or x, c) -> c iff (x & ~c) == 0
3934   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3935     return N1;
3936 
3937   if (SDValue Combined = visitORLike(N0, N1, N))
3938     return Combined;
3939 
3940   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3941   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3942     return BSwap;
3943   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3944     return BSwap;
3945 
3946   // reassociate or
3947   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3948     return ROR;
3949   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3950   // iff (c1 & c2) == 0.
3951   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3952              isa<ConstantSDNode>(N0.getOperand(1))) {
3953     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3954     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3955       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3956                                                    N1C, C1))
3957         return DAG.getNode(
3958             ISD::AND, SDLoc(N), VT,
3959             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3960       return SDValue();
3961     }
3962   }
3963   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3964   if (N0.getOpcode() == N1.getOpcode())
3965     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3966       return Tmp;
3967 
3968   // See if this is some rotate idiom.
3969   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3970     return SDValue(Rot, 0);
3971 
3972   // Simplify the operands using demanded-bits information.
3973   if (!VT.isVector() &&
3974       SimplifyDemandedBits(SDValue(N, 0)))
3975     return SDValue(N, 0);
3976 
3977   return SDValue();
3978 }
3979 
3980 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3981 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3982   if (Op.getOpcode() == ISD::AND) {
3983     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3984       Mask = Op.getOperand(1);
3985       Op = Op.getOperand(0);
3986     } else {
3987       return false;
3988     }
3989   }
3990 
3991   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3992     Shift = Op;
3993     return true;
3994   }
3995 
3996   return false;
3997 }
3998 
3999 // Return true if we can prove that, whenever Neg and Pos are both in the
4000 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4001 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4002 //
4003 //     (or (shift1 X, Neg), (shift2 X, Pos))
4004 //
4005 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4006 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4007 // to consider shift amounts with defined behavior.
4008 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4009   // If EltSize is a power of 2 then:
4010   //
4011   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4012   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4013   //
4014   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4015   // for the stronger condition:
4016   //
4017   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4018   //
4019   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4020   // we can just replace Neg with Neg' for the rest of the function.
4021   //
4022   // In other cases we check for the even stronger condition:
4023   //
4024   //     Neg == EltSize - Pos                                    [B]
4025   //
4026   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4027   // behavior if Pos == 0 (and consequently Neg == EltSize).
4028   //
4029   // We could actually use [A] whenever EltSize is a power of 2, but the
4030   // only extra cases that it would match are those uninteresting ones
4031   // where Neg and Pos are never in range at the same time.  E.g. for
4032   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4033   // as well as (sub 32, Pos), but:
4034   //
4035   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4036   //
4037   // always invokes undefined behavior for 32-bit X.
4038   //
4039   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4040   unsigned MaskLoBits = 0;
4041   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4042     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4043       if (NegC->getAPIntValue() == EltSize - 1) {
4044         Neg = Neg.getOperand(0);
4045         MaskLoBits = Log2_64(EltSize);
4046       }
4047     }
4048   }
4049 
4050   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4051   if (Neg.getOpcode() != ISD::SUB)
4052     return false;
4053   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4054   if (!NegC)
4055     return false;
4056   SDValue NegOp1 = Neg.getOperand(1);
4057 
4058   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4059   // Pos'.  The truncation is redundant for the purpose of the equality.
4060   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4061     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4062       if (PosC->getAPIntValue() == EltSize - 1)
4063         Pos = Pos.getOperand(0);
4064 
4065   // The condition we need is now:
4066   //
4067   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4068   //
4069   // If NegOp1 == Pos then we need:
4070   //
4071   //              EltSize & Mask == NegC & Mask
4072   //
4073   // (because "x & Mask" is a truncation and distributes through subtraction).
4074   APInt Width;
4075   if (Pos == NegOp1)
4076     Width = NegC->getAPIntValue();
4077 
4078   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4079   // Then the condition we want to prove becomes:
4080   //
4081   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4082   //
4083   // which, again because "x & Mask" is a truncation, becomes:
4084   //
4085   //                NegC & Mask == (EltSize - PosC) & Mask
4086   //             EltSize & Mask == (NegC + PosC) & Mask
4087   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4088     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4089       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4090     else
4091       return false;
4092   } else
4093     return false;
4094 
4095   // Now we just need to check that EltSize & Mask == Width & Mask.
4096   if (MaskLoBits)
4097     // EltSize & Mask is 0 since Mask is EltSize - 1.
4098     return Width.getLoBits(MaskLoBits) == 0;
4099   return Width == EltSize;
4100 }
4101 
4102 // A subroutine of MatchRotate used once we have found an OR of two opposite
4103 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4104 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4105 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4106 // Neg with outer conversions stripped away.
4107 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4108                                        SDValue Neg, SDValue InnerPos,
4109                                        SDValue InnerNeg, unsigned PosOpcode,
4110                                        unsigned NegOpcode, const SDLoc &DL) {
4111   // fold (or (shl x, (*ext y)),
4112   //          (srl x, (*ext (sub 32, y)))) ->
4113   //   (rotl x, y) or (rotr x, (sub 32, y))
4114   //
4115   // fold (or (shl x, (*ext (sub 32, y))),
4116   //          (srl x, (*ext y))) ->
4117   //   (rotr x, y) or (rotl x, (sub 32, y))
4118   EVT VT = Shifted.getValueType();
4119   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4120     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4121     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4122                        HasPos ? Pos : Neg).getNode();
4123   }
4124 
4125   return nullptr;
4126 }
4127 
4128 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4129 // idioms for rotate, and if the target supports rotation instructions, generate
4130 // a rot[lr].
4131 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4132   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4133   EVT VT = LHS.getValueType();
4134   if (!TLI.isTypeLegal(VT)) return nullptr;
4135 
4136   // The target must have at least one rotate flavor.
4137   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4138   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4139   if (!HasROTL && !HasROTR) return nullptr;
4140 
4141   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4142   SDValue LHSShift;   // The shift.
4143   SDValue LHSMask;    // AND value if any.
4144   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4145     return nullptr; // Not part of a rotate.
4146 
4147   SDValue RHSShift;   // The shift.
4148   SDValue RHSMask;    // AND value if any.
4149   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4150     return nullptr; // Not part of a rotate.
4151 
4152   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4153     return nullptr;   // Not shifting the same value.
4154 
4155   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4156     return nullptr;   // Shifts must disagree.
4157 
4158   // Canonicalize shl to left side in a shl/srl pair.
4159   if (RHSShift.getOpcode() == ISD::SHL) {
4160     std::swap(LHS, RHS);
4161     std::swap(LHSShift, RHSShift);
4162     std::swap(LHSMask, RHSMask);
4163   }
4164 
4165   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4166   SDValue LHSShiftArg = LHSShift.getOperand(0);
4167   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4168   SDValue RHSShiftArg = RHSShift.getOperand(0);
4169   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4170 
4171   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4172   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4173   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4174     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4175     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4176     if ((LShVal + RShVal) != EltSizeInBits)
4177       return nullptr;
4178 
4179     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4180                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4181 
4182     // If there is an AND of either shifted operand, apply it to the result.
4183     if (LHSMask.getNode() || RHSMask.getNode()) {
4184       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4185       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4186 
4187       if (LHSMask.getNode()) {
4188         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4189         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4190                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4191                                        DAG.getConstant(RHSBits, DL, VT)));
4192       }
4193       if (RHSMask.getNode()) {
4194         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4195         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4196                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4197                                        DAG.getConstant(LHSBits, DL, VT)));
4198       }
4199 
4200       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4201     }
4202 
4203     return Rot.getNode();
4204   }
4205 
4206   // If there is a mask here, and we have a variable shift, we can't be sure
4207   // that we're masking out the right stuff.
4208   if (LHSMask.getNode() || RHSMask.getNode())
4209     return nullptr;
4210 
4211   // If the shift amount is sign/zext/any-extended just peel it off.
4212   SDValue LExtOp0 = LHSShiftAmt;
4213   SDValue RExtOp0 = RHSShiftAmt;
4214   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4215        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4216        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4217        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4218       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4219        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4220        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4221        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4222     LExtOp0 = LHSShiftAmt.getOperand(0);
4223     RExtOp0 = RHSShiftAmt.getOperand(0);
4224   }
4225 
4226   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4227                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4228   if (TryL)
4229     return TryL;
4230 
4231   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4232                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4233   if (TryR)
4234     return TryR;
4235 
4236   return nullptr;
4237 }
4238 
4239 SDValue DAGCombiner::visitXOR(SDNode *N) {
4240   SDValue N0 = N->getOperand(0);
4241   SDValue N1 = N->getOperand(1);
4242   EVT VT = N0.getValueType();
4243 
4244   // fold vector ops
4245   if (VT.isVector()) {
4246     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4247       return FoldedVOp;
4248 
4249     // fold (xor x, 0) -> x, vector edition
4250     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4251       return N1;
4252     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4253       return N0;
4254   }
4255 
4256   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4257   if (N0.isUndef() && N1.isUndef())
4258     return DAG.getConstant(0, SDLoc(N), VT);
4259   // fold (xor x, undef) -> undef
4260   if (N0.isUndef())
4261     return N0;
4262   if (N1.isUndef())
4263     return N1;
4264   // fold (xor c1, c2) -> c1^c2
4265   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4266   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4267   if (N0C && N1C)
4268     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4269   // canonicalize constant to RHS
4270   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4271      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4272     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4273   // fold (xor x, 0) -> x
4274   if (isNullConstant(N1))
4275     return N0;
4276   // reassociate xor
4277   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4278     return RXOR;
4279 
4280   // fold !(x cc y) -> (x !cc y)
4281   SDValue LHS, RHS, CC;
4282   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4283     bool isInt = LHS.getValueType().isInteger();
4284     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4285                                                isInt);
4286 
4287     if (!LegalOperations ||
4288         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4289       switch (N0.getOpcode()) {
4290       default:
4291         llvm_unreachable("Unhandled SetCC Equivalent!");
4292       case ISD::SETCC:
4293         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4294       case ISD::SELECT_CC:
4295         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4296                                N0.getOperand(3), NotCC);
4297       }
4298     }
4299   }
4300 
4301   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4302   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4303       N0.getNode()->hasOneUse() &&
4304       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4305     SDValue V = N0.getOperand(0);
4306     SDLoc DL(N0);
4307     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4308                     DAG.getConstant(1, DL, V.getValueType()));
4309     AddToWorklist(V.getNode());
4310     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4311   }
4312 
4313   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4314   if (isOneConstant(N1) && VT == MVT::i1 &&
4315       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4316     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4317     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4318       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4319       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4320       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4321       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4322       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4323     }
4324   }
4325   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4326   if (isAllOnesConstant(N1) &&
4327       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4328     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4329     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4330       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4331       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4332       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4333       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4334       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4335     }
4336   }
4337   // fold (xor (and x, y), y) -> (and (not x), y)
4338   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4339       N0->getOperand(1) == N1) {
4340     SDValue X = N0->getOperand(0);
4341     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4342     AddToWorklist(NotX.getNode());
4343     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4344   }
4345   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4346   if (N1C && N0.getOpcode() == ISD::XOR) {
4347     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4348       SDLoc DL(N);
4349       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4350                          DAG.getConstant(N1C->getAPIntValue() ^
4351                                          N00C->getAPIntValue(), DL, VT));
4352     }
4353     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4354       SDLoc DL(N);
4355       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4356                          DAG.getConstant(N1C->getAPIntValue() ^
4357                                          N01C->getAPIntValue(), DL, VT));
4358     }
4359   }
4360   // fold (xor x, x) -> 0
4361   if (N0 == N1)
4362     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4363 
4364   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4365   // Here is a concrete example of this equivalence:
4366   // i16   x ==  14
4367   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4368   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4369   //
4370   // =>
4371   //
4372   // i16     ~1      == 0b1111111111111110
4373   // i16 rol(~1, 14) == 0b1011111111111111
4374   //
4375   // Some additional tips to help conceptualize this transform:
4376   // - Try to see the operation as placing a single zero in a value of all ones.
4377   // - There exists no value for x which would allow the result to contain zero.
4378   // - Values of x larger than the bitwidth are undefined and do not require a
4379   //   consistent result.
4380   // - Pushing the zero left requires shifting one bits in from the right.
4381   // A rotate left of ~1 is a nice way of achieving the desired result.
4382   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4383       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4384     SDLoc DL(N);
4385     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4386                        N0.getOperand(1));
4387   }
4388 
4389   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4390   if (N0.getOpcode() == N1.getOpcode())
4391     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4392       return Tmp;
4393 
4394   // Simplify the expression using non-local knowledge.
4395   if (!VT.isVector() &&
4396       SimplifyDemandedBits(SDValue(N, 0)))
4397     return SDValue(N, 0);
4398 
4399   return SDValue();
4400 }
4401 
4402 /// Handle transforms common to the three shifts, when the shift amount is a
4403 /// constant.
4404 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4405   SDNode *LHS = N->getOperand(0).getNode();
4406   if (!LHS->hasOneUse()) return SDValue();
4407 
4408   // We want to pull some binops through shifts, so that we have (and (shift))
4409   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4410   // thing happens with address calculations, so it's important to canonicalize
4411   // it.
4412   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4413 
4414   switch (LHS->getOpcode()) {
4415   default: return SDValue();
4416   case ISD::OR:
4417   case ISD::XOR:
4418     HighBitSet = false; // We can only transform sra if the high bit is clear.
4419     break;
4420   case ISD::AND:
4421     HighBitSet = true;  // We can only transform sra if the high bit is set.
4422     break;
4423   case ISD::ADD:
4424     if (N->getOpcode() != ISD::SHL)
4425       return SDValue(); // only shl(add) not sr[al](add).
4426     HighBitSet = false; // We can only transform sra if the high bit is clear.
4427     break;
4428   }
4429 
4430   // We require the RHS of the binop to be a constant and not opaque as well.
4431   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4432   if (!BinOpCst) return SDValue();
4433 
4434   // FIXME: disable this unless the input to the binop is a shift by a constant.
4435   // If it is not a shift, it pessimizes some common cases like:
4436   //
4437   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4438   //    int bar(int *X, int i) { return X[i & 255]; }
4439   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4440   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4441        BinOpLHSVal->getOpcode() != ISD::SRA &&
4442        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4443       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4444     return SDValue();
4445 
4446   EVT VT = N->getValueType(0);
4447 
4448   // If this is a signed shift right, and the high bit is modified by the
4449   // logical operation, do not perform the transformation. The highBitSet
4450   // boolean indicates the value of the high bit of the constant which would
4451   // cause it to be modified for this operation.
4452   if (N->getOpcode() == ISD::SRA) {
4453     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4454     if (BinOpRHSSignSet != HighBitSet)
4455       return SDValue();
4456   }
4457 
4458   if (!TLI.isDesirableToCommuteWithShift(LHS))
4459     return SDValue();
4460 
4461   // Fold the constants, shifting the binop RHS by the shift amount.
4462   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4463                                N->getValueType(0),
4464                                LHS->getOperand(1), N->getOperand(1));
4465   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4466 
4467   // Create the new shift.
4468   SDValue NewShift = DAG.getNode(N->getOpcode(),
4469                                  SDLoc(LHS->getOperand(0)),
4470                                  VT, LHS->getOperand(0), N->getOperand(1));
4471 
4472   // Create the new binop.
4473   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4474 }
4475 
4476 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4477   assert(N->getOpcode() == ISD::TRUNCATE);
4478   assert(N->getOperand(0).getOpcode() == ISD::AND);
4479 
4480   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4481   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4482     SDValue N01 = N->getOperand(0).getOperand(1);
4483     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
4484       SDLoc DL(N);
4485       EVT TruncVT = N->getValueType(0);
4486       SDValue N00 = N->getOperand(0).getOperand(0);
4487       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
4488       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
4489       AddToWorklist(Trunc00.getNode());
4490       AddToWorklist(Trunc01.getNode());
4491       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
4492     }
4493   }
4494 
4495   return SDValue();
4496 }
4497 
4498 SDValue DAGCombiner::visitRotate(SDNode *N) {
4499   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4500   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4501       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4502     if (SDValue NewOp1 =
4503             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4504       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4505                          N->getOperand(0), NewOp1);
4506   }
4507   return SDValue();
4508 }
4509 
4510 SDValue DAGCombiner::visitSHL(SDNode *N) {
4511   SDValue N0 = N->getOperand(0);
4512   SDValue N1 = N->getOperand(1);
4513   EVT VT = N0.getValueType();
4514   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4515 
4516   // fold vector ops
4517   if (VT.isVector()) {
4518     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4519       return FoldedVOp;
4520 
4521     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4522     // If setcc produces all-one true value then:
4523     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4524     if (N1CV && N1CV->isConstant()) {
4525       if (N0.getOpcode() == ISD::AND) {
4526         SDValue N00 = N0->getOperand(0);
4527         SDValue N01 = N0->getOperand(1);
4528         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4529 
4530         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4531             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4532                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4533           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4534                                                      N01CV, N1CV))
4535             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4536         }
4537       }
4538     }
4539   }
4540 
4541   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4542 
4543   // fold (shl c1, c2) -> c1<<c2
4544   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4545   if (N0C && N1C && !N1C->isOpaque())
4546     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4547   // fold (shl 0, x) -> 0
4548   if (isNullConstant(N0))
4549     return N0;
4550   // fold (shl x, c >= size(x)) -> undef
4551   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4552     return DAG.getUNDEF(VT);
4553   // fold (shl x, 0) -> x
4554   if (N1C && N1C->isNullValue())
4555     return N0;
4556   // fold (shl undef, x) -> 0
4557   if (N0.isUndef())
4558     return DAG.getConstant(0, SDLoc(N), VT);
4559   // if (shl x, c) is known to be zero, return 0
4560   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4561                             APInt::getAllOnesValue(OpSizeInBits)))
4562     return DAG.getConstant(0, SDLoc(N), VT);
4563   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4564   if (N1.getOpcode() == ISD::TRUNCATE &&
4565       N1.getOperand(0).getOpcode() == ISD::AND) {
4566     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4567       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4568   }
4569 
4570   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4571     return SDValue(N, 0);
4572 
4573   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4574   if (N1C && N0.getOpcode() == ISD::SHL) {
4575     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4576       SDLoc DL(N);
4577       APInt c1 = N0C1->getAPIntValue();
4578       APInt c2 = N1C->getAPIntValue();
4579       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4580 
4581       APInt Sum = c1 + c2;
4582       if (Sum.uge(OpSizeInBits))
4583         return DAG.getConstant(0, DL, VT);
4584 
4585       return DAG.getNode(
4586           ISD::SHL, DL, VT, N0.getOperand(0),
4587           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4588     }
4589   }
4590 
4591   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4592   // For this to be valid, the second form must not preserve any of the bits
4593   // that are shifted out by the inner shift in the first form.  This means
4594   // the outer shift size must be >= the number of bits added by the ext.
4595   // As a corollary, we don't care what kind of ext it is.
4596   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4597               N0.getOpcode() == ISD::ANY_EXTEND ||
4598               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4599       N0.getOperand(0).getOpcode() == ISD::SHL) {
4600     SDValue N0Op0 = N0.getOperand(0);
4601     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4602       APInt c1 = N0Op0C1->getAPIntValue();
4603       APInt c2 = N1C->getAPIntValue();
4604       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4605 
4606       EVT InnerShiftVT = N0Op0.getValueType();
4607       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4608       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
4609         SDLoc DL(N0);
4610         APInt Sum = c1 + c2;
4611         if (Sum.uge(OpSizeInBits))
4612           return DAG.getConstant(0, DL, VT);
4613 
4614         return DAG.getNode(
4615             ISD::SHL, DL, VT,
4616             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
4617             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4618       }
4619     }
4620   }
4621 
4622   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4623   // Only fold this if the inner zext has no other uses to avoid increasing
4624   // the total number of instructions.
4625   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4626       N0.getOperand(0).getOpcode() == ISD::SRL) {
4627     SDValue N0Op0 = N0.getOperand(0);
4628     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4629       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
4630         uint64_t c1 = N0Op0C1->getZExtValue();
4631         uint64_t c2 = N1C->getZExtValue();
4632         if (c1 == c2) {
4633           SDValue NewOp0 = N0.getOperand(0);
4634           EVT CountVT = NewOp0.getOperand(1).getValueType();
4635           SDLoc DL(N);
4636           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4637                                        NewOp0,
4638                                        DAG.getConstant(c2, DL, CountVT));
4639           AddToWorklist(NewSHL.getNode());
4640           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4641         }
4642       }
4643     }
4644   }
4645 
4646   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4647   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4648   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4649       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4650     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4651       uint64_t C1 = N0C1->getZExtValue();
4652       uint64_t C2 = N1C->getZExtValue();
4653       SDLoc DL(N);
4654       if (C1 <= C2)
4655         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4656                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4657       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4658                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4659     }
4660   }
4661 
4662   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4663   //                               (and (srl x, (sub c1, c2), MASK)
4664   // Only fold this if the inner shift has no other uses -- if it does, folding
4665   // this will increase the total number of instructions.
4666   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4667     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4668       uint64_t c1 = N0C1->getZExtValue();
4669       if (c1 < OpSizeInBits) {
4670         uint64_t c2 = N1C->getZExtValue();
4671         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4672         SDValue Shift;
4673         if (c2 > c1) {
4674           Mask = Mask.shl(c2 - c1);
4675           SDLoc DL(N);
4676           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4677                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4678         } else {
4679           Mask = Mask.lshr(c1 - c2);
4680           SDLoc DL(N);
4681           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4682                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4683         }
4684         SDLoc DL(N0);
4685         return DAG.getNode(ISD::AND, DL, VT, Shift,
4686                            DAG.getConstant(Mask, DL, VT));
4687       }
4688     }
4689   }
4690 
4691   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4692   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
4693       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
4694     unsigned BitSize = VT.getScalarSizeInBits();
4695     SDLoc DL(N);
4696     SDValue AllBits = DAG.getConstant(APInt::getAllOnesValue(BitSize), DL, VT);
4697     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
4698     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
4699   }
4700 
4701   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4702   // Variant of version done on multiply, except mul by a power of 2 is turned
4703   // into a shift.
4704   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4705       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
4706       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
4707     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4708     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4709     AddToWorklist(Shl0.getNode());
4710     AddToWorklist(Shl1.getNode());
4711     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4712   }
4713 
4714   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4715   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
4716       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
4717       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
4718     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4719     if (isConstantOrConstantVector(Shl))
4720       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
4721   }
4722 
4723   if (N1C && !N1C->isOpaque())
4724     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4725       return NewSHL;
4726 
4727   return SDValue();
4728 }
4729 
4730 SDValue DAGCombiner::visitSRA(SDNode *N) {
4731   SDValue N0 = N->getOperand(0);
4732   SDValue N1 = N->getOperand(1);
4733   EVT VT = N0.getValueType();
4734   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4735 
4736   // Arithmetic shifting an all-sign-bit value is a no-op.
4737   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
4738     return N0;
4739 
4740   // fold vector ops
4741   if (VT.isVector())
4742     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4743       return FoldedVOp;
4744 
4745   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4746 
4747   // fold (sra c1, c2) -> (sra c1, c2)
4748   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4749   if (N0C && N1C && !N1C->isOpaque())
4750     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4751   // fold (sra 0, x) -> 0
4752   if (isNullConstant(N0))
4753     return N0;
4754   // fold (sra -1, x) -> -1
4755   if (isAllOnesConstant(N0))
4756     return N0;
4757   // fold (sra x, c >= size(x)) -> undef
4758   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4759     return DAG.getUNDEF(VT);
4760   // fold (sra x, 0) -> x
4761   if (N1C && N1C->isNullValue())
4762     return N0;
4763   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4764   // sext_inreg.
4765   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4766     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4767     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4768     if (VT.isVector())
4769       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4770                                ExtVT, VT.getVectorNumElements());
4771     if ((!LegalOperations ||
4772          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4773       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4774                          N0.getOperand(0), DAG.getValueType(ExtVT));
4775   }
4776 
4777   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4778   if (N1C && N0.getOpcode() == ISD::SRA) {
4779     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4780       SDLoc DL(N);
4781       APInt c1 = N0C1->getAPIntValue();
4782       APInt c2 = N1C->getAPIntValue();
4783       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4784 
4785       APInt Sum = c1 + c2;
4786       if (Sum.uge(OpSizeInBits))
4787         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
4788 
4789       return DAG.getNode(
4790           ISD::SRA, DL, VT, N0.getOperand(0),
4791           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4792     }
4793   }
4794 
4795   // fold (sra (shl X, m), (sub result_size, n))
4796   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4797   // result_size - n != m.
4798   // If truncate is free for the target sext(shl) is likely to result in better
4799   // code.
4800   if (N0.getOpcode() == ISD::SHL && N1C) {
4801     // Get the two constanst of the shifts, CN0 = m, CN = n.
4802     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4803     if (N01C) {
4804       LLVMContext &Ctx = *DAG.getContext();
4805       // Determine what the truncate's result bitsize and type would be.
4806       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4807 
4808       if (VT.isVector())
4809         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4810 
4811       // Determine the residual right-shift amount.
4812       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4813 
4814       // If the shift is not a no-op (in which case this should be just a sign
4815       // extend already), the truncated to type is legal, sign_extend is legal
4816       // on that type, and the truncate to that type is both legal and free,
4817       // perform the transform.
4818       if ((ShiftAmt > 0) &&
4819           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4820           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4821           TLI.isTruncateFree(VT, TruncVT)) {
4822 
4823         SDLoc DL(N);
4824         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4825             getShiftAmountTy(N0.getOperand(0).getValueType()));
4826         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4827                                     N0.getOperand(0), Amt);
4828         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4829                                     Shift);
4830         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4831                            N->getValueType(0), Trunc);
4832       }
4833     }
4834   }
4835 
4836   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4837   if (N1.getOpcode() == ISD::TRUNCATE &&
4838       N1.getOperand(0).getOpcode() == ISD::AND) {
4839     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4840       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4841   }
4842 
4843   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4844   //      if c1 is equal to the number of bits the trunc removes
4845   if (N0.getOpcode() == ISD::TRUNCATE &&
4846       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4847        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4848       N0.getOperand(0).hasOneUse() &&
4849       N0.getOperand(0).getOperand(1).hasOneUse() &&
4850       N1C) {
4851     SDValue N0Op0 = N0.getOperand(0);
4852     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4853       unsigned LargeShiftVal = LargeShift->getZExtValue();
4854       EVT LargeVT = N0Op0.getValueType();
4855 
4856       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4857         SDLoc DL(N);
4858         SDValue Amt =
4859           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4860                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4861         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4862                                   N0Op0.getOperand(0), Amt);
4863         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4864       }
4865     }
4866   }
4867 
4868   // Simplify, based on bits shifted out of the LHS.
4869   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4870     return SDValue(N, 0);
4871 
4872 
4873   // If the sign bit is known to be zero, switch this to a SRL.
4874   if (DAG.SignBitIsZero(N0))
4875     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4876 
4877   if (N1C && !N1C->isOpaque())
4878     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4879       return NewSRA;
4880 
4881   return SDValue();
4882 }
4883 
4884 SDValue DAGCombiner::visitSRL(SDNode *N) {
4885   SDValue N0 = N->getOperand(0);
4886   SDValue N1 = N->getOperand(1);
4887   EVT VT = N0.getValueType();
4888   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4889 
4890   // fold vector ops
4891   if (VT.isVector())
4892     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4893       return FoldedVOp;
4894 
4895   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4896 
4897   // fold (srl c1, c2) -> c1 >>u c2
4898   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4899   if (N0C && N1C && !N1C->isOpaque())
4900     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4901   // fold (srl 0, x) -> 0
4902   if (isNullConstant(N0))
4903     return N0;
4904   // fold (srl x, c >= size(x)) -> undef
4905   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4906     return DAG.getUNDEF(VT);
4907   // fold (srl x, 0) -> x
4908   if (N1C && N1C->isNullValue())
4909     return N0;
4910   // if (srl x, c) is known to be zero, return 0
4911   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4912                                    APInt::getAllOnesValue(OpSizeInBits)))
4913     return DAG.getConstant(0, SDLoc(N), VT);
4914 
4915   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4916   if (N1C && N0.getOpcode() == ISD::SRL) {
4917     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4918       SDLoc DL(N);
4919       APInt c1 = N0C1->getAPIntValue();
4920       APInt c2 = N1C->getAPIntValue();
4921       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4922 
4923       APInt Sum = c1 + c2;
4924       if (Sum.uge(OpSizeInBits))
4925         return DAG.getConstant(0, DL, VT);
4926 
4927       return DAG.getNode(
4928           ISD::SRL, DL, VT, N0.getOperand(0),
4929           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4930     }
4931   }
4932 
4933   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4934   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4935       N0.getOperand(0).getOpcode() == ISD::SRL &&
4936       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4937     uint64_t c1 =
4938       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4939     uint64_t c2 = N1C->getZExtValue();
4940     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4941     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4942     uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4943     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4944     if (c1 + OpSizeInBits == InnerShiftSize) {
4945       SDLoc DL(N0);
4946       if (c1 + c2 >= InnerShiftSize)
4947         return DAG.getConstant(0, DL, VT);
4948       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4949                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4950                                      N0.getOperand(0)->getOperand(0),
4951                                      DAG.getConstant(c1 + c2, DL,
4952                                                      ShiftCountVT)));
4953     }
4954   }
4955 
4956   // fold (srl (shl x, c), c) -> (and x, cst2)
4957   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4958       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
4959     SDLoc DL(N);
4960     APInt AllBits = APInt::getAllOnesValue(N0.getScalarValueSizeInBits());
4961     SDValue Mask =
4962         DAG.getNode(ISD::SRL, DL, VT, DAG.getConstant(AllBits, DL, VT), N1);
4963     AddToWorklist(Mask.getNode());
4964     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
4965   }
4966 
4967   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4968   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4969     // Shifting in all undef bits?
4970     EVT SmallVT = N0.getOperand(0).getValueType();
4971     unsigned BitSize = SmallVT.getScalarSizeInBits();
4972     if (N1C->getZExtValue() >= BitSize)
4973       return DAG.getUNDEF(VT);
4974 
4975     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4976       uint64_t ShiftAmt = N1C->getZExtValue();
4977       SDLoc DL0(N0);
4978       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4979                                        N0.getOperand(0),
4980                           DAG.getConstant(ShiftAmt, DL0,
4981                                           getShiftAmountTy(SmallVT)));
4982       AddToWorklist(SmallShift.getNode());
4983       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4984       SDLoc DL(N);
4985       return DAG.getNode(ISD::AND, DL, VT,
4986                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4987                          DAG.getConstant(Mask, DL, VT));
4988     }
4989   }
4990 
4991   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4992   // bit, which is unmodified by sra.
4993   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4994     if (N0.getOpcode() == ISD::SRA)
4995       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4996   }
4997 
4998   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4999   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5000       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5001     APInt KnownZero, KnownOne;
5002     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
5003 
5004     // If any of the input bits are KnownOne, then the input couldn't be all
5005     // zeros, thus the result of the srl will always be zero.
5006     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5007 
5008     // If all of the bits input the to ctlz node are known to be zero, then
5009     // the result of the ctlz is "32" and the result of the shift is one.
5010     APInt UnknownBits = ~KnownZero;
5011     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5012 
5013     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5014     if ((UnknownBits & (UnknownBits - 1)) == 0) {
5015       // Okay, we know that only that the single bit specified by UnknownBits
5016       // could be set on input to the CTLZ node. If this bit is set, the SRL
5017       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5018       // to an SRL/XOR pair, which is likely to simplify more.
5019       unsigned ShAmt = UnknownBits.countTrailingZeros();
5020       SDValue Op = N0.getOperand(0);
5021 
5022       if (ShAmt) {
5023         SDLoc DL(N0);
5024         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5025                   DAG.getConstant(ShAmt, DL,
5026                                   getShiftAmountTy(Op.getValueType())));
5027         AddToWorklist(Op.getNode());
5028       }
5029 
5030       SDLoc DL(N);
5031       return DAG.getNode(ISD::XOR, DL, VT,
5032                          Op, DAG.getConstant(1, DL, VT));
5033     }
5034   }
5035 
5036   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5037   if (N1.getOpcode() == ISD::TRUNCATE &&
5038       N1.getOperand(0).getOpcode() == ISD::AND) {
5039     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5040       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5041   }
5042 
5043   // fold operands of srl based on knowledge that the low bits are not
5044   // demanded.
5045   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5046     return SDValue(N, 0);
5047 
5048   if (N1C && !N1C->isOpaque())
5049     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5050       return NewSRL;
5051 
5052   // Attempt to convert a srl of a load into a narrower zero-extending load.
5053   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5054     return NarrowLoad;
5055 
5056   // Here is a common situation. We want to optimize:
5057   //
5058   //   %a = ...
5059   //   %b = and i32 %a, 2
5060   //   %c = srl i32 %b, 1
5061   //   brcond i32 %c ...
5062   //
5063   // into
5064   //
5065   //   %a = ...
5066   //   %b = and %a, 2
5067   //   %c = setcc eq %b, 0
5068   //   brcond %c ...
5069   //
5070   // However when after the source operand of SRL is optimized into AND, the SRL
5071   // itself may not be optimized further. Look for it and add the BRCOND into
5072   // the worklist.
5073   if (N->hasOneUse()) {
5074     SDNode *Use = *N->use_begin();
5075     if (Use->getOpcode() == ISD::BRCOND)
5076       AddToWorklist(Use);
5077     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5078       // Also look pass the truncate.
5079       Use = *Use->use_begin();
5080       if (Use->getOpcode() == ISD::BRCOND)
5081         AddToWorklist(Use);
5082     }
5083   }
5084 
5085   return SDValue();
5086 }
5087 
5088 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5089   SDValue N0 = N->getOperand(0);
5090   EVT VT = N->getValueType(0);
5091 
5092   // fold (bswap c1) -> c2
5093   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5094     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5095   // fold (bswap (bswap x)) -> x
5096   if (N0.getOpcode() == ISD::BSWAP)
5097     return N0->getOperand(0);
5098   return SDValue();
5099 }
5100 
5101 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5102   SDValue N0 = N->getOperand(0);
5103 
5104   // fold (bitreverse (bitreverse x)) -> x
5105   if (N0.getOpcode() == ISD::BITREVERSE)
5106     return N0.getOperand(0);
5107   return SDValue();
5108 }
5109 
5110 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5111   SDValue N0 = N->getOperand(0);
5112   EVT VT = N->getValueType(0);
5113 
5114   // fold (ctlz c1) -> c2
5115   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5116     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5117   return SDValue();
5118 }
5119 
5120 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5121   SDValue N0 = N->getOperand(0);
5122   EVT VT = N->getValueType(0);
5123 
5124   // fold (ctlz_zero_undef c1) -> c2
5125   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5126     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5127   return SDValue();
5128 }
5129 
5130 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5131   SDValue N0 = N->getOperand(0);
5132   EVT VT = N->getValueType(0);
5133 
5134   // fold (cttz c1) -> c2
5135   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5136     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5137   return SDValue();
5138 }
5139 
5140 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5141   SDValue N0 = N->getOperand(0);
5142   EVT VT = N->getValueType(0);
5143 
5144   // fold (cttz_zero_undef c1) -> c2
5145   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5146     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5147   return SDValue();
5148 }
5149 
5150 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5151   SDValue N0 = N->getOperand(0);
5152   EVT VT = N->getValueType(0);
5153 
5154   // fold (ctpop c1) -> c2
5155   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5156     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5157   return SDValue();
5158 }
5159 
5160 
5161 /// \brief Generate Min/Max node
5162 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5163                                    SDValue RHS, SDValue True, SDValue False,
5164                                    ISD::CondCode CC, const TargetLowering &TLI,
5165                                    SelectionDAG &DAG) {
5166   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5167     return SDValue();
5168 
5169   switch (CC) {
5170   case ISD::SETOLT:
5171   case ISD::SETOLE:
5172   case ISD::SETLT:
5173   case ISD::SETLE:
5174   case ISD::SETULT:
5175   case ISD::SETULE: {
5176     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5177     if (TLI.isOperationLegal(Opcode, VT))
5178       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5179     return SDValue();
5180   }
5181   case ISD::SETOGT:
5182   case ISD::SETOGE:
5183   case ISD::SETGT:
5184   case ISD::SETGE:
5185   case ISD::SETUGT:
5186   case ISD::SETUGE: {
5187     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5188     if (TLI.isOperationLegal(Opcode, VT))
5189       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5190     return SDValue();
5191   }
5192   default:
5193     return SDValue();
5194   }
5195 }
5196 
5197 // TODO: We should handle other cases of selecting between {-1,0,1} here.
5198 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5199   SDValue Cond = N->getOperand(0);
5200   SDValue N1 = N->getOperand(1);
5201   SDValue N2 = N->getOperand(2);
5202   EVT VT = N->getValueType(0);
5203   EVT CondVT = Cond.getValueType();
5204   SDLoc DL(N);
5205 
5206   // fold (select Cond, 0, 1) -> (xor Cond, 1)
5207   // We can't do this reliably if integer based booleans have different contents
5208   // to floating point based booleans. This is because we can't tell whether we
5209   // have an integer-based boolean or a floating-point-based boolean unless we
5210   // can find the SETCC that produced it and inspect its operands. This is
5211   // fairly easy if C is the SETCC node, but it can potentially be
5212   // undiscoverable (or not reasonably discoverable). For example, it could be
5213   // in another basic block or it could require searching a complicated
5214   // expression.
5215   if (VT.isInteger() &&
5216       (CondVT == MVT::i1 || (CondVT.isInteger() &&
5217                              TLI.getBooleanContents(false, true) ==
5218                                  TargetLowering::ZeroOrOneBooleanContent &&
5219                              TLI.getBooleanContents(false, false) ==
5220                                  TargetLowering::ZeroOrOneBooleanContent)) &&
5221       isNullConstant(N1) && isOneConstant(N2)) {
5222     SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond,
5223                                   DAG.getConstant(1, DL, CondVT));
5224     if (VT.bitsEq(CondVT))
5225       return NotCond;
5226     return DAG.getZExtOrTrunc(NotCond, DL, VT);
5227   }
5228 
5229   return SDValue();
5230 }
5231 
5232 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5233   SDValue N0 = N->getOperand(0);
5234   SDValue N1 = N->getOperand(1);
5235   SDValue N2 = N->getOperand(2);
5236   EVT VT = N->getValueType(0);
5237   EVT VT0 = N0.getValueType();
5238 
5239   // fold (select C, X, X) -> X
5240   if (N1 == N2)
5241     return N1;
5242   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5243     // fold (select true, X, Y) -> X
5244     // fold (select false, X, Y) -> Y
5245     return !N0C->isNullValue() ? N1 : N2;
5246   }
5247   // fold (select C, 1, X) -> (or C, X)
5248   if (VT == MVT::i1 && isOneConstant(N1))
5249     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5250 
5251   if (SDValue V = foldSelectOfConstants(N))
5252     return V;
5253 
5254   // fold (select C, 0, X) -> (and (not C), X)
5255   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5256     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5257     AddToWorklist(NOTNode.getNode());
5258     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5259   }
5260   // fold (select C, X, 1) -> (or (not C), X)
5261   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5262     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5263     AddToWorklist(NOTNode.getNode());
5264     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5265   }
5266   // fold (select C, X, 0) -> (and C, X)
5267   if (VT == MVT::i1 && isNullConstant(N2))
5268     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5269   // fold (select X, X, Y) -> (or X, Y)
5270   // fold (select X, 1, Y) -> (or X, Y)
5271   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5272     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5273   // fold (select X, Y, X) -> (and X, Y)
5274   // fold (select X, Y, 0) -> (and X, Y)
5275   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5276     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5277 
5278   // If we can fold this based on the true/false value, do so.
5279   if (SimplifySelectOps(N, N1, N2))
5280     return SDValue(N, 0);  // Don't revisit N.
5281 
5282   if (VT0 == MVT::i1) {
5283     // The code in this block deals with the following 2 equivalences:
5284     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5285     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5286     // The target can specify its preferred form with the
5287     // shouldNormalizeToSelectSequence() callback. However we always transform
5288     // to the right anyway if we find the inner select exists in the DAG anyway
5289     // and we always transform to the left side if we know that we can further
5290     // optimize the combination of the conditions.
5291     bool normalizeToSequence
5292       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5293     // select (and Cond0, Cond1), X, Y
5294     //   -> select Cond0, (select Cond1, X, Y), Y
5295     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5296       SDValue Cond0 = N0->getOperand(0);
5297       SDValue Cond1 = N0->getOperand(1);
5298       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5299                                         N1.getValueType(), Cond1, N1, N2);
5300       if (normalizeToSequence || !InnerSelect.use_empty())
5301         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5302                            InnerSelect, N2);
5303     }
5304     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5305     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5306       SDValue Cond0 = N0->getOperand(0);
5307       SDValue Cond1 = N0->getOperand(1);
5308       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5309                                         N1.getValueType(), Cond1, N1, N2);
5310       if (normalizeToSequence || !InnerSelect.use_empty())
5311         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5312                            InnerSelect);
5313     }
5314 
5315     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5316     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5317       SDValue N1_0 = N1->getOperand(0);
5318       SDValue N1_1 = N1->getOperand(1);
5319       SDValue N1_2 = N1->getOperand(2);
5320       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5321         // Create the actual and node if we can generate good code for it.
5322         if (!normalizeToSequence) {
5323           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5324                                     N0, N1_0);
5325           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5326                              N1_1, N2);
5327         }
5328         // Otherwise see if we can optimize the "and" to a better pattern.
5329         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5330           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5331                              N1_1, N2);
5332       }
5333     }
5334     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5335     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5336       SDValue N2_0 = N2->getOperand(0);
5337       SDValue N2_1 = N2->getOperand(1);
5338       SDValue N2_2 = N2->getOperand(2);
5339       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5340         // Create the actual or node if we can generate good code for it.
5341         if (!normalizeToSequence) {
5342           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5343                                    N0, N2_0);
5344           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5345                              N1, N2_2);
5346         }
5347         // Otherwise see if we can optimize to a better pattern.
5348         if (SDValue Combined = visitORLike(N0, N2_0, N))
5349           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5350                              N1, N2_2);
5351       }
5352     }
5353   }
5354 
5355   // select (xor Cond, 1), X, Y -> select Cond, Y, X
5356   // select (xor Cond, 0), X, Y -> selext Cond, X, Y
5357   if (VT0 == MVT::i1) {
5358     if (N0->getOpcode() == ISD::XOR) {
5359       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
5360         SDValue Cond0 = N0->getOperand(0);
5361         if (C->isOne())
5362           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5363                              Cond0, N2, N1);
5364         else
5365           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5366                              Cond0, N1, N2);
5367       }
5368     }
5369   }
5370 
5371   // fold selects based on a setcc into other things, such as min/max/abs
5372   if (N0.getOpcode() == ISD::SETCC) {
5373     // select x, y (fcmp lt x, y) -> fminnum x, y
5374     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5375     //
5376     // This is OK if we don't care about what happens if either operand is a
5377     // NaN.
5378     //
5379 
5380     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5381     // no signed zeros as well as no nans.
5382     const TargetOptions &Options = DAG.getTarget().Options;
5383     if (Options.UnsafeFPMath &&
5384         VT.isFloatingPoint() && N0.hasOneUse() &&
5385         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5386       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5387 
5388       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5389                                                 N0.getOperand(1), N1, N2, CC,
5390                                                 TLI, DAG))
5391         return FMinMax;
5392     }
5393 
5394     if ((!LegalOperations &&
5395          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5396         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5397       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5398                          N0.getOperand(0), N0.getOperand(1),
5399                          N1, N2, N0.getOperand(2));
5400     return SimplifySelect(SDLoc(N), N0, N1, N2);
5401   }
5402 
5403   return SDValue();
5404 }
5405 
5406 static
5407 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5408   SDLoc DL(N);
5409   EVT LoVT, HiVT;
5410   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5411 
5412   // Split the inputs.
5413   SDValue Lo, Hi, LL, LH, RL, RH;
5414   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5415   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5416 
5417   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5418   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5419 
5420   return std::make_pair(Lo, Hi);
5421 }
5422 
5423 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5424 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5425 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5426   SDLoc DL(N);
5427   SDValue Cond = N->getOperand(0);
5428   SDValue LHS = N->getOperand(1);
5429   SDValue RHS = N->getOperand(2);
5430   EVT VT = N->getValueType(0);
5431   int NumElems = VT.getVectorNumElements();
5432   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5433          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5434          Cond.getOpcode() == ISD::BUILD_VECTOR);
5435 
5436   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5437   // binary ones here.
5438   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5439     return SDValue();
5440 
5441   // We're sure we have an even number of elements due to the
5442   // concat_vectors we have as arguments to vselect.
5443   // Skip BV elements until we find one that's not an UNDEF
5444   // After we find an UNDEF element, keep looping until we get to half the
5445   // length of the BV and see if all the non-undef nodes are the same.
5446   ConstantSDNode *BottomHalf = nullptr;
5447   for (int i = 0; i < NumElems / 2; ++i) {
5448     if (Cond->getOperand(i)->isUndef())
5449       continue;
5450 
5451     if (BottomHalf == nullptr)
5452       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5453     else if (Cond->getOperand(i).getNode() != BottomHalf)
5454       return SDValue();
5455   }
5456 
5457   // Do the same for the second half of the BuildVector
5458   ConstantSDNode *TopHalf = nullptr;
5459   for (int i = NumElems / 2; i < NumElems; ++i) {
5460     if (Cond->getOperand(i)->isUndef())
5461       continue;
5462 
5463     if (TopHalf == nullptr)
5464       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5465     else if (Cond->getOperand(i).getNode() != TopHalf)
5466       return SDValue();
5467   }
5468 
5469   assert(TopHalf && BottomHalf &&
5470          "One half of the selector was all UNDEFs and the other was all the "
5471          "same value. This should have been addressed before this function.");
5472   return DAG.getNode(
5473       ISD::CONCAT_VECTORS, DL, VT,
5474       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5475       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5476 }
5477 
5478 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5479 
5480   if (Level >= AfterLegalizeTypes)
5481     return SDValue();
5482 
5483   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5484   SDValue Mask = MSC->getMask();
5485   SDValue Data  = MSC->getValue();
5486   SDLoc DL(N);
5487 
5488   // If the MSCATTER data type requires splitting and the mask is provided by a
5489   // SETCC, then split both nodes and its operands before legalization. This
5490   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5491   // and enables future optimizations (e.g. min/max pattern matching on X86).
5492   if (Mask.getOpcode() != ISD::SETCC)
5493     return SDValue();
5494 
5495   // Check if any splitting is required.
5496   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5497       TargetLowering::TypeSplitVector)
5498     return SDValue();
5499   SDValue MaskLo, MaskHi, Lo, Hi;
5500   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5501 
5502   EVT LoVT, HiVT;
5503   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5504 
5505   SDValue Chain = MSC->getChain();
5506 
5507   EVT MemoryVT = MSC->getMemoryVT();
5508   unsigned Alignment = MSC->getOriginalAlignment();
5509 
5510   EVT LoMemVT, HiMemVT;
5511   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5512 
5513   SDValue DataLo, DataHi;
5514   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5515 
5516   SDValue BasePtr = MSC->getBasePtr();
5517   SDValue IndexLo, IndexHi;
5518   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5519 
5520   MachineMemOperand *MMO = DAG.getMachineFunction().
5521     getMachineMemOperand(MSC->getPointerInfo(),
5522                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5523                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5524 
5525   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5526   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5527                             DL, OpsLo, MMO);
5528 
5529   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5530   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5531                             DL, OpsHi, MMO);
5532 
5533   AddToWorklist(Lo.getNode());
5534   AddToWorklist(Hi.getNode());
5535 
5536   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5537 }
5538 
5539 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5540 
5541   if (Level >= AfterLegalizeTypes)
5542     return SDValue();
5543 
5544   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5545   SDValue Mask = MST->getMask();
5546   SDValue Data  = MST->getValue();
5547   EVT VT = Data.getValueType();
5548   SDLoc DL(N);
5549 
5550   // If the MSTORE data type requires splitting and the mask is provided by a
5551   // SETCC, then split both nodes and its operands before legalization. This
5552   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5553   // and enables future optimizations (e.g. min/max pattern matching on X86).
5554   if (Mask.getOpcode() == ISD::SETCC) {
5555 
5556     // Check if any splitting is required.
5557     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5558         TargetLowering::TypeSplitVector)
5559       return SDValue();
5560 
5561     SDValue MaskLo, MaskHi, Lo, Hi;
5562     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5563 
5564     SDValue Chain = MST->getChain();
5565     SDValue Ptr   = MST->getBasePtr();
5566 
5567     EVT MemoryVT = MST->getMemoryVT();
5568     unsigned Alignment = MST->getOriginalAlignment();
5569 
5570     // if Alignment is equal to the vector size,
5571     // take the half of it for the second part
5572     unsigned SecondHalfAlignment =
5573       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
5574 
5575     EVT LoMemVT, HiMemVT;
5576     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5577 
5578     SDValue DataLo, DataHi;
5579     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5580 
5581     MachineMemOperand *MMO = DAG.getMachineFunction().
5582       getMachineMemOperand(MST->getPointerInfo(),
5583                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5584                            Alignment, MST->getAAInfo(), MST->getRanges());
5585 
5586     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5587                             MST->isTruncatingStore(),
5588                             MST->isCompressingStore());
5589 
5590     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
5591                                      MST->isCompressingStore());
5592 
5593     MMO = DAG.getMachineFunction().
5594       getMachineMemOperand(MST->getPointerInfo(),
5595                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5596                            SecondHalfAlignment, MST->getAAInfo(),
5597                            MST->getRanges());
5598 
5599     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5600                             MST->isTruncatingStore(),
5601                             MST->isCompressingStore());
5602 
5603     AddToWorklist(Lo.getNode());
5604     AddToWorklist(Hi.getNode());
5605 
5606     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5607   }
5608   return SDValue();
5609 }
5610 
5611 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5612 
5613   if (Level >= AfterLegalizeTypes)
5614     return SDValue();
5615 
5616   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5617   SDValue Mask = MGT->getMask();
5618   SDLoc DL(N);
5619 
5620   // If the MGATHER result requires splitting and the mask is provided by a
5621   // SETCC, then split both nodes and its operands before legalization. This
5622   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5623   // and enables future optimizations (e.g. min/max pattern matching on X86).
5624 
5625   if (Mask.getOpcode() != ISD::SETCC)
5626     return SDValue();
5627 
5628   EVT VT = N->getValueType(0);
5629 
5630   // Check if any splitting is required.
5631   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5632       TargetLowering::TypeSplitVector)
5633     return SDValue();
5634 
5635   SDValue MaskLo, MaskHi, Lo, Hi;
5636   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5637 
5638   SDValue Src0 = MGT->getValue();
5639   SDValue Src0Lo, Src0Hi;
5640   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5641 
5642   EVT LoVT, HiVT;
5643   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5644 
5645   SDValue Chain = MGT->getChain();
5646   EVT MemoryVT = MGT->getMemoryVT();
5647   unsigned Alignment = MGT->getOriginalAlignment();
5648 
5649   EVT LoMemVT, HiMemVT;
5650   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5651 
5652   SDValue BasePtr = MGT->getBasePtr();
5653   SDValue Index = MGT->getIndex();
5654   SDValue IndexLo, IndexHi;
5655   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5656 
5657   MachineMemOperand *MMO = DAG.getMachineFunction().
5658     getMachineMemOperand(MGT->getPointerInfo(),
5659                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5660                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5661 
5662   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5663   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5664                             MMO);
5665 
5666   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5667   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5668                             MMO);
5669 
5670   AddToWorklist(Lo.getNode());
5671   AddToWorklist(Hi.getNode());
5672 
5673   // Build a factor node to remember that this load is independent of the
5674   // other one.
5675   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5676                       Hi.getValue(1));
5677 
5678   // Legalized the chain result - switch anything that used the old chain to
5679   // use the new one.
5680   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5681 
5682   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5683 
5684   SDValue RetOps[] = { GatherRes, Chain };
5685   return DAG.getMergeValues(RetOps, DL);
5686 }
5687 
5688 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5689 
5690   if (Level >= AfterLegalizeTypes)
5691     return SDValue();
5692 
5693   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5694   SDValue Mask = MLD->getMask();
5695   SDLoc DL(N);
5696 
5697   // If the MLOAD result requires splitting and the mask is provided by a
5698   // SETCC, then split both nodes and its operands before legalization. This
5699   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5700   // and enables future optimizations (e.g. min/max pattern matching on X86).
5701 
5702   if (Mask.getOpcode() == ISD::SETCC) {
5703     EVT VT = N->getValueType(0);
5704 
5705     // Check if any splitting is required.
5706     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5707         TargetLowering::TypeSplitVector)
5708       return SDValue();
5709 
5710     SDValue MaskLo, MaskHi, Lo, Hi;
5711     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5712 
5713     SDValue Src0 = MLD->getSrc0();
5714     SDValue Src0Lo, Src0Hi;
5715     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5716 
5717     EVT LoVT, HiVT;
5718     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5719 
5720     SDValue Chain = MLD->getChain();
5721     SDValue Ptr   = MLD->getBasePtr();
5722     EVT MemoryVT = MLD->getMemoryVT();
5723     unsigned Alignment = MLD->getOriginalAlignment();
5724 
5725     // if Alignment is equal to the vector size,
5726     // take the half of it for the second part
5727     unsigned SecondHalfAlignment =
5728       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5729          Alignment/2 : Alignment;
5730 
5731     EVT LoMemVT, HiMemVT;
5732     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5733 
5734     MachineMemOperand *MMO = DAG.getMachineFunction().
5735     getMachineMemOperand(MLD->getPointerInfo(),
5736                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5737                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5738 
5739     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5740                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
5741 
5742     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
5743                                      MLD->isExpandingLoad());
5744 
5745     MMO = DAG.getMachineFunction().
5746     getMachineMemOperand(MLD->getPointerInfo(),
5747                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5748                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5749 
5750     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5751                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
5752 
5753     AddToWorklist(Lo.getNode());
5754     AddToWorklist(Hi.getNode());
5755 
5756     // Build a factor node to remember that this load is independent of the
5757     // other one.
5758     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5759                         Hi.getValue(1));
5760 
5761     // Legalized the chain result - switch anything that used the old chain to
5762     // use the new one.
5763     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5764 
5765     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5766 
5767     SDValue RetOps[] = { LoadRes, Chain };
5768     return DAG.getMergeValues(RetOps, DL);
5769   }
5770   return SDValue();
5771 }
5772 
5773 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5774   SDValue N0 = N->getOperand(0);
5775   SDValue N1 = N->getOperand(1);
5776   SDValue N2 = N->getOperand(2);
5777   SDLoc DL(N);
5778 
5779   // fold (vselect C, X, X) -> X
5780   if (N1 == N2)
5781     return N1;
5782 
5783   // Canonicalize integer abs.
5784   // vselect (setg[te] X,  0),  X, -X ->
5785   // vselect (setgt    X, -1),  X, -X ->
5786   // vselect (setl[te] X,  0), -X,  X ->
5787   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5788   if (N0.getOpcode() == ISD::SETCC) {
5789     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5790     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5791     bool isAbs = false;
5792     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5793 
5794     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5795          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5796         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5797       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5798     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5799              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5800       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5801 
5802     if (isAbs) {
5803       EVT VT = LHS.getValueType();
5804       SDValue Shift = DAG.getNode(
5805           ISD::SRA, DL, VT, LHS,
5806           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
5807       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5808       AddToWorklist(Shift.getNode());
5809       AddToWorklist(Add.getNode());
5810       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5811     }
5812   }
5813 
5814   if (SimplifySelectOps(N, N1, N2))
5815     return SDValue(N, 0);  // Don't revisit N.
5816 
5817   // If the VSELECT result requires splitting and the mask is provided by a
5818   // SETCC, then split both nodes and its operands before legalization. This
5819   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5820   // and enables future optimizations (e.g. min/max pattern matching on X86).
5821   if (N0.getOpcode() == ISD::SETCC) {
5822     EVT VT = N->getValueType(0);
5823 
5824     // Check if any splitting is required.
5825     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5826         TargetLowering::TypeSplitVector)
5827       return SDValue();
5828 
5829     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5830     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5831     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5832     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5833 
5834     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5835     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5836 
5837     // Add the new VSELECT nodes to the work list in case they need to be split
5838     // again.
5839     AddToWorklist(Lo.getNode());
5840     AddToWorklist(Hi.getNode());
5841 
5842     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5843   }
5844 
5845   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5846   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5847     return N1;
5848   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5849   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5850     return N2;
5851 
5852   // The ConvertSelectToConcatVector function is assuming both the above
5853   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5854   // and addressed.
5855   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5856       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5857       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5858     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5859       return CV;
5860   }
5861 
5862   return SDValue();
5863 }
5864 
5865 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5866   SDValue N0 = N->getOperand(0);
5867   SDValue N1 = N->getOperand(1);
5868   SDValue N2 = N->getOperand(2);
5869   SDValue N3 = N->getOperand(3);
5870   SDValue N4 = N->getOperand(4);
5871   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5872 
5873   // fold select_cc lhs, rhs, x, x, cc -> x
5874   if (N2 == N3)
5875     return N2;
5876 
5877   // Determine if the condition we're dealing with is constant
5878   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5879                                   CC, SDLoc(N), false)) {
5880     AddToWorklist(SCC.getNode());
5881 
5882     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5883       if (!SCCC->isNullValue())
5884         return N2;    // cond always true -> true val
5885       else
5886         return N3;    // cond always false -> false val
5887     } else if (SCC->isUndef()) {
5888       // When the condition is UNDEF, just return the first operand. This is
5889       // coherent the DAG creation, no setcc node is created in this case
5890       return N2;
5891     } else if (SCC.getOpcode() == ISD::SETCC) {
5892       // Fold to a simpler select_cc
5893       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5894                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5895                          SCC.getOperand(2));
5896     }
5897   }
5898 
5899   // If we can fold this based on the true/false value, do so.
5900   if (SimplifySelectOps(N, N2, N3))
5901     return SDValue(N, 0);  // Don't revisit N.
5902 
5903   // fold select_cc into other things, such as min/max/abs
5904   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5905 }
5906 
5907 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5908   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5909                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5910                        SDLoc(N));
5911 }
5912 
5913 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5914   SDValue LHS = N->getOperand(0);
5915   SDValue RHS = N->getOperand(1);
5916   SDValue Carry = N->getOperand(2);
5917   SDValue Cond = N->getOperand(3);
5918 
5919   // If Carry is false, fold to a regular SETCC.
5920   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5921     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5922 
5923   return SDValue();
5924 }
5925 
5926 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5927 /// a build_vector of constants.
5928 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5929 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5930 /// Vector extends are not folded if operations are legal; this is to
5931 /// avoid introducing illegal build_vector dag nodes.
5932 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5933                                          SelectionDAG &DAG, bool LegalTypes,
5934                                          bool LegalOperations) {
5935   unsigned Opcode = N->getOpcode();
5936   SDValue N0 = N->getOperand(0);
5937   EVT VT = N->getValueType(0);
5938 
5939   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5940          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5941          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5942          && "Expected EXTEND dag node in input!");
5943 
5944   // fold (sext c1) -> c1
5945   // fold (zext c1) -> c1
5946   // fold (aext c1) -> c1
5947   if (isa<ConstantSDNode>(N0))
5948     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5949 
5950   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5951   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5952   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5953   EVT SVT = VT.getScalarType();
5954   if (!(VT.isVector() &&
5955       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5956       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5957     return nullptr;
5958 
5959   // We can fold this node into a build_vector.
5960   unsigned VTBits = SVT.getSizeInBits();
5961   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
5962   SmallVector<SDValue, 8> Elts;
5963   unsigned NumElts = VT.getVectorNumElements();
5964   SDLoc DL(N);
5965 
5966   for (unsigned i=0; i != NumElts; ++i) {
5967     SDValue Op = N0->getOperand(i);
5968     if (Op->isUndef()) {
5969       Elts.push_back(DAG.getUNDEF(SVT));
5970       continue;
5971     }
5972 
5973     SDLoc DL(Op);
5974     // Get the constant value and if needed trunc it to the size of the type.
5975     // Nodes like build_vector might have constants wider than the scalar type.
5976     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5977     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5978       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5979     else
5980       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5981   }
5982 
5983   return DAG.getBuildVector(VT, DL, Elts).getNode();
5984 }
5985 
5986 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5987 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5988 // transformation. Returns true if extension are possible and the above
5989 // mentioned transformation is profitable.
5990 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5991                                     unsigned ExtOpc,
5992                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5993                                     const TargetLowering &TLI) {
5994   bool HasCopyToRegUses = false;
5995   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5996   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5997                             UE = N0.getNode()->use_end();
5998        UI != UE; ++UI) {
5999     SDNode *User = *UI;
6000     if (User == N)
6001       continue;
6002     if (UI.getUse().getResNo() != N0.getResNo())
6003       continue;
6004     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6005     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6006       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6007       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6008         // Sign bits will be lost after a zext.
6009         return false;
6010       bool Add = false;
6011       for (unsigned i = 0; i != 2; ++i) {
6012         SDValue UseOp = User->getOperand(i);
6013         if (UseOp == N0)
6014           continue;
6015         if (!isa<ConstantSDNode>(UseOp))
6016           return false;
6017         Add = true;
6018       }
6019       if (Add)
6020         ExtendNodes.push_back(User);
6021       continue;
6022     }
6023     // If truncates aren't free and there are users we can't
6024     // extend, it isn't worthwhile.
6025     if (!isTruncFree)
6026       return false;
6027     // Remember if this value is live-out.
6028     if (User->getOpcode() == ISD::CopyToReg)
6029       HasCopyToRegUses = true;
6030   }
6031 
6032   if (HasCopyToRegUses) {
6033     bool BothLiveOut = false;
6034     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6035          UI != UE; ++UI) {
6036       SDUse &Use = UI.getUse();
6037       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6038         BothLiveOut = true;
6039         break;
6040       }
6041     }
6042     if (BothLiveOut)
6043       // Both unextended and extended values are live out. There had better be
6044       // a good reason for the transformation.
6045       return ExtendNodes.size();
6046   }
6047   return true;
6048 }
6049 
6050 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6051                                   SDValue Trunc, SDValue ExtLoad,
6052                                   const SDLoc &DL, ISD::NodeType ExtType) {
6053   // Extend SetCC uses if necessary.
6054   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6055     SDNode *SetCC = SetCCs[i];
6056     SmallVector<SDValue, 4> Ops;
6057 
6058     for (unsigned j = 0; j != 2; ++j) {
6059       SDValue SOp = SetCC->getOperand(j);
6060       if (SOp == Trunc)
6061         Ops.push_back(ExtLoad);
6062       else
6063         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6064     }
6065 
6066     Ops.push_back(SetCC->getOperand(2));
6067     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6068   }
6069 }
6070 
6071 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6072 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6073   SDValue N0 = N->getOperand(0);
6074   EVT DstVT = N->getValueType(0);
6075   EVT SrcVT = N0.getValueType();
6076 
6077   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6078           N->getOpcode() == ISD::ZERO_EXTEND) &&
6079          "Unexpected node type (not an extend)!");
6080 
6081   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6082   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6083   //   (v8i32 (sext (v8i16 (load x))))
6084   // into:
6085   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6086   //                          (v4i32 (sextload (x + 16)))))
6087   // Where uses of the original load, i.e.:
6088   //   (v8i16 (load x))
6089   // are replaced with:
6090   //   (v8i16 (truncate
6091   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6092   //                            (v4i32 (sextload (x + 16)))))))
6093   //
6094   // This combine is only applicable to illegal, but splittable, vectors.
6095   // All legal types, and illegal non-vector types, are handled elsewhere.
6096   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6097   //
6098   if (N0->getOpcode() != ISD::LOAD)
6099     return SDValue();
6100 
6101   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6102 
6103   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6104       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6105       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6106     return SDValue();
6107 
6108   SmallVector<SDNode *, 4> SetCCs;
6109   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6110     return SDValue();
6111 
6112   ISD::LoadExtType ExtType =
6113       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6114 
6115   // Try to split the vector types to get down to legal types.
6116   EVT SplitSrcVT = SrcVT;
6117   EVT SplitDstVT = DstVT;
6118   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6119          SplitSrcVT.getVectorNumElements() > 1) {
6120     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6121     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6122   }
6123 
6124   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6125     return SDValue();
6126 
6127   SDLoc DL(N);
6128   const unsigned NumSplits =
6129       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6130   const unsigned Stride = SplitSrcVT.getStoreSize();
6131   SmallVector<SDValue, 4> Loads;
6132   SmallVector<SDValue, 4> Chains;
6133 
6134   SDValue BasePtr = LN0->getBasePtr();
6135   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6136     const unsigned Offset = Idx * Stride;
6137     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6138 
6139     SDValue SplitLoad = DAG.getExtLoad(
6140         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6141         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6142         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6143 
6144     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6145                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6146 
6147     Loads.push_back(SplitLoad.getValue(0));
6148     Chains.push_back(SplitLoad.getValue(1));
6149   }
6150 
6151   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6152   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6153 
6154   CombineTo(N, NewValue);
6155 
6156   // Replace uses of the original load (before extension)
6157   // with a truncate of the concatenated sextloaded vectors.
6158   SDValue Trunc =
6159       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6160   CombineTo(N0.getNode(), Trunc, NewChain);
6161   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6162                   (ISD::NodeType)N->getOpcode());
6163   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6164 }
6165 
6166 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6167   SDValue N0 = N->getOperand(0);
6168   EVT VT = N->getValueType(0);
6169 
6170   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6171                                               LegalOperations))
6172     return SDValue(Res, 0);
6173 
6174   // fold (sext (sext x)) -> (sext x)
6175   // fold (sext (aext x)) -> (sext x)
6176   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6177     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6178                        N0.getOperand(0));
6179 
6180   if (N0.getOpcode() == ISD::TRUNCATE) {
6181     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6182     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6183     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6184       SDNode *oye = N0.getOperand(0).getNode();
6185       if (NarrowLoad.getNode() != N0.getNode()) {
6186         CombineTo(N0.getNode(), NarrowLoad);
6187         // CombineTo deleted the truncate, if needed, but not what's under it.
6188         AddToWorklist(oye);
6189       }
6190       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6191     }
6192 
6193     // See if the value being truncated is already sign extended.  If so, just
6194     // eliminate the trunc/sext pair.
6195     SDValue Op = N0.getOperand(0);
6196     unsigned OpBits   = Op.getScalarValueSizeInBits();
6197     unsigned MidBits  = N0.getScalarValueSizeInBits();
6198     unsigned DestBits = VT.getScalarSizeInBits();
6199     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6200 
6201     if (OpBits == DestBits) {
6202       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6203       // bits, it is already ready.
6204       if (NumSignBits > DestBits-MidBits)
6205         return Op;
6206     } else if (OpBits < DestBits) {
6207       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6208       // bits, just sext from i32.
6209       if (NumSignBits > OpBits-MidBits)
6210         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6211     } else {
6212       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6213       // bits, just truncate to i32.
6214       if (NumSignBits > OpBits-MidBits)
6215         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6216     }
6217 
6218     // fold (sext (truncate x)) -> (sextinreg x).
6219     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6220                                                  N0.getValueType())) {
6221       if (OpBits < DestBits)
6222         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6223       else if (OpBits > DestBits)
6224         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6225       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6226                          DAG.getValueType(N0.getValueType()));
6227     }
6228   }
6229 
6230   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6231   // Only generate vector extloads when 1) they're legal, and 2) they are
6232   // deemed desirable by the target.
6233   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6234       ((!LegalOperations && !VT.isVector() &&
6235         !cast<LoadSDNode>(N0)->isVolatile()) ||
6236        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6237     bool DoXform = true;
6238     SmallVector<SDNode*, 4> SetCCs;
6239     if (!N0.hasOneUse())
6240       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6241     if (VT.isVector())
6242       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6243     if (DoXform) {
6244       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6245       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6246                                        LN0->getChain(),
6247                                        LN0->getBasePtr(), N0.getValueType(),
6248                                        LN0->getMemOperand());
6249       CombineTo(N, ExtLoad);
6250       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6251                                   N0.getValueType(), ExtLoad);
6252       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6253       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6254                       ISD::SIGN_EXTEND);
6255       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6256     }
6257   }
6258 
6259   // fold (sext (load x)) to multiple smaller sextloads.
6260   // Only on illegal but splittable vectors.
6261   if (SDValue ExtLoad = CombineExtLoad(N))
6262     return ExtLoad;
6263 
6264   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6265   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6266   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6267       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6268     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6269     EVT MemVT = LN0->getMemoryVT();
6270     if ((!LegalOperations && !LN0->isVolatile()) ||
6271         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6272       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6273                                        LN0->getChain(),
6274                                        LN0->getBasePtr(), MemVT,
6275                                        LN0->getMemOperand());
6276       CombineTo(N, ExtLoad);
6277       CombineTo(N0.getNode(),
6278                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6279                             N0.getValueType(), ExtLoad),
6280                 ExtLoad.getValue(1));
6281       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6282     }
6283   }
6284 
6285   // fold (sext (and/or/xor (load x), cst)) ->
6286   //      (and/or/xor (sextload x), (sext cst))
6287   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6288        N0.getOpcode() == ISD::XOR) &&
6289       isa<LoadSDNode>(N0.getOperand(0)) &&
6290       N0.getOperand(1).getOpcode() == ISD::Constant &&
6291       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6292       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6293     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6294     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6295       bool DoXform = true;
6296       SmallVector<SDNode*, 4> SetCCs;
6297       if (!N0.hasOneUse())
6298         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6299                                           SetCCs, TLI);
6300       if (DoXform) {
6301         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6302                                          LN0->getChain(), LN0->getBasePtr(),
6303                                          LN0->getMemoryVT(),
6304                                          LN0->getMemOperand());
6305         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6306         Mask = Mask.sext(VT.getSizeInBits());
6307         SDLoc DL(N);
6308         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6309                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6310         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6311                                     SDLoc(N0.getOperand(0)),
6312                                     N0.getOperand(0).getValueType(), ExtLoad);
6313         CombineTo(N, And);
6314         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6315         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6316                         ISD::SIGN_EXTEND);
6317         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6318       }
6319     }
6320   }
6321 
6322   if (N0.getOpcode() == ISD::SETCC) {
6323     EVT N0VT = N0.getOperand(0).getValueType();
6324     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6325     // Only do this before legalize for now.
6326     if (VT.isVector() && !LegalOperations &&
6327         TLI.getBooleanContents(N0VT) ==
6328             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6329       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6330       // of the same size as the compared operands. Only optimize sext(setcc())
6331       // if this is the case.
6332       EVT SVT = getSetCCResultType(N0VT);
6333 
6334       // We know that the # elements of the results is the same as the
6335       // # elements of the compare (and the # elements of the compare result
6336       // for that matter).  Check to see that they are the same size.  If so,
6337       // we know that the element size of the sext'd result matches the
6338       // element size of the compare operands.
6339       if (VT.getSizeInBits() == SVT.getSizeInBits())
6340         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6341                              N0.getOperand(1),
6342                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6343 
6344       // If the desired elements are smaller or larger than the source
6345       // elements we can use a matching integer vector type and then
6346       // truncate/sign extend
6347       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6348       if (SVT == MatchingVectorType) {
6349         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6350                                N0.getOperand(0), N0.getOperand(1),
6351                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6352         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6353       }
6354     }
6355 
6356     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
6357     // Here, T can be 1 or -1, depending on the type of the setcc and
6358     // getBooleanContents().
6359     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
6360 
6361     SDLoc DL(N);
6362     // To determine the "true" side of the select, we need to know the high bit
6363     // of the value returned by the setcc if it evaluates to true.
6364     // If the type of the setcc is i1, then the true case of the select is just
6365     // sext(i1 1), that is, -1.
6366     // If the type of the setcc is larger (say, i8) then the value of the high
6367     // bit depends on getBooleanContents(). So, ask TLI for a real "true" value
6368     // of the appropriate width.
6369     SDValue ExtTrueVal =
6370         (SetCCWidth == 1)
6371             ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()),
6372                               DL, VT)
6373             : TLI.getConstTrueVal(DAG, VT, DL);
6374 
6375     if (SDValue SCC = SimplifySelectCC(
6376             DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal,
6377             DAG.getConstant(0, DL, VT),
6378             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6379       return SCC;
6380 
6381     if (!VT.isVector()) {
6382       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6383       if (!LegalOperations ||
6384           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6385         SDLoc DL(N);
6386         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6387         SDValue SetCC =
6388             DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC);
6389         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal,
6390                              DAG.getConstant(0, DL, VT));
6391       }
6392     }
6393   }
6394 
6395   // fold (sext x) -> (zext x) if the sign bit is known zero.
6396   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6397       DAG.SignBitIsZero(N0))
6398     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6399 
6400   return SDValue();
6401 }
6402 
6403 // isTruncateOf - If N is a truncate of some other value, return true, record
6404 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6405 // This function computes KnownZero to avoid a duplicated call to
6406 // computeKnownBits in the caller.
6407 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6408                          APInt &KnownZero) {
6409   APInt KnownOne;
6410   if (N->getOpcode() == ISD::TRUNCATE) {
6411     Op = N->getOperand(0);
6412     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6413     return true;
6414   }
6415 
6416   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6417       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6418     return false;
6419 
6420   SDValue Op0 = N->getOperand(0);
6421   SDValue Op1 = N->getOperand(1);
6422   assert(Op0.getValueType() == Op1.getValueType());
6423 
6424   if (isNullConstant(Op0))
6425     Op = Op1;
6426   else if (isNullConstant(Op1))
6427     Op = Op0;
6428   else
6429     return false;
6430 
6431   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6432 
6433   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6434     return false;
6435 
6436   return true;
6437 }
6438 
6439 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6440   SDValue N0 = N->getOperand(0);
6441   EVT VT = N->getValueType(0);
6442 
6443   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6444                                               LegalOperations))
6445     return SDValue(Res, 0);
6446 
6447   // fold (zext (zext x)) -> (zext x)
6448   // fold (zext (aext x)) -> (zext x)
6449   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6450     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6451                        N0.getOperand(0));
6452 
6453   // fold (zext (truncate x)) -> (zext x) or
6454   //      (zext (truncate x)) -> (truncate x)
6455   // This is valid when the truncated bits of x are already zero.
6456   // FIXME: We should extend this to work for vectors too.
6457   SDValue Op;
6458   APInt KnownZero;
6459   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6460     APInt TruncatedBits =
6461       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6462       APInt(Op.getValueSizeInBits(), 0) :
6463       APInt::getBitsSet(Op.getValueSizeInBits(),
6464                         N0.getValueSizeInBits(),
6465                         std::min(Op.getValueSizeInBits(),
6466                                  VT.getSizeInBits()));
6467     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6468       if (VT.bitsGT(Op.getValueType()))
6469         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6470       if (VT.bitsLT(Op.getValueType()))
6471         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6472 
6473       return Op;
6474     }
6475   }
6476 
6477   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6478   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6479   if (N0.getOpcode() == ISD::TRUNCATE) {
6480     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6481       SDNode *oye = N0.getOperand(0).getNode();
6482       if (NarrowLoad.getNode() != N0.getNode()) {
6483         CombineTo(N0.getNode(), NarrowLoad);
6484         // CombineTo deleted the truncate, if needed, but not what's under it.
6485         AddToWorklist(oye);
6486       }
6487       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6488     }
6489   }
6490 
6491   // fold (zext (truncate x)) -> (and x, mask)
6492   if (N0.getOpcode() == ISD::TRUNCATE) {
6493     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6494     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6495     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6496       SDNode *oye = N0.getOperand(0).getNode();
6497       if (NarrowLoad.getNode() != N0.getNode()) {
6498         CombineTo(N0.getNode(), NarrowLoad);
6499         // CombineTo deleted the truncate, if needed, but not what's under it.
6500         AddToWorklist(oye);
6501       }
6502       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6503     }
6504 
6505     EVT SrcVT = N0.getOperand(0).getValueType();
6506     EVT MinVT = N0.getValueType();
6507 
6508     // Try to mask before the extension to avoid having to generate a larger mask,
6509     // possibly over several sub-vectors.
6510     if (SrcVT.bitsLT(VT)) {
6511       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6512                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6513         SDValue Op = N0.getOperand(0);
6514         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6515         AddToWorklist(Op.getNode());
6516         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6517       }
6518     }
6519 
6520     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6521       SDValue Op = N0.getOperand(0);
6522       if (SrcVT.bitsLT(VT)) {
6523         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6524         AddToWorklist(Op.getNode());
6525       } else if (SrcVT.bitsGT(VT)) {
6526         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6527         AddToWorklist(Op.getNode());
6528       }
6529       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6530     }
6531   }
6532 
6533   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6534   // if either of the casts is not free.
6535   if (N0.getOpcode() == ISD::AND &&
6536       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6537       N0.getOperand(1).getOpcode() == ISD::Constant &&
6538       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6539                            N0.getValueType()) ||
6540        !TLI.isZExtFree(N0.getValueType(), VT))) {
6541     SDValue X = N0.getOperand(0).getOperand(0);
6542     if (X.getValueType().bitsLT(VT)) {
6543       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6544     } else if (X.getValueType().bitsGT(VT)) {
6545       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6546     }
6547     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6548     Mask = Mask.zext(VT.getSizeInBits());
6549     SDLoc DL(N);
6550     return DAG.getNode(ISD::AND, DL, VT,
6551                        X, DAG.getConstant(Mask, DL, VT));
6552   }
6553 
6554   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6555   // Only generate vector extloads when 1) they're legal, and 2) they are
6556   // deemed desirable by the target.
6557   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6558       ((!LegalOperations && !VT.isVector() &&
6559         !cast<LoadSDNode>(N0)->isVolatile()) ||
6560        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6561     bool DoXform = true;
6562     SmallVector<SDNode*, 4> SetCCs;
6563     if (!N0.hasOneUse())
6564       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6565     if (VT.isVector())
6566       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6567     if (DoXform) {
6568       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6569       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6570                                        LN0->getChain(),
6571                                        LN0->getBasePtr(), N0.getValueType(),
6572                                        LN0->getMemOperand());
6573       CombineTo(N, ExtLoad);
6574       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6575                                   N0.getValueType(), ExtLoad);
6576       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6577 
6578       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6579                       ISD::ZERO_EXTEND);
6580       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6581     }
6582   }
6583 
6584   // fold (zext (load x)) to multiple smaller zextloads.
6585   // Only on illegal but splittable vectors.
6586   if (SDValue ExtLoad = CombineExtLoad(N))
6587     return ExtLoad;
6588 
6589   // fold (zext (and/or/xor (load x), cst)) ->
6590   //      (and/or/xor (zextload x), (zext cst))
6591   // Unless (and (load x) cst) will match as a zextload already and has
6592   // additional users.
6593   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6594        N0.getOpcode() == ISD::XOR) &&
6595       isa<LoadSDNode>(N0.getOperand(0)) &&
6596       N0.getOperand(1).getOpcode() == ISD::Constant &&
6597       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6598       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6599     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6600     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6601       bool DoXform = true;
6602       SmallVector<SDNode*, 4> SetCCs;
6603       if (!N0.hasOneUse()) {
6604         if (N0.getOpcode() == ISD::AND) {
6605           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6606           auto NarrowLoad = false;
6607           EVT LoadResultTy = AndC->getValueType(0);
6608           EVT ExtVT, LoadedVT;
6609           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6610                                NarrowLoad))
6611             DoXform = false;
6612         }
6613         if (DoXform)
6614           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6615                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6616       }
6617       if (DoXform) {
6618         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6619                                          LN0->getChain(), LN0->getBasePtr(),
6620                                          LN0->getMemoryVT(),
6621                                          LN0->getMemOperand());
6622         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6623         Mask = Mask.zext(VT.getSizeInBits());
6624         SDLoc DL(N);
6625         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6626                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6627         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6628                                     SDLoc(N0.getOperand(0)),
6629                                     N0.getOperand(0).getValueType(), ExtLoad);
6630         CombineTo(N, And);
6631         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6632         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6633                         ISD::ZERO_EXTEND);
6634         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6635       }
6636     }
6637   }
6638 
6639   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6640   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6641   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6642       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6643     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6644     EVT MemVT = LN0->getMemoryVT();
6645     if ((!LegalOperations && !LN0->isVolatile()) ||
6646         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6647       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6648                                        LN0->getChain(),
6649                                        LN0->getBasePtr(), MemVT,
6650                                        LN0->getMemOperand());
6651       CombineTo(N, ExtLoad);
6652       CombineTo(N0.getNode(),
6653                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6654                             ExtLoad),
6655                 ExtLoad.getValue(1));
6656       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6657     }
6658   }
6659 
6660   if (N0.getOpcode() == ISD::SETCC) {
6661     // Only do this before legalize for now.
6662     if (!LegalOperations && VT.isVector() &&
6663         N0.getValueType().getVectorElementType() == MVT::i1) {
6664       EVT N00VT = N0.getOperand(0).getValueType();
6665       if (getSetCCResultType(N00VT) == N0.getValueType())
6666         return SDValue();
6667 
6668       // We know that the # elements of the results is the same as the #
6669       // elements of the compare (and the # elements of the compare result for
6670       // that matter). Check to see that they are the same size. If so, we know
6671       // that the element size of the sext'd result matches the element size of
6672       // the compare operands.
6673       SDLoc DL(N);
6674       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6675       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
6676         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6677         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
6678                                      N0.getOperand(1), N0.getOperand(2));
6679         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
6680       }
6681 
6682       // If the desired elements are smaller or larger than the source
6683       // elements we can use a matching integer vector type and then
6684       // truncate/sign extend.
6685       EVT MatchingElementType = EVT::getIntegerVT(
6686           *DAG.getContext(), N00VT.getScalarSizeInBits());
6687       EVT MatchingVectorType = EVT::getVectorVT(
6688           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
6689       SDValue VsetCC =
6690           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
6691                       N0.getOperand(1), N0.getOperand(2));
6692       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
6693                          VecOnes);
6694     }
6695 
6696     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6697     SDLoc DL(N);
6698     if (SDValue SCC = SimplifySelectCC(
6699             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6700             DAG.getConstant(0, DL, VT),
6701             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6702       return SCC;
6703   }
6704 
6705   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6706   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6707       isa<ConstantSDNode>(N0.getOperand(1)) &&
6708       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6709       N0.hasOneUse()) {
6710     SDValue ShAmt = N0.getOperand(1);
6711     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6712     if (N0.getOpcode() == ISD::SHL) {
6713       SDValue InnerZExt = N0.getOperand(0);
6714       // If the original shl may be shifting out bits, do not perform this
6715       // transformation.
6716       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
6717         InnerZExt.getOperand(0).getValueSizeInBits();
6718       if (ShAmtVal > KnownZeroBits)
6719         return SDValue();
6720     }
6721 
6722     SDLoc DL(N);
6723 
6724     // Ensure that the shift amount is wide enough for the shifted value.
6725     if (VT.getSizeInBits() >= 256)
6726       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6727 
6728     return DAG.getNode(N0.getOpcode(), DL, VT,
6729                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6730                        ShAmt);
6731   }
6732 
6733   return SDValue();
6734 }
6735 
6736 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6737   SDValue N0 = N->getOperand(0);
6738   EVT VT = N->getValueType(0);
6739 
6740   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6741                                               LegalOperations))
6742     return SDValue(Res, 0);
6743 
6744   // fold (aext (aext x)) -> (aext x)
6745   // fold (aext (zext x)) -> (zext x)
6746   // fold (aext (sext x)) -> (sext x)
6747   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6748       N0.getOpcode() == ISD::ZERO_EXTEND ||
6749       N0.getOpcode() == ISD::SIGN_EXTEND)
6750     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6751 
6752   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6753   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6754   if (N0.getOpcode() == ISD::TRUNCATE) {
6755     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6756       SDNode *oye = N0.getOperand(0).getNode();
6757       if (NarrowLoad.getNode() != N0.getNode()) {
6758         CombineTo(N0.getNode(), NarrowLoad);
6759         // CombineTo deleted the truncate, if needed, but not what's under it.
6760         AddToWorklist(oye);
6761       }
6762       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6763     }
6764   }
6765 
6766   // fold (aext (truncate x))
6767   if (N0.getOpcode() == ISD::TRUNCATE) {
6768     SDValue TruncOp = N0.getOperand(0);
6769     if (TruncOp.getValueType() == VT)
6770       return TruncOp; // x iff x size == zext size.
6771     if (TruncOp.getValueType().bitsGT(VT))
6772       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6773     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6774   }
6775 
6776   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6777   // if the trunc is not free.
6778   if (N0.getOpcode() == ISD::AND &&
6779       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6780       N0.getOperand(1).getOpcode() == ISD::Constant &&
6781       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6782                           N0.getValueType())) {
6783     SDLoc DL(N);
6784     SDValue X = N0.getOperand(0).getOperand(0);
6785     if (X.getValueType().bitsLT(VT)) {
6786       X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
6787     } else if (X.getValueType().bitsGT(VT)) {
6788       X = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
6789     }
6790     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6791     Mask = Mask.zext(VT.getSizeInBits());
6792     return DAG.getNode(ISD::AND, DL, VT,
6793                        X, DAG.getConstant(Mask, DL, VT));
6794   }
6795 
6796   // fold (aext (load x)) -> (aext (truncate (extload x)))
6797   // None of the supported targets knows how to perform load and any_ext
6798   // on vectors in one instruction.  We only perform this transformation on
6799   // scalars.
6800   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6801       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6802       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6803     bool DoXform = true;
6804     SmallVector<SDNode*, 4> SetCCs;
6805     if (!N0.hasOneUse())
6806       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6807     if (DoXform) {
6808       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6809       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6810                                        LN0->getChain(),
6811                                        LN0->getBasePtr(), N0.getValueType(),
6812                                        LN0->getMemOperand());
6813       CombineTo(N, ExtLoad);
6814       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6815                                   N0.getValueType(), ExtLoad);
6816       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6817       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6818                       ISD::ANY_EXTEND);
6819       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6820     }
6821   }
6822 
6823   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6824   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6825   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6826   if (N0.getOpcode() == ISD::LOAD &&
6827       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6828       N0.hasOneUse()) {
6829     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6830     ISD::LoadExtType ExtType = LN0->getExtensionType();
6831     EVT MemVT = LN0->getMemoryVT();
6832     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6833       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6834                                        VT, LN0->getChain(), LN0->getBasePtr(),
6835                                        MemVT, LN0->getMemOperand());
6836       CombineTo(N, ExtLoad);
6837       CombineTo(N0.getNode(),
6838                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6839                             N0.getValueType(), ExtLoad),
6840                 ExtLoad.getValue(1));
6841       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6842     }
6843   }
6844 
6845   if (N0.getOpcode() == ISD::SETCC) {
6846     // For vectors:
6847     // aext(setcc) -> vsetcc
6848     // aext(setcc) -> truncate(vsetcc)
6849     // aext(setcc) -> aext(vsetcc)
6850     // Only do this before legalize for now.
6851     if (VT.isVector() && !LegalOperations) {
6852       EVT N0VT = N0.getOperand(0).getValueType();
6853         // We know that the # elements of the results is the same as the
6854         // # elements of the compare (and the # elements of the compare result
6855         // for that matter).  Check to see that they are the same size.  If so,
6856         // we know that the element size of the sext'd result matches the
6857         // element size of the compare operands.
6858       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6859         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6860                              N0.getOperand(1),
6861                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6862       // If the desired elements are smaller or larger than the source
6863       // elements we can use a matching integer vector type and then
6864       // truncate/any extend
6865       else {
6866         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6867         SDValue VsetCC =
6868           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6869                         N0.getOperand(1),
6870                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6871         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6872       }
6873     }
6874 
6875     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6876     SDLoc DL(N);
6877     if (SDValue SCC = SimplifySelectCC(
6878             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6879             DAG.getConstant(0, DL, VT),
6880             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6881       return SCC;
6882   }
6883 
6884   return SDValue();
6885 }
6886 
6887 /// See if the specified operand can be simplified with the knowledge that only
6888 /// the bits specified by Mask are used.  If so, return the simpler operand,
6889 /// otherwise return a null SDValue.
6890 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6891   switch (V.getOpcode()) {
6892   default: break;
6893   case ISD::Constant: {
6894     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6895     assert(CV && "Const value should be ConstSDNode.");
6896     const APInt &CVal = CV->getAPIntValue();
6897     APInt NewVal = CVal & Mask;
6898     if (NewVal != CVal)
6899       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6900     break;
6901   }
6902   case ISD::OR:
6903   case ISD::XOR:
6904     // If the LHS or RHS don't contribute bits to the or, drop them.
6905     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6906       return V.getOperand(1);
6907     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6908       return V.getOperand(0);
6909     break;
6910   case ISD::SRL:
6911     // Only look at single-use SRLs.
6912     if (!V.getNode()->hasOneUse())
6913       break;
6914     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6915       // See if we can recursively simplify the LHS.
6916       unsigned Amt = RHSC->getZExtValue();
6917 
6918       // Watch out for shift count overflow though.
6919       if (Amt >= Mask.getBitWidth()) break;
6920       APInt NewMask = Mask << Amt;
6921       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6922         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6923                            SimplifyLHS, V.getOperand(1));
6924     }
6925   }
6926   return SDValue();
6927 }
6928 
6929 /// If the result of a wider load is shifted to right of N  bits and then
6930 /// truncated to a narrower type and where N is a multiple of number of bits of
6931 /// the narrower type, transform it to a narrower load from address + N / num of
6932 /// bits of new type. If the result is to be extended, also fold the extension
6933 /// to form a extending load.
6934 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6935   unsigned Opc = N->getOpcode();
6936 
6937   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6938   SDValue N0 = N->getOperand(0);
6939   EVT VT = N->getValueType(0);
6940   EVT ExtVT = VT;
6941 
6942   // This transformation isn't valid for vector loads.
6943   if (VT.isVector())
6944     return SDValue();
6945 
6946   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6947   // extended to VT.
6948   if (Opc == ISD::SIGN_EXTEND_INREG) {
6949     ExtType = ISD::SEXTLOAD;
6950     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6951   } else if (Opc == ISD::SRL) {
6952     // Another special-case: SRL is basically zero-extending a narrower value.
6953     ExtType = ISD::ZEXTLOAD;
6954     N0 = SDValue(N, 0);
6955     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6956     if (!N01) return SDValue();
6957     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6958                               VT.getSizeInBits() - N01->getZExtValue());
6959   }
6960   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6961     return SDValue();
6962 
6963   unsigned EVTBits = ExtVT.getSizeInBits();
6964 
6965   // Do not generate loads of non-round integer types since these can
6966   // be expensive (and would be wrong if the type is not byte sized).
6967   if (!ExtVT.isRound())
6968     return SDValue();
6969 
6970   unsigned ShAmt = 0;
6971   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6972     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6973       ShAmt = N01->getZExtValue();
6974       // Is the shift amount a multiple of size of VT?
6975       if ((ShAmt & (EVTBits-1)) == 0) {
6976         N0 = N0.getOperand(0);
6977         // Is the load width a multiple of size of VT?
6978         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
6979           return SDValue();
6980       }
6981 
6982       // At this point, we must have a load or else we can't do the transform.
6983       if (!isa<LoadSDNode>(N0)) return SDValue();
6984 
6985       // Because a SRL must be assumed to *need* to zero-extend the high bits
6986       // (as opposed to anyext the high bits), we can't combine the zextload
6987       // lowering of SRL and an sextload.
6988       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6989         return SDValue();
6990 
6991       // If the shift amount is larger than the input type then we're not
6992       // accessing any of the loaded bytes.  If the load was a zextload/extload
6993       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6994       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6995         return SDValue();
6996     }
6997   }
6998 
6999   // If the load is shifted left (and the result isn't shifted back right),
7000   // we can fold the truncate through the shift.
7001   unsigned ShLeftAmt = 0;
7002   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7003       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7004     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7005       ShLeftAmt = N01->getZExtValue();
7006       N0 = N0.getOperand(0);
7007     }
7008   }
7009 
7010   // If we haven't found a load, we can't narrow it.  Don't transform one with
7011   // multiple uses, this would require adding a new load.
7012   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7013     return SDValue();
7014 
7015   // Don't change the width of a volatile load.
7016   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7017   if (LN0->isVolatile())
7018     return SDValue();
7019 
7020   // Verify that we are actually reducing a load width here.
7021   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7022     return SDValue();
7023 
7024   // For the transform to be legal, the load must produce only two values
7025   // (the value loaded and the chain).  Don't transform a pre-increment
7026   // load, for example, which produces an extra value.  Otherwise the
7027   // transformation is not equivalent, and the downstream logic to replace
7028   // uses gets things wrong.
7029   if (LN0->getNumValues() > 2)
7030     return SDValue();
7031 
7032   // If the load that we're shrinking is an extload and we're not just
7033   // discarding the extension we can't simply shrink the load. Bail.
7034   // TODO: It would be possible to merge the extensions in some cases.
7035   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7036       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7037     return SDValue();
7038 
7039   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7040     return SDValue();
7041 
7042   EVT PtrType = N0.getOperand(1).getValueType();
7043 
7044   if (PtrType == MVT::Untyped || PtrType.isExtended())
7045     // It's not possible to generate a constant of extended or untyped type.
7046     return SDValue();
7047 
7048   // For big endian targets, we need to adjust the offset to the pointer to
7049   // load the correct bytes.
7050   if (DAG.getDataLayout().isBigEndian()) {
7051     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7052     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7053     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7054   }
7055 
7056   uint64_t PtrOff = ShAmt / 8;
7057   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7058   SDLoc DL(LN0);
7059   // The original load itself didn't wrap, so an offset within it doesn't.
7060   SDNodeFlags Flags;
7061   Flags.setNoUnsignedWrap(true);
7062   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7063                                PtrType, LN0->getBasePtr(),
7064                                DAG.getConstant(PtrOff, DL, PtrType),
7065                                &Flags);
7066   AddToWorklist(NewPtr.getNode());
7067 
7068   SDValue Load;
7069   if (ExtType == ISD::NON_EXTLOAD)
7070     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7071                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7072                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7073   else
7074     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7075                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7076                           NewAlign, LN0->getMemOperand()->getFlags(),
7077                           LN0->getAAInfo());
7078 
7079   // Replace the old load's chain with the new load's chain.
7080   WorklistRemover DeadNodes(*this);
7081   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7082 
7083   // Shift the result left, if we've swallowed a left shift.
7084   SDValue Result = Load;
7085   if (ShLeftAmt != 0) {
7086     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7087     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7088       ShImmTy = VT;
7089     // If the shift amount is as large as the result size (but, presumably,
7090     // no larger than the source) then the useful bits of the result are
7091     // zero; we can't simply return the shortened shift, because the result
7092     // of that operation is undefined.
7093     SDLoc DL(N0);
7094     if (ShLeftAmt >= VT.getSizeInBits())
7095       Result = DAG.getConstant(0, DL, VT);
7096     else
7097       Result = DAG.getNode(ISD::SHL, DL, VT,
7098                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7099   }
7100 
7101   // Return the new loaded value.
7102   return Result;
7103 }
7104 
7105 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7106   SDValue N0 = N->getOperand(0);
7107   SDValue N1 = N->getOperand(1);
7108   EVT VT = N->getValueType(0);
7109   EVT EVT = cast<VTSDNode>(N1)->getVT();
7110   unsigned VTBits = VT.getScalarSizeInBits();
7111   unsigned EVTBits = EVT.getScalarSizeInBits();
7112 
7113   if (N0.isUndef())
7114     return DAG.getUNDEF(VT);
7115 
7116   // fold (sext_in_reg c1) -> c1
7117   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7118     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7119 
7120   // If the input is already sign extended, just drop the extension.
7121   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7122     return N0;
7123 
7124   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7125   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7126       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7127     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7128                        N0.getOperand(0), N1);
7129 
7130   // fold (sext_in_reg (sext x)) -> (sext x)
7131   // fold (sext_in_reg (aext x)) -> (sext x)
7132   // if x is small enough.
7133   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7134     SDValue N00 = N0.getOperand(0);
7135     if (N00.getScalarValueSizeInBits() <= EVTBits &&
7136         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7137       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7138   }
7139 
7140   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7141   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7142     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7143 
7144   // fold operands of sext_in_reg based on knowledge that the top bits are not
7145   // demanded.
7146   if (SimplifyDemandedBits(SDValue(N, 0)))
7147     return SDValue(N, 0);
7148 
7149   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7150   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7151   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7152     return NarrowLoad;
7153 
7154   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7155   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7156   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7157   if (N0.getOpcode() == ISD::SRL) {
7158     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7159       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7160         // We can turn this into an SRA iff the input to the SRL is already sign
7161         // extended enough.
7162         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7163         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7164           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7165                              N0.getOperand(0), N0.getOperand(1));
7166       }
7167   }
7168 
7169   // fold (sext_inreg (extload x)) -> (sextload x)
7170   if (ISD::isEXTLoad(N0.getNode()) &&
7171       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7172       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7173       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7174        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7175     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7176     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7177                                      LN0->getChain(),
7178                                      LN0->getBasePtr(), EVT,
7179                                      LN0->getMemOperand());
7180     CombineTo(N, ExtLoad);
7181     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7182     AddToWorklist(ExtLoad.getNode());
7183     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7184   }
7185   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7186   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7187       N0.hasOneUse() &&
7188       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7189       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7190        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7191     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7192     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7193                                      LN0->getChain(),
7194                                      LN0->getBasePtr(), EVT,
7195                                      LN0->getMemOperand());
7196     CombineTo(N, ExtLoad);
7197     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7198     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7199   }
7200 
7201   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7202   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7203     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7204                                            N0.getOperand(1), false))
7205       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7206                          BSwap, N1);
7207   }
7208 
7209   return SDValue();
7210 }
7211 
7212 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7213   SDValue N0 = N->getOperand(0);
7214   EVT VT = N->getValueType(0);
7215 
7216   if (N0.isUndef())
7217     return DAG.getUNDEF(VT);
7218 
7219   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7220                                               LegalOperations))
7221     return SDValue(Res, 0);
7222 
7223   return SDValue();
7224 }
7225 
7226 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7227   SDValue N0 = N->getOperand(0);
7228   EVT VT = N->getValueType(0);
7229 
7230   if (N0.isUndef())
7231     return DAG.getUNDEF(VT);
7232 
7233   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7234                                               LegalOperations))
7235     return SDValue(Res, 0);
7236 
7237   return SDValue();
7238 }
7239 
7240 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7241   SDValue N0 = N->getOperand(0);
7242   EVT VT = N->getValueType(0);
7243   bool isLE = DAG.getDataLayout().isLittleEndian();
7244 
7245   // noop truncate
7246   if (N0.getValueType() == N->getValueType(0))
7247     return N0;
7248   // fold (truncate c1) -> c1
7249   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7250     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7251   // fold (truncate (truncate x)) -> (truncate x)
7252   if (N0.getOpcode() == ISD::TRUNCATE)
7253     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7254   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7255   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7256       N0.getOpcode() == ISD::SIGN_EXTEND ||
7257       N0.getOpcode() == ISD::ANY_EXTEND) {
7258     // if the source is smaller than the dest, we still need an extend.
7259     if (N0.getOperand(0).getValueType().bitsLT(VT))
7260       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7261     // if the source is larger than the dest, than we just need the truncate.
7262     if (N0.getOperand(0).getValueType().bitsGT(VT))
7263       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7264     // if the source and dest are the same type, we can drop both the extend
7265     // and the truncate.
7266     return N0.getOperand(0);
7267   }
7268 
7269   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
7270   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
7271     return SDValue();
7272 
7273   // Fold extract-and-trunc into a narrow extract. For example:
7274   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7275   //   i32 y = TRUNCATE(i64 x)
7276   //        -- becomes --
7277   //   v16i8 b = BITCAST (v2i64 val)
7278   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7279   //
7280   // Note: We only run this optimization after type legalization (which often
7281   // creates this pattern) and before operation legalization after which
7282   // we need to be more careful about the vector instructions that we generate.
7283   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7284       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7285 
7286     EVT VecTy = N0.getOperand(0).getValueType();
7287     EVT ExTy = N0.getValueType();
7288     EVT TrTy = N->getValueType(0);
7289 
7290     unsigned NumElem = VecTy.getVectorNumElements();
7291     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7292 
7293     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7294     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7295 
7296     SDValue EltNo = N0->getOperand(1);
7297     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7298       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7299       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7300       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7301 
7302       SDLoc DL(N);
7303       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7304                          DAG.getBitcast(NVT, N0.getOperand(0)),
7305                          DAG.getConstant(Index, DL, IndexTy));
7306     }
7307   }
7308 
7309   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7310   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
7311     EVT SrcVT = N0.getValueType();
7312     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7313         TLI.isTruncateFree(SrcVT, VT)) {
7314       SDLoc SL(N0);
7315       SDValue Cond = N0.getOperand(0);
7316       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7317       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7318       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7319     }
7320   }
7321 
7322   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
7323   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7324       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7325       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7326     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7327       uint64_t Amt = CAmt->getZExtValue();
7328       unsigned Size = VT.getScalarSizeInBits();
7329 
7330       if (Amt < Size) {
7331         SDLoc SL(N);
7332         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7333 
7334         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7335         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7336                            DAG.getConstant(Amt, SL, AmtVT));
7337       }
7338     }
7339   }
7340 
7341   // Fold a series of buildvector, bitcast, and truncate if possible.
7342   // For example fold
7343   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7344   //   (2xi32 (buildvector x, y)).
7345   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7346       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7347       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7348       N0.getOperand(0).hasOneUse()) {
7349 
7350     SDValue BuildVect = N0.getOperand(0);
7351     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7352     EVT TruncVecEltTy = VT.getVectorElementType();
7353 
7354     // Check that the element types match.
7355     if (BuildVectEltTy == TruncVecEltTy) {
7356       // Now we only need to compute the offset of the truncated elements.
7357       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7358       unsigned TruncVecNumElts = VT.getVectorNumElements();
7359       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7360 
7361       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7362              "Invalid number of elements");
7363 
7364       SmallVector<SDValue, 8> Opnds;
7365       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7366         Opnds.push_back(BuildVect.getOperand(i));
7367 
7368       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7369     }
7370   }
7371 
7372   // See if we can simplify the input to this truncate through knowledge that
7373   // only the low bits are being used.
7374   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7375   // Currently we only perform this optimization on scalars because vectors
7376   // may have different active low bits.
7377   if (!VT.isVector()) {
7378     if (SDValue Shorter =
7379             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7380                                                      VT.getSizeInBits())))
7381       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7382   }
7383   // fold (truncate (load x)) -> (smaller load x)
7384   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7385   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7386     if (SDValue Reduced = ReduceLoadWidth(N))
7387       return Reduced;
7388 
7389     // Handle the case where the load remains an extending load even
7390     // after truncation.
7391     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7392       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7393       if (!LN0->isVolatile() &&
7394           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7395         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7396                                          VT, LN0->getChain(), LN0->getBasePtr(),
7397                                          LN0->getMemoryVT(),
7398                                          LN0->getMemOperand());
7399         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7400         return NewLoad;
7401       }
7402     }
7403   }
7404   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7405   // where ... are all 'undef'.
7406   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7407     SmallVector<EVT, 8> VTs;
7408     SDValue V;
7409     unsigned Idx = 0;
7410     unsigned NumDefs = 0;
7411 
7412     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7413       SDValue X = N0.getOperand(i);
7414       if (!X.isUndef()) {
7415         V = X;
7416         Idx = i;
7417         NumDefs++;
7418       }
7419       // Stop if more than one members are non-undef.
7420       if (NumDefs > 1)
7421         break;
7422       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7423                                      VT.getVectorElementType(),
7424                                      X.getValueType().getVectorNumElements()));
7425     }
7426 
7427     if (NumDefs == 0)
7428       return DAG.getUNDEF(VT);
7429 
7430     if (NumDefs == 1) {
7431       assert(V.getNode() && "The single defined operand is empty!");
7432       SmallVector<SDValue, 8> Opnds;
7433       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7434         if (i != Idx) {
7435           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7436           continue;
7437         }
7438         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7439         AddToWorklist(NV.getNode());
7440         Opnds.push_back(NV);
7441       }
7442       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7443     }
7444   }
7445 
7446   // Fold truncate of a bitcast of a vector to an extract of the low vector
7447   // element.
7448   //
7449   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7450   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7451     SDValue VecSrc = N0.getOperand(0);
7452     EVT SrcVT = VecSrc.getValueType();
7453     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7454         (!LegalOperations ||
7455          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7456       SDLoc SL(N);
7457 
7458       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7459       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7460                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7461     }
7462   }
7463 
7464   // Simplify the operands using demanded-bits information.
7465   if (!VT.isVector() &&
7466       SimplifyDemandedBits(SDValue(N, 0)))
7467     return SDValue(N, 0);
7468 
7469   return SDValue();
7470 }
7471 
7472 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7473   SDValue Elt = N->getOperand(i);
7474   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7475     return Elt.getNode();
7476   return Elt.getOperand(Elt.getResNo()).getNode();
7477 }
7478 
7479 /// build_pair (load, load) -> load
7480 /// if load locations are consecutive.
7481 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7482   assert(N->getOpcode() == ISD::BUILD_PAIR);
7483 
7484   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7485   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7486   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7487       LD1->getAddressSpace() != LD2->getAddressSpace())
7488     return SDValue();
7489   EVT LD1VT = LD1->getValueType(0);
7490   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7491   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7492       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7493     unsigned Align = LD1->getAlignment();
7494     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7495         VT.getTypeForEVT(*DAG.getContext()));
7496 
7497     if (NewAlign <= Align &&
7498         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7499       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
7500                          LD1->getPointerInfo(), Align);
7501   }
7502 
7503   return SDValue();
7504 }
7505 
7506 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7507   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7508   // and Lo parts; on big-endian machines it doesn't.
7509   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7510 }
7511 
7512 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7513                                     const TargetLowering &TLI) {
7514   // If this is not a bitcast to an FP type or if the target doesn't have
7515   // IEEE754-compliant FP logic, we're done.
7516   EVT VT = N->getValueType(0);
7517   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7518     return SDValue();
7519 
7520   // TODO: Use splat values for the constant-checking below and remove this
7521   // restriction.
7522   SDValue N0 = N->getOperand(0);
7523   EVT SourceVT = N0.getValueType();
7524   if (SourceVT.isVector())
7525     return SDValue();
7526 
7527   unsigned FPOpcode;
7528   APInt SignMask;
7529   switch (N0.getOpcode()) {
7530   case ISD::AND:
7531     FPOpcode = ISD::FABS;
7532     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7533     break;
7534   case ISD::XOR:
7535     FPOpcode = ISD::FNEG;
7536     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7537     break;
7538   // TODO: ISD::OR --> ISD::FNABS?
7539   default:
7540     return SDValue();
7541   }
7542 
7543   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7544   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7545   SDValue LogicOp0 = N0.getOperand(0);
7546   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7547   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7548       LogicOp0.getOpcode() == ISD::BITCAST &&
7549       LogicOp0->getOperand(0).getValueType() == VT)
7550     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7551 
7552   return SDValue();
7553 }
7554 
7555 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7556   SDValue N0 = N->getOperand(0);
7557   EVT VT = N->getValueType(0);
7558 
7559   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7560   // Only do this before legalize, since afterward the target may be depending
7561   // on the bitconvert.
7562   // First check to see if this is all constant.
7563   if (!LegalTypes &&
7564       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7565       VT.isVector()) {
7566     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7567 
7568     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7569     assert(!DestEltVT.isVector() &&
7570            "Element type of vector ValueType must not be vector!");
7571     if (isSimple)
7572       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7573   }
7574 
7575   // If the input is a constant, let getNode fold it.
7576   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7577     // If we can't allow illegal operations, we need to check that this is just
7578     // a fp -> int or int -> conversion and that the resulting operation will
7579     // be legal.
7580     if (!LegalOperations ||
7581         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7582          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7583         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7584          TLI.isOperationLegal(ISD::Constant, VT)))
7585       return DAG.getBitcast(VT, N0);
7586   }
7587 
7588   // (conv (conv x, t1), t2) -> (conv x, t2)
7589   if (N0.getOpcode() == ISD::BITCAST)
7590     return DAG.getBitcast(VT, N0.getOperand(0));
7591 
7592   // fold (conv (load x)) -> (load (conv*)x)
7593   // If the resultant load doesn't need a higher alignment than the original!
7594   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7595       // Do not change the width of a volatile load.
7596       !cast<LoadSDNode>(N0)->isVolatile() &&
7597       // Do not remove the cast if the types differ in endian layout.
7598       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7599           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7600       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7601       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7602     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7603     unsigned OrigAlign = LN0->getAlignment();
7604 
7605     bool Fast = false;
7606     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7607                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7608         Fast) {
7609       SDValue Load =
7610           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7611                       LN0->getPointerInfo(), OrigAlign,
7612                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7613       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7614       return Load;
7615     }
7616   }
7617 
7618   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7619     return V;
7620 
7621   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7622   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7623   //
7624   // For ppc_fp128:
7625   // fold (bitcast (fneg x)) ->
7626   //     flipbit = signbit
7627   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7628   //
7629   // fold (bitcast (fabs x)) ->
7630   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7631   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7632   // This often reduces constant pool loads.
7633   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7634        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7635       N0.getNode()->hasOneUse() && VT.isInteger() &&
7636       !VT.isVector() && !N0.getValueType().isVector()) {
7637     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7638     AddToWorklist(NewConv.getNode());
7639 
7640     SDLoc DL(N);
7641     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7642       assert(VT.getSizeInBits() == 128);
7643       SDValue SignBit = DAG.getConstant(
7644           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7645       SDValue FlipBit;
7646       if (N0.getOpcode() == ISD::FNEG) {
7647         FlipBit = SignBit;
7648         AddToWorklist(FlipBit.getNode());
7649       } else {
7650         assert(N0.getOpcode() == ISD::FABS);
7651         SDValue Hi =
7652             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7653                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7654                                               SDLoc(NewConv)));
7655         AddToWorklist(Hi.getNode());
7656         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7657         AddToWorklist(FlipBit.getNode());
7658       }
7659       SDValue FlipBits =
7660           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7661       AddToWorklist(FlipBits.getNode());
7662       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7663     }
7664     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7665     if (N0.getOpcode() == ISD::FNEG)
7666       return DAG.getNode(ISD::XOR, DL, VT,
7667                          NewConv, DAG.getConstant(SignBit, DL, VT));
7668     assert(N0.getOpcode() == ISD::FABS);
7669     return DAG.getNode(ISD::AND, DL, VT,
7670                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7671   }
7672 
7673   // fold (bitconvert (fcopysign cst, x)) ->
7674   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7675   // Note that we don't handle (copysign x, cst) because this can always be
7676   // folded to an fneg or fabs.
7677   //
7678   // For ppc_fp128:
7679   // fold (bitcast (fcopysign cst, x)) ->
7680   //     flipbit = (and (extract_element
7681   //                     (xor (bitcast cst), (bitcast x)), 0),
7682   //                    signbit)
7683   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7684   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7685       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7686       VT.isInteger() && !VT.isVector()) {
7687     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
7688     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7689     if (isTypeLegal(IntXVT)) {
7690       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7691       AddToWorklist(X.getNode());
7692 
7693       // If X has a different width than the result/lhs, sext it or truncate it.
7694       unsigned VTWidth = VT.getSizeInBits();
7695       if (OrigXWidth < VTWidth) {
7696         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7697         AddToWorklist(X.getNode());
7698       } else if (OrigXWidth > VTWidth) {
7699         // To get the sign bit in the right place, we have to shift it right
7700         // before truncating.
7701         SDLoc DL(X);
7702         X = DAG.getNode(ISD::SRL, DL,
7703                         X.getValueType(), X,
7704                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7705                                         X.getValueType()));
7706         AddToWorklist(X.getNode());
7707         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7708         AddToWorklist(X.getNode());
7709       }
7710 
7711       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7712         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7713         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7714         AddToWorklist(Cst.getNode());
7715         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7716         AddToWorklist(X.getNode());
7717         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7718         AddToWorklist(XorResult.getNode());
7719         SDValue XorResult64 = DAG.getNode(
7720             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7721             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7722                                   SDLoc(XorResult)));
7723         AddToWorklist(XorResult64.getNode());
7724         SDValue FlipBit =
7725             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7726                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7727         AddToWorklist(FlipBit.getNode());
7728         SDValue FlipBits =
7729             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7730         AddToWorklist(FlipBits.getNode());
7731         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7732       }
7733       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7734       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7735                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7736       AddToWorklist(X.getNode());
7737 
7738       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7739       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7740                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7741       AddToWorklist(Cst.getNode());
7742 
7743       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7744     }
7745   }
7746 
7747   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7748   if (N0.getOpcode() == ISD::BUILD_PAIR)
7749     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7750       return CombineLD;
7751 
7752   // Remove double bitcasts from shuffles - this is often a legacy of
7753   // XformToShuffleWithZero being used to combine bitmaskings (of
7754   // float vectors bitcast to integer vectors) into shuffles.
7755   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7756   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7757       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7758       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7759       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7760     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7761 
7762     // If operands are a bitcast, peek through if it casts the original VT.
7763     // If operands are a constant, just bitcast back to original VT.
7764     auto PeekThroughBitcast = [&](SDValue Op) {
7765       if (Op.getOpcode() == ISD::BITCAST &&
7766           Op.getOperand(0).getValueType() == VT)
7767         return SDValue(Op.getOperand(0));
7768       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7769           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7770         return DAG.getBitcast(VT, Op);
7771       return SDValue();
7772     };
7773 
7774     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7775     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7776     if (!(SV0 && SV1))
7777       return SDValue();
7778 
7779     int MaskScale =
7780         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7781     SmallVector<int, 8> NewMask;
7782     for (int M : SVN->getMask())
7783       for (int i = 0; i != MaskScale; ++i)
7784         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7785 
7786     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7787     if (!LegalMask) {
7788       std::swap(SV0, SV1);
7789       ShuffleVectorSDNode::commuteMask(NewMask);
7790       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7791     }
7792 
7793     if (LegalMask)
7794       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7795   }
7796 
7797   return SDValue();
7798 }
7799 
7800 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7801   EVT VT = N->getValueType(0);
7802   return CombineConsecutiveLoads(N, VT);
7803 }
7804 
7805 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7806 /// operands. DstEltVT indicates the destination element value type.
7807 SDValue DAGCombiner::
7808 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7809   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7810 
7811   // If this is already the right type, we're done.
7812   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7813 
7814   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7815   unsigned DstBitSize = DstEltVT.getSizeInBits();
7816 
7817   // If this is a conversion of N elements of one type to N elements of another
7818   // type, convert each element.  This handles FP<->INT cases.
7819   if (SrcBitSize == DstBitSize) {
7820     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7821                               BV->getValueType(0).getVectorNumElements());
7822 
7823     // Due to the FP element handling below calling this routine recursively,
7824     // we can end up with a scalar-to-vector node here.
7825     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7826       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7827                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7828 
7829     SmallVector<SDValue, 8> Ops;
7830     for (SDValue Op : BV->op_values()) {
7831       // If the vector element type is not legal, the BUILD_VECTOR operands
7832       // are promoted and implicitly truncated.  Make that explicit here.
7833       if (Op.getValueType() != SrcEltVT)
7834         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7835       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7836       AddToWorklist(Ops.back().getNode());
7837     }
7838     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7839   }
7840 
7841   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7842   // handle annoying details of growing/shrinking FP values, we convert them to
7843   // int first.
7844   if (SrcEltVT.isFloatingPoint()) {
7845     // Convert the input float vector to a int vector where the elements are the
7846     // same sizes.
7847     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7848     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7849     SrcEltVT = IntVT;
7850   }
7851 
7852   // Now we know the input is an integer vector.  If the output is a FP type,
7853   // convert to integer first, then to FP of the right size.
7854   if (DstEltVT.isFloatingPoint()) {
7855     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7856     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7857 
7858     // Next, convert to FP elements of the same size.
7859     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7860   }
7861 
7862   SDLoc DL(BV);
7863 
7864   // Okay, we know the src/dst types are both integers of differing types.
7865   // Handling growing first.
7866   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7867   if (SrcBitSize < DstBitSize) {
7868     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7869 
7870     SmallVector<SDValue, 8> Ops;
7871     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7872          i += NumInputsPerOutput) {
7873       bool isLE = DAG.getDataLayout().isLittleEndian();
7874       APInt NewBits = APInt(DstBitSize, 0);
7875       bool EltIsUndef = true;
7876       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7877         // Shift the previously computed bits over.
7878         NewBits <<= SrcBitSize;
7879         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7880         if (Op.isUndef()) continue;
7881         EltIsUndef = false;
7882 
7883         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7884                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7885       }
7886 
7887       if (EltIsUndef)
7888         Ops.push_back(DAG.getUNDEF(DstEltVT));
7889       else
7890         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7891     }
7892 
7893     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7894     return DAG.getBuildVector(VT, DL, Ops);
7895   }
7896 
7897   // Finally, this must be the case where we are shrinking elements: each input
7898   // turns into multiple outputs.
7899   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7900   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7901                             NumOutputsPerInput*BV->getNumOperands());
7902   SmallVector<SDValue, 8> Ops;
7903 
7904   for (const SDValue &Op : BV->op_values()) {
7905     if (Op.isUndef()) {
7906       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7907       continue;
7908     }
7909 
7910     APInt OpVal = cast<ConstantSDNode>(Op)->
7911                   getAPIntValue().zextOrTrunc(SrcBitSize);
7912 
7913     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7914       APInt ThisVal = OpVal.trunc(DstBitSize);
7915       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7916       OpVal = OpVal.lshr(DstBitSize);
7917     }
7918 
7919     // For big endian targets, swap the order of the pieces of each element.
7920     if (DAG.getDataLayout().isBigEndian())
7921       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7922   }
7923 
7924   return DAG.getBuildVector(VT, DL, Ops);
7925 }
7926 
7927 /// Try to perform FMA combining on a given FADD node.
7928 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7929   SDValue N0 = N->getOperand(0);
7930   SDValue N1 = N->getOperand(1);
7931   EVT VT = N->getValueType(0);
7932   SDLoc SL(N);
7933 
7934   const TargetOptions &Options = DAG.getTarget().Options;
7935   bool AllowFusion =
7936       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7937 
7938   // Floating-point multiply-add with intermediate rounding.
7939   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7940 
7941   // Floating-point multiply-add without intermediate rounding.
7942   bool HasFMA =
7943       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7944       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7945 
7946   // No valid opcode, do not combine.
7947   if (!HasFMAD && !HasFMA)
7948     return SDValue();
7949 
7950   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7951   ;
7952   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7953     return SDValue();
7954 
7955   // Always prefer FMAD to FMA for precision.
7956   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7957   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7958   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7959 
7960   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7961   // prefer to fold the multiply with fewer uses.
7962   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7963       N1.getOpcode() == ISD::FMUL) {
7964     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7965       std::swap(N0, N1);
7966   }
7967 
7968   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7969   if (N0.getOpcode() == ISD::FMUL &&
7970       (Aggressive || N0->hasOneUse())) {
7971     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7972                        N0.getOperand(0), N0.getOperand(1), N1);
7973   }
7974 
7975   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7976   // Note: Commutes FADD operands.
7977   if (N1.getOpcode() == ISD::FMUL &&
7978       (Aggressive || N1->hasOneUse())) {
7979     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7980                        N1.getOperand(0), N1.getOperand(1), N0);
7981   }
7982 
7983   // Look through FP_EXTEND nodes to do more combining.
7984   if (AllowFusion && LookThroughFPExt) {
7985     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7986     if (N0.getOpcode() == ISD::FP_EXTEND) {
7987       SDValue N00 = N0.getOperand(0);
7988       if (N00.getOpcode() == ISD::FMUL)
7989         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7990                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7991                                        N00.getOperand(0)),
7992                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7993                                        N00.getOperand(1)), N1);
7994     }
7995 
7996     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7997     // Note: Commutes FADD operands.
7998     if (N1.getOpcode() == ISD::FP_EXTEND) {
7999       SDValue N10 = N1.getOperand(0);
8000       if (N10.getOpcode() == ISD::FMUL)
8001         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8002                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8003                                        N10.getOperand(0)),
8004                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8005                                        N10.getOperand(1)), N0);
8006     }
8007   }
8008 
8009   // More folding opportunities when target permits.
8010   if ((AllowFusion || HasFMAD)  && Aggressive) {
8011     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8012     if (N0.getOpcode() == PreferredFusedOpcode &&
8013         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8014       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8015                          N0.getOperand(0), N0.getOperand(1),
8016                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8017                                      N0.getOperand(2).getOperand(0),
8018                                      N0.getOperand(2).getOperand(1),
8019                                      N1));
8020     }
8021 
8022     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8023     if (N1->getOpcode() == PreferredFusedOpcode &&
8024         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8025       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8026                          N1.getOperand(0), N1.getOperand(1),
8027                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8028                                      N1.getOperand(2).getOperand(0),
8029                                      N1.getOperand(2).getOperand(1),
8030                                      N0));
8031     }
8032 
8033     if (AllowFusion && LookThroughFPExt) {
8034       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8035       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
8036       auto FoldFAddFMAFPExtFMul = [&] (
8037           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8038         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8039                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8040                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8041                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8042                                        Z));
8043       };
8044       if (N0.getOpcode() == PreferredFusedOpcode) {
8045         SDValue N02 = N0.getOperand(2);
8046         if (N02.getOpcode() == ISD::FP_EXTEND) {
8047           SDValue N020 = N02.getOperand(0);
8048           if (N020.getOpcode() == ISD::FMUL)
8049             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8050                                         N020.getOperand(0), N020.getOperand(1),
8051                                         N1);
8052         }
8053       }
8054 
8055       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8056       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8057       // FIXME: This turns two single-precision and one double-precision
8058       // operation into two double-precision operations, which might not be
8059       // interesting for all targets, especially GPUs.
8060       auto FoldFAddFPExtFMAFMul = [&] (
8061           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8062         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8063                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8064                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8065                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8066                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8067                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8068                                        Z));
8069       };
8070       if (N0.getOpcode() == ISD::FP_EXTEND) {
8071         SDValue N00 = N0.getOperand(0);
8072         if (N00.getOpcode() == PreferredFusedOpcode) {
8073           SDValue N002 = N00.getOperand(2);
8074           if (N002.getOpcode() == ISD::FMUL)
8075             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8076                                         N002.getOperand(0), N002.getOperand(1),
8077                                         N1);
8078         }
8079       }
8080 
8081       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
8082       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
8083       if (N1.getOpcode() == PreferredFusedOpcode) {
8084         SDValue N12 = N1.getOperand(2);
8085         if (N12.getOpcode() == ISD::FP_EXTEND) {
8086           SDValue N120 = N12.getOperand(0);
8087           if (N120.getOpcode() == ISD::FMUL)
8088             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8089                                         N120.getOperand(0), N120.getOperand(1),
8090                                         N0);
8091         }
8092       }
8093 
8094       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8095       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8096       // FIXME: This turns two single-precision and one double-precision
8097       // operation into two double-precision operations, which might not be
8098       // interesting for all targets, especially GPUs.
8099       if (N1.getOpcode() == ISD::FP_EXTEND) {
8100         SDValue N10 = N1.getOperand(0);
8101         if (N10.getOpcode() == PreferredFusedOpcode) {
8102           SDValue N102 = N10.getOperand(2);
8103           if (N102.getOpcode() == ISD::FMUL)
8104             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8105                                         N102.getOperand(0), N102.getOperand(1),
8106                                         N0);
8107         }
8108       }
8109     }
8110   }
8111 
8112   return SDValue();
8113 }
8114 
8115 /// Try to perform FMA combining on a given FSUB node.
8116 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8117   SDValue N0 = N->getOperand(0);
8118   SDValue N1 = N->getOperand(1);
8119   EVT VT = N->getValueType(0);
8120   SDLoc SL(N);
8121 
8122   const TargetOptions &Options = DAG.getTarget().Options;
8123   bool AllowFusion =
8124       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8125 
8126   // Floating-point multiply-add with intermediate rounding.
8127   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8128 
8129   // Floating-point multiply-add without intermediate rounding.
8130   bool HasFMA =
8131       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8132       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8133 
8134   // No valid opcode, do not combine.
8135   if (!HasFMAD && !HasFMA)
8136     return SDValue();
8137 
8138   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8139   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8140     return SDValue();
8141 
8142   // Always prefer FMAD to FMA for precision.
8143   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8144   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8145   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8146 
8147   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8148   if (N0.getOpcode() == ISD::FMUL &&
8149       (Aggressive || N0->hasOneUse())) {
8150     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8151                        N0.getOperand(0), N0.getOperand(1),
8152                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8153   }
8154 
8155   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8156   // Note: Commutes FSUB operands.
8157   if (N1.getOpcode() == ISD::FMUL &&
8158       (Aggressive || N1->hasOneUse()))
8159     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8160                        DAG.getNode(ISD::FNEG, SL, VT,
8161                                    N1.getOperand(0)),
8162                        N1.getOperand(1), N0);
8163 
8164   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8165   if (N0.getOpcode() == ISD::FNEG &&
8166       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8167       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8168     SDValue N00 = N0.getOperand(0).getOperand(0);
8169     SDValue N01 = N0.getOperand(0).getOperand(1);
8170     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8171                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8172                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8173   }
8174 
8175   // Look through FP_EXTEND nodes to do more combining.
8176   if (AllowFusion && LookThroughFPExt) {
8177     // fold (fsub (fpext (fmul x, y)), z)
8178     //   -> (fma (fpext x), (fpext y), (fneg z))
8179     if (N0.getOpcode() == ISD::FP_EXTEND) {
8180       SDValue N00 = N0.getOperand(0);
8181       if (N00.getOpcode() == ISD::FMUL)
8182         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8183                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8184                                        N00.getOperand(0)),
8185                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8186                                        N00.getOperand(1)),
8187                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8188     }
8189 
8190     // fold (fsub x, (fpext (fmul y, z)))
8191     //   -> (fma (fneg (fpext y)), (fpext z), x)
8192     // Note: Commutes FSUB operands.
8193     if (N1.getOpcode() == ISD::FP_EXTEND) {
8194       SDValue N10 = N1.getOperand(0);
8195       if (N10.getOpcode() == ISD::FMUL)
8196         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8197                            DAG.getNode(ISD::FNEG, SL, VT,
8198                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8199                                                    N10.getOperand(0))),
8200                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8201                                        N10.getOperand(1)),
8202                            N0);
8203     }
8204 
8205     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8206     //   -> (fneg (fma (fpext x), (fpext y), z))
8207     // Note: This could be removed with appropriate canonicalization of the
8208     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8209     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8210     // from implementing the canonicalization in visitFSUB.
8211     if (N0.getOpcode() == ISD::FP_EXTEND) {
8212       SDValue N00 = N0.getOperand(0);
8213       if (N00.getOpcode() == ISD::FNEG) {
8214         SDValue N000 = N00.getOperand(0);
8215         if (N000.getOpcode() == ISD::FMUL) {
8216           return DAG.getNode(ISD::FNEG, SL, VT,
8217                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8218                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8219                                                      N000.getOperand(0)),
8220                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8221                                                      N000.getOperand(1)),
8222                                          N1));
8223         }
8224       }
8225     }
8226 
8227     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8228     //   -> (fneg (fma (fpext x)), (fpext y), z)
8229     // Note: This could be removed with appropriate canonicalization of the
8230     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8231     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8232     // from implementing the canonicalization in visitFSUB.
8233     if (N0.getOpcode() == ISD::FNEG) {
8234       SDValue N00 = N0.getOperand(0);
8235       if (N00.getOpcode() == ISD::FP_EXTEND) {
8236         SDValue N000 = N00.getOperand(0);
8237         if (N000.getOpcode() == ISD::FMUL) {
8238           return DAG.getNode(ISD::FNEG, SL, VT,
8239                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8240                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8241                                                      N000.getOperand(0)),
8242                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8243                                                      N000.getOperand(1)),
8244                                          N1));
8245         }
8246       }
8247     }
8248 
8249   }
8250 
8251   // More folding opportunities when target permits.
8252   if ((AllowFusion || HasFMAD) && Aggressive) {
8253     // fold (fsub (fma x, y, (fmul u, v)), z)
8254     //   -> (fma x, y (fma u, v, (fneg z)))
8255     if (N0.getOpcode() == PreferredFusedOpcode &&
8256         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8257       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8258                          N0.getOperand(0), N0.getOperand(1),
8259                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8260                                      N0.getOperand(2).getOperand(0),
8261                                      N0.getOperand(2).getOperand(1),
8262                                      DAG.getNode(ISD::FNEG, SL, VT,
8263                                                  N1)));
8264     }
8265 
8266     // fold (fsub x, (fma y, z, (fmul u, v)))
8267     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8268     if (N1.getOpcode() == PreferredFusedOpcode &&
8269         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8270       SDValue N20 = N1.getOperand(2).getOperand(0);
8271       SDValue N21 = N1.getOperand(2).getOperand(1);
8272       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8273                          DAG.getNode(ISD::FNEG, SL, VT,
8274                                      N1.getOperand(0)),
8275                          N1.getOperand(1),
8276                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8277                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8278 
8279                                      N21, N0));
8280     }
8281 
8282     if (AllowFusion && LookThroughFPExt) {
8283       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8284       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8285       if (N0.getOpcode() == PreferredFusedOpcode) {
8286         SDValue N02 = N0.getOperand(2);
8287         if (N02.getOpcode() == ISD::FP_EXTEND) {
8288           SDValue N020 = N02.getOperand(0);
8289           if (N020.getOpcode() == ISD::FMUL)
8290             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8291                                N0.getOperand(0), N0.getOperand(1),
8292                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8293                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8294                                                        N020.getOperand(0)),
8295                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8296                                                        N020.getOperand(1)),
8297                                            DAG.getNode(ISD::FNEG, SL, VT,
8298                                                        N1)));
8299         }
8300       }
8301 
8302       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8303       //   -> (fma (fpext x), (fpext y),
8304       //           (fma (fpext u), (fpext v), (fneg z)))
8305       // FIXME: This turns two single-precision and one double-precision
8306       // operation into two double-precision operations, which might not be
8307       // interesting for all targets, especially GPUs.
8308       if (N0.getOpcode() == ISD::FP_EXTEND) {
8309         SDValue N00 = N0.getOperand(0);
8310         if (N00.getOpcode() == PreferredFusedOpcode) {
8311           SDValue N002 = N00.getOperand(2);
8312           if (N002.getOpcode() == ISD::FMUL)
8313             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8314                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8315                                            N00.getOperand(0)),
8316                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8317                                            N00.getOperand(1)),
8318                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8319                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8320                                                        N002.getOperand(0)),
8321                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8322                                                        N002.getOperand(1)),
8323                                            DAG.getNode(ISD::FNEG, SL, VT,
8324                                                        N1)));
8325         }
8326       }
8327 
8328       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8329       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8330       if (N1.getOpcode() == PreferredFusedOpcode &&
8331         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8332         SDValue N120 = N1.getOperand(2).getOperand(0);
8333         if (N120.getOpcode() == ISD::FMUL) {
8334           SDValue N1200 = N120.getOperand(0);
8335           SDValue N1201 = N120.getOperand(1);
8336           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8337                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8338                              N1.getOperand(1),
8339                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8340                                          DAG.getNode(ISD::FNEG, SL, VT,
8341                                              DAG.getNode(ISD::FP_EXTEND, SL,
8342                                                          VT, N1200)),
8343                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8344                                                      N1201),
8345                                          N0));
8346         }
8347       }
8348 
8349       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8350       //   -> (fma (fneg (fpext y)), (fpext z),
8351       //           (fma (fneg (fpext u)), (fpext v), x))
8352       // FIXME: This turns two single-precision and one double-precision
8353       // operation into two double-precision operations, which might not be
8354       // interesting for all targets, especially GPUs.
8355       if (N1.getOpcode() == ISD::FP_EXTEND &&
8356         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8357         SDValue N100 = N1.getOperand(0).getOperand(0);
8358         SDValue N101 = N1.getOperand(0).getOperand(1);
8359         SDValue N102 = N1.getOperand(0).getOperand(2);
8360         if (N102.getOpcode() == ISD::FMUL) {
8361           SDValue N1020 = N102.getOperand(0);
8362           SDValue N1021 = N102.getOperand(1);
8363           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8364                              DAG.getNode(ISD::FNEG, SL, VT,
8365                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8366                                                      N100)),
8367                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8368                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8369                                          DAG.getNode(ISD::FNEG, SL, VT,
8370                                              DAG.getNode(ISD::FP_EXTEND, SL,
8371                                                          VT, N1020)),
8372                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8373                                                      N1021),
8374                                          N0));
8375         }
8376       }
8377     }
8378   }
8379 
8380   return SDValue();
8381 }
8382 
8383 /// Try to perform FMA combining on a given FMUL node based on the distributive
8384 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
8385 /// subtraction instead of addition).
8386 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
8387   SDValue N0 = N->getOperand(0);
8388   SDValue N1 = N->getOperand(1);
8389   EVT VT = N->getValueType(0);
8390   SDLoc SL(N);
8391 
8392   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8393 
8394   const TargetOptions &Options = DAG.getTarget().Options;
8395 
8396   // The transforms below are incorrect when x == 0 and y == inf, because the
8397   // intermediate multiplication produces a nan.
8398   if (!Options.NoInfsFPMath)
8399     return SDValue();
8400 
8401   // Floating-point multiply-add without intermediate rounding.
8402   bool HasFMA =
8403       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
8404       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8405       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8406 
8407   // Floating-point multiply-add with intermediate rounding. This can result
8408   // in a less precise result due to the changed rounding order.
8409   bool HasFMAD = Options.UnsafeFPMath &&
8410                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8411 
8412   // No valid opcode, do not combine.
8413   if (!HasFMAD && !HasFMA)
8414     return SDValue();
8415 
8416   // Always prefer FMAD to FMA for precision.
8417   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8418   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8419 
8420   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8421   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8422   auto FuseFADD = [&](SDValue X, SDValue Y) {
8423     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8424       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8425       if (XC1 && XC1->isExactlyValue(+1.0))
8426         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8427       if (XC1 && XC1->isExactlyValue(-1.0))
8428         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8429                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8430     }
8431     return SDValue();
8432   };
8433 
8434   if (SDValue FMA = FuseFADD(N0, N1))
8435     return FMA;
8436   if (SDValue FMA = FuseFADD(N1, N0))
8437     return FMA;
8438 
8439   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8440   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8441   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8442   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8443   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8444     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8445       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8446       if (XC0 && XC0->isExactlyValue(+1.0))
8447         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8448                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8449                            Y);
8450       if (XC0 && XC0->isExactlyValue(-1.0))
8451         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8452                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8453                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8454 
8455       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8456       if (XC1 && XC1->isExactlyValue(+1.0))
8457         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8458                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8459       if (XC1 && XC1->isExactlyValue(-1.0))
8460         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8461     }
8462     return SDValue();
8463   };
8464 
8465   if (SDValue FMA = FuseFSUB(N0, N1))
8466     return FMA;
8467   if (SDValue FMA = FuseFSUB(N1, N0))
8468     return FMA;
8469 
8470   return SDValue();
8471 }
8472 
8473 SDValue DAGCombiner::visitFADD(SDNode *N) {
8474   SDValue N0 = N->getOperand(0);
8475   SDValue N1 = N->getOperand(1);
8476   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8477   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8478   EVT VT = N->getValueType(0);
8479   SDLoc DL(N);
8480   const TargetOptions &Options = DAG.getTarget().Options;
8481   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8482 
8483   // fold vector ops
8484   if (VT.isVector())
8485     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8486       return FoldedVOp;
8487 
8488   // fold (fadd c1, c2) -> c1 + c2
8489   if (N0CFP && N1CFP)
8490     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8491 
8492   // canonicalize constant to RHS
8493   if (N0CFP && !N1CFP)
8494     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8495 
8496   // fold (fadd A, (fneg B)) -> (fsub A, B)
8497   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8498       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8499     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8500                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8501 
8502   // fold (fadd (fneg A), B) -> (fsub B, A)
8503   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8504       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8505     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8506                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8507 
8508   // FIXME: Auto-upgrade the target/function-level option.
8509   if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8510     // fold (fadd A, 0) -> A
8511     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8512       if (N1C->isZero())
8513         return N0;
8514   }
8515 
8516   // If 'unsafe math' is enabled, fold lots of things.
8517   if (Options.UnsafeFPMath) {
8518     // No FP constant should be created after legalization as Instruction
8519     // Selection pass has a hard time dealing with FP constants.
8520     bool AllowNewConst = (Level < AfterLegalizeDAG);
8521 
8522     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8523     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8524         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8525       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8526                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8527                                      Flags),
8528                          Flags);
8529 
8530     // If allowed, fold (fadd (fneg x), x) -> 0.0
8531     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8532       return DAG.getConstantFP(0.0, DL, VT);
8533 
8534     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8535     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8536       return DAG.getConstantFP(0.0, DL, VT);
8537 
8538     // We can fold chains of FADD's of the same value into multiplications.
8539     // This transform is not safe in general because we are reducing the number
8540     // of rounding steps.
8541     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8542       if (N0.getOpcode() == ISD::FMUL) {
8543         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8544         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8545 
8546         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8547         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8548           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8549                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8550           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8551         }
8552 
8553         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8554         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8555             N1.getOperand(0) == N1.getOperand(1) &&
8556             N0.getOperand(0) == N1.getOperand(0)) {
8557           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8558                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8559           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8560         }
8561       }
8562 
8563       if (N1.getOpcode() == ISD::FMUL) {
8564         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8565         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8566 
8567         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8568         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8569           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8570                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8571           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8572         }
8573 
8574         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8575         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8576             N0.getOperand(0) == N0.getOperand(1) &&
8577             N1.getOperand(0) == N0.getOperand(0)) {
8578           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8579                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8580           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8581         }
8582       }
8583 
8584       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8585         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8586         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8587         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8588             (N0.getOperand(0) == N1)) {
8589           return DAG.getNode(ISD::FMUL, DL, VT,
8590                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8591         }
8592       }
8593 
8594       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8595         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8596         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8597         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8598             N1.getOperand(0) == N0) {
8599           return DAG.getNode(ISD::FMUL, DL, VT,
8600                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8601         }
8602       }
8603 
8604       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8605       if (AllowNewConst &&
8606           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8607           N0.getOperand(0) == N0.getOperand(1) &&
8608           N1.getOperand(0) == N1.getOperand(1) &&
8609           N0.getOperand(0) == N1.getOperand(0)) {
8610         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8611                            DAG.getConstantFP(4.0, DL, VT), Flags);
8612       }
8613     }
8614   } // enable-unsafe-fp-math
8615 
8616   // FADD -> FMA combines:
8617   if (SDValue Fused = visitFADDForFMACombine(N)) {
8618     AddToWorklist(Fused.getNode());
8619     return Fused;
8620   }
8621   return SDValue();
8622 }
8623 
8624 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8625   SDValue N0 = N->getOperand(0);
8626   SDValue N1 = N->getOperand(1);
8627   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8628   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8629   EVT VT = N->getValueType(0);
8630   SDLoc DL(N);
8631   const TargetOptions &Options = DAG.getTarget().Options;
8632   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8633 
8634   // fold vector ops
8635   if (VT.isVector())
8636     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8637       return FoldedVOp;
8638 
8639   // fold (fsub c1, c2) -> c1-c2
8640   if (N0CFP && N1CFP)
8641     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
8642 
8643   // fold (fsub A, (fneg B)) -> (fadd A, B)
8644   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8645     return DAG.getNode(ISD::FADD, DL, VT, N0,
8646                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8647 
8648   // FIXME: Auto-upgrade the target/function-level option.
8649   if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8650     // (fsub 0, B) -> -B
8651     if (N0CFP && N0CFP->isZero()) {
8652       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8653         return GetNegatedExpression(N1, DAG, LegalOperations);
8654       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8655         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
8656     }
8657   }
8658 
8659   // If 'unsafe math' is enabled, fold lots of things.
8660   if (Options.UnsafeFPMath) {
8661     // (fsub A, 0) -> A
8662     if (N1CFP && N1CFP->isZero())
8663       return N0;
8664 
8665     // (fsub x, x) -> 0.0
8666     if (N0 == N1)
8667       return DAG.getConstantFP(0.0f, DL, VT);
8668 
8669     // (fsub x, (fadd x, y)) -> (fneg y)
8670     // (fsub x, (fadd y, x)) -> (fneg y)
8671     if (N1.getOpcode() == ISD::FADD) {
8672       SDValue N10 = N1->getOperand(0);
8673       SDValue N11 = N1->getOperand(1);
8674 
8675       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8676         return GetNegatedExpression(N11, DAG, LegalOperations);
8677 
8678       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8679         return GetNegatedExpression(N10, DAG, LegalOperations);
8680     }
8681   }
8682 
8683   // FSUB -> FMA combines:
8684   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8685     AddToWorklist(Fused.getNode());
8686     return Fused;
8687   }
8688 
8689   return SDValue();
8690 }
8691 
8692 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8693   SDValue N0 = N->getOperand(0);
8694   SDValue N1 = N->getOperand(1);
8695   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8696   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8697   EVT VT = N->getValueType(0);
8698   SDLoc DL(N);
8699   const TargetOptions &Options = DAG.getTarget().Options;
8700   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8701 
8702   // fold vector ops
8703   if (VT.isVector()) {
8704     // This just handles C1 * C2 for vectors. Other vector folds are below.
8705     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8706       return FoldedVOp;
8707   }
8708 
8709   // fold (fmul c1, c2) -> c1*c2
8710   if (N0CFP && N1CFP)
8711     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8712 
8713   // canonicalize constant to RHS
8714   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8715      !isConstantFPBuildVectorOrConstantFP(N1))
8716     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8717 
8718   // fold (fmul A, 1.0) -> A
8719   if (N1CFP && N1CFP->isExactlyValue(1.0))
8720     return N0;
8721 
8722   if (Options.UnsafeFPMath) {
8723     // fold (fmul A, 0) -> 0
8724     if (N1CFP && N1CFP->isZero())
8725       return N1;
8726 
8727     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8728     if (N0.getOpcode() == ISD::FMUL) {
8729       // Fold scalars or any vector constants (not just splats).
8730       // This fold is done in general by InstCombine, but extra fmul insts
8731       // may have been generated during lowering.
8732       SDValue N00 = N0.getOperand(0);
8733       SDValue N01 = N0.getOperand(1);
8734       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8735       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8736       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8737 
8738       // Check 1: Make sure that the first operand of the inner multiply is NOT
8739       // a constant. Otherwise, we may induce infinite looping.
8740       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8741         // Check 2: Make sure that the second operand of the inner multiply and
8742         // the second operand of the outer multiply are constants.
8743         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8744             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8745           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8746           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8747         }
8748       }
8749     }
8750 
8751     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8752     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8753     // during an early run of DAGCombiner can prevent folding with fmuls
8754     // inserted during lowering.
8755     if (N0.getOpcode() == ISD::FADD &&
8756         (N0.getOperand(0) == N0.getOperand(1)) &&
8757         N0.hasOneUse()) {
8758       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8759       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8760       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8761     }
8762   }
8763 
8764   // fold (fmul X, 2.0) -> (fadd X, X)
8765   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8766     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8767 
8768   // fold (fmul X, -1.0) -> (fneg X)
8769   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8770     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8771       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8772 
8773   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8774   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8775     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8776       // Both can be negated for free, check to see if at least one is cheaper
8777       // negated.
8778       if (LHSNeg == 2 || RHSNeg == 2)
8779         return DAG.getNode(ISD::FMUL, DL, VT,
8780                            GetNegatedExpression(N0, DAG, LegalOperations),
8781                            GetNegatedExpression(N1, DAG, LegalOperations),
8782                            Flags);
8783     }
8784   }
8785 
8786   // FMUL -> FMA combines:
8787   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
8788     AddToWorklist(Fused.getNode());
8789     return Fused;
8790   }
8791 
8792   return SDValue();
8793 }
8794 
8795 SDValue DAGCombiner::visitFMA(SDNode *N) {
8796   SDValue N0 = N->getOperand(0);
8797   SDValue N1 = N->getOperand(1);
8798   SDValue N2 = N->getOperand(2);
8799   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8800   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8801   EVT VT = N->getValueType(0);
8802   SDLoc DL(N);
8803   const TargetOptions &Options = DAG.getTarget().Options;
8804 
8805   // Constant fold FMA.
8806   if (isa<ConstantFPSDNode>(N0) &&
8807       isa<ConstantFPSDNode>(N1) &&
8808       isa<ConstantFPSDNode>(N2)) {
8809     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
8810   }
8811 
8812   if (Options.UnsafeFPMath) {
8813     if (N0CFP && N0CFP->isZero())
8814       return N2;
8815     if (N1CFP && N1CFP->isZero())
8816       return N2;
8817   }
8818   // TODO: The FMA node should have flags that propagate to these nodes.
8819   if (N0CFP && N0CFP->isExactlyValue(1.0))
8820     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8821   if (N1CFP && N1CFP->isExactlyValue(1.0))
8822     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8823 
8824   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8825   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8826      !isConstantFPBuildVectorOrConstantFP(N1))
8827     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8828 
8829   // TODO: FMA nodes should have flags that propagate to the created nodes.
8830   // For now, create a Flags object for use with all unsafe math transforms.
8831   SDNodeFlags Flags;
8832   Flags.setUnsafeAlgebra(true);
8833 
8834   if (Options.UnsafeFPMath) {
8835     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8836     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8837         isConstantFPBuildVectorOrConstantFP(N1) &&
8838         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8839       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8840                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
8841                                      &Flags), &Flags);
8842     }
8843 
8844     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8845     if (N0.getOpcode() == ISD::FMUL &&
8846         isConstantFPBuildVectorOrConstantFP(N1) &&
8847         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8848       return DAG.getNode(ISD::FMA, DL, VT,
8849                          N0.getOperand(0),
8850                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
8851                                      &Flags),
8852                          N2);
8853     }
8854   }
8855 
8856   // (fma x, 1, y) -> (fadd x, y)
8857   // (fma x, -1, y) -> (fadd (fneg x), y)
8858   if (N1CFP) {
8859     if (N1CFP->isExactlyValue(1.0))
8860       // TODO: The FMA node should have flags that propagate to this node.
8861       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
8862 
8863     if (N1CFP->isExactlyValue(-1.0) &&
8864         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8865       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
8866       AddToWorklist(RHSNeg.getNode());
8867       // TODO: The FMA node should have flags that propagate to this node.
8868       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
8869     }
8870   }
8871 
8872   if (Options.UnsafeFPMath) {
8873     // (fma x, c, x) -> (fmul x, (c+1))
8874     if (N1CFP && N0 == N2) {
8875       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8876                          DAG.getNode(ISD::FADD, DL, VT, N1,
8877                                      DAG.getConstantFP(1.0, DL, VT), &Flags),
8878                          &Flags);
8879     }
8880 
8881     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8882     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8883       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8884                          DAG.getNode(ISD::FADD, DL, VT, N1,
8885                                      DAG.getConstantFP(-1.0, DL, VT), &Flags),
8886                          &Flags);
8887     }
8888   }
8889 
8890   return SDValue();
8891 }
8892 
8893 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8894 // reciprocal.
8895 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8896 // Notice that this is not always beneficial. One reason is different targets
8897 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8898 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8899 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8900 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8901   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8902   const SDNodeFlags *Flags = N->getFlags();
8903   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8904     return SDValue();
8905 
8906   // Skip if current node is a reciprocal.
8907   SDValue N0 = N->getOperand(0);
8908   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8909   if (N0CFP && N0CFP->isExactlyValue(1.0))
8910     return SDValue();
8911 
8912   // Exit early if the target does not want this transform or if there can't
8913   // possibly be enough uses of the divisor to make the transform worthwhile.
8914   SDValue N1 = N->getOperand(1);
8915   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8916   if (!MinUses || N1->use_size() < MinUses)
8917     return SDValue();
8918 
8919   // Find all FDIV users of the same divisor.
8920   // Use a set because duplicates may be present in the user list.
8921   SetVector<SDNode *> Users;
8922   for (auto *U : N1->uses()) {
8923     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8924       // This division is eligible for optimization only if global unsafe math
8925       // is enabled or if this division allows reciprocal formation.
8926       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8927         Users.insert(U);
8928     }
8929   }
8930 
8931   // Now that we have the actual number of divisor uses, make sure it meets
8932   // the minimum threshold specified by the target.
8933   if (Users.size() < MinUses)
8934     return SDValue();
8935 
8936   EVT VT = N->getValueType(0);
8937   SDLoc DL(N);
8938   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8939   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8940 
8941   // Dividend / Divisor -> Dividend * Reciprocal
8942   for (auto *U : Users) {
8943     SDValue Dividend = U->getOperand(0);
8944     if (Dividend != FPOne) {
8945       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8946                                     Reciprocal, Flags);
8947       CombineTo(U, NewNode);
8948     } else if (U != Reciprocal.getNode()) {
8949       // In the absence of fast-math-flags, this user node is always the
8950       // same node as Reciprocal, but with FMF they may be different nodes.
8951       CombineTo(U, Reciprocal);
8952     }
8953   }
8954   return SDValue(N, 0);  // N was replaced.
8955 }
8956 
8957 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8958   SDValue N0 = N->getOperand(0);
8959   SDValue N1 = N->getOperand(1);
8960   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8961   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8962   EVT VT = N->getValueType(0);
8963   SDLoc DL(N);
8964   const TargetOptions &Options = DAG.getTarget().Options;
8965   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8966 
8967   // fold vector ops
8968   if (VT.isVector())
8969     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8970       return FoldedVOp;
8971 
8972   // fold (fdiv c1, c2) -> c1/c2
8973   if (N0CFP && N1CFP)
8974     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8975 
8976   if (Options.UnsafeFPMath) {
8977     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8978     if (N1CFP) {
8979       // Compute the reciprocal 1.0 / c2.
8980       const APFloat &N1APF = N1CFP->getValueAPF();
8981       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8982       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8983       // Only do the transform if the reciprocal is a legal fp immediate that
8984       // isn't too nasty (eg NaN, denormal, ...).
8985       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8986           (!LegalOperations ||
8987            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8988            // backend)... we should handle this gracefully after Legalize.
8989            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8990            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8991            TLI.isFPImmLegal(Recip, VT)))
8992         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8993                            DAG.getConstantFP(Recip, DL, VT), Flags);
8994     }
8995 
8996     // If this FDIV is part of a reciprocal square root, it may be folded
8997     // into a target-specific square root estimate instruction.
8998     if (N1.getOpcode() == ISD::FSQRT) {
8999       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
9000         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9001       }
9002     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
9003                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9004       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9005                                           Flags)) {
9006         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
9007         AddToWorklist(RV.getNode());
9008         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9009       }
9010     } else if (N1.getOpcode() == ISD::FP_ROUND &&
9011                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9012       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9013                                           Flags)) {
9014         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9015         AddToWorklist(RV.getNode());
9016         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9017       }
9018     } else if (N1.getOpcode() == ISD::FMUL) {
9019       // Look through an FMUL. Even though this won't remove the FDIV directly,
9020       // it's still worthwhile to get rid of the FSQRT if possible.
9021       SDValue SqrtOp;
9022       SDValue OtherOp;
9023       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9024         SqrtOp = N1.getOperand(0);
9025         OtherOp = N1.getOperand(1);
9026       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
9027         SqrtOp = N1.getOperand(1);
9028         OtherOp = N1.getOperand(0);
9029       }
9030       if (SqrtOp.getNode()) {
9031         // We found a FSQRT, so try to make this fold:
9032         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9033         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9034           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9035           AddToWorklist(RV.getNode());
9036           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9037         }
9038       }
9039     }
9040 
9041     // Fold into a reciprocal estimate and multiply instead of a real divide.
9042     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
9043       AddToWorklist(RV.getNode());
9044       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9045     }
9046   }
9047 
9048   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
9049   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9050     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9051       // Both can be negated for free, check to see if at least one is cheaper
9052       // negated.
9053       if (LHSNeg == 2 || RHSNeg == 2)
9054         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
9055                            GetNegatedExpression(N0, DAG, LegalOperations),
9056                            GetNegatedExpression(N1, DAG, LegalOperations),
9057                            Flags);
9058     }
9059   }
9060 
9061   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
9062     return CombineRepeatedDivisors;
9063 
9064   return SDValue();
9065 }
9066 
9067 SDValue DAGCombiner::visitFREM(SDNode *N) {
9068   SDValue N0 = N->getOperand(0);
9069   SDValue N1 = N->getOperand(1);
9070   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9071   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9072   EVT VT = N->getValueType(0);
9073 
9074   // fold (frem c1, c2) -> fmod(c1,c2)
9075   if (N0CFP && N1CFP)
9076     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
9077                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
9078 
9079   return SDValue();
9080 }
9081 
9082 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
9083   if (!DAG.getTarget().Options.UnsafeFPMath)
9084     return SDValue();
9085 
9086   SDValue N0 = N->getOperand(0);
9087   if (TLI.isFsqrtCheap(N0, DAG))
9088     return SDValue();
9089 
9090   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
9091   // For now, create a Flags object for use with all unsafe math transforms.
9092   SDNodeFlags Flags;
9093   Flags.setUnsafeAlgebra(true);
9094   return buildSqrtEstimate(N0, &Flags);
9095 }
9096 
9097 /// copysign(x, fp_extend(y)) -> copysign(x, y)
9098 /// copysign(x, fp_round(y)) -> copysign(x, y)
9099 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9100   SDValue N1 = N->getOperand(1);
9101   if ((N1.getOpcode() == ISD::FP_EXTEND ||
9102        N1.getOpcode() == ISD::FP_ROUND)) {
9103     // Do not optimize out type conversion of f128 type yet.
9104     // For some targets like x86_64, configuration is changed to keep one f128
9105     // value in one SSE register, but instruction selection cannot handle
9106     // FCOPYSIGN on SSE registers yet.
9107     EVT N1VT = N1->getValueType(0);
9108     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9109     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9110   }
9111   return false;
9112 }
9113 
9114 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9115   SDValue N0 = N->getOperand(0);
9116   SDValue N1 = N->getOperand(1);
9117   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9118   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9119   EVT VT = N->getValueType(0);
9120 
9121   if (N0CFP && N1CFP) // Constant fold
9122     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9123 
9124   if (N1CFP) {
9125     const APFloat &V = N1CFP->getValueAPF();
9126     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
9127     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9128     if (!V.isNegative()) {
9129       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9130         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9131     } else {
9132       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9133         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9134                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9135     }
9136   }
9137 
9138   // copysign(fabs(x), y) -> copysign(x, y)
9139   // copysign(fneg(x), y) -> copysign(x, y)
9140   // copysign(copysign(x,z), y) -> copysign(x, y)
9141   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9142       N0.getOpcode() == ISD::FCOPYSIGN)
9143     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9144 
9145   // copysign(x, abs(y)) -> abs(x)
9146   if (N1.getOpcode() == ISD::FABS)
9147     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9148 
9149   // copysign(x, copysign(y,z)) -> copysign(x, z)
9150   if (N1.getOpcode() == ISD::FCOPYSIGN)
9151     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9152 
9153   // copysign(x, fp_extend(y)) -> copysign(x, y)
9154   // copysign(x, fp_round(y)) -> copysign(x, y)
9155   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9156     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9157 
9158   return SDValue();
9159 }
9160 
9161 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9162   SDValue N0 = N->getOperand(0);
9163   EVT VT = N->getValueType(0);
9164   EVT OpVT = N0.getValueType();
9165 
9166   // fold (sint_to_fp c1) -> c1fp
9167   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9168       // ...but only if the target supports immediate floating-point values
9169       (!LegalOperations ||
9170        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9171     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9172 
9173   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9174   // but UINT_TO_FP is legal on this target, try to convert.
9175   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9176       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9177     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9178     if (DAG.SignBitIsZero(N0))
9179       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9180   }
9181 
9182   // The next optimizations are desirable only if SELECT_CC can be lowered.
9183   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9184     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9185     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9186         !VT.isVector() &&
9187         (!LegalOperations ||
9188          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9189       SDLoc DL(N);
9190       SDValue Ops[] =
9191         { N0.getOperand(0), N0.getOperand(1),
9192           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9193           N0.getOperand(2) };
9194       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9195     }
9196 
9197     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9198     //      (select_cc x, y, 1.0, 0.0,, cc)
9199     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9200         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9201         (!LegalOperations ||
9202          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9203       SDLoc DL(N);
9204       SDValue Ops[] =
9205         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9206           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9207           N0.getOperand(0).getOperand(2) };
9208       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9209     }
9210   }
9211 
9212   return SDValue();
9213 }
9214 
9215 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9216   SDValue N0 = N->getOperand(0);
9217   EVT VT = N->getValueType(0);
9218   EVT OpVT = N0.getValueType();
9219 
9220   // fold (uint_to_fp c1) -> c1fp
9221   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9222       // ...but only if the target supports immediate floating-point values
9223       (!LegalOperations ||
9224        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9225     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9226 
9227   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9228   // but SINT_TO_FP is legal on this target, try to convert.
9229   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9230       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9231     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9232     if (DAG.SignBitIsZero(N0))
9233       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9234   }
9235 
9236   // The next optimizations are desirable only if SELECT_CC can be lowered.
9237   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9238     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9239 
9240     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9241         (!LegalOperations ||
9242          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9243       SDLoc DL(N);
9244       SDValue Ops[] =
9245         { N0.getOperand(0), N0.getOperand(1),
9246           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9247           N0.getOperand(2) };
9248       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9249     }
9250   }
9251 
9252   return SDValue();
9253 }
9254 
9255 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9256 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9257   SDValue N0 = N->getOperand(0);
9258   EVT VT = N->getValueType(0);
9259 
9260   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9261     return SDValue();
9262 
9263   SDValue Src = N0.getOperand(0);
9264   EVT SrcVT = Src.getValueType();
9265   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9266   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9267 
9268   // We can safely assume the conversion won't overflow the output range,
9269   // because (for example) (uint8_t)18293.f is undefined behavior.
9270 
9271   // Since we can assume the conversion won't overflow, our decision as to
9272   // whether the input will fit in the float should depend on the minimum
9273   // of the input range and output range.
9274 
9275   // This means this is also safe for a signed input and unsigned output, since
9276   // a negative input would lead to undefined behavior.
9277   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9278   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9279   unsigned ActualSize = std::min(InputSize, OutputSize);
9280   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9281 
9282   // We can only fold away the float conversion if the input range can be
9283   // represented exactly in the float range.
9284   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9285     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9286       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9287                                                        : ISD::ZERO_EXTEND;
9288       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9289     }
9290     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9291       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9292     return DAG.getBitcast(VT, Src);
9293   }
9294   return SDValue();
9295 }
9296 
9297 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9298   SDValue N0 = N->getOperand(0);
9299   EVT VT = N->getValueType(0);
9300 
9301   // fold (fp_to_sint c1fp) -> c1
9302   if (isConstantFPBuildVectorOrConstantFP(N0))
9303     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9304 
9305   return FoldIntToFPToInt(N, DAG);
9306 }
9307 
9308 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9309   SDValue N0 = N->getOperand(0);
9310   EVT VT = N->getValueType(0);
9311 
9312   // fold (fp_to_uint c1fp) -> c1
9313   if (isConstantFPBuildVectorOrConstantFP(N0))
9314     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9315 
9316   return FoldIntToFPToInt(N, DAG);
9317 }
9318 
9319 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9320   SDValue N0 = N->getOperand(0);
9321   SDValue N1 = N->getOperand(1);
9322   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9323   EVT VT = N->getValueType(0);
9324 
9325   // fold (fp_round c1fp) -> c1fp
9326   if (N0CFP)
9327     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9328 
9329   // fold (fp_round (fp_extend x)) -> x
9330   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9331     return N0.getOperand(0);
9332 
9333   // fold (fp_round (fp_round x)) -> (fp_round x)
9334   if (N0.getOpcode() == ISD::FP_ROUND) {
9335     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9336     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
9337 
9338     // Skip this folding if it results in an fp_round from f80 to f16.
9339     //
9340     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9341     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9342     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9343     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9344     // x86.
9345     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9346       return SDValue();
9347 
9348     // If the first fp_round isn't a value preserving truncation, it might
9349     // introduce a tie in the second fp_round, that wouldn't occur in the
9350     // single-step fp_round we want to fold to.
9351     // In other words, double rounding isn't the same as rounding.
9352     // Also, this is a value preserving truncation iff both fp_round's are.
9353     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9354       SDLoc DL(N);
9355       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9356                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9357     }
9358   }
9359 
9360   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9361   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9362     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9363                               N0.getOperand(0), N1);
9364     AddToWorklist(Tmp.getNode());
9365     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9366                        Tmp, N0.getOperand(1));
9367   }
9368 
9369   return SDValue();
9370 }
9371 
9372 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9373   SDValue N0 = N->getOperand(0);
9374   EVT VT = N->getValueType(0);
9375   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9376   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9377 
9378   // fold (fp_round_inreg c1fp) -> c1fp
9379   if (N0CFP && isTypeLegal(EVT)) {
9380     SDLoc DL(N);
9381     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9382     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9383   }
9384 
9385   return SDValue();
9386 }
9387 
9388 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9389   SDValue N0 = N->getOperand(0);
9390   EVT VT = N->getValueType(0);
9391 
9392   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9393   if (N->hasOneUse() &&
9394       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9395     return SDValue();
9396 
9397   // fold (fp_extend c1fp) -> c1fp
9398   if (isConstantFPBuildVectorOrConstantFP(N0))
9399     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9400 
9401   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9402   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9403       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9404     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9405 
9406   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9407   // value of X.
9408   if (N0.getOpcode() == ISD::FP_ROUND
9409       && N0.getConstantOperandVal(1) == 1) {
9410     SDValue In = N0.getOperand(0);
9411     if (In.getValueType() == VT) return In;
9412     if (VT.bitsLT(In.getValueType()))
9413       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9414                          In, N0.getOperand(1));
9415     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9416   }
9417 
9418   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9419   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9420        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9421     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9422     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9423                                      LN0->getChain(),
9424                                      LN0->getBasePtr(), N0.getValueType(),
9425                                      LN0->getMemOperand());
9426     CombineTo(N, ExtLoad);
9427     CombineTo(N0.getNode(),
9428               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9429                           N0.getValueType(), ExtLoad,
9430                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9431               ExtLoad.getValue(1));
9432     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9433   }
9434 
9435   return SDValue();
9436 }
9437 
9438 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9439   SDValue N0 = N->getOperand(0);
9440   EVT VT = N->getValueType(0);
9441 
9442   // fold (fceil c1) -> fceil(c1)
9443   if (isConstantFPBuildVectorOrConstantFP(N0))
9444     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9445 
9446   return SDValue();
9447 }
9448 
9449 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9450   SDValue N0 = N->getOperand(0);
9451   EVT VT = N->getValueType(0);
9452 
9453   // fold (ftrunc c1) -> ftrunc(c1)
9454   if (isConstantFPBuildVectorOrConstantFP(N0))
9455     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9456 
9457   return SDValue();
9458 }
9459 
9460 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9461   SDValue N0 = N->getOperand(0);
9462   EVT VT = N->getValueType(0);
9463 
9464   // fold (ffloor c1) -> ffloor(c1)
9465   if (isConstantFPBuildVectorOrConstantFP(N0))
9466     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9467 
9468   return SDValue();
9469 }
9470 
9471 // FIXME: FNEG and FABS have a lot in common; refactor.
9472 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9473   SDValue N0 = N->getOperand(0);
9474   EVT VT = N->getValueType(0);
9475 
9476   // Constant fold FNEG.
9477   if (isConstantFPBuildVectorOrConstantFP(N0))
9478     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9479 
9480   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9481                          &DAG.getTarget().Options))
9482     return GetNegatedExpression(N0, DAG, LegalOperations);
9483 
9484   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9485   // constant pool values.
9486   if (!TLI.isFNegFree(VT) &&
9487       N0.getOpcode() == ISD::BITCAST &&
9488       N0.getNode()->hasOneUse()) {
9489     SDValue Int = N0.getOperand(0);
9490     EVT IntVT = Int.getValueType();
9491     if (IntVT.isInteger() && !IntVT.isVector()) {
9492       APInt SignMask;
9493       if (N0.getValueType().isVector()) {
9494         // For a vector, get a mask such as 0x80... per scalar element
9495         // and splat it.
9496         SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits());
9497         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9498       } else {
9499         // For a scalar, just generate 0x80...
9500         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9501       }
9502       SDLoc DL0(N0);
9503       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9504                         DAG.getConstant(SignMask, DL0, IntVT));
9505       AddToWorklist(Int.getNode());
9506       return DAG.getBitcast(VT, Int);
9507     }
9508   }
9509 
9510   // (fneg (fmul c, x)) -> (fmul -c, x)
9511   if (N0.getOpcode() == ISD::FMUL &&
9512       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9513     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9514     if (CFP1) {
9515       APFloat CVal = CFP1->getValueAPF();
9516       CVal.changeSign();
9517       if (Level >= AfterLegalizeDAG &&
9518           (TLI.isFPImmLegal(CVal, VT) ||
9519            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9520         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9521                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9522                                        N0.getOperand(1)),
9523                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9524     }
9525   }
9526 
9527   return SDValue();
9528 }
9529 
9530 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9531   SDValue N0 = N->getOperand(0);
9532   SDValue N1 = N->getOperand(1);
9533   EVT VT = N->getValueType(0);
9534   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9535   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9536 
9537   if (N0CFP && N1CFP) {
9538     const APFloat &C0 = N0CFP->getValueAPF();
9539     const APFloat &C1 = N1CFP->getValueAPF();
9540     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9541   }
9542 
9543   // Canonicalize to constant on RHS.
9544   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9545      !isConstantFPBuildVectorOrConstantFP(N1))
9546     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9547 
9548   return SDValue();
9549 }
9550 
9551 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9552   SDValue N0 = N->getOperand(0);
9553   SDValue N1 = N->getOperand(1);
9554   EVT VT = N->getValueType(0);
9555   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9556   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9557 
9558   if (N0CFP && N1CFP) {
9559     const APFloat &C0 = N0CFP->getValueAPF();
9560     const APFloat &C1 = N1CFP->getValueAPF();
9561     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9562   }
9563 
9564   // Canonicalize to constant on RHS.
9565   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9566      !isConstantFPBuildVectorOrConstantFP(N1))
9567     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9568 
9569   return SDValue();
9570 }
9571 
9572 SDValue DAGCombiner::visitFABS(SDNode *N) {
9573   SDValue N0 = N->getOperand(0);
9574   EVT VT = N->getValueType(0);
9575 
9576   // fold (fabs c1) -> fabs(c1)
9577   if (isConstantFPBuildVectorOrConstantFP(N0))
9578     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9579 
9580   // fold (fabs (fabs x)) -> (fabs x)
9581   if (N0.getOpcode() == ISD::FABS)
9582     return N->getOperand(0);
9583 
9584   // fold (fabs (fneg x)) -> (fabs x)
9585   // fold (fabs (fcopysign x, y)) -> (fabs x)
9586   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9587     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9588 
9589   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9590   // constant pool values.
9591   if (!TLI.isFAbsFree(VT) &&
9592       N0.getOpcode() == ISD::BITCAST &&
9593       N0.getNode()->hasOneUse()) {
9594     SDValue Int = N0.getOperand(0);
9595     EVT IntVT = Int.getValueType();
9596     if (IntVT.isInteger() && !IntVT.isVector()) {
9597       APInt SignMask;
9598       if (N0.getValueType().isVector()) {
9599         // For a vector, get a mask such as 0x7f... per scalar element
9600         // and splat it.
9601         SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits());
9602         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9603       } else {
9604         // For a scalar, just generate 0x7f...
9605         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9606       }
9607       SDLoc DL(N0);
9608       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9609                         DAG.getConstant(SignMask, DL, IntVT));
9610       AddToWorklist(Int.getNode());
9611       return DAG.getBitcast(N->getValueType(0), Int);
9612     }
9613   }
9614 
9615   return SDValue();
9616 }
9617 
9618 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9619   SDValue Chain = N->getOperand(0);
9620   SDValue N1 = N->getOperand(1);
9621   SDValue N2 = N->getOperand(2);
9622 
9623   // If N is a constant we could fold this into a fallthrough or unconditional
9624   // branch. However that doesn't happen very often in normal code, because
9625   // Instcombine/SimplifyCFG should have handled the available opportunities.
9626   // If we did this folding here, it would be necessary to update the
9627   // MachineBasicBlock CFG, which is awkward.
9628 
9629   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9630   // on the target.
9631   if (N1.getOpcode() == ISD::SETCC &&
9632       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9633                                    N1.getOperand(0).getValueType())) {
9634     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9635                        Chain, N1.getOperand(2),
9636                        N1.getOperand(0), N1.getOperand(1), N2);
9637   }
9638 
9639   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9640       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9641        (N1.getOperand(0).hasOneUse() &&
9642         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9643     SDNode *Trunc = nullptr;
9644     if (N1.getOpcode() == ISD::TRUNCATE) {
9645       // Look pass the truncate.
9646       Trunc = N1.getNode();
9647       N1 = N1.getOperand(0);
9648     }
9649 
9650     // Match this pattern so that we can generate simpler code:
9651     //
9652     //   %a = ...
9653     //   %b = and i32 %a, 2
9654     //   %c = srl i32 %b, 1
9655     //   brcond i32 %c ...
9656     //
9657     // into
9658     //
9659     //   %a = ...
9660     //   %b = and i32 %a, 2
9661     //   %c = setcc eq %b, 0
9662     //   brcond %c ...
9663     //
9664     // This applies only when the AND constant value has one bit set and the
9665     // SRL constant is equal to the log2 of the AND constant. The back-end is
9666     // smart enough to convert the result into a TEST/JMP sequence.
9667     SDValue Op0 = N1.getOperand(0);
9668     SDValue Op1 = N1.getOperand(1);
9669 
9670     if (Op0.getOpcode() == ISD::AND &&
9671         Op1.getOpcode() == ISD::Constant) {
9672       SDValue AndOp1 = Op0.getOperand(1);
9673 
9674       if (AndOp1.getOpcode() == ISD::Constant) {
9675         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9676 
9677         if (AndConst.isPowerOf2() &&
9678             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9679           SDLoc DL(N);
9680           SDValue SetCC =
9681             DAG.getSetCC(DL,
9682                          getSetCCResultType(Op0.getValueType()),
9683                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9684                          ISD::SETNE);
9685 
9686           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9687                                           MVT::Other, Chain, SetCC, N2);
9688           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9689           // will convert it back to (X & C1) >> C2.
9690           CombineTo(N, NewBRCond, false);
9691           // Truncate is dead.
9692           if (Trunc)
9693             deleteAndRecombine(Trunc);
9694           // Replace the uses of SRL with SETCC
9695           WorklistRemover DeadNodes(*this);
9696           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9697           deleteAndRecombine(N1.getNode());
9698           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9699         }
9700       }
9701     }
9702 
9703     if (Trunc)
9704       // Restore N1 if the above transformation doesn't match.
9705       N1 = N->getOperand(1);
9706   }
9707 
9708   // Transform br(xor(x, y)) -> br(x != y)
9709   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9710   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9711     SDNode *TheXor = N1.getNode();
9712     SDValue Op0 = TheXor->getOperand(0);
9713     SDValue Op1 = TheXor->getOperand(1);
9714     if (Op0.getOpcode() == Op1.getOpcode()) {
9715       // Avoid missing important xor optimizations.
9716       if (SDValue Tmp = visitXOR(TheXor)) {
9717         if (Tmp.getNode() != TheXor) {
9718           DEBUG(dbgs() << "\nReplacing.8 ";
9719                 TheXor->dump(&DAG);
9720                 dbgs() << "\nWith: ";
9721                 Tmp.getNode()->dump(&DAG);
9722                 dbgs() << '\n');
9723           WorklistRemover DeadNodes(*this);
9724           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9725           deleteAndRecombine(TheXor);
9726           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9727                              MVT::Other, Chain, Tmp, N2);
9728         }
9729 
9730         // visitXOR has changed XOR's operands or replaced the XOR completely,
9731         // bail out.
9732         return SDValue(N, 0);
9733       }
9734     }
9735 
9736     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9737       bool Equal = false;
9738       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9739           Op0.getOpcode() == ISD::XOR) {
9740         TheXor = Op0.getNode();
9741         Equal = true;
9742       }
9743 
9744       EVT SetCCVT = N1.getValueType();
9745       if (LegalTypes)
9746         SetCCVT = getSetCCResultType(SetCCVT);
9747       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9748                                    SetCCVT,
9749                                    Op0, Op1,
9750                                    Equal ? ISD::SETEQ : ISD::SETNE);
9751       // Replace the uses of XOR with SETCC
9752       WorklistRemover DeadNodes(*this);
9753       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9754       deleteAndRecombine(N1.getNode());
9755       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9756                          MVT::Other, Chain, SetCC, N2);
9757     }
9758   }
9759 
9760   return SDValue();
9761 }
9762 
9763 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9764 //
9765 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9766   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9767   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9768 
9769   // If N is a constant we could fold this into a fallthrough or unconditional
9770   // branch. However that doesn't happen very often in normal code, because
9771   // Instcombine/SimplifyCFG should have handled the available opportunities.
9772   // If we did this folding here, it would be necessary to update the
9773   // MachineBasicBlock CFG, which is awkward.
9774 
9775   // Use SimplifySetCC to simplify SETCC's.
9776   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9777                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9778                                false);
9779   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9780 
9781   // fold to a simpler setcc
9782   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9783     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9784                        N->getOperand(0), Simp.getOperand(2),
9785                        Simp.getOperand(0), Simp.getOperand(1),
9786                        N->getOperand(4));
9787 
9788   return SDValue();
9789 }
9790 
9791 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9792 /// and that N may be folded in the load / store addressing mode.
9793 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9794                                     SelectionDAG &DAG,
9795                                     const TargetLowering &TLI) {
9796   EVT VT;
9797   unsigned AS;
9798 
9799   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9800     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9801       return false;
9802     VT = LD->getMemoryVT();
9803     AS = LD->getAddressSpace();
9804   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9805     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9806       return false;
9807     VT = ST->getMemoryVT();
9808     AS = ST->getAddressSpace();
9809   } else
9810     return false;
9811 
9812   TargetLowering::AddrMode AM;
9813   if (N->getOpcode() == ISD::ADD) {
9814     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9815     if (Offset)
9816       // [reg +/- imm]
9817       AM.BaseOffs = Offset->getSExtValue();
9818     else
9819       // [reg +/- reg]
9820       AM.Scale = 1;
9821   } else if (N->getOpcode() == ISD::SUB) {
9822     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9823     if (Offset)
9824       // [reg +/- imm]
9825       AM.BaseOffs = -Offset->getSExtValue();
9826     else
9827       // [reg +/- reg]
9828       AM.Scale = 1;
9829   } else
9830     return false;
9831 
9832   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9833                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9834 }
9835 
9836 /// Try turning a load/store into a pre-indexed load/store when the base
9837 /// pointer is an add or subtract and it has other uses besides the load/store.
9838 /// After the transformation, the new indexed load/store has effectively folded
9839 /// the add/subtract in and all of its other uses are redirected to the
9840 /// new load/store.
9841 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9842   if (Level < AfterLegalizeDAG)
9843     return false;
9844 
9845   bool isLoad = true;
9846   SDValue Ptr;
9847   EVT VT;
9848   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9849     if (LD->isIndexed())
9850       return false;
9851     VT = LD->getMemoryVT();
9852     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9853         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9854       return false;
9855     Ptr = LD->getBasePtr();
9856   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9857     if (ST->isIndexed())
9858       return false;
9859     VT = ST->getMemoryVT();
9860     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9861         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9862       return false;
9863     Ptr = ST->getBasePtr();
9864     isLoad = false;
9865   } else {
9866     return false;
9867   }
9868 
9869   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9870   // out.  There is no reason to make this a preinc/predec.
9871   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9872       Ptr.getNode()->hasOneUse())
9873     return false;
9874 
9875   // Ask the target to do addressing mode selection.
9876   SDValue BasePtr;
9877   SDValue Offset;
9878   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9879   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9880     return false;
9881 
9882   // Backends without true r+i pre-indexed forms may need to pass a
9883   // constant base with a variable offset so that constant coercion
9884   // will work with the patterns in canonical form.
9885   bool Swapped = false;
9886   if (isa<ConstantSDNode>(BasePtr)) {
9887     std::swap(BasePtr, Offset);
9888     Swapped = true;
9889   }
9890 
9891   // Don't create a indexed load / store with zero offset.
9892   if (isNullConstant(Offset))
9893     return false;
9894 
9895   // Try turning it into a pre-indexed load / store except when:
9896   // 1) The new base ptr is a frame index.
9897   // 2) If N is a store and the new base ptr is either the same as or is a
9898   //    predecessor of the value being stored.
9899   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9900   //    that would create a cycle.
9901   // 4) All uses are load / store ops that use it as old base ptr.
9902 
9903   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9904   // (plus the implicit offset) to a register to preinc anyway.
9905   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9906     return false;
9907 
9908   // Check #2.
9909   if (!isLoad) {
9910     SDValue Val = cast<StoreSDNode>(N)->getValue();
9911     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9912       return false;
9913   }
9914 
9915   // Caches for hasPredecessorHelper.
9916   SmallPtrSet<const SDNode *, 32> Visited;
9917   SmallVector<const SDNode *, 16> Worklist;
9918   Worklist.push_back(N);
9919 
9920   // If the offset is a constant, there may be other adds of constants that
9921   // can be folded with this one. We should do this to avoid having to keep
9922   // a copy of the original base pointer.
9923   SmallVector<SDNode *, 16> OtherUses;
9924   if (isa<ConstantSDNode>(Offset))
9925     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9926                               UE = BasePtr.getNode()->use_end();
9927          UI != UE; ++UI) {
9928       SDUse &Use = UI.getUse();
9929       // Skip the use that is Ptr and uses of other results from BasePtr's
9930       // node (important for nodes that return multiple results).
9931       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9932         continue;
9933 
9934       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9935         continue;
9936 
9937       if (Use.getUser()->getOpcode() != ISD::ADD &&
9938           Use.getUser()->getOpcode() != ISD::SUB) {
9939         OtherUses.clear();
9940         break;
9941       }
9942 
9943       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9944       if (!isa<ConstantSDNode>(Op1)) {
9945         OtherUses.clear();
9946         break;
9947       }
9948 
9949       // FIXME: In some cases, we can be smarter about this.
9950       if (Op1.getValueType() != Offset.getValueType()) {
9951         OtherUses.clear();
9952         break;
9953       }
9954 
9955       OtherUses.push_back(Use.getUser());
9956     }
9957 
9958   if (Swapped)
9959     std::swap(BasePtr, Offset);
9960 
9961   // Now check for #3 and #4.
9962   bool RealUse = false;
9963 
9964   for (SDNode *Use : Ptr.getNode()->uses()) {
9965     if (Use == N)
9966       continue;
9967     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9968       return false;
9969 
9970     // If Ptr may be folded in addressing mode of other use, then it's
9971     // not profitable to do this transformation.
9972     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9973       RealUse = true;
9974   }
9975 
9976   if (!RealUse)
9977     return false;
9978 
9979   SDValue Result;
9980   if (isLoad)
9981     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9982                                 BasePtr, Offset, AM);
9983   else
9984     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9985                                  BasePtr, Offset, AM);
9986   ++PreIndexedNodes;
9987   ++NodesCombined;
9988   DEBUG(dbgs() << "\nReplacing.4 ";
9989         N->dump(&DAG);
9990         dbgs() << "\nWith: ";
9991         Result.getNode()->dump(&DAG);
9992         dbgs() << '\n');
9993   WorklistRemover DeadNodes(*this);
9994   if (isLoad) {
9995     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9996     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9997   } else {
9998     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9999   }
10000 
10001   // Finally, since the node is now dead, remove it from the graph.
10002   deleteAndRecombine(N);
10003 
10004   if (Swapped)
10005     std::swap(BasePtr, Offset);
10006 
10007   // Replace other uses of BasePtr that can be updated to use Ptr
10008   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
10009     unsigned OffsetIdx = 1;
10010     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
10011       OffsetIdx = 0;
10012     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
10013            BasePtr.getNode() && "Expected BasePtr operand");
10014 
10015     // We need to replace ptr0 in the following expression:
10016     //   x0 * offset0 + y0 * ptr0 = t0
10017     // knowing that
10018     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
10019     //
10020     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
10021     // indexed load/store and the expresion that needs to be re-written.
10022     //
10023     // Therefore, we have:
10024     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
10025 
10026     ConstantSDNode *CN =
10027       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
10028     int X0, X1, Y0, Y1;
10029     const APInt &Offset0 = CN->getAPIntValue();
10030     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
10031 
10032     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
10033     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
10034     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
10035     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
10036 
10037     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
10038 
10039     APInt CNV = Offset0;
10040     if (X0 < 0) CNV = -CNV;
10041     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
10042     else CNV = CNV - Offset1;
10043 
10044     SDLoc DL(OtherUses[i]);
10045 
10046     // We can now generate the new expression.
10047     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
10048     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
10049 
10050     SDValue NewUse = DAG.getNode(Opcode,
10051                                  DL,
10052                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
10053     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
10054     deleteAndRecombine(OtherUses[i]);
10055   }
10056 
10057   // Replace the uses of Ptr with uses of the updated base value.
10058   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
10059   deleteAndRecombine(Ptr.getNode());
10060 
10061   return true;
10062 }
10063 
10064 /// Try to combine a load/store with a add/sub of the base pointer node into a
10065 /// post-indexed load/store. The transformation folded the add/subtract into the
10066 /// new indexed load/store effectively and all of its uses are redirected to the
10067 /// new load/store.
10068 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
10069   if (Level < AfterLegalizeDAG)
10070     return false;
10071 
10072   bool isLoad = true;
10073   SDValue Ptr;
10074   EVT VT;
10075   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10076     if (LD->isIndexed())
10077       return false;
10078     VT = LD->getMemoryVT();
10079     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
10080         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
10081       return false;
10082     Ptr = LD->getBasePtr();
10083   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10084     if (ST->isIndexed())
10085       return false;
10086     VT = ST->getMemoryVT();
10087     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
10088         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
10089       return false;
10090     Ptr = ST->getBasePtr();
10091     isLoad = false;
10092   } else {
10093     return false;
10094   }
10095 
10096   if (Ptr.getNode()->hasOneUse())
10097     return false;
10098 
10099   for (SDNode *Op : Ptr.getNode()->uses()) {
10100     if (Op == N ||
10101         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10102       continue;
10103 
10104     SDValue BasePtr;
10105     SDValue Offset;
10106     ISD::MemIndexedMode AM = ISD::UNINDEXED;
10107     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10108       // Don't create a indexed load / store with zero offset.
10109       if (isNullConstant(Offset))
10110         continue;
10111 
10112       // Try turning it into a post-indexed load / store except when
10113       // 1) All uses are load / store ops that use it as base ptr (and
10114       //    it may be folded as addressing mmode).
10115       // 2) Op must be independent of N, i.e. Op is neither a predecessor
10116       //    nor a successor of N. Otherwise, if Op is folded that would
10117       //    create a cycle.
10118 
10119       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10120         continue;
10121 
10122       // Check for #1.
10123       bool TryNext = false;
10124       for (SDNode *Use : BasePtr.getNode()->uses()) {
10125         if (Use == Ptr.getNode())
10126           continue;
10127 
10128         // If all the uses are load / store addresses, then don't do the
10129         // transformation.
10130         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10131           bool RealUse = false;
10132           for (SDNode *UseUse : Use->uses()) {
10133             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10134               RealUse = true;
10135           }
10136 
10137           if (!RealUse) {
10138             TryNext = true;
10139             break;
10140           }
10141         }
10142       }
10143 
10144       if (TryNext)
10145         continue;
10146 
10147       // Check for #2
10148       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10149         SDValue Result = isLoad
10150           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10151                                BasePtr, Offset, AM)
10152           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10153                                 BasePtr, Offset, AM);
10154         ++PostIndexedNodes;
10155         ++NodesCombined;
10156         DEBUG(dbgs() << "\nReplacing.5 ";
10157               N->dump(&DAG);
10158               dbgs() << "\nWith: ";
10159               Result.getNode()->dump(&DAG);
10160               dbgs() << '\n');
10161         WorklistRemover DeadNodes(*this);
10162         if (isLoad) {
10163           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10164           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10165         } else {
10166           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10167         }
10168 
10169         // Finally, since the node is now dead, remove it from the graph.
10170         deleteAndRecombine(N);
10171 
10172         // Replace the uses of Use with uses of the updated base value.
10173         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10174                                       Result.getValue(isLoad ? 1 : 0));
10175         deleteAndRecombine(Op);
10176         return true;
10177       }
10178     }
10179   }
10180 
10181   return false;
10182 }
10183 
10184 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10185 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10186   ISD::MemIndexedMode AM = LD->getAddressingMode();
10187   assert(AM != ISD::UNINDEXED);
10188   SDValue BP = LD->getOperand(1);
10189   SDValue Inc = LD->getOperand(2);
10190 
10191   // Some backends use TargetConstants for load offsets, but don't expect
10192   // TargetConstants in general ADD nodes. We can convert these constants into
10193   // regular Constants (if the constant is not opaque).
10194   assert((Inc.getOpcode() != ISD::TargetConstant ||
10195           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10196          "Cannot split out indexing using opaque target constants");
10197   if (Inc.getOpcode() == ISD::TargetConstant) {
10198     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10199     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10200                           ConstInc->getValueType(0));
10201   }
10202 
10203   unsigned Opc =
10204       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10205   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10206 }
10207 
10208 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10209   LoadSDNode *LD  = cast<LoadSDNode>(N);
10210   SDValue Chain = LD->getChain();
10211   SDValue Ptr   = LD->getBasePtr();
10212 
10213   // If load is not volatile and there are no uses of the loaded value (and
10214   // the updated indexed value in case of indexed loads), change uses of the
10215   // chain value into uses of the chain input (i.e. delete the dead load).
10216   if (!LD->isVolatile()) {
10217     if (N->getValueType(1) == MVT::Other) {
10218       // Unindexed loads.
10219       if (!N->hasAnyUseOfValue(0)) {
10220         // It's not safe to use the two value CombineTo variant here. e.g.
10221         // v1, chain2 = load chain1, loc
10222         // v2, chain3 = load chain2, loc
10223         // v3         = add v2, c
10224         // Now we replace use of chain2 with chain1.  This makes the second load
10225         // isomorphic to the one we are deleting, and thus makes this load live.
10226         DEBUG(dbgs() << "\nReplacing.6 ";
10227               N->dump(&DAG);
10228               dbgs() << "\nWith chain: ";
10229               Chain.getNode()->dump(&DAG);
10230               dbgs() << "\n");
10231         WorklistRemover DeadNodes(*this);
10232         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10233 
10234         if (N->use_empty())
10235           deleteAndRecombine(N);
10236 
10237         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10238       }
10239     } else {
10240       // Indexed loads.
10241       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10242 
10243       // If this load has an opaque TargetConstant offset, then we cannot split
10244       // the indexing into an add/sub directly (that TargetConstant may not be
10245       // valid for a different type of node, and we cannot convert an opaque
10246       // target constant into a regular constant).
10247       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10248                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10249 
10250       if (!N->hasAnyUseOfValue(0) &&
10251           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10252         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10253         SDValue Index;
10254         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10255           Index = SplitIndexingFromLoad(LD);
10256           // Try to fold the base pointer arithmetic into subsequent loads and
10257           // stores.
10258           AddUsersToWorklist(N);
10259         } else
10260           Index = DAG.getUNDEF(N->getValueType(1));
10261         DEBUG(dbgs() << "\nReplacing.7 ";
10262               N->dump(&DAG);
10263               dbgs() << "\nWith: ";
10264               Undef.getNode()->dump(&DAG);
10265               dbgs() << " and 2 other values\n");
10266         WorklistRemover DeadNodes(*this);
10267         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10268         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10269         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10270         deleteAndRecombine(N);
10271         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10272       }
10273     }
10274   }
10275 
10276   // If this load is directly stored, replace the load value with the stored
10277   // value.
10278   // TODO: Handle store large -> read small portion.
10279   // TODO: Handle TRUNCSTORE/LOADEXT
10280   if (OptLevel != CodeGenOpt::None &&
10281       ISD::isNormalLoad(N) && !LD->isVolatile()) {
10282     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10283       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10284       if (PrevST->getBasePtr() == Ptr &&
10285           PrevST->getValue().getValueType() == N->getValueType(0))
10286       return CombineTo(N, Chain.getOperand(1), Chain);
10287     }
10288   }
10289 
10290   // Try to infer better alignment information than the load already has.
10291   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10292     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10293       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10294         SDValue NewLoad = DAG.getExtLoad(
10295             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
10296             LD->getPointerInfo(), LD->getMemoryVT(), Align,
10297             LD->getMemOperand()->getFlags(), LD->getAAInfo());
10298         if (NewLoad.getNode() != N)
10299           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10300       }
10301     }
10302   }
10303 
10304   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10305                                                   : DAG.getSubtarget().useAA();
10306 #ifndef NDEBUG
10307   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10308       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10309     UseAA = false;
10310 #endif
10311   if (UseAA && LD->isUnindexed()) {
10312     // Walk up chain skipping non-aliasing memory nodes.
10313     SDValue BetterChain = FindBetterChain(N, Chain);
10314 
10315     // If there is a better chain.
10316     if (Chain != BetterChain) {
10317       SDValue ReplLoad;
10318 
10319       // Replace the chain to void dependency.
10320       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10321         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10322                                BetterChain, Ptr, LD->getMemOperand());
10323       } else {
10324         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10325                                   LD->getValueType(0),
10326                                   BetterChain, Ptr, LD->getMemoryVT(),
10327                                   LD->getMemOperand());
10328       }
10329 
10330       // Create token factor to keep old chain connected.
10331       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10332                                   MVT::Other, Chain, ReplLoad.getValue(1));
10333 
10334       // Make sure the new and old chains are cleaned up.
10335       AddToWorklist(Token.getNode());
10336 
10337       // Replace uses with load result and token factor. Don't add users
10338       // to work list.
10339       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10340     }
10341   }
10342 
10343   // Try transforming N to an indexed load.
10344   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10345     return SDValue(N, 0);
10346 
10347   // Try to slice up N to more direct loads if the slices are mapped to
10348   // different register banks or pairing can take place.
10349   if (SliceUpLoad(N))
10350     return SDValue(N, 0);
10351 
10352   return SDValue();
10353 }
10354 
10355 namespace {
10356 /// \brief Helper structure used to slice a load in smaller loads.
10357 /// Basically a slice is obtained from the following sequence:
10358 /// Origin = load Ty1, Base
10359 /// Shift = srl Ty1 Origin, CstTy Amount
10360 /// Inst = trunc Shift to Ty2
10361 ///
10362 /// Then, it will be rewriten into:
10363 /// Slice = load SliceTy, Base + SliceOffset
10364 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10365 ///
10366 /// SliceTy is deduced from the number of bits that are actually used to
10367 /// build Inst.
10368 struct LoadedSlice {
10369   /// \brief Helper structure used to compute the cost of a slice.
10370   struct Cost {
10371     /// Are we optimizing for code size.
10372     bool ForCodeSize;
10373     /// Various cost.
10374     unsigned Loads;
10375     unsigned Truncates;
10376     unsigned CrossRegisterBanksCopies;
10377     unsigned ZExts;
10378     unsigned Shift;
10379 
10380     Cost(bool ForCodeSize = false)
10381         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10382           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10383 
10384     /// \brief Get the cost of one isolated slice.
10385     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10386         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10387           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10388       EVT TruncType = LS.Inst->getValueType(0);
10389       EVT LoadedType = LS.getLoadedType();
10390       if (TruncType != LoadedType &&
10391           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10392         ZExts = 1;
10393     }
10394 
10395     /// \brief Account for slicing gain in the current cost.
10396     /// Slicing provide a few gains like removing a shift or a
10397     /// truncate. This method allows to grow the cost of the original
10398     /// load with the gain from this slice.
10399     void addSliceGain(const LoadedSlice &LS) {
10400       // Each slice saves a truncate.
10401       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10402       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10403                               LS.Inst->getValueType(0)))
10404         ++Truncates;
10405       // If there is a shift amount, this slice gets rid of it.
10406       if (LS.Shift)
10407         ++Shift;
10408       // If this slice can merge a cross register bank copy, account for it.
10409       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10410         ++CrossRegisterBanksCopies;
10411     }
10412 
10413     Cost &operator+=(const Cost &RHS) {
10414       Loads += RHS.Loads;
10415       Truncates += RHS.Truncates;
10416       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10417       ZExts += RHS.ZExts;
10418       Shift += RHS.Shift;
10419       return *this;
10420     }
10421 
10422     bool operator==(const Cost &RHS) const {
10423       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10424              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10425              ZExts == RHS.ZExts && Shift == RHS.Shift;
10426     }
10427 
10428     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10429 
10430     bool operator<(const Cost &RHS) const {
10431       // Assume cross register banks copies are as expensive as loads.
10432       // FIXME: Do we want some more target hooks?
10433       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10434       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10435       // Unless we are optimizing for code size, consider the
10436       // expensive operation first.
10437       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10438         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10439       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10440              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10441     }
10442 
10443     bool operator>(const Cost &RHS) const { return RHS < *this; }
10444 
10445     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10446 
10447     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10448   };
10449   // The last instruction that represent the slice. This should be a
10450   // truncate instruction.
10451   SDNode *Inst;
10452   // The original load instruction.
10453   LoadSDNode *Origin;
10454   // The right shift amount in bits from the original load.
10455   unsigned Shift;
10456   // The DAG from which Origin came from.
10457   // This is used to get some contextual information about legal types, etc.
10458   SelectionDAG *DAG;
10459 
10460   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10461               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10462       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10463 
10464   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10465   /// \return Result is \p BitWidth and has used bits set to 1 and
10466   ///         not used bits set to 0.
10467   APInt getUsedBits() const {
10468     // Reproduce the trunc(lshr) sequence:
10469     // - Start from the truncated value.
10470     // - Zero extend to the desired bit width.
10471     // - Shift left.
10472     assert(Origin && "No original load to compare against.");
10473     unsigned BitWidth = Origin->getValueSizeInBits(0);
10474     assert(Inst && "This slice is not bound to an instruction");
10475     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10476            "Extracted slice is bigger than the whole type!");
10477     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10478     UsedBits.setAllBits();
10479     UsedBits = UsedBits.zext(BitWidth);
10480     UsedBits <<= Shift;
10481     return UsedBits;
10482   }
10483 
10484   /// \brief Get the size of the slice to be loaded in bytes.
10485   unsigned getLoadedSize() const {
10486     unsigned SliceSize = getUsedBits().countPopulation();
10487     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10488     return SliceSize / 8;
10489   }
10490 
10491   /// \brief Get the type that will be loaded for this slice.
10492   /// Note: This may not be the final type for the slice.
10493   EVT getLoadedType() const {
10494     assert(DAG && "Missing context");
10495     LLVMContext &Ctxt = *DAG->getContext();
10496     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10497   }
10498 
10499   /// \brief Get the alignment of the load used for this slice.
10500   unsigned getAlignment() const {
10501     unsigned Alignment = Origin->getAlignment();
10502     unsigned Offset = getOffsetFromBase();
10503     if (Offset != 0)
10504       Alignment = MinAlign(Alignment, Alignment + Offset);
10505     return Alignment;
10506   }
10507 
10508   /// \brief Check if this slice can be rewritten with legal operations.
10509   bool isLegal() const {
10510     // An invalid slice is not legal.
10511     if (!Origin || !Inst || !DAG)
10512       return false;
10513 
10514     // Offsets are for indexed load only, we do not handle that.
10515     if (!Origin->getOffset().isUndef())
10516       return false;
10517 
10518     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10519 
10520     // Check that the type is legal.
10521     EVT SliceType = getLoadedType();
10522     if (!TLI.isTypeLegal(SliceType))
10523       return false;
10524 
10525     // Check that the load is legal for this type.
10526     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10527       return false;
10528 
10529     // Check that the offset can be computed.
10530     // 1. Check its type.
10531     EVT PtrType = Origin->getBasePtr().getValueType();
10532     if (PtrType == MVT::Untyped || PtrType.isExtended())
10533       return false;
10534 
10535     // 2. Check that it fits in the immediate.
10536     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10537       return false;
10538 
10539     // 3. Check that the computation is legal.
10540     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10541       return false;
10542 
10543     // Check that the zext is legal if it needs one.
10544     EVT TruncateType = Inst->getValueType(0);
10545     if (TruncateType != SliceType &&
10546         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10547       return false;
10548 
10549     return true;
10550   }
10551 
10552   /// \brief Get the offset in bytes of this slice in the original chunk of
10553   /// bits.
10554   /// \pre DAG != nullptr.
10555   uint64_t getOffsetFromBase() const {
10556     assert(DAG && "Missing context.");
10557     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10558     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10559     uint64_t Offset = Shift / 8;
10560     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10561     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10562            "The size of the original loaded type is not a multiple of a"
10563            " byte.");
10564     // If Offset is bigger than TySizeInBytes, it means we are loading all
10565     // zeros. This should have been optimized before in the process.
10566     assert(TySizeInBytes > Offset &&
10567            "Invalid shift amount for given loaded size");
10568     if (IsBigEndian)
10569       Offset = TySizeInBytes - Offset - getLoadedSize();
10570     return Offset;
10571   }
10572 
10573   /// \brief Generate the sequence of instructions to load the slice
10574   /// represented by this object and redirect the uses of this slice to
10575   /// this new sequence of instructions.
10576   /// \pre this->Inst && this->Origin are valid Instructions and this
10577   /// object passed the legal check: LoadedSlice::isLegal returned true.
10578   /// \return The last instruction of the sequence used to load the slice.
10579   SDValue loadSlice() const {
10580     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10581     const SDValue &OldBaseAddr = Origin->getBasePtr();
10582     SDValue BaseAddr = OldBaseAddr;
10583     // Get the offset in that chunk of bytes w.r.t. the endianness.
10584     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10585     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10586     if (Offset) {
10587       // BaseAddr = BaseAddr + Offset.
10588       EVT ArithType = BaseAddr.getValueType();
10589       SDLoc DL(Origin);
10590       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10591                               DAG->getConstant(Offset, DL, ArithType));
10592     }
10593 
10594     // Create the type of the loaded slice according to its size.
10595     EVT SliceType = getLoadedType();
10596 
10597     // Create the load for the slice.
10598     SDValue LastInst =
10599         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10600                      Origin->getPointerInfo().getWithOffset(Offset),
10601                      getAlignment(), Origin->getMemOperand()->getFlags());
10602     // If the final type is not the same as the loaded type, this means that
10603     // we have to pad with zero. Create a zero extend for that.
10604     EVT FinalType = Inst->getValueType(0);
10605     if (SliceType != FinalType)
10606       LastInst =
10607           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10608     return LastInst;
10609   }
10610 
10611   /// \brief Check if this slice can be merged with an expensive cross register
10612   /// bank copy. E.g.,
10613   /// i = load i32
10614   /// f = bitcast i32 i to float
10615   bool canMergeExpensiveCrossRegisterBankCopy() const {
10616     if (!Inst || !Inst->hasOneUse())
10617       return false;
10618     SDNode *Use = *Inst->use_begin();
10619     if (Use->getOpcode() != ISD::BITCAST)
10620       return false;
10621     assert(DAG && "Missing context");
10622     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10623     EVT ResVT = Use->getValueType(0);
10624     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10625     const TargetRegisterClass *ArgRC =
10626         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10627     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10628       return false;
10629 
10630     // At this point, we know that we perform a cross-register-bank copy.
10631     // Check if it is expensive.
10632     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10633     // Assume bitcasts are cheap, unless both register classes do not
10634     // explicitly share a common sub class.
10635     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10636       return false;
10637 
10638     // Check if it will be merged with the load.
10639     // 1. Check the alignment constraint.
10640     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10641         ResVT.getTypeForEVT(*DAG->getContext()));
10642 
10643     if (RequiredAlignment > getAlignment())
10644       return false;
10645 
10646     // 2. Check that the load is a legal operation for that type.
10647     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10648       return false;
10649 
10650     // 3. Check that we do not have a zext in the way.
10651     if (Inst->getValueType(0) != getLoadedType())
10652       return false;
10653 
10654     return true;
10655   }
10656 };
10657 }
10658 
10659 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10660 /// \p UsedBits looks like 0..0 1..1 0..0.
10661 static bool areUsedBitsDense(const APInt &UsedBits) {
10662   // If all the bits are one, this is dense!
10663   if (UsedBits.isAllOnesValue())
10664     return true;
10665 
10666   // Get rid of the unused bits on the right.
10667   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10668   // Get rid of the unused bits on the left.
10669   if (NarrowedUsedBits.countLeadingZeros())
10670     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10671   // Check that the chunk of bits is completely used.
10672   return NarrowedUsedBits.isAllOnesValue();
10673 }
10674 
10675 /// \brief Check whether or not \p First and \p Second are next to each other
10676 /// in memory. This means that there is no hole between the bits loaded
10677 /// by \p First and the bits loaded by \p Second.
10678 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10679                                      const LoadedSlice &Second) {
10680   assert(First.Origin == Second.Origin && First.Origin &&
10681          "Unable to match different memory origins.");
10682   APInt UsedBits = First.getUsedBits();
10683   assert((UsedBits & Second.getUsedBits()) == 0 &&
10684          "Slices are not supposed to overlap.");
10685   UsedBits |= Second.getUsedBits();
10686   return areUsedBitsDense(UsedBits);
10687 }
10688 
10689 /// \brief Adjust the \p GlobalLSCost according to the target
10690 /// paring capabilities and the layout of the slices.
10691 /// \pre \p GlobalLSCost should account for at least as many loads as
10692 /// there is in the slices in \p LoadedSlices.
10693 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10694                                  LoadedSlice::Cost &GlobalLSCost) {
10695   unsigned NumberOfSlices = LoadedSlices.size();
10696   // If there is less than 2 elements, no pairing is possible.
10697   if (NumberOfSlices < 2)
10698     return;
10699 
10700   // Sort the slices so that elements that are likely to be next to each
10701   // other in memory are next to each other in the list.
10702   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10703             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10704     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10705     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10706   });
10707   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10708   // First (resp. Second) is the first (resp. Second) potentially candidate
10709   // to be placed in a paired load.
10710   const LoadedSlice *First = nullptr;
10711   const LoadedSlice *Second = nullptr;
10712   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10713                 // Set the beginning of the pair.
10714                                                            First = Second) {
10715 
10716     Second = &LoadedSlices[CurrSlice];
10717 
10718     // If First is NULL, it means we start a new pair.
10719     // Get to the next slice.
10720     if (!First)
10721       continue;
10722 
10723     EVT LoadedType = First->getLoadedType();
10724 
10725     // If the types of the slices are different, we cannot pair them.
10726     if (LoadedType != Second->getLoadedType())
10727       continue;
10728 
10729     // Check if the target supplies paired loads for this type.
10730     unsigned RequiredAlignment = 0;
10731     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10732       // move to the next pair, this type is hopeless.
10733       Second = nullptr;
10734       continue;
10735     }
10736     // Check if we meet the alignment requirement.
10737     if (RequiredAlignment > First->getAlignment())
10738       continue;
10739 
10740     // Check that both loads are next to each other in memory.
10741     if (!areSlicesNextToEachOther(*First, *Second))
10742       continue;
10743 
10744     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10745     --GlobalLSCost.Loads;
10746     // Move to the next pair.
10747     Second = nullptr;
10748   }
10749 }
10750 
10751 /// \brief Check the profitability of all involved LoadedSlice.
10752 /// Currently, it is considered profitable if there is exactly two
10753 /// involved slices (1) which are (2) next to each other in memory, and
10754 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10755 ///
10756 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10757 /// the elements themselves.
10758 ///
10759 /// FIXME: When the cost model will be mature enough, we can relax
10760 /// constraints (1) and (2).
10761 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10762                                 const APInt &UsedBits, bool ForCodeSize) {
10763   unsigned NumberOfSlices = LoadedSlices.size();
10764   if (StressLoadSlicing)
10765     return NumberOfSlices > 1;
10766 
10767   // Check (1).
10768   if (NumberOfSlices != 2)
10769     return false;
10770 
10771   // Check (2).
10772   if (!areUsedBitsDense(UsedBits))
10773     return false;
10774 
10775   // Check (3).
10776   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10777   // The original code has one big load.
10778   OrigCost.Loads = 1;
10779   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10780     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10781     // Accumulate the cost of all the slices.
10782     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10783     GlobalSlicingCost += SliceCost;
10784 
10785     // Account as cost in the original configuration the gain obtained
10786     // with the current slices.
10787     OrigCost.addSliceGain(LS);
10788   }
10789 
10790   // If the target supports paired load, adjust the cost accordingly.
10791   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10792   return OrigCost > GlobalSlicingCost;
10793 }
10794 
10795 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10796 /// operations, split it in the various pieces being extracted.
10797 ///
10798 /// This sort of thing is introduced by SROA.
10799 /// This slicing takes care not to insert overlapping loads.
10800 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10801 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10802   if (Level < AfterLegalizeDAG)
10803     return false;
10804 
10805   LoadSDNode *LD = cast<LoadSDNode>(N);
10806   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10807       !LD->getValueType(0).isInteger())
10808     return false;
10809 
10810   // Keep track of already used bits to detect overlapping values.
10811   // In that case, we will just abort the transformation.
10812   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10813 
10814   SmallVector<LoadedSlice, 4> LoadedSlices;
10815 
10816   // Check if this load is used as several smaller chunks of bits.
10817   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10818   // of computation for each trunc.
10819   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10820        UI != UIEnd; ++UI) {
10821     // Skip the uses of the chain.
10822     if (UI.getUse().getResNo() != 0)
10823       continue;
10824 
10825     SDNode *User = *UI;
10826     unsigned Shift = 0;
10827 
10828     // Check if this is a trunc(lshr).
10829     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10830         isa<ConstantSDNode>(User->getOperand(1))) {
10831       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10832       User = *User->use_begin();
10833     }
10834 
10835     // At this point, User is a Truncate, iff we encountered, trunc or
10836     // trunc(lshr).
10837     if (User->getOpcode() != ISD::TRUNCATE)
10838       return false;
10839 
10840     // The width of the type must be a power of 2 and greater than 8-bits.
10841     // Otherwise the load cannot be represented in LLVM IR.
10842     // Moreover, if we shifted with a non-8-bits multiple, the slice
10843     // will be across several bytes. We do not support that.
10844     unsigned Width = User->getValueSizeInBits(0);
10845     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10846       return 0;
10847 
10848     // Build the slice for this chain of computations.
10849     LoadedSlice LS(User, LD, Shift, &DAG);
10850     APInt CurrentUsedBits = LS.getUsedBits();
10851 
10852     // Check if this slice overlaps with another.
10853     if ((CurrentUsedBits & UsedBits) != 0)
10854       return false;
10855     // Update the bits used globally.
10856     UsedBits |= CurrentUsedBits;
10857 
10858     // Check if the new slice would be legal.
10859     if (!LS.isLegal())
10860       return false;
10861 
10862     // Record the slice.
10863     LoadedSlices.push_back(LS);
10864   }
10865 
10866   // Abort slicing if it does not seem to be profitable.
10867   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10868     return false;
10869 
10870   ++SlicedLoads;
10871 
10872   // Rewrite each chain to use an independent load.
10873   // By construction, each chain can be represented by a unique load.
10874 
10875   // Prepare the argument for the new token factor for all the slices.
10876   SmallVector<SDValue, 8> ArgChains;
10877   for (SmallVectorImpl<LoadedSlice>::const_iterator
10878            LSIt = LoadedSlices.begin(),
10879            LSItEnd = LoadedSlices.end();
10880        LSIt != LSItEnd; ++LSIt) {
10881     SDValue SliceInst = LSIt->loadSlice();
10882     CombineTo(LSIt->Inst, SliceInst, true);
10883     if (SliceInst.getOpcode() != ISD::LOAD)
10884       SliceInst = SliceInst.getOperand(0);
10885     assert(SliceInst->getOpcode() == ISD::LOAD &&
10886            "It takes more than a zext to get to the loaded slice!!");
10887     ArgChains.push_back(SliceInst.getValue(1));
10888   }
10889 
10890   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10891                               ArgChains);
10892   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10893   return true;
10894 }
10895 
10896 /// Check to see if V is (and load (ptr), imm), where the load is having
10897 /// specific bytes cleared out.  If so, return the byte size being masked out
10898 /// and the shift amount.
10899 static std::pair<unsigned, unsigned>
10900 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10901   std::pair<unsigned, unsigned> Result(0, 0);
10902 
10903   // Check for the structure we're looking for.
10904   if (V->getOpcode() != ISD::AND ||
10905       !isa<ConstantSDNode>(V->getOperand(1)) ||
10906       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10907     return Result;
10908 
10909   // Check the chain and pointer.
10910   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10911   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10912 
10913   // The store should be chained directly to the load or be an operand of a
10914   // tokenfactor.
10915   if (LD == Chain.getNode())
10916     ; // ok.
10917   else if (Chain->getOpcode() != ISD::TokenFactor)
10918     return Result; // Fail.
10919   else {
10920     bool isOk = false;
10921     for (const SDValue &ChainOp : Chain->op_values())
10922       if (ChainOp.getNode() == LD) {
10923         isOk = true;
10924         break;
10925       }
10926     if (!isOk) return Result;
10927   }
10928 
10929   // This only handles simple types.
10930   if (V.getValueType() != MVT::i16 &&
10931       V.getValueType() != MVT::i32 &&
10932       V.getValueType() != MVT::i64)
10933     return Result;
10934 
10935   // Check the constant mask.  Invert it so that the bits being masked out are
10936   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10937   // follow the sign bit for uniformity.
10938   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10939   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10940   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10941   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10942   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10943   if (NotMaskLZ == 64) return Result;  // All zero mask.
10944 
10945   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10946   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10947     return Result;
10948 
10949   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10950   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10951     NotMaskLZ -= 64-V.getValueSizeInBits();
10952 
10953   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10954   switch (MaskedBytes) {
10955   case 1:
10956   case 2:
10957   case 4: break;
10958   default: return Result; // All one mask, or 5-byte mask.
10959   }
10960 
10961   // Verify that the first bit starts at a multiple of mask so that the access
10962   // is aligned the same as the access width.
10963   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10964 
10965   Result.first = MaskedBytes;
10966   Result.second = NotMaskTZ/8;
10967   return Result;
10968 }
10969 
10970 
10971 /// Check to see if IVal is something that provides a value as specified by
10972 /// MaskInfo. If so, replace the specified store with a narrower store of
10973 /// truncated IVal.
10974 static SDNode *
10975 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10976                                 SDValue IVal, StoreSDNode *St,
10977                                 DAGCombiner *DC) {
10978   unsigned NumBytes = MaskInfo.first;
10979   unsigned ByteShift = MaskInfo.second;
10980   SelectionDAG &DAG = DC->getDAG();
10981 
10982   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10983   // that uses this.  If not, this is not a replacement.
10984   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10985                                   ByteShift*8, (ByteShift+NumBytes)*8);
10986   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10987 
10988   // Check that it is legal on the target to do this.  It is legal if the new
10989   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10990   // legalization.
10991   MVT VT = MVT::getIntegerVT(NumBytes*8);
10992   if (!DC->isTypeLegal(VT))
10993     return nullptr;
10994 
10995   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10996   // shifted by ByteShift and truncated down to NumBytes.
10997   if (ByteShift) {
10998     SDLoc DL(IVal);
10999     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
11000                        DAG.getConstant(ByteShift*8, DL,
11001                                     DC->getShiftAmountTy(IVal.getValueType())));
11002   }
11003 
11004   // Figure out the offset for the store and the alignment of the access.
11005   unsigned StOffset;
11006   unsigned NewAlign = St->getAlignment();
11007 
11008   if (DAG.getDataLayout().isLittleEndian())
11009     StOffset = ByteShift;
11010   else
11011     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
11012 
11013   SDValue Ptr = St->getBasePtr();
11014   if (StOffset) {
11015     SDLoc DL(IVal);
11016     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11017                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11018     NewAlign = MinAlign(NewAlign, StOffset);
11019   }
11020 
11021   // Truncate down to the new size.
11022   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
11023 
11024   ++OpsNarrowed;
11025   return DAG
11026       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
11027                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
11028       .getNode();
11029 }
11030 
11031 
11032 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11033 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
11034 /// narrowing the load and store if it would end up being a win for performance
11035 /// or code size.
11036 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
11037   StoreSDNode *ST  = cast<StoreSDNode>(N);
11038   if (ST->isVolatile())
11039     return SDValue();
11040 
11041   SDValue Chain = ST->getChain();
11042   SDValue Value = ST->getValue();
11043   SDValue Ptr   = ST->getBasePtr();
11044   EVT VT = Value.getValueType();
11045 
11046   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
11047     return SDValue();
11048 
11049   unsigned Opc = Value.getOpcode();
11050 
11051   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
11052   // is a byte mask indicating a consecutive number of bytes, check to see if
11053   // Y is known to provide just those bytes.  If so, we try to replace the
11054   // load + replace + store sequence with a single (narrower) store, which makes
11055   // the load dead.
11056   if (Opc == ISD::OR) {
11057     std::pair<unsigned, unsigned> MaskedLoad;
11058     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
11059     if (MaskedLoad.first)
11060       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11061                                                   Value.getOperand(1), ST,this))
11062         return SDValue(NewST, 0);
11063 
11064     // Or is commutative, so try swapping X and Y.
11065     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
11066     if (MaskedLoad.first)
11067       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11068                                                   Value.getOperand(0), ST,this))
11069         return SDValue(NewST, 0);
11070   }
11071 
11072   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
11073       Value.getOperand(1).getOpcode() != ISD::Constant)
11074     return SDValue();
11075 
11076   SDValue N0 = Value.getOperand(0);
11077   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11078       Chain == SDValue(N0.getNode(), 1)) {
11079     LoadSDNode *LD = cast<LoadSDNode>(N0);
11080     if (LD->getBasePtr() != Ptr ||
11081         LD->getPointerInfo().getAddrSpace() !=
11082         ST->getPointerInfo().getAddrSpace())
11083       return SDValue();
11084 
11085     // Find the type to narrow it the load / op / store to.
11086     SDValue N1 = Value.getOperand(1);
11087     unsigned BitWidth = N1.getValueSizeInBits();
11088     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
11089     if (Opc == ISD::AND)
11090       Imm ^= APInt::getAllOnesValue(BitWidth);
11091     if (Imm == 0 || Imm.isAllOnesValue())
11092       return SDValue();
11093     unsigned ShAmt = Imm.countTrailingZeros();
11094     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
11095     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
11096     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11097     // The narrowing should be profitable, the load/store operation should be
11098     // legal (or custom) and the store size should be equal to the NewVT width.
11099     while (NewBW < BitWidth &&
11100            (NewVT.getStoreSizeInBits() != NewBW ||
11101             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11102             !TLI.isNarrowingProfitable(VT, NewVT))) {
11103       NewBW = NextPowerOf2(NewBW);
11104       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11105     }
11106     if (NewBW >= BitWidth)
11107       return SDValue();
11108 
11109     // If the lsb changed does not start at the type bitwidth boundary,
11110     // start at the previous one.
11111     if (ShAmt % NewBW)
11112       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11113     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11114                                    std::min(BitWidth, ShAmt + NewBW));
11115     if ((Imm & Mask) == Imm) {
11116       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11117       if (Opc == ISD::AND)
11118         NewImm ^= APInt::getAllOnesValue(NewBW);
11119       uint64_t PtrOff = ShAmt / 8;
11120       // For big endian targets, we need to adjust the offset to the pointer to
11121       // load the correct bytes.
11122       if (DAG.getDataLayout().isBigEndian())
11123         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11124 
11125       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11126       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11127       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11128         return SDValue();
11129 
11130       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11131                                    Ptr.getValueType(), Ptr,
11132                                    DAG.getConstant(PtrOff, SDLoc(LD),
11133                                                    Ptr.getValueType()));
11134       SDValue NewLD =
11135           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11136                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11137                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
11138       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11139                                    DAG.getConstant(NewImm, SDLoc(Value),
11140                                                    NewVT));
11141       SDValue NewST =
11142           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11143                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11144 
11145       AddToWorklist(NewPtr.getNode());
11146       AddToWorklist(NewLD.getNode());
11147       AddToWorklist(NewVal.getNode());
11148       WorklistRemover DeadNodes(*this);
11149       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11150       ++OpsNarrowed;
11151       return NewST;
11152     }
11153   }
11154 
11155   return SDValue();
11156 }
11157 
11158 /// For a given floating point load / store pair, if the load value isn't used
11159 /// by any other operations, then consider transforming the pair to integer
11160 /// load / store operations if the target deems the transformation profitable.
11161 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11162   StoreSDNode *ST  = cast<StoreSDNode>(N);
11163   SDValue Chain = ST->getChain();
11164   SDValue Value = ST->getValue();
11165   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11166       Value.hasOneUse() &&
11167       Chain == SDValue(Value.getNode(), 1)) {
11168     LoadSDNode *LD = cast<LoadSDNode>(Value);
11169     EVT VT = LD->getMemoryVT();
11170     if (!VT.isFloatingPoint() ||
11171         VT != ST->getMemoryVT() ||
11172         LD->isNonTemporal() ||
11173         ST->isNonTemporal() ||
11174         LD->getPointerInfo().getAddrSpace() != 0 ||
11175         ST->getPointerInfo().getAddrSpace() != 0)
11176       return SDValue();
11177 
11178     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11179     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11180         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11181         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11182         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11183       return SDValue();
11184 
11185     unsigned LDAlign = LD->getAlignment();
11186     unsigned STAlign = ST->getAlignment();
11187     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11188     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11189     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11190       return SDValue();
11191 
11192     SDValue NewLD =
11193         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
11194                     LD->getPointerInfo(), LDAlign);
11195 
11196     SDValue NewST =
11197         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
11198                      ST->getPointerInfo(), STAlign);
11199 
11200     AddToWorklist(NewLD.getNode());
11201     AddToWorklist(NewST.getNode());
11202     WorklistRemover DeadNodes(*this);
11203     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11204     ++LdStFP2Int;
11205     return NewST;
11206   }
11207 
11208   return SDValue();
11209 }
11210 
11211 namespace {
11212 /// Helper struct to parse and store a memory address as base + index + offset.
11213 /// We ignore sign extensions when it is safe to do so.
11214 /// The following two expressions are not equivalent. To differentiate we need
11215 /// to store whether there was a sign extension involved in the index
11216 /// computation.
11217 ///  (load (i64 add (i64 copyfromreg %c)
11218 ///                 (i64 signextend (add (i8 load %index)
11219 ///                                      (i8 1))))
11220 /// vs
11221 ///
11222 /// (load (i64 add (i64 copyfromreg %c)
11223 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11224 ///                                         (i32 1)))))
11225 struct BaseIndexOffset {
11226   SDValue Base;
11227   SDValue Index;
11228   int64_t Offset;
11229   bool IsIndexSignExt;
11230 
11231   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11232 
11233   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11234                   bool IsIndexSignExt) :
11235     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11236 
11237   bool equalBaseIndex(const BaseIndexOffset &Other) {
11238     return Other.Base == Base && Other.Index == Index &&
11239       Other.IsIndexSignExt == IsIndexSignExt;
11240   }
11241 
11242   /// Parses tree in Ptr for base, index, offset addresses.
11243   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11244     bool IsIndexSignExt = false;
11245 
11246     // Split up a folded GlobalAddress+Offset into its component parts.
11247     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11248       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11249         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11250                                                     SDLoc(GA),
11251                                                     GA->getValueType(0),
11252                                                     /*Offset=*/0,
11253                                                     /*isTargetGA=*/false,
11254                                                     GA->getTargetFlags()),
11255                                SDValue(),
11256                                GA->getOffset(),
11257                                IsIndexSignExt);
11258       }
11259 
11260     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11261     // instruction, then it could be just the BASE or everything else we don't
11262     // know how to handle. Just use Ptr as BASE and give up.
11263     if (Ptr->getOpcode() != ISD::ADD)
11264       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11265 
11266     // We know that we have at least an ADD instruction. Try to pattern match
11267     // the simple case of BASE + OFFSET.
11268     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11269       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11270       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11271                               IsIndexSignExt);
11272     }
11273 
11274     // Inside a loop the current BASE pointer is calculated using an ADD and a
11275     // MUL instruction. In this case Ptr is the actual BASE pointer.
11276     // (i64 add (i64 %array_ptr)
11277     //          (i64 mul (i64 %induction_var)
11278     //                   (i64 %element_size)))
11279     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11280       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11281 
11282     // Look at Base + Index + Offset cases.
11283     SDValue Base = Ptr->getOperand(0);
11284     SDValue IndexOffset = Ptr->getOperand(1);
11285 
11286     // Skip signextends.
11287     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11288       IndexOffset = IndexOffset->getOperand(0);
11289       IsIndexSignExt = true;
11290     }
11291 
11292     // Either the case of Base + Index (no offset) or something else.
11293     if (IndexOffset->getOpcode() != ISD::ADD)
11294       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11295 
11296     // Now we have the case of Base + Index + offset.
11297     SDValue Index = IndexOffset->getOperand(0);
11298     SDValue Offset = IndexOffset->getOperand(1);
11299 
11300     if (!isa<ConstantSDNode>(Offset))
11301       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11302 
11303     // Ignore signextends.
11304     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11305       Index = Index->getOperand(0);
11306       IsIndexSignExt = true;
11307     } else IsIndexSignExt = false;
11308 
11309     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11310     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11311   }
11312 };
11313 } // namespace
11314 
11315 // This is a helper function for visitMUL to check the profitability
11316 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11317 // MulNode is the original multiply, AddNode is (add x, c1),
11318 // and ConstNode is c2.
11319 //
11320 // If the (add x, c1) has multiple uses, we could increase
11321 // the number of adds if we make this transformation.
11322 // It would only be worth doing this if we can remove a
11323 // multiply in the process. Check for that here.
11324 // To illustrate:
11325 //     (A + c1) * c3
11326 //     (A + c2) * c3
11327 // We're checking for cases where we have common "c3 * A" expressions.
11328 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11329                                               SDValue &AddNode,
11330                                               SDValue &ConstNode) {
11331   APInt Val;
11332 
11333   // If the add only has one use, this would be OK to do.
11334   if (AddNode.getNode()->hasOneUse())
11335     return true;
11336 
11337   // Walk all the users of the constant with which we're multiplying.
11338   for (SDNode *Use : ConstNode->uses()) {
11339 
11340     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11341       continue;
11342 
11343     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11344       SDNode *OtherOp;
11345       SDNode *MulVar = AddNode.getOperand(0).getNode();
11346 
11347       // OtherOp is what we're multiplying against the constant.
11348       if (Use->getOperand(0) == ConstNode)
11349         OtherOp = Use->getOperand(1).getNode();
11350       else
11351         OtherOp = Use->getOperand(0).getNode();
11352 
11353       // Check to see if multiply is with the same operand of our "add".
11354       //
11355       //     ConstNode  = CONST
11356       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11357       //     ...
11358       //     AddNode  = (A + c1)  <-- MulVar is A.
11359       //         = AddNode * ConstNode   <-- current visiting instruction.
11360       //
11361       // If we make this transformation, we will have a common
11362       // multiply (ConstNode * A) that we can save.
11363       if (OtherOp == MulVar)
11364         return true;
11365 
11366       // Now check to see if a future expansion will give us a common
11367       // multiply.
11368       //
11369       //     ConstNode  = CONST
11370       //     AddNode    = (A + c1)
11371       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11372       //     ...
11373       //     OtherOp = (A + c2)
11374       //     Use     = OtherOp * ConstNode <-- visiting Use.
11375       //
11376       // If we make this transformation, we will have a common
11377       // multiply (CONST * A) after we also do the same transformation
11378       // to the "t2" instruction.
11379       if (OtherOp->getOpcode() == ISD::ADD &&
11380           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11381           OtherOp->getOperand(0).getNode() == MulVar)
11382         return true;
11383     }
11384   }
11385 
11386   // Didn't find a case where this would be profitable.
11387   return false;
11388 }
11389 
11390 SDValue DAGCombiner::getMergedConstantVectorStore(
11391     SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11392     SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11393   SmallVector<SDValue, 8> BuildVector;
11394 
11395   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11396     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11397     Chains.push_back(St->getChain());
11398     BuildVector.push_back(St->getValue());
11399   }
11400 
11401   return DAG.getBuildVector(Ty, SL, BuildVector);
11402 }
11403 
11404 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11405                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11406                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11407   // Make sure we have something to merge.
11408   if (NumStores < 2)
11409     return false;
11410 
11411   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11412   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11413   unsigned LatestNodeUsed = 0;
11414 
11415   for (unsigned i=0; i < NumStores; ++i) {
11416     // Find a chain for the new wide-store operand. Notice that some
11417     // of the store nodes that we found may not be selected for inclusion
11418     // in the wide store. The chain we use needs to be the chain of the
11419     // latest store node which is *used* and replaced by the wide store.
11420     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11421       LatestNodeUsed = i;
11422   }
11423 
11424   SmallVector<SDValue, 8> Chains;
11425 
11426   // The latest Node in the DAG.
11427   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11428   SDLoc DL(StoreNodes[0].MemNode);
11429 
11430   SDValue StoredVal;
11431   if (UseVector) {
11432     bool IsVec = MemVT.isVector();
11433     unsigned Elts = NumStores;
11434     if (IsVec) {
11435       // When merging vector stores, get the total number of elements.
11436       Elts *= MemVT.getVectorNumElements();
11437     }
11438     // Get the type for the merged vector store.
11439     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11440     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11441 
11442     if (IsConstantSrc) {
11443       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11444     } else {
11445       SmallVector<SDValue, 8> Ops;
11446       for (unsigned i = 0; i < NumStores; ++i) {
11447         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11448         SDValue Val = St->getValue();
11449         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11450         if (Val.getValueType() != MemVT)
11451           return false;
11452         Ops.push_back(Val);
11453         Chains.push_back(St->getChain());
11454       }
11455 
11456       // Build the extracted vector elements back into a vector.
11457       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11458                               DL, Ty, Ops);    }
11459   } else {
11460     // We should always use a vector store when merging extracted vector
11461     // elements, so this path implies a store of constants.
11462     assert(IsConstantSrc && "Merged vector elements should use vector store");
11463 
11464     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11465     APInt StoreInt(SizeInBits, 0);
11466 
11467     // Construct a single integer constant which is made of the smaller
11468     // constant inputs.
11469     bool IsLE = DAG.getDataLayout().isLittleEndian();
11470     for (unsigned i = 0; i < NumStores; ++i) {
11471       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11472       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11473       Chains.push_back(St->getChain());
11474 
11475       SDValue Val = St->getValue();
11476       StoreInt <<= ElementSizeBytes * 8;
11477       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11478         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11479       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11480         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11481       } else {
11482         llvm_unreachable("Invalid constant element type");
11483       }
11484     }
11485 
11486     // Create the new Load and Store operations.
11487     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11488     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11489   }
11490 
11491   assert(!Chains.empty());
11492 
11493   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11494   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11495                                   FirstInChain->getBasePtr(),
11496                                   FirstInChain->getPointerInfo(),
11497                                   FirstInChain->getAlignment());
11498 
11499   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11500                                                   : DAG.getSubtarget().useAA();
11501   if (UseAA) {
11502     // Replace all merged stores with the new store.
11503     for (unsigned i = 0; i < NumStores; ++i)
11504       CombineTo(StoreNodes[i].MemNode, NewStore);
11505   } else {
11506     // Replace the last store with the new store.
11507     CombineTo(LatestOp, NewStore);
11508     // Erase all other stores.
11509     for (unsigned i = 0; i < NumStores; ++i) {
11510       if (StoreNodes[i].MemNode == LatestOp)
11511         continue;
11512       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11513       // ReplaceAllUsesWith will replace all uses that existed when it was
11514       // called, but graph optimizations may cause new ones to appear. For
11515       // example, the case in pr14333 looks like
11516       //
11517       //  St's chain -> St -> another store -> X
11518       //
11519       // And the only difference from St to the other store is the chain.
11520       // When we change it's chain to be St's chain they become identical,
11521       // get CSEed and the net result is that X is now a use of St.
11522       // Since we know that St is redundant, just iterate.
11523       while (!St->use_empty())
11524         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11525       deleteAndRecombine(St);
11526     }
11527   }
11528 
11529   StoreNodes.erase(StoreNodes.begin() + NumStores, StoreNodes.end());
11530   return true;
11531 }
11532 
11533 void DAGCombiner::getStoreMergeAndAliasCandidates(
11534     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11535     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11536   // This holds the base pointer, index, and the offset in bytes from the base
11537   // pointer.
11538   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11539 
11540   // We must have a base and an offset.
11541   if (!BasePtr.Base.getNode())
11542     return;
11543 
11544   // Do not handle stores to undef base pointers.
11545   if (BasePtr.Base.isUndef())
11546     return;
11547 
11548   // Walk up the chain and look for nodes with offsets from the same
11549   // base pointer. Stop when reaching an instruction with a different kind
11550   // or instruction which has a different base pointer.
11551   EVT MemVT = St->getMemoryVT();
11552   unsigned Seq = 0;
11553   StoreSDNode *Index = St;
11554 
11555 
11556   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11557                                                   : DAG.getSubtarget().useAA();
11558 
11559   if (UseAA) {
11560     // Look at other users of the same chain. Stores on the same chain do not
11561     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11562     // to be on the same chain, so don't bother looking at adjacent chains.
11563 
11564     SDValue Chain = St->getChain();
11565     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11566       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11567         if (I.getOperandNo() != 0)
11568           continue;
11569 
11570         if (OtherST->isVolatile() || OtherST->isIndexed())
11571           continue;
11572 
11573         if (OtherST->getMemoryVT() != MemVT)
11574           continue;
11575 
11576         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11577 
11578         if (Ptr.equalBaseIndex(BasePtr))
11579           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11580       }
11581     }
11582 
11583     return;
11584   }
11585 
11586   while (Index) {
11587     // If the chain has more than one use, then we can't reorder the mem ops.
11588     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11589       break;
11590 
11591     // Find the base pointer and offset for this memory node.
11592     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11593 
11594     // Check that the base pointer is the same as the original one.
11595     if (!Ptr.equalBaseIndex(BasePtr))
11596       break;
11597 
11598     // The memory operands must not be volatile.
11599     if (Index->isVolatile() || Index->isIndexed())
11600       break;
11601 
11602     // No truncation.
11603     if (Index->isTruncatingStore())
11604       break;
11605 
11606     // The stored memory type must be the same.
11607     if (Index->getMemoryVT() != MemVT)
11608       break;
11609 
11610     // We do not allow under-aligned stores in order to prevent
11611     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11612     // be irrelevant here; what MATTERS is that we not move memory
11613     // operations that potentially overlap past each-other.
11614     if (Index->getAlignment() < MemVT.getStoreSize())
11615       break;
11616 
11617     // We found a potential memory operand to merge.
11618     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11619 
11620     // Find the next memory operand in the chain. If the next operand in the
11621     // chain is a store then move up and continue the scan with the next
11622     // memory operand. If the next operand is a load save it and use alias
11623     // information to check if it interferes with anything.
11624     SDNode *NextInChain = Index->getChain().getNode();
11625     while (1) {
11626       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11627         // We found a store node. Use it for the next iteration.
11628         Index = STn;
11629         break;
11630       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11631         if (Ldn->isVolatile()) {
11632           Index = nullptr;
11633           break;
11634         }
11635 
11636         // Save the load node for later. Continue the scan.
11637         AliasLoadNodes.push_back(Ldn);
11638         NextInChain = Ldn->getChain().getNode();
11639         continue;
11640       } else {
11641         Index = nullptr;
11642         break;
11643       }
11644     }
11645   }
11646 }
11647 
11648 // We need to check that merging these stores does not cause a loop
11649 // in the DAG. Any store candidate may depend on another candidate
11650 // indirectly through its operand (we already consider dependencies
11651 // through the chain). Check in parallel by searching up from
11652 // non-chain operands of candidates.
11653 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11654     SmallVectorImpl<MemOpLink> &StoreNodes) {
11655   SmallPtrSet<const SDNode *, 16> Visited;
11656   SmallVector<const SDNode *, 8> Worklist;
11657   // search ops of store candidates
11658   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11659     SDNode *n = StoreNodes[i].MemNode;
11660     // Potential loops may happen only through non-chain operands
11661     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11662       Worklist.push_back(n->getOperand(j).getNode());
11663   }
11664   // search through DAG. We can stop early if we find a storenode
11665   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11666     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11667       return false;
11668   }
11669   return true;
11670 }
11671 
11672 bool DAGCombiner::MergeConsecutiveStores(
11673     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes) {
11674   if (OptLevel == CodeGenOpt::None)
11675     return false;
11676 
11677   EVT MemVT = St->getMemoryVT();
11678   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11679   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11680       Attribute::NoImplicitFloat);
11681 
11682   // This function cannot currently deal with non-byte-sized memory sizes.
11683   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11684     return false;
11685 
11686   if (!MemVT.isSimple())
11687     return false;
11688 
11689   // Perform an early exit check. Do not bother looking at stored values that
11690   // are not constants, loads, or extracted vector elements.
11691   SDValue StoredVal = St->getValue();
11692   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11693   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11694                        isa<ConstantFPSDNode>(StoredVal);
11695   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11696                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11697 
11698   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11699     return false;
11700 
11701   // Don't merge vectors into wider vectors if the source data comes from loads.
11702   // TODO: This restriction can be lifted by using logic similar to the
11703   // ExtractVecSrc case.
11704   if (MemVT.isVector() && IsLoadSrc)
11705     return false;
11706 
11707   // Only look at ends of store sequences.
11708   SDValue Chain = SDValue(St, 0);
11709   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11710     return false;
11711 
11712   // Save the LoadSDNodes that we find in the chain.
11713   // We need to make sure that these nodes do not interfere with
11714   // any of the store nodes.
11715   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11716 
11717   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11718 
11719   // Check if there is anything to merge.
11720   if (StoreNodes.size() < 2)
11721     return false;
11722 
11723   // only do dependence check in AA case
11724   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11725                                                   : DAG.getSubtarget().useAA();
11726   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11727     return false;
11728 
11729   // Sort the memory operands according to their distance from the
11730   // base pointer.  As a secondary criteria: make sure stores coming
11731   // later in the code come first in the list. This is important for
11732   // the non-UseAA case, because we're merging stores into the FINAL
11733   // store along a chain which potentially contains aliasing stores.
11734   // Thus, if there are multiple stores to the same address, the last
11735   // one can be considered for merging but not the others.
11736   std::sort(StoreNodes.begin(), StoreNodes.end(),
11737             [](MemOpLink LHS, MemOpLink RHS) {
11738     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11739            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11740             LHS.SequenceNum < RHS.SequenceNum);
11741   });
11742 
11743   // Scan the memory operations on the chain and find the first non-consecutive
11744   // store memory address.
11745   unsigned LastConsecutiveStore = 0;
11746   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11747   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11748 
11749     // Check that the addresses are consecutive starting from the second
11750     // element in the list of stores.
11751     if (i > 0) {
11752       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11753       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11754         break;
11755     }
11756 
11757     // Check if this store interferes with any of the loads that we found.
11758     // If we find a load that alias with this store. Stop the sequence.
11759     if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) {
11760           return isAlias(Ldn, StoreNodes[i].MemNode);
11761         }))
11762       break;
11763 
11764     // Mark this node as useful.
11765     LastConsecutiveStore = i;
11766   }
11767 
11768   // The node with the lowest store address.
11769   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11770   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11771   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11772   LLVMContext &Context = *DAG.getContext();
11773   const DataLayout &DL = DAG.getDataLayout();
11774 
11775   // Store the constants into memory as one consecutive store.
11776   if (IsConstantSrc) {
11777     unsigned LastLegalType = 0;
11778     unsigned LastLegalVectorType = 0;
11779     bool NonZero = false;
11780     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11781       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11782       SDValue StoredVal = St->getValue();
11783 
11784       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11785         NonZero |= !C->isNullValue();
11786       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11787         NonZero |= !C->getConstantFPValue()->isNullValue();
11788       } else {
11789         // Non-constant.
11790         break;
11791       }
11792 
11793       // Find a legal type for the constant store.
11794       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11795       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11796       bool IsFast;
11797       if (TLI.isTypeLegal(StoreTy) &&
11798           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11799                                  FirstStoreAlign, &IsFast) && IsFast) {
11800         LastLegalType = i+1;
11801       // Or check whether a truncstore is legal.
11802       } else if (TLI.getTypeAction(Context, StoreTy) ==
11803                  TargetLowering::TypePromoteInteger) {
11804         EVT LegalizedStoredValueTy =
11805           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11806         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11807             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11808                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11809             IsFast) {
11810           LastLegalType = i + 1;
11811         }
11812       }
11813 
11814       // We only use vectors if the constant is known to be zero or the target
11815       // allows it and the function is not marked with the noimplicitfloat
11816       // attribute.
11817       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11818                                                         FirstStoreAS)) &&
11819           !NoVectors) {
11820         // Find a legal type for the vector store.
11821         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11822         if (TLI.isTypeLegal(Ty) &&
11823             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11824                                    FirstStoreAlign, &IsFast) && IsFast)
11825           LastLegalVectorType = i + 1;
11826       }
11827     }
11828 
11829     // Check if we found a legal integer type to store.
11830     if (LastLegalType == 0 && LastLegalVectorType == 0)
11831       return false;
11832 
11833     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11834     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11835 
11836     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11837                                            true, UseVector);
11838   }
11839 
11840   // When extracting multiple vector elements, try to store them
11841   // in one vector store rather than a sequence of scalar stores.
11842   if (IsExtractVecSrc) {
11843     unsigned NumStoresToMerge = 0;
11844     bool IsVec = MemVT.isVector();
11845     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11846       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11847       unsigned StoreValOpcode = St->getValue().getOpcode();
11848       // This restriction could be loosened.
11849       // Bail out if any stored values are not elements extracted from a vector.
11850       // It should be possible to handle mixed sources, but load sources need
11851       // more careful handling (see the block of code below that handles
11852       // consecutive loads).
11853       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11854           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11855         return false;
11856 
11857       // Find a legal type for the vector store.
11858       unsigned Elts = i + 1;
11859       if (IsVec) {
11860         // When merging vector stores, get the total number of elements.
11861         Elts *= MemVT.getVectorNumElements();
11862       }
11863       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11864       bool IsFast;
11865       if (TLI.isTypeLegal(Ty) &&
11866           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11867                                  FirstStoreAlign, &IsFast) && IsFast)
11868         NumStoresToMerge = i + 1;
11869     }
11870 
11871     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11872                                            false, true);
11873   }
11874 
11875   // Below we handle the case of multiple consecutive stores that
11876   // come from multiple consecutive loads. We merge them into a single
11877   // wide load and a single wide store.
11878 
11879   // Look for load nodes which are used by the stored values.
11880   SmallVector<MemOpLink, 8> LoadNodes;
11881 
11882   // Find acceptable loads. Loads need to have the same chain (token factor),
11883   // must not be zext, volatile, indexed, and they must be consecutive.
11884   BaseIndexOffset LdBasePtr;
11885   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11886     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11887     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11888     if (!Ld) break;
11889 
11890     // Loads must only have one use.
11891     if (!Ld->hasNUsesOfValue(1, 0))
11892       break;
11893 
11894     // The memory operands must not be volatile.
11895     if (Ld->isVolatile() || Ld->isIndexed())
11896       break;
11897 
11898     // We do not accept ext loads.
11899     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11900       break;
11901 
11902     // The stored memory type must be the same.
11903     if (Ld->getMemoryVT() != MemVT)
11904       break;
11905 
11906     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11907     // If this is not the first ptr that we check.
11908     if (LdBasePtr.Base.getNode()) {
11909       // The base ptr must be the same.
11910       if (!LdPtr.equalBaseIndex(LdBasePtr))
11911         break;
11912     } else {
11913       // Check that all other base pointers are the same as this one.
11914       LdBasePtr = LdPtr;
11915     }
11916 
11917     // We found a potential memory operand to merge.
11918     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11919   }
11920 
11921   if (LoadNodes.size() < 2)
11922     return false;
11923 
11924   // If we have load/store pair instructions and we only have two values,
11925   // don't bother.
11926   unsigned RequiredAlignment;
11927   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11928       St->getAlignment() >= RequiredAlignment)
11929     return false;
11930 
11931   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11932   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11933   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11934 
11935   // Scan the memory operations on the chain and find the first non-consecutive
11936   // load memory address. These variables hold the index in the store node
11937   // array.
11938   unsigned LastConsecutiveLoad = 0;
11939   // This variable refers to the size and not index in the array.
11940   unsigned LastLegalVectorType = 0;
11941   unsigned LastLegalIntegerType = 0;
11942   StartAddress = LoadNodes[0].OffsetFromBase;
11943   SDValue FirstChain = FirstLoad->getChain();
11944   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11945     // All loads must share the same chain.
11946     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11947       break;
11948 
11949     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11950     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11951       break;
11952     LastConsecutiveLoad = i;
11953     // Find a legal type for the vector store.
11954     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11955     bool IsFastSt, IsFastLd;
11956     if (TLI.isTypeLegal(StoreTy) &&
11957         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11958                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11959         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11960                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11961       LastLegalVectorType = i + 1;
11962     }
11963 
11964     // Find a legal type for the integer store.
11965     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11966     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11967     if (TLI.isTypeLegal(StoreTy) &&
11968         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11969                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11970         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11971                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11972       LastLegalIntegerType = i + 1;
11973     // Or check whether a truncstore and extload is legal.
11974     else if (TLI.getTypeAction(Context, StoreTy) ==
11975              TargetLowering::TypePromoteInteger) {
11976       EVT LegalizedStoredValueTy =
11977         TLI.getTypeToTransformTo(Context, StoreTy);
11978       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11979           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11980           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11981           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11982           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11983                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11984           IsFastSt &&
11985           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11986                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11987           IsFastLd)
11988         LastLegalIntegerType = i+1;
11989     }
11990   }
11991 
11992   // Only use vector types if the vector type is larger than the integer type.
11993   // If they are the same, use integers.
11994   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11995   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11996 
11997   // We add +1 here because the LastXXX variables refer to location while
11998   // the NumElem refers to array/index size.
11999   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
12000   NumElem = std::min(LastLegalType, NumElem);
12001 
12002   if (NumElem < 2)
12003     return false;
12004 
12005   // Collect the chains from all merged stores.
12006   SmallVector<SDValue, 8> MergeStoreChains;
12007   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
12008 
12009   // The latest Node in the DAG.
12010   unsigned LatestNodeUsed = 0;
12011   for (unsigned i=1; i<NumElem; ++i) {
12012     // Find a chain for the new wide-store operand. Notice that some
12013     // of the store nodes that we found may not be selected for inclusion
12014     // in the wide store. The chain we use needs to be the chain of the
12015     // latest store node which is *used* and replaced by the wide store.
12016     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
12017       LatestNodeUsed = i;
12018 
12019     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
12020   }
12021 
12022   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
12023 
12024   // Find if it is better to use vectors or integers to load and store
12025   // to memory.
12026   EVT JointMemOpVT;
12027   if (UseVectorTy) {
12028     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12029   } else {
12030     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12031     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12032   }
12033 
12034   SDLoc LoadDL(LoadNodes[0].MemNode);
12035   SDLoc StoreDL(StoreNodes[0].MemNode);
12036 
12037   // The merged loads are required to have the same incoming chain, so
12038   // using the first's chain is acceptable.
12039   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12040                                 FirstLoad->getBasePtr(),
12041                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
12042 
12043   SDValue NewStoreChain =
12044     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
12045 
12046   SDValue NewStore =
12047       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12048                    FirstInChain->getPointerInfo(), FirstStoreAlign);
12049 
12050   // Transfer chain users from old loads to the new load.
12051   for (unsigned i = 0; i < NumElem; ++i) {
12052     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12053     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12054                                   SDValue(NewLoad.getNode(), 1));
12055   }
12056 
12057   if (UseAA) {
12058     // Replace the all stores with the new store.
12059     for (unsigned i = 0; i < NumElem; ++i)
12060       CombineTo(StoreNodes[i].MemNode, NewStore);
12061   } else {
12062     // Replace the last store with the new store.
12063     CombineTo(LatestOp, NewStore);
12064     // Erase all other stores.
12065     for (unsigned i = 0; i < NumElem; ++i) {
12066       // Remove all Store nodes.
12067       if (StoreNodes[i].MemNode == LatestOp)
12068         continue;
12069       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12070       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
12071       deleteAndRecombine(St);
12072     }
12073   }
12074 
12075   StoreNodes.erase(StoreNodes.begin() + NumElem, StoreNodes.end());
12076   return true;
12077 }
12078 
12079 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12080   SDLoc SL(ST);
12081   SDValue ReplStore;
12082 
12083   // Replace the chain to avoid dependency.
12084   if (ST->isTruncatingStore()) {
12085     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12086                                   ST->getBasePtr(), ST->getMemoryVT(),
12087                                   ST->getMemOperand());
12088   } else {
12089     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12090                              ST->getMemOperand());
12091   }
12092 
12093   // Create token to keep both nodes around.
12094   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12095                               MVT::Other, ST->getChain(), ReplStore);
12096 
12097   // Make sure the new and old chains are cleaned up.
12098   AddToWorklist(Token.getNode());
12099 
12100   // Don't add users to work list.
12101   return CombineTo(ST, Token, false);
12102 }
12103 
12104 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12105   SDValue Value = ST->getValue();
12106   if (Value.getOpcode() == ISD::TargetConstantFP)
12107     return SDValue();
12108 
12109   SDLoc DL(ST);
12110 
12111   SDValue Chain = ST->getChain();
12112   SDValue Ptr = ST->getBasePtr();
12113 
12114   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12115 
12116   // NOTE: If the original store is volatile, this transform must not increase
12117   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12118   // processor operation but an i64 (which is not legal) requires two.  So the
12119   // transform should not be done in this case.
12120 
12121   SDValue Tmp;
12122   switch (CFP->getSimpleValueType(0).SimpleTy) {
12123   default:
12124     llvm_unreachable("Unknown FP type");
12125   case MVT::f16:    // We don't do this for these yet.
12126   case MVT::f80:
12127   case MVT::f128:
12128   case MVT::ppcf128:
12129     return SDValue();
12130   case MVT::f32:
12131     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12132         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12133       ;
12134       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12135                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12136                             MVT::i32);
12137       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12138     }
12139 
12140     return SDValue();
12141   case MVT::f64:
12142     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12143          !ST->isVolatile()) ||
12144         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12145       ;
12146       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12147                             getZExtValue(), SDLoc(CFP), MVT::i64);
12148       return DAG.getStore(Chain, DL, Tmp,
12149                           Ptr, ST->getMemOperand());
12150     }
12151 
12152     if (!ST->isVolatile() &&
12153         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12154       // Many FP stores are not made apparent until after legalize, e.g. for
12155       // argument passing.  Since this is so common, custom legalize the
12156       // 64-bit integer store into two 32-bit stores.
12157       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12158       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12159       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12160       if (DAG.getDataLayout().isBigEndian())
12161         std::swap(Lo, Hi);
12162 
12163       unsigned Alignment = ST->getAlignment();
12164       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12165       AAMDNodes AAInfo = ST->getAAInfo();
12166 
12167       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12168                                  ST->getAlignment(), MMOFlags, AAInfo);
12169       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12170                         DAG.getConstant(4, DL, Ptr.getValueType()));
12171       Alignment = MinAlign(Alignment, 4U);
12172       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12173                                  ST->getPointerInfo().getWithOffset(4),
12174                                  Alignment, MMOFlags, AAInfo);
12175       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12176                          St0, St1);
12177     }
12178 
12179     return SDValue();
12180   }
12181 }
12182 
12183 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12184   StoreSDNode *ST  = cast<StoreSDNode>(N);
12185   SDValue Chain = ST->getChain();
12186   SDValue Value = ST->getValue();
12187   SDValue Ptr   = ST->getBasePtr();
12188 
12189   // If this is a store of a bit convert, store the input value if the
12190   // resultant store does not need a higher alignment than the original.
12191   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12192       ST->isUnindexed()) {
12193     EVT SVT = Value.getOperand(0).getValueType();
12194     if (((!LegalOperations && !ST->isVolatile()) ||
12195          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12196         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12197       unsigned OrigAlign = ST->getAlignment();
12198       bool Fast = false;
12199       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12200                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12201           Fast) {
12202         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12203                             ST->getPointerInfo(), OrigAlign,
12204                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
12205       }
12206     }
12207   }
12208 
12209   // Turn 'store undef, Ptr' -> nothing.
12210   if (Value.isUndef() && ST->isUnindexed())
12211     return Chain;
12212 
12213   // Try to infer better alignment information than the store already has.
12214   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12215     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12216       if (Align > ST->getAlignment()) {
12217         SDValue NewStore =
12218             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12219                               ST->getMemoryVT(), Align,
12220                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
12221         if (NewStore.getNode() != N)
12222           return CombineTo(ST, NewStore, true);
12223       }
12224     }
12225   }
12226 
12227   // Try transforming a pair floating point load / store ops to integer
12228   // load / store ops.
12229   if (SDValue NewST = TransformFPLoadStorePair(N))
12230     return NewST;
12231 
12232   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12233                                                   : DAG.getSubtarget().useAA();
12234 #ifndef NDEBUG
12235   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12236       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12237     UseAA = false;
12238 #endif
12239   if (UseAA && ST->isUnindexed()) {
12240     // FIXME: We should do this even without AA enabled. AA will just allow
12241     // FindBetterChain to work in more situations. The problem with this is that
12242     // any combine that expects memory operations to be on consecutive chains
12243     // first needs to be updated to look for users of the same chain.
12244 
12245     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12246     // adjacent stores.
12247     if (findBetterNeighborChains(ST)) {
12248       // replaceStoreChain uses CombineTo, which handled all of the worklist
12249       // manipulation. Return the original node to not do anything else.
12250       return SDValue(ST, 0);
12251     }
12252     Chain = ST->getChain();
12253   }
12254 
12255   // Try transforming N to an indexed store.
12256   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12257     return SDValue(N, 0);
12258 
12259   // FIXME: is there such a thing as a truncating indexed store?
12260   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12261       Value.getValueType().isInteger()) {
12262     // See if we can simplify the input to this truncstore with knowledge that
12263     // only the low bits are being used.  For example:
12264     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12265     SDValue Shorter = GetDemandedBits(
12266         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12267                                     ST->getMemoryVT().getScalarSizeInBits()));
12268     AddToWorklist(Value.getNode());
12269     if (Shorter.getNode())
12270       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12271                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12272 
12273     // Otherwise, see if we can simplify the operation with
12274     // SimplifyDemandedBits, which only works if the value has a single use.
12275     if (SimplifyDemandedBits(
12276             Value,
12277             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12278                                  ST->getMemoryVT().getScalarSizeInBits())))
12279       return SDValue(N, 0);
12280   }
12281 
12282   // If this is a load followed by a store to the same location, then the store
12283   // is dead/noop.
12284   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12285     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12286         ST->isUnindexed() && !ST->isVolatile() &&
12287         // There can't be any side effects between the load and store, such as
12288         // a call or store.
12289         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12290       // The store is dead, remove it.
12291       return Chain;
12292     }
12293   }
12294 
12295   // If this is a store followed by a store with the same value to the same
12296   // location, then the store is dead/noop.
12297   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12298     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12299         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12300         ST1->isUnindexed() && !ST1->isVolatile()) {
12301       // The store is dead, remove it.
12302       return Chain;
12303     }
12304   }
12305 
12306   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12307   // truncating store.  We can do this even if this is already a truncstore.
12308   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12309       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12310       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12311                             ST->getMemoryVT())) {
12312     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12313                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12314   }
12315 
12316   // Only perform this optimization before the types are legal, because we
12317   // don't want to perform this optimization on every DAGCombine invocation.
12318   if (!LegalTypes) {
12319     for (;;) {
12320       // There can be multiple store sequences on the same chain.
12321       // Keep trying to merge store sequences until we are unable to do so
12322       // or until we merge the last store on the chain.
12323       SmallVector<MemOpLink, 8> StoreNodes;
12324       bool Changed = MergeConsecutiveStores(ST, StoreNodes);
12325       if (!Changed) break;
12326 
12327       if (any_of(StoreNodes,
12328                  [ST](const MemOpLink &Link) { return Link.MemNode == ST; })) {
12329         // ST has been merged and no longer exists.
12330         return SDValue(N, 0);
12331       }
12332     }
12333   }
12334 
12335   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12336   //
12337   // Make sure to do this only after attempting to merge stores in order to
12338   //  avoid changing the types of some subset of stores due to visit order,
12339   //  preventing their merging.
12340   if (isa<ConstantFPSDNode>(Value)) {
12341     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12342       return NewSt;
12343   }
12344 
12345   if (SDValue NewSt = splitMergedValStore(ST))
12346     return NewSt;
12347 
12348   return ReduceLoadOpStoreWidth(N);
12349 }
12350 
12351 /// For the instruction sequence of store below, F and I values
12352 /// are bundled together as an i64 value before being stored into memory.
12353 /// Sometimes it is more efficent to generate separate stores for F and I,
12354 /// which can remove the bitwise instructions or sink them to colder places.
12355 ///
12356 ///   (store (or (zext (bitcast F to i32) to i64),
12357 ///              (shl (zext I to i64), 32)), addr)  -->
12358 ///   (store F, addr) and (store I, addr+4)
12359 ///
12360 /// Similarly, splitting for other merged store can also be beneficial, like:
12361 /// For pair of {i32, i32}, i64 store --> two i32 stores.
12362 /// For pair of {i32, i16}, i64 store --> two i32 stores.
12363 /// For pair of {i16, i16}, i32 store --> two i16 stores.
12364 /// For pair of {i16, i8},  i32 store --> two i16 stores.
12365 /// For pair of {i8, i8},   i16 store --> two i8 stores.
12366 ///
12367 /// We allow each target to determine specifically which kind of splitting is
12368 /// supported.
12369 ///
12370 /// The store patterns are commonly seen from the simple code snippet below
12371 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
12372 ///   void goo(const std::pair<int, float> &);
12373 ///   hoo() {
12374 ///     ...
12375 ///     goo(std::make_pair(tmp, ftmp));
12376 ///     ...
12377 ///   }
12378 ///
12379 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
12380   if (OptLevel == CodeGenOpt::None)
12381     return SDValue();
12382 
12383   SDValue Val = ST->getValue();
12384   SDLoc DL(ST);
12385 
12386   // Match OR operand.
12387   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
12388     return SDValue();
12389 
12390   // Match SHL operand and get Lower and Higher parts of Val.
12391   SDValue Op1 = Val.getOperand(0);
12392   SDValue Op2 = Val.getOperand(1);
12393   SDValue Lo, Hi;
12394   if (Op1.getOpcode() != ISD::SHL) {
12395     std::swap(Op1, Op2);
12396     if (Op1.getOpcode() != ISD::SHL)
12397       return SDValue();
12398   }
12399   Lo = Op2;
12400   Hi = Op1.getOperand(0);
12401   if (!Op1.hasOneUse())
12402     return SDValue();
12403 
12404   // Match shift amount to HalfValBitSize.
12405   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
12406   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
12407   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
12408     return SDValue();
12409 
12410   // Lo and Hi are zero-extended from int with size less equal than 32
12411   // to i64.
12412   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
12413       !Lo.getOperand(0).getValueType().isScalarInteger() ||
12414       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
12415       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
12416       !Hi.getOperand(0).getValueType().isScalarInteger() ||
12417       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
12418     return SDValue();
12419 
12420   if (!TLI.isMultiStoresCheaperThanBitsMerge(Lo.getOperand(0),
12421                                              Hi.getOperand(0)))
12422     return SDValue();
12423 
12424   // Start to split store.
12425   unsigned Alignment = ST->getAlignment();
12426   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12427   AAMDNodes AAInfo = ST->getAAInfo();
12428 
12429   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
12430   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
12431   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
12432   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
12433 
12434   SDValue Chain = ST->getChain();
12435   SDValue Ptr = ST->getBasePtr();
12436   // Lower value store.
12437   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12438                              ST->getAlignment(), MMOFlags, AAInfo);
12439   Ptr =
12440       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12441                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
12442   // Higher value store.
12443   SDValue St1 =
12444       DAG.getStore(St0, DL, Hi, Ptr,
12445                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
12446                    Alignment / 2, MMOFlags, AAInfo);
12447   return St1;
12448 }
12449 
12450 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12451   SDValue InVec = N->getOperand(0);
12452   SDValue InVal = N->getOperand(1);
12453   SDValue EltNo = N->getOperand(2);
12454   SDLoc DL(N);
12455 
12456   // If the inserted element is an UNDEF, just use the input vector.
12457   if (InVal.isUndef())
12458     return InVec;
12459 
12460   EVT VT = InVec.getValueType();
12461 
12462   // If we can't generate a legal BUILD_VECTOR, exit
12463   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12464     return SDValue();
12465 
12466   // Check that we know which element is being inserted
12467   if (!isa<ConstantSDNode>(EltNo))
12468     return SDValue();
12469   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12470 
12471   // Canonicalize insert_vector_elt dag nodes.
12472   // Example:
12473   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12474   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12475   //
12476   // Do this only if the child insert_vector node has one use; also
12477   // do this only if indices are both constants and Idx1 < Idx0.
12478   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12479       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12480     unsigned OtherElt =
12481       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12482     if (Elt < OtherElt) {
12483       // Swap nodes.
12484       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
12485                                   InVec.getOperand(0), InVal, EltNo);
12486       AddToWorklist(NewOp.getNode());
12487       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12488                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12489     }
12490   }
12491 
12492   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12493   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12494   // vector elements.
12495   SmallVector<SDValue, 8> Ops;
12496   // Do not combine these two vectors if the output vector will not replace
12497   // the input vector.
12498   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12499     Ops.append(InVec.getNode()->op_begin(),
12500                InVec.getNode()->op_end());
12501   } else if (InVec.isUndef()) {
12502     unsigned NElts = VT.getVectorNumElements();
12503     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12504   } else {
12505     return SDValue();
12506   }
12507 
12508   // Insert the element
12509   if (Elt < Ops.size()) {
12510     // All the operands of BUILD_VECTOR must have the same type;
12511     // we enforce that here.
12512     EVT OpVT = Ops[0].getValueType();
12513     if (InVal.getValueType() != OpVT)
12514       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12515                 DAG.getNode(ISD::ANY_EXTEND, DL, OpVT, InVal) :
12516                 DAG.getNode(ISD::TRUNCATE, DL, OpVT, InVal);
12517     Ops[Elt] = InVal;
12518   }
12519 
12520   // Return the new vector
12521   return DAG.getBuildVector(VT, DL, Ops);
12522 }
12523 
12524 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12525     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12526   assert(!OriginalLoad->isVolatile());
12527 
12528   EVT ResultVT = EVE->getValueType(0);
12529   EVT VecEltVT = InVecVT.getVectorElementType();
12530   unsigned Align = OriginalLoad->getAlignment();
12531   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12532       VecEltVT.getTypeForEVT(*DAG.getContext()));
12533 
12534   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12535     return SDValue();
12536 
12537   Align = NewAlign;
12538 
12539   SDValue NewPtr = OriginalLoad->getBasePtr();
12540   SDValue Offset;
12541   EVT PtrType = NewPtr.getValueType();
12542   MachinePointerInfo MPI;
12543   SDLoc DL(EVE);
12544   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12545     int Elt = ConstEltNo->getZExtValue();
12546     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12547     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12548     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12549   } else {
12550     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12551     Offset = DAG.getNode(
12552         ISD::MUL, DL, PtrType, Offset,
12553         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12554     MPI = OriginalLoad->getPointerInfo();
12555   }
12556   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12557 
12558   // The replacement we need to do here is a little tricky: we need to
12559   // replace an extractelement of a load with a load.
12560   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12561   // Note that this replacement assumes that the extractvalue is the only
12562   // use of the load; that's okay because we don't want to perform this
12563   // transformation in other cases anyway.
12564   SDValue Load;
12565   SDValue Chain;
12566   if (ResultVT.bitsGT(VecEltVT)) {
12567     // If the result type of vextract is wider than the load, then issue an
12568     // extending load instead.
12569     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12570                                                   VecEltVT)
12571                                    ? ISD::ZEXTLOAD
12572                                    : ISD::EXTLOAD;
12573     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
12574                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
12575                           Align, OriginalLoad->getMemOperand()->getFlags(),
12576                           OriginalLoad->getAAInfo());
12577     Chain = Load.getValue(1);
12578   } else {
12579     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
12580                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
12581                        OriginalLoad->getAAInfo());
12582     Chain = Load.getValue(1);
12583     if (ResultVT.bitsLT(VecEltVT))
12584       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12585     else
12586       Load = DAG.getBitcast(ResultVT, Load);
12587   }
12588   WorklistRemover DeadNodes(*this);
12589   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12590   SDValue To[] = { Load, Chain };
12591   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12592   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12593   // worklist explicitly as well.
12594   AddToWorklist(Load.getNode());
12595   AddUsersToWorklist(Load.getNode()); // Add users too
12596   // Make sure to revisit this node to clean it up; it will usually be dead.
12597   AddToWorklist(EVE);
12598   ++OpsNarrowed;
12599   return SDValue(EVE, 0);
12600 }
12601 
12602 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12603   // (vextract (scalar_to_vector val, 0) -> val
12604   SDValue InVec = N->getOperand(0);
12605   EVT VT = InVec.getValueType();
12606   EVT NVT = N->getValueType(0);
12607 
12608   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12609     // Check if the result type doesn't match the inserted element type. A
12610     // SCALAR_TO_VECTOR may truncate the inserted element and the
12611     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12612     SDValue InOp = InVec.getOperand(0);
12613     if (InOp.getValueType() != NVT) {
12614       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12615       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12616     }
12617     return InOp;
12618   }
12619 
12620   SDValue EltNo = N->getOperand(1);
12621   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12622 
12623   // extract_vector_elt (build_vector x, y), 1 -> y
12624   if (ConstEltNo &&
12625       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12626       TLI.isTypeLegal(VT) &&
12627       (InVec.hasOneUse() ||
12628        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12629     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12630     EVT InEltVT = Elt.getValueType();
12631 
12632     // Sometimes build_vector's scalar input types do not match result type.
12633     if (NVT == InEltVT)
12634       return Elt;
12635 
12636     // TODO: It may be useful to truncate if free if the build_vector implicitly
12637     // converts.
12638   }
12639 
12640   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12641   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12642       ConstEltNo->isNullValue() && VT.isInteger()) {
12643     SDValue BCSrc = InVec.getOperand(0);
12644     if (BCSrc.getValueType().isScalarInteger())
12645       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12646   }
12647 
12648   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
12649   //
12650   // This only really matters if the index is non-constant since other combines
12651   // on the constant elements already work.
12652   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12653       EltNo == InVec.getOperand(2)) {
12654     SDValue Elt = InVec.getOperand(1);
12655     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
12656   }
12657 
12658   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12659   // We only perform this optimization before the op legalization phase because
12660   // we may introduce new vector instructions which are not backed by TD
12661   // patterns. For example on AVX, extracting elements from a wide vector
12662   // without using extract_subvector. However, if we can find an underlying
12663   // scalar value, then we can always use that.
12664   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12665     int NumElem = VT.getVectorNumElements();
12666     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12667     // Find the new index to extract from.
12668     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12669 
12670     // Extracting an undef index is undef.
12671     if (OrigElt == -1)
12672       return DAG.getUNDEF(NVT);
12673 
12674     // Select the right vector half to extract from.
12675     SDValue SVInVec;
12676     if (OrigElt < NumElem) {
12677       SVInVec = InVec->getOperand(0);
12678     } else {
12679       SVInVec = InVec->getOperand(1);
12680       OrigElt -= NumElem;
12681     }
12682 
12683     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12684       SDValue InOp = SVInVec.getOperand(OrigElt);
12685       if (InOp.getValueType() != NVT) {
12686         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12687         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12688       }
12689 
12690       return InOp;
12691     }
12692 
12693     // FIXME: We should handle recursing on other vector shuffles and
12694     // scalar_to_vector here as well.
12695 
12696     if (!LegalOperations) {
12697       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12698       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12699                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12700     }
12701   }
12702 
12703   bool BCNumEltsChanged = false;
12704   EVT ExtVT = VT.getVectorElementType();
12705   EVT LVT = ExtVT;
12706 
12707   // If the result of load has to be truncated, then it's not necessarily
12708   // profitable.
12709   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12710     return SDValue();
12711 
12712   if (InVec.getOpcode() == ISD::BITCAST) {
12713     // Don't duplicate a load with other uses.
12714     if (!InVec.hasOneUse())
12715       return SDValue();
12716 
12717     EVT BCVT = InVec.getOperand(0).getValueType();
12718     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12719       return SDValue();
12720     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12721       BCNumEltsChanged = true;
12722     InVec = InVec.getOperand(0);
12723     ExtVT = BCVT.getVectorElementType();
12724   }
12725 
12726   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12727   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12728       ISD::isNormalLoad(InVec.getNode()) &&
12729       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12730     SDValue Index = N->getOperand(1);
12731     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
12732       if (!OrigLoad->isVolatile()) {
12733         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12734                                                              OrigLoad);
12735       }
12736     }
12737   }
12738 
12739   // Perform only after legalization to ensure build_vector / vector_shuffle
12740   // optimizations have already been done.
12741   if (!LegalOperations) return SDValue();
12742 
12743   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12744   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12745   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12746 
12747   if (ConstEltNo) {
12748     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12749 
12750     LoadSDNode *LN0 = nullptr;
12751     const ShuffleVectorSDNode *SVN = nullptr;
12752     if (ISD::isNormalLoad(InVec.getNode())) {
12753       LN0 = cast<LoadSDNode>(InVec);
12754     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12755                InVec.getOperand(0).getValueType() == ExtVT &&
12756                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12757       // Don't duplicate a load with other uses.
12758       if (!InVec.hasOneUse())
12759         return SDValue();
12760 
12761       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12762     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12763       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12764       // =>
12765       // (load $addr+1*size)
12766 
12767       // Don't duplicate a load with other uses.
12768       if (!InVec.hasOneUse())
12769         return SDValue();
12770 
12771       // If the bit convert changed the number of elements, it is unsafe
12772       // to examine the mask.
12773       if (BCNumEltsChanged)
12774         return SDValue();
12775 
12776       // Select the input vector, guarding against out of range extract vector.
12777       unsigned NumElems = VT.getVectorNumElements();
12778       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12779       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12780 
12781       if (InVec.getOpcode() == ISD::BITCAST) {
12782         // Don't duplicate a load with other uses.
12783         if (!InVec.hasOneUse())
12784           return SDValue();
12785 
12786         InVec = InVec.getOperand(0);
12787       }
12788       if (ISD::isNormalLoad(InVec.getNode())) {
12789         LN0 = cast<LoadSDNode>(InVec);
12790         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12791         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12792       }
12793     }
12794 
12795     // Make sure we found a non-volatile load and the extractelement is
12796     // the only use.
12797     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12798       return SDValue();
12799 
12800     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12801     if (Elt == -1)
12802       return DAG.getUNDEF(LVT);
12803 
12804     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12805   }
12806 
12807   return SDValue();
12808 }
12809 
12810 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12811 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12812   // We perform this optimization post type-legalization because
12813   // the type-legalizer often scalarizes integer-promoted vectors.
12814   // Performing this optimization before may create bit-casts which
12815   // will be type-legalized to complex code sequences.
12816   // We perform this optimization only before the operation legalizer because we
12817   // may introduce illegal operations.
12818   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12819     return SDValue();
12820 
12821   unsigned NumInScalars = N->getNumOperands();
12822   SDLoc DL(N);
12823   EVT VT = N->getValueType(0);
12824 
12825   // Check to see if this is a BUILD_VECTOR of a bunch of values
12826   // which come from any_extend or zero_extend nodes. If so, we can create
12827   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12828   // optimizations. We do not handle sign-extend because we can't fill the sign
12829   // using shuffles.
12830   EVT SourceType = MVT::Other;
12831   bool AllAnyExt = true;
12832 
12833   for (unsigned i = 0; i != NumInScalars; ++i) {
12834     SDValue In = N->getOperand(i);
12835     // Ignore undef inputs.
12836     if (In.isUndef()) continue;
12837 
12838     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12839     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12840 
12841     // Abort if the element is not an extension.
12842     if (!ZeroExt && !AnyExt) {
12843       SourceType = MVT::Other;
12844       break;
12845     }
12846 
12847     // The input is a ZeroExt or AnyExt. Check the original type.
12848     EVT InTy = In.getOperand(0).getValueType();
12849 
12850     // Check that all of the widened source types are the same.
12851     if (SourceType == MVT::Other)
12852       // First time.
12853       SourceType = InTy;
12854     else if (InTy != SourceType) {
12855       // Multiple income types. Abort.
12856       SourceType = MVT::Other;
12857       break;
12858     }
12859 
12860     // Check if all of the extends are ANY_EXTENDs.
12861     AllAnyExt &= AnyExt;
12862   }
12863 
12864   // In order to have valid types, all of the inputs must be extended from the
12865   // same source type and all of the inputs must be any or zero extend.
12866   // Scalar sizes must be a power of two.
12867   EVT OutScalarTy = VT.getScalarType();
12868   bool ValidTypes = SourceType != MVT::Other &&
12869                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12870                  isPowerOf2_32(SourceType.getSizeInBits());
12871 
12872   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12873   // turn into a single shuffle instruction.
12874   if (!ValidTypes)
12875     return SDValue();
12876 
12877   bool isLE = DAG.getDataLayout().isLittleEndian();
12878   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12879   assert(ElemRatio > 1 && "Invalid element size ratio");
12880   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12881                                DAG.getConstant(0, DL, SourceType);
12882 
12883   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12884   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12885 
12886   // Populate the new build_vector
12887   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12888     SDValue Cast = N->getOperand(i);
12889     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12890             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12891             Cast.isUndef()) && "Invalid cast opcode");
12892     SDValue In;
12893     if (Cast.isUndef())
12894       In = DAG.getUNDEF(SourceType);
12895     else
12896       In = Cast->getOperand(0);
12897     unsigned Index = isLE ? (i * ElemRatio) :
12898                             (i * ElemRatio + (ElemRatio - 1));
12899 
12900     assert(Index < Ops.size() && "Invalid index");
12901     Ops[Index] = In;
12902   }
12903 
12904   // The type of the new BUILD_VECTOR node.
12905   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12906   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12907          "Invalid vector size");
12908   // Check if the new vector type is legal.
12909   if (!isTypeLegal(VecVT)) return SDValue();
12910 
12911   // Make the new BUILD_VECTOR.
12912   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
12913 
12914   // The new BUILD_VECTOR node has the potential to be further optimized.
12915   AddToWorklist(BV.getNode());
12916   // Bitcast to the desired type.
12917   return DAG.getBitcast(VT, BV);
12918 }
12919 
12920 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12921   EVT VT = N->getValueType(0);
12922 
12923   unsigned NumInScalars = N->getNumOperands();
12924   SDLoc DL(N);
12925 
12926   EVT SrcVT = MVT::Other;
12927   unsigned Opcode = ISD::DELETED_NODE;
12928   unsigned NumDefs = 0;
12929 
12930   for (unsigned i = 0; i != NumInScalars; ++i) {
12931     SDValue In = N->getOperand(i);
12932     unsigned Opc = In.getOpcode();
12933 
12934     if (Opc == ISD::UNDEF)
12935       continue;
12936 
12937     // If all scalar values are floats and converted from integers.
12938     if (Opcode == ISD::DELETED_NODE &&
12939         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12940       Opcode = Opc;
12941     }
12942 
12943     if (Opc != Opcode)
12944       return SDValue();
12945 
12946     EVT InVT = In.getOperand(0).getValueType();
12947 
12948     // If all scalar values are typed differently, bail out. It's chosen to
12949     // simplify BUILD_VECTOR of integer types.
12950     if (SrcVT == MVT::Other)
12951       SrcVT = InVT;
12952     if (SrcVT != InVT)
12953       return SDValue();
12954     NumDefs++;
12955   }
12956 
12957   // If the vector has just one element defined, it's not worth to fold it into
12958   // a vectorized one.
12959   if (NumDefs < 2)
12960     return SDValue();
12961 
12962   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12963          && "Should only handle conversion from integer to float.");
12964   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12965 
12966   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12967 
12968   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12969     return SDValue();
12970 
12971   // Just because the floating-point vector type is legal does not necessarily
12972   // mean that the corresponding integer vector type is.
12973   if (!isTypeLegal(NVT))
12974     return SDValue();
12975 
12976   SmallVector<SDValue, 8> Opnds;
12977   for (unsigned i = 0; i != NumInScalars; ++i) {
12978     SDValue In = N->getOperand(i);
12979 
12980     if (In.isUndef())
12981       Opnds.push_back(DAG.getUNDEF(SrcVT));
12982     else
12983       Opnds.push_back(In.getOperand(0));
12984   }
12985   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
12986   AddToWorklist(BV.getNode());
12987 
12988   return DAG.getNode(Opcode, DL, VT, BV);
12989 }
12990 
12991 SDValue DAGCombiner::createBuildVecShuffle(SDLoc DL, SDNode *N,
12992                                            ArrayRef<int> VectorMask,
12993                                            SDValue VecIn1, SDValue VecIn2,
12994                                            unsigned LeftIdx) {
12995   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12996   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
12997 
12998   EVT VT = N->getValueType(0);
12999   EVT InVT1 = VecIn1.getValueType();
13000   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
13001 
13002   unsigned Vec2Offset = InVT1.getVectorNumElements();
13003   unsigned NumElems = VT.getVectorNumElements();
13004   unsigned ShuffleNumElems = NumElems;
13005 
13006   // We can't generate a shuffle node with mismatched input and output types.
13007   // Try to make the types match the type of the output.
13008   if (InVT1 != VT || InVT2 != VT) {
13009     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13010       // If the output vector length is a multiple of both input lengths,
13011       // we can concatenate them and pad the rest with undefs.
13012       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13013       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13014       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13015       ConcatOps[0] = VecIn1;
13016       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13017       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13018       VecIn2 = SDValue();
13019     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13020       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13021         return SDValue();
13022 
13023       if (!VecIn2.getNode()) {
13024         // If we only have one input vector, and it's twice the size of the
13025         // output, split it in two.
13026         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13027                              DAG.getConstant(NumElems, DL, IdxTy));
13028         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13029         // Since we now have shorter input vectors, adjust the offset of the
13030         // second vector's start.
13031         Vec2Offset = NumElems;
13032       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13033         // VecIn1 is wider than the output, and we have another, possibly
13034         // smaller input. Pad the smaller input with undefs, shuffle at the
13035         // input vector width, and extract the output.
13036         // The shuffle type is different than VT, so check legality again.
13037         if (LegalOperations &&
13038             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13039           return SDValue();
13040 
13041         if (InVT1 != InVT2)
13042           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13043                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13044         ShuffleNumElems = NumElems * 2;
13045       } else {
13046         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13047         // than VecIn1. We can't handle this for now - this case will disappear
13048         // when we start sorting the vectors by type.
13049         return SDValue();
13050       }
13051     } else {
13052       // TODO: Support cases where the length mismatch isn't exactly by a
13053       // factor of 2.
13054       // TODO: Move this check upwards, so that if we have bad type
13055       // mismatches, we don't create any DAG nodes.
13056       return SDValue();
13057     }
13058   }
13059 
13060   // Initialize mask to undef.
13061   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13062 
13063   // Only need to run up to the number of elements actually used, not the
13064   // total number of elements in the shuffle - if we are shuffling a wider
13065   // vector, the high lanes should be set to undef.
13066   for (unsigned i = 0; i != NumElems; ++i) {
13067     if (VectorMask[i] <= 0)
13068       continue;
13069 
13070     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13071     if (VectorMask[i] == (int)LeftIdx) {
13072       Mask[i] = ExtIndex;
13073     } else if (VectorMask[i] == (int)LeftIdx + 1) {
13074       Mask[i] = Vec2Offset + ExtIndex;
13075     }
13076   }
13077 
13078   // The type the input vectors may have changed above.
13079   InVT1 = VecIn1.getValueType();
13080 
13081   // If we already have a VecIn2, it should have the same type as VecIn1.
13082   // If we don't, get an undef/zero vector of the appropriate type.
13083   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13084   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13085 
13086   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13087   if (ShuffleNumElems > NumElems)
13088     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13089 
13090   return Shuffle;
13091 }
13092 
13093 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13094 // operations. If the types of the vectors we're extracting from allow it,
13095 // turn this into a vector_shuffle node.
13096 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13097   SDLoc DL(N);
13098   EVT VT = N->getValueType(0);
13099 
13100   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13101   if (!isTypeLegal(VT))
13102     return SDValue();
13103 
13104   // May only combine to shuffle after legalize if shuffle is legal.
13105   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13106     return SDValue();
13107 
13108   bool UsesZeroVector = false;
13109   unsigned NumElems = N->getNumOperands();
13110 
13111   // Record, for each element of the newly built vector, which input vector
13112   // that element comes from. -1 stands for undef, 0 for the zero vector,
13113   // and positive values for the input vectors.
13114   // VectorMask maps each element to its vector number, and VecIn maps vector
13115   // numbers to their initial SDValues.
13116 
13117   SmallVector<int, 8> VectorMask(NumElems, -1);
13118   SmallVector<SDValue, 8> VecIn;
13119   VecIn.push_back(SDValue());
13120 
13121   for (unsigned i = 0; i != NumElems; ++i) {
13122     SDValue Op = N->getOperand(i);
13123 
13124     if (Op.isUndef())
13125       continue;
13126 
13127     // See if we can use a blend with a zero vector.
13128     // TODO: Should we generalize this to a blend with an arbitrary constant
13129     // vector?
13130     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13131       UsesZeroVector = true;
13132       VectorMask[i] = 0;
13133       continue;
13134     }
13135 
13136     // Not an undef or zero. If the input is something other than an
13137     // EXTRACT_VECTOR_ELT with a constant index, bail out.
13138     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13139         !isa<ConstantSDNode>(Op.getOperand(1)))
13140       return SDValue();
13141 
13142     SDValue ExtractedFromVec = Op.getOperand(0);
13143 
13144     // All inputs must have the same element type as the output.
13145     if (VT.getVectorElementType() !=
13146         ExtractedFromVec.getValueType().getVectorElementType())
13147       return SDValue();
13148 
13149     // Have we seen this input vector before?
13150     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13151     // a map back from SDValues to numbers isn't worth it.
13152     unsigned Idx = std::distance(
13153         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13154     if (Idx == VecIn.size())
13155       VecIn.push_back(ExtractedFromVec);
13156 
13157     VectorMask[i] = Idx;
13158   }
13159 
13160   // If we didn't find at least one input vector, bail out.
13161   if (VecIn.size() < 2)
13162     return SDValue();
13163 
13164   // TODO: We want to sort the vectors by descending length, so that adjacent
13165   // pairs have similar length, and the longer vector is always first in the
13166   // pair.
13167 
13168   // TODO: Should this fire if some of the input vectors has illegal type (like
13169   // it does now), or should we let legalization run its course first?
13170 
13171   // Shuffle phase:
13172   // Take pairs of vectors, and shuffle them so that the result has elements
13173   // from these vectors in the correct places.
13174   // For example, given:
13175   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13176   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13177   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13178   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13179   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13180   // We will generate:
13181   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13182   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13183   SmallVector<SDValue, 4> Shuffles;
13184   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13185     unsigned LeftIdx = 2 * In + 1;
13186     SDValue VecLeft = VecIn[LeftIdx];
13187     SDValue VecRight =
13188         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13189 
13190     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13191                                                 VecRight, LeftIdx))
13192       Shuffles.push_back(Shuffle);
13193     else
13194       return SDValue();
13195   }
13196 
13197   // If we need the zero vector as an "ingredient" in the blend tree, add it
13198   // to the list of shuffles.
13199   if (UsesZeroVector)
13200     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13201                                       : DAG.getConstantFP(0.0, DL, VT));
13202 
13203   // If we only have one shuffle, we're done.
13204   if (Shuffles.size() == 1)
13205     return Shuffles[0];
13206 
13207   // Update the vector mask to point to the post-shuffle vectors.
13208   for (int &Vec : VectorMask)
13209     if (Vec == 0)
13210       Vec = Shuffles.size() - 1;
13211     else
13212       Vec = (Vec - 1) / 2;
13213 
13214   // More than one shuffle. Generate a binary tree of blends, e.g. if from
13215   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13216   // generate:
13217   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13218   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13219   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13220   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13221   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13222   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13223   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13224 
13225   // Make sure the initial size of the shuffle list is even.
13226   if (Shuffles.size() % 2)
13227     Shuffles.push_back(DAG.getUNDEF(VT));
13228 
13229   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13230     if (CurSize % 2) {
13231       Shuffles[CurSize] = DAG.getUNDEF(VT);
13232       CurSize++;
13233     }
13234     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13235       int Left = 2 * In;
13236       int Right = 2 * In + 1;
13237       SmallVector<int, 8> Mask(NumElems, -1);
13238       for (unsigned i = 0; i != NumElems; ++i) {
13239         if (VectorMask[i] == Left) {
13240           Mask[i] = i;
13241           VectorMask[i] = In;
13242         } else if (VectorMask[i] == Right) {
13243           Mask[i] = i + NumElems;
13244           VectorMask[i] = In;
13245         }
13246       }
13247 
13248       Shuffles[In] =
13249           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13250     }
13251   }
13252 
13253   return Shuffles[0];
13254 }
13255 
13256 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13257   EVT VT = N->getValueType(0);
13258 
13259   // A vector built entirely of undefs is undef.
13260   if (ISD::allOperandsUndef(N))
13261     return DAG.getUNDEF(VT);
13262 
13263   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13264     return V;
13265 
13266   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13267     return V;
13268 
13269   if (SDValue V = reduceBuildVecToShuffle(N))
13270     return V;
13271 
13272   return SDValue();
13273 }
13274 
13275 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13276   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13277   EVT OpVT = N->getOperand(0).getValueType();
13278 
13279   // If the operands are legal vectors, leave them alone.
13280   if (TLI.isTypeLegal(OpVT))
13281     return SDValue();
13282 
13283   SDLoc DL(N);
13284   EVT VT = N->getValueType(0);
13285   SmallVector<SDValue, 8> Ops;
13286 
13287   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13288   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13289 
13290   // Keep track of what we encounter.
13291   bool AnyInteger = false;
13292   bool AnyFP = false;
13293   for (const SDValue &Op : N->ops()) {
13294     if (ISD::BITCAST == Op.getOpcode() &&
13295         !Op.getOperand(0).getValueType().isVector())
13296       Ops.push_back(Op.getOperand(0));
13297     else if (ISD::UNDEF == Op.getOpcode())
13298       Ops.push_back(ScalarUndef);
13299     else
13300       return SDValue();
13301 
13302     // Note whether we encounter an integer or floating point scalar.
13303     // If it's neither, bail out, it could be something weird like x86mmx.
13304     EVT LastOpVT = Ops.back().getValueType();
13305     if (LastOpVT.isFloatingPoint())
13306       AnyFP = true;
13307     else if (LastOpVT.isInteger())
13308       AnyInteger = true;
13309     else
13310       return SDValue();
13311   }
13312 
13313   // If any of the operands is a floating point scalar bitcast to a vector,
13314   // use floating point types throughout, and bitcast everything.
13315   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
13316   if (AnyFP) {
13317     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
13318     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13319     if (AnyInteger) {
13320       for (SDValue &Op : Ops) {
13321         if (Op.getValueType() == SVT)
13322           continue;
13323         if (Op.isUndef())
13324           Op = ScalarUndef;
13325         else
13326           Op = DAG.getBitcast(SVT, Op);
13327       }
13328     }
13329   }
13330 
13331   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
13332                                VT.getSizeInBits() / SVT.getSizeInBits());
13333   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
13334 }
13335 
13336 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
13337 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
13338 // most two distinct vectors the same size as the result, attempt to turn this
13339 // into a legal shuffle.
13340 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
13341   EVT VT = N->getValueType(0);
13342   EVT OpVT = N->getOperand(0).getValueType();
13343   int NumElts = VT.getVectorNumElements();
13344   int NumOpElts = OpVT.getVectorNumElements();
13345 
13346   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
13347   SmallVector<int, 8> Mask;
13348 
13349   for (SDValue Op : N->ops()) {
13350     // Peek through any bitcast.
13351     while (Op.getOpcode() == ISD::BITCAST)
13352       Op = Op.getOperand(0);
13353 
13354     // UNDEF nodes convert to UNDEF shuffle mask values.
13355     if (Op.isUndef()) {
13356       Mask.append((unsigned)NumOpElts, -1);
13357       continue;
13358     }
13359 
13360     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13361       return SDValue();
13362 
13363     // What vector are we extracting the subvector from and at what index?
13364     SDValue ExtVec = Op.getOperand(0);
13365 
13366     // We want the EVT of the original extraction to correctly scale the
13367     // extraction index.
13368     EVT ExtVT = ExtVec.getValueType();
13369 
13370     // Peek through any bitcast.
13371     while (ExtVec.getOpcode() == ISD::BITCAST)
13372       ExtVec = ExtVec.getOperand(0);
13373 
13374     // UNDEF nodes convert to UNDEF shuffle mask values.
13375     if (ExtVec.isUndef()) {
13376       Mask.append((unsigned)NumOpElts, -1);
13377       continue;
13378     }
13379 
13380     if (!isa<ConstantSDNode>(Op.getOperand(1)))
13381       return SDValue();
13382     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13383 
13384     // Ensure that we are extracting a subvector from a vector the same
13385     // size as the result.
13386     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13387       return SDValue();
13388 
13389     // Scale the subvector index to account for any bitcast.
13390     int NumExtElts = ExtVT.getVectorNumElements();
13391     if (0 == (NumExtElts % NumElts))
13392       ExtIdx /= (NumExtElts / NumElts);
13393     else if (0 == (NumElts % NumExtElts))
13394       ExtIdx *= (NumElts / NumExtElts);
13395     else
13396       return SDValue();
13397 
13398     // At most we can reference 2 inputs in the final shuffle.
13399     if (SV0.isUndef() || SV0 == ExtVec) {
13400       SV0 = ExtVec;
13401       for (int i = 0; i != NumOpElts; ++i)
13402         Mask.push_back(i + ExtIdx);
13403     } else if (SV1.isUndef() || SV1 == ExtVec) {
13404       SV1 = ExtVec;
13405       for (int i = 0; i != NumOpElts; ++i)
13406         Mask.push_back(i + ExtIdx + NumElts);
13407     } else {
13408       return SDValue();
13409     }
13410   }
13411 
13412   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13413     return SDValue();
13414 
13415   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13416                               DAG.getBitcast(VT, SV1), Mask);
13417 }
13418 
13419 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13420   // If we only have one input vector, we don't need to do any concatenation.
13421   if (N->getNumOperands() == 1)
13422     return N->getOperand(0);
13423 
13424   // Check if all of the operands are undefs.
13425   EVT VT = N->getValueType(0);
13426   if (ISD::allOperandsUndef(N))
13427     return DAG.getUNDEF(VT);
13428 
13429   // Optimize concat_vectors where all but the first of the vectors are undef.
13430   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13431         return Op.isUndef();
13432       })) {
13433     SDValue In = N->getOperand(0);
13434     assert(In.getValueType().isVector() && "Must concat vectors");
13435 
13436     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13437     if (In->getOpcode() == ISD::BITCAST &&
13438         !In->getOperand(0)->getValueType(0).isVector()) {
13439       SDValue Scalar = In->getOperand(0);
13440 
13441       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13442       // look through the trunc so we can still do the transform:
13443       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13444       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13445           !TLI.isTypeLegal(Scalar.getValueType()) &&
13446           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13447         Scalar = Scalar->getOperand(0);
13448 
13449       EVT SclTy = Scalar->getValueType(0);
13450 
13451       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13452         return SDValue();
13453 
13454       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13455                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13456       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13457         return SDValue();
13458 
13459       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
13460       return DAG.getBitcast(VT, Res);
13461     }
13462   }
13463 
13464   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13465   // We have already tested above for an UNDEF only concatenation.
13466   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13467   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13468   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13469     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13470   };
13471   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13472     SmallVector<SDValue, 8> Opnds;
13473     EVT SVT = VT.getScalarType();
13474 
13475     EVT MinVT = SVT;
13476     if (!SVT.isFloatingPoint()) {
13477       // If BUILD_VECTOR are from built from integer, they may have different
13478       // operand types. Get the smallest type and truncate all operands to it.
13479       bool FoundMinVT = false;
13480       for (const SDValue &Op : N->ops())
13481         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13482           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13483           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13484           FoundMinVT = true;
13485         }
13486       assert(FoundMinVT && "Concat vector type mismatch");
13487     }
13488 
13489     for (const SDValue &Op : N->ops()) {
13490       EVT OpVT = Op.getValueType();
13491       unsigned NumElts = OpVT.getVectorNumElements();
13492 
13493       if (ISD::UNDEF == Op.getOpcode())
13494         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13495 
13496       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13497         if (SVT.isFloatingPoint()) {
13498           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13499           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13500         } else {
13501           for (unsigned i = 0; i != NumElts; ++i)
13502             Opnds.push_back(
13503                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13504         }
13505       }
13506     }
13507 
13508     assert(VT.getVectorNumElements() == Opnds.size() &&
13509            "Concat vector type mismatch");
13510     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13511   }
13512 
13513   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13514   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13515     return V;
13516 
13517   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13518   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13519     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13520       return V;
13521 
13522   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13523   // nodes often generate nop CONCAT_VECTOR nodes.
13524   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13525   // place the incoming vectors at the exact same location.
13526   SDValue SingleSource = SDValue();
13527   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13528 
13529   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13530     SDValue Op = N->getOperand(i);
13531 
13532     if (Op.isUndef())
13533       continue;
13534 
13535     // Check if this is the identity extract:
13536     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13537       return SDValue();
13538 
13539     // Find the single incoming vector for the extract_subvector.
13540     if (SingleSource.getNode()) {
13541       if (Op.getOperand(0) != SingleSource)
13542         return SDValue();
13543     } else {
13544       SingleSource = Op.getOperand(0);
13545 
13546       // Check the source type is the same as the type of the result.
13547       // If not, this concat may extend the vector, so we can not
13548       // optimize it away.
13549       if (SingleSource.getValueType() != N->getValueType(0))
13550         return SDValue();
13551     }
13552 
13553     unsigned IdentityIndex = i * PartNumElem;
13554     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13555     // The extract index must be constant.
13556     if (!CS)
13557       return SDValue();
13558 
13559     // Check that we are reading from the identity index.
13560     if (CS->getZExtValue() != IdentityIndex)
13561       return SDValue();
13562   }
13563 
13564   if (SingleSource.getNode())
13565     return SingleSource;
13566 
13567   return SDValue();
13568 }
13569 
13570 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13571   EVT NVT = N->getValueType(0);
13572   SDValue V = N->getOperand(0);
13573 
13574   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13575     // Combine:
13576     //    (extract_subvec (concat V1, V2, ...), i)
13577     // Into:
13578     //    Vi if possible
13579     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13580     // type.
13581     if (V->getOperand(0).getValueType() != NVT)
13582       return SDValue();
13583     unsigned Idx = N->getConstantOperandVal(1);
13584     unsigned NumElems = NVT.getVectorNumElements();
13585     assert((Idx % NumElems) == 0 &&
13586            "IDX in concat is not a multiple of the result vector length.");
13587     return V->getOperand(Idx / NumElems);
13588   }
13589 
13590   // Skip bitcasting
13591   if (V->getOpcode() == ISD::BITCAST)
13592     V = V.getOperand(0);
13593 
13594   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13595     // Handle only simple case where vector being inserted and vector
13596     // being extracted are of same type, and are half size of larger vectors.
13597     EVT BigVT = V->getOperand(0).getValueType();
13598     EVT SmallVT = V->getOperand(1).getValueType();
13599     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13600       return SDValue();
13601 
13602     // Only handle cases where both indexes are constants with the same type.
13603     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13604     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13605 
13606     if (InsIdx && ExtIdx &&
13607         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13608         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13609       // Combine:
13610       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13611       // Into:
13612       //    indices are equal or bit offsets are equal => V1
13613       //    otherwise => (extract_subvec V1, ExtIdx)
13614       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
13615           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
13616         return DAG.getBitcast(NVT, V->getOperand(1));
13617       return DAG.getNode(
13618           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
13619           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13620           N->getOperand(1));
13621     }
13622   }
13623 
13624   return SDValue();
13625 }
13626 
13627 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13628                                                  SDValue V, SelectionDAG &DAG) {
13629   SDLoc DL(V);
13630   EVT VT = V.getValueType();
13631 
13632   switch (V.getOpcode()) {
13633   default:
13634     return V;
13635 
13636   case ISD::CONCAT_VECTORS: {
13637     EVT OpVT = V->getOperand(0).getValueType();
13638     int OpSize = OpVT.getVectorNumElements();
13639     SmallBitVector OpUsedElements(OpSize, false);
13640     bool FoundSimplification = false;
13641     SmallVector<SDValue, 4> NewOps;
13642     NewOps.reserve(V->getNumOperands());
13643     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13644       SDValue Op = V->getOperand(i);
13645       bool OpUsed = false;
13646       for (int j = 0; j < OpSize; ++j)
13647         if (UsedElements[i * OpSize + j]) {
13648           OpUsedElements[j] = true;
13649           OpUsed = true;
13650         }
13651       NewOps.push_back(
13652           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13653                  : DAG.getUNDEF(OpVT));
13654       FoundSimplification |= Op == NewOps.back();
13655       OpUsedElements.reset();
13656     }
13657     if (FoundSimplification)
13658       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13659     return V;
13660   }
13661 
13662   case ISD::INSERT_SUBVECTOR: {
13663     SDValue BaseV = V->getOperand(0);
13664     SDValue SubV = V->getOperand(1);
13665     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13666     if (!IdxN)
13667       return V;
13668 
13669     int SubSize = SubV.getValueType().getVectorNumElements();
13670     int Idx = IdxN->getZExtValue();
13671     bool SubVectorUsed = false;
13672     SmallBitVector SubUsedElements(SubSize, false);
13673     for (int i = 0; i < SubSize; ++i)
13674       if (UsedElements[i + Idx]) {
13675         SubVectorUsed = true;
13676         SubUsedElements[i] = true;
13677         UsedElements[i + Idx] = false;
13678       }
13679 
13680     // Now recurse on both the base and sub vectors.
13681     SDValue SimplifiedSubV =
13682         SubVectorUsed
13683             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13684             : DAG.getUNDEF(SubV.getValueType());
13685     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13686     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13687       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13688                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13689     return V;
13690   }
13691   }
13692 }
13693 
13694 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13695                                        SDValue N1, SelectionDAG &DAG) {
13696   EVT VT = SVN->getValueType(0);
13697   int NumElts = VT.getVectorNumElements();
13698   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13699   for (int M : SVN->getMask())
13700     if (M >= 0 && M < NumElts)
13701       N0UsedElements[M] = true;
13702     else if (M >= NumElts)
13703       N1UsedElements[M - NumElts] = true;
13704 
13705   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13706   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13707   if (S0 == N0 && S1 == N1)
13708     return SDValue();
13709 
13710   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13711 }
13712 
13713 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13714 // or turn a shuffle of a single concat into simpler shuffle then concat.
13715 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13716   EVT VT = N->getValueType(0);
13717   unsigned NumElts = VT.getVectorNumElements();
13718 
13719   SDValue N0 = N->getOperand(0);
13720   SDValue N1 = N->getOperand(1);
13721   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13722 
13723   SmallVector<SDValue, 4> Ops;
13724   EVT ConcatVT = N0.getOperand(0).getValueType();
13725   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13726   unsigned NumConcats = NumElts / NumElemsPerConcat;
13727 
13728   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13729   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13730   // half vector elements.
13731   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13732       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13733                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13734     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13735                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13736     N1 = DAG.getUNDEF(ConcatVT);
13737     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13738   }
13739 
13740   // Look at every vector that's inserted. We're looking for exact
13741   // subvector-sized copies from a concatenated vector
13742   for (unsigned I = 0; I != NumConcats; ++I) {
13743     // Make sure we're dealing with a copy.
13744     unsigned Begin = I * NumElemsPerConcat;
13745     bool AllUndef = true, NoUndef = true;
13746     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13747       if (SVN->getMaskElt(J) >= 0)
13748         AllUndef = false;
13749       else
13750         NoUndef = false;
13751     }
13752 
13753     if (NoUndef) {
13754       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13755         return SDValue();
13756 
13757       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13758         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13759           return SDValue();
13760 
13761       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13762       if (FirstElt < N0.getNumOperands())
13763         Ops.push_back(N0.getOperand(FirstElt));
13764       else
13765         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13766 
13767     } else if (AllUndef) {
13768       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13769     } else { // Mixed with general masks and undefs, can't do optimization.
13770       return SDValue();
13771     }
13772   }
13773 
13774   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13775 }
13776 
13777 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13778 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13779 // This combine is done in the following cases:
13780 // 1. Both N0,N1 are BUILD_VECTOR's composed of constants or undefs.
13781 // 2. Only one of N0,N1 is a BUILD_VECTOR composed of constants or undefs -
13782 //    Combine iff that node is ALL_ZEROS. We prefer not to combine a
13783 //    BUILD_VECTOR of all constants to allow efficient materialization of
13784 //    constant vectors, but the ALL_ZEROS is an exception because
13785 //    zero-extension matching seems to rely on having BUILD_VECTOR nodes with
13786 //    zero padding between elements. FIXME: Eliminate this exception for
13787 //    ALL_ZEROS constant vectors.
13788 // 3. Neither N0,N1 are composed of only constants.
13789 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
13790                                        SelectionDAG &DAG,
13791                                        const TargetLowering &TLI) {
13792   EVT VT = SVN->getValueType(0);
13793   unsigned NumElts = VT.getVectorNumElements();
13794   SDValue N0 = SVN->getOperand(0);
13795   SDValue N1 = SVN->getOperand(1);
13796 
13797   if (!N0->hasOneUse() || !N1->hasOneUse())
13798     return SDValue();
13799   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
13800   // discussed above.
13801   if (!N1.isUndef()) {
13802     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
13803     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
13804     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
13805       return SDValue();
13806     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
13807       return SDValue();
13808   }
13809 
13810   SmallVector<SDValue, 8> Ops;
13811   for (int M : SVN->getMask()) {
13812     SDValue Op = DAG.getUNDEF(VT.getScalarType());
13813     if (M >= 0) {
13814       int Idx = M < (int)NumElts ? M : M - NumElts;
13815       SDValue &S = (M < (int)NumElts ? N0 : N1);
13816       if (S.getOpcode() == ISD::BUILD_VECTOR) {
13817         Op = S.getOperand(Idx);
13818       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13819         if (Idx == 0)
13820           Op = S.getOperand(0);
13821       } else {
13822         // Operand can't be combined - bail out.
13823         return SDValue();
13824       }
13825     }
13826     Ops.push_back(Op);
13827   }
13828   // BUILD_VECTOR requires all inputs to be of the same type, find the
13829   // maximum type and extend them all.
13830   EVT SVT = VT.getScalarType();
13831   if (SVT.isInteger())
13832     for (SDValue &Op : Ops)
13833       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13834   if (SVT != VT.getScalarType())
13835     for (SDValue &Op : Ops)
13836       Op = TLI.isZExtFree(Op.getValueType(), SVT)
13837                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
13838                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
13839   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
13840 }
13841 
13842 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13843   EVT VT = N->getValueType(0);
13844   unsigned NumElts = VT.getVectorNumElements();
13845 
13846   SDValue N0 = N->getOperand(0);
13847   SDValue N1 = N->getOperand(1);
13848 
13849   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13850 
13851   // Canonicalize shuffle undef, undef -> undef
13852   if (N0.isUndef() && N1.isUndef())
13853     return DAG.getUNDEF(VT);
13854 
13855   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13856 
13857   // Canonicalize shuffle v, v -> v, undef
13858   if (N0 == N1) {
13859     SmallVector<int, 8> NewMask;
13860     for (unsigned i = 0; i != NumElts; ++i) {
13861       int Idx = SVN->getMaskElt(i);
13862       if (Idx >= (int)NumElts) Idx -= NumElts;
13863       NewMask.push_back(Idx);
13864     }
13865     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
13866   }
13867 
13868   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13869   if (N0.isUndef())
13870     return DAG.getCommutedVectorShuffle(*SVN);
13871 
13872   // Remove references to rhs if it is undef
13873   if (N1.isUndef()) {
13874     bool Changed = false;
13875     SmallVector<int, 8> NewMask;
13876     for (unsigned i = 0; i != NumElts; ++i) {
13877       int Idx = SVN->getMaskElt(i);
13878       if (Idx >= (int)NumElts) {
13879         Idx = -1;
13880         Changed = true;
13881       }
13882       NewMask.push_back(Idx);
13883     }
13884     if (Changed)
13885       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
13886   }
13887 
13888   // If it is a splat, check if the argument vector is another splat or a
13889   // build_vector.
13890   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13891     SDNode *V = N0.getNode();
13892 
13893     // If this is a bit convert that changes the element type of the vector but
13894     // not the number of vector elements, look through it.  Be careful not to
13895     // look though conversions that change things like v4f32 to v2f64.
13896     if (V->getOpcode() == ISD::BITCAST) {
13897       SDValue ConvInput = V->getOperand(0);
13898       if (ConvInput.getValueType().isVector() &&
13899           ConvInput.getValueType().getVectorNumElements() == NumElts)
13900         V = ConvInput.getNode();
13901     }
13902 
13903     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13904       assert(V->getNumOperands() == NumElts &&
13905              "BUILD_VECTOR has wrong number of operands");
13906       SDValue Base;
13907       bool AllSame = true;
13908       for (unsigned i = 0; i != NumElts; ++i) {
13909         if (!V->getOperand(i).isUndef()) {
13910           Base = V->getOperand(i);
13911           break;
13912         }
13913       }
13914       // Splat of <u, u, u, u>, return <u, u, u, u>
13915       if (!Base.getNode())
13916         return N0;
13917       for (unsigned i = 0; i != NumElts; ++i) {
13918         if (V->getOperand(i) != Base) {
13919           AllSame = false;
13920           break;
13921         }
13922       }
13923       // Splat of <x, x, x, x>, return <x, x, x, x>
13924       if (AllSame)
13925         return N0;
13926 
13927       // Canonicalize any other splat as a build_vector.
13928       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13929       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13930       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13931 
13932       // We may have jumped through bitcasts, so the type of the
13933       // BUILD_VECTOR may not match the type of the shuffle.
13934       if (V->getValueType(0) != VT)
13935         NewBV = DAG.getBitcast(VT, NewBV);
13936       return NewBV;
13937     }
13938   }
13939 
13940   // There are various patterns used to build up a vector from smaller vectors,
13941   // subvectors, or elements. Scan chains of these and replace unused insertions
13942   // or components with undef.
13943   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13944     return S;
13945 
13946   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13947       Level < AfterLegalizeVectorOps &&
13948       (N1.isUndef() ||
13949       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13950        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13951     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13952       return V;
13953   }
13954 
13955   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13956   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13957   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13958     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
13959       return Res;
13960 
13961   // If this shuffle only has a single input that is a bitcasted shuffle,
13962   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13963   // back to their original types.
13964   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13965       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13966       TLI.isTypeLegal(VT)) {
13967 
13968     // Peek through the bitcast only if there is one user.
13969     SDValue BC0 = N0;
13970     while (BC0.getOpcode() == ISD::BITCAST) {
13971       if (!BC0.hasOneUse())
13972         break;
13973       BC0 = BC0.getOperand(0);
13974     }
13975 
13976     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13977       if (Scale == 1)
13978         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13979 
13980       SmallVector<int, 8> NewMask;
13981       for (int M : Mask)
13982         for (int s = 0; s != Scale; ++s)
13983           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13984       return NewMask;
13985     };
13986 
13987     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13988       EVT SVT = VT.getScalarType();
13989       EVT InnerVT = BC0->getValueType(0);
13990       EVT InnerSVT = InnerVT.getScalarType();
13991 
13992       // Determine which shuffle works with the smaller scalar type.
13993       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13994       EVT ScaleSVT = ScaleVT.getScalarType();
13995 
13996       if (TLI.isTypeLegal(ScaleVT) &&
13997           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13998           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13999 
14000         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
14001         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
14002 
14003         // Scale the shuffle masks to the smaller scalar type.
14004         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
14005         SmallVector<int, 8> InnerMask =
14006             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
14007         SmallVector<int, 8> OuterMask =
14008             ScaleShuffleMask(SVN->getMask(), OuterScale);
14009 
14010         // Merge the shuffle masks.
14011         SmallVector<int, 8> NewMask;
14012         for (int M : OuterMask)
14013           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
14014 
14015         // Test for shuffle mask legality over both commutations.
14016         SDValue SV0 = BC0->getOperand(0);
14017         SDValue SV1 = BC0->getOperand(1);
14018         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14019         if (!LegalMask) {
14020           std::swap(SV0, SV1);
14021           ShuffleVectorSDNode::commuteMask(NewMask);
14022           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14023         }
14024 
14025         if (LegalMask) {
14026           SV0 = DAG.getBitcast(ScaleVT, SV0);
14027           SV1 = DAG.getBitcast(ScaleVT, SV1);
14028           return DAG.getBitcast(
14029               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
14030         }
14031       }
14032     }
14033   }
14034 
14035   // Canonicalize shuffles according to rules:
14036   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
14037   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
14038   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
14039   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
14040       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
14041       TLI.isTypeLegal(VT)) {
14042     // The incoming shuffle must be of the same type as the result of the
14043     // current shuffle.
14044     assert(N1->getOperand(0).getValueType() == VT &&
14045            "Shuffle types don't match");
14046 
14047     SDValue SV0 = N1->getOperand(0);
14048     SDValue SV1 = N1->getOperand(1);
14049     bool HasSameOp0 = N0 == SV0;
14050     bool IsSV1Undef = SV1.isUndef();
14051     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
14052       // Commute the operands of this shuffle so that next rule
14053       // will trigger.
14054       return DAG.getCommutedVectorShuffle(*SVN);
14055   }
14056 
14057   // Try to fold according to rules:
14058   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14059   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14060   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14061   // Don't try to fold shuffles with illegal type.
14062   // Only fold if this shuffle is the only user of the other shuffle.
14063   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
14064       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
14065     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
14066 
14067     // The incoming shuffle must be of the same type as the result of the
14068     // current shuffle.
14069     assert(OtherSV->getOperand(0).getValueType() == VT &&
14070            "Shuffle types don't match");
14071 
14072     SDValue SV0, SV1;
14073     SmallVector<int, 4> Mask;
14074     // Compute the combined shuffle mask for a shuffle with SV0 as the first
14075     // operand, and SV1 as the second operand.
14076     for (unsigned i = 0; i != NumElts; ++i) {
14077       int Idx = SVN->getMaskElt(i);
14078       if (Idx < 0) {
14079         // Propagate Undef.
14080         Mask.push_back(Idx);
14081         continue;
14082       }
14083 
14084       SDValue CurrentVec;
14085       if (Idx < (int)NumElts) {
14086         // This shuffle index refers to the inner shuffle N0. Lookup the inner
14087         // shuffle mask to identify which vector is actually referenced.
14088         Idx = OtherSV->getMaskElt(Idx);
14089         if (Idx < 0) {
14090           // Propagate Undef.
14091           Mask.push_back(Idx);
14092           continue;
14093         }
14094 
14095         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
14096                                            : OtherSV->getOperand(1);
14097       } else {
14098         // This shuffle index references an element within N1.
14099         CurrentVec = N1;
14100       }
14101 
14102       // Simple case where 'CurrentVec' is UNDEF.
14103       if (CurrentVec.isUndef()) {
14104         Mask.push_back(-1);
14105         continue;
14106       }
14107 
14108       // Canonicalize the shuffle index. We don't know yet if CurrentVec
14109       // will be the first or second operand of the combined shuffle.
14110       Idx = Idx % NumElts;
14111       if (!SV0.getNode() || SV0 == CurrentVec) {
14112         // Ok. CurrentVec is the left hand side.
14113         // Update the mask accordingly.
14114         SV0 = CurrentVec;
14115         Mask.push_back(Idx);
14116         continue;
14117       }
14118 
14119       // Bail out if we cannot convert the shuffle pair into a single shuffle.
14120       if (SV1.getNode() && SV1 != CurrentVec)
14121         return SDValue();
14122 
14123       // Ok. CurrentVec is the right hand side.
14124       // Update the mask accordingly.
14125       SV1 = CurrentVec;
14126       Mask.push_back(Idx + NumElts);
14127     }
14128 
14129     // Check if all indices in Mask are Undef. In case, propagate Undef.
14130     bool isUndefMask = true;
14131     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
14132       isUndefMask &= Mask[i] < 0;
14133 
14134     if (isUndefMask)
14135       return DAG.getUNDEF(VT);
14136 
14137     if (!SV0.getNode())
14138       SV0 = DAG.getUNDEF(VT);
14139     if (!SV1.getNode())
14140       SV1 = DAG.getUNDEF(VT);
14141 
14142     // Avoid introducing shuffles with illegal mask.
14143     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14144       ShuffleVectorSDNode::commuteMask(Mask);
14145 
14146       if (!TLI.isShuffleMaskLegal(Mask, VT))
14147         return SDValue();
14148 
14149       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14150       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14151       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14152       std::swap(SV0, SV1);
14153     }
14154 
14155     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14156     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14157     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14158     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14159   }
14160 
14161   return SDValue();
14162 }
14163 
14164 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14165   SDValue InVal = N->getOperand(0);
14166   EVT VT = N->getValueType(0);
14167 
14168   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14169   // with a VECTOR_SHUFFLE.
14170   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14171     SDValue InVec = InVal->getOperand(0);
14172     SDValue EltNo = InVal->getOperand(1);
14173 
14174     // FIXME: We could support implicit truncation if the shuffle can be
14175     // scaled to a smaller vector scalar type.
14176     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
14177     if (C0 && VT == InVec.getValueType() &&
14178         VT.getScalarType() == InVal.getValueType()) {
14179       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
14180       int Elt = C0->getZExtValue();
14181       NewMask[0] = Elt;
14182 
14183       if (TLI.isShuffleMaskLegal(NewMask, VT))
14184         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
14185                                     NewMask);
14186     }
14187   }
14188 
14189   return SDValue();
14190 }
14191 
14192 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
14193   EVT VT = N->getValueType(0);
14194   SDValue N0 = N->getOperand(0);
14195   SDValue N1 = N->getOperand(1);
14196   SDValue N2 = N->getOperand(2);
14197 
14198   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
14199   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
14200   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
14201   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
14202       N0.getOperand(1).getValueType() == N1.getValueType() &&
14203       N0.getOperand(2) == N2)
14204     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
14205                        N1, N2);
14206 
14207   if (N0.getValueType() != N1.getValueType())
14208     return SDValue();
14209 
14210   // If the input vector is a concatenation, and the insert replaces
14211   // one of the halves, we can optimize into a single concat_vectors.
14212   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
14213       N2.getOpcode() == ISD::Constant) {
14214     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
14215 
14216     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14217     // (concat_vectors Z, Y)
14218     if (InsIdx == 0)
14219       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
14220                          N0.getOperand(1));
14221 
14222     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14223     // (concat_vectors X, Z)
14224     if (InsIdx == VT.getVectorNumElements() / 2)
14225       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
14226                          N1);
14227   }
14228 
14229   return SDValue();
14230 }
14231 
14232 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
14233   SDValue N0 = N->getOperand(0);
14234 
14235   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
14236   if (N0->getOpcode() == ISD::FP16_TO_FP)
14237     return N0->getOperand(0);
14238 
14239   return SDValue();
14240 }
14241 
14242 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
14243   SDValue N0 = N->getOperand(0);
14244 
14245   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
14246   if (N0->getOpcode() == ISD::AND) {
14247     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
14248     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
14249       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
14250                          N0.getOperand(0));
14251     }
14252   }
14253 
14254   return SDValue();
14255 }
14256 
14257 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
14258 /// with the destination vector and a zero vector.
14259 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
14260 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
14261 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
14262   EVT VT = N->getValueType(0);
14263   SDValue LHS = N->getOperand(0);
14264   SDValue RHS = N->getOperand(1);
14265   SDLoc DL(N);
14266 
14267   // Make sure we're not running after operation legalization where it
14268   // may have custom lowered the vector shuffles.
14269   if (LegalOperations)
14270     return SDValue();
14271 
14272   if (N->getOpcode() != ISD::AND)
14273     return SDValue();
14274 
14275   if (RHS.getOpcode() == ISD::BITCAST)
14276     RHS = RHS.getOperand(0);
14277 
14278   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
14279     return SDValue();
14280 
14281   EVT RVT = RHS.getValueType();
14282   unsigned NumElts = RHS.getNumOperands();
14283 
14284   // Attempt to create a valid clear mask, splitting the mask into
14285   // sub elements and checking to see if each is
14286   // all zeros or all ones - suitable for shuffle masking.
14287   auto BuildClearMask = [&](int Split) {
14288     int NumSubElts = NumElts * Split;
14289     int NumSubBits = RVT.getScalarSizeInBits() / Split;
14290 
14291     SmallVector<int, 8> Indices;
14292     for (int i = 0; i != NumSubElts; ++i) {
14293       int EltIdx = i / Split;
14294       int SubIdx = i % Split;
14295       SDValue Elt = RHS.getOperand(EltIdx);
14296       if (Elt.isUndef()) {
14297         Indices.push_back(-1);
14298         continue;
14299       }
14300 
14301       APInt Bits;
14302       if (isa<ConstantSDNode>(Elt))
14303         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
14304       else if (isa<ConstantFPSDNode>(Elt))
14305         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
14306       else
14307         return SDValue();
14308 
14309       // Extract the sub element from the constant bit mask.
14310       if (DAG.getDataLayout().isBigEndian()) {
14311         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
14312       } else {
14313         Bits = Bits.lshr(SubIdx * NumSubBits);
14314       }
14315 
14316       if (Split > 1)
14317         Bits = Bits.trunc(NumSubBits);
14318 
14319       if (Bits.isAllOnesValue())
14320         Indices.push_back(i);
14321       else if (Bits == 0)
14322         Indices.push_back(i + NumSubElts);
14323       else
14324         return SDValue();
14325     }
14326 
14327     // Let's see if the target supports this vector_shuffle.
14328     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
14329     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
14330     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
14331       return SDValue();
14332 
14333     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
14334     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
14335                                                    DAG.getBitcast(ClearVT, LHS),
14336                                                    Zero, Indices));
14337   };
14338 
14339   // Determine maximum split level (byte level masking).
14340   int MaxSplit = 1;
14341   if (RVT.getScalarSizeInBits() % 8 == 0)
14342     MaxSplit = RVT.getScalarSizeInBits() / 8;
14343 
14344   for (int Split = 1; Split <= MaxSplit; ++Split)
14345     if (RVT.getScalarSizeInBits() % Split == 0)
14346       if (SDValue S = BuildClearMask(Split))
14347         return S;
14348 
14349   return SDValue();
14350 }
14351 
14352 /// Visit a binary vector operation, like ADD.
14353 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
14354   assert(N->getValueType(0).isVector() &&
14355          "SimplifyVBinOp only works on vectors!");
14356 
14357   SDValue LHS = N->getOperand(0);
14358   SDValue RHS = N->getOperand(1);
14359   SDValue Ops[] = {LHS, RHS};
14360 
14361   // See if we can constant fold the vector operation.
14362   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
14363           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
14364     return Fold;
14365 
14366   // Try to convert a constant mask AND into a shuffle clear mask.
14367   if (SDValue Shuffle = XformToShuffleWithZero(N))
14368     return Shuffle;
14369 
14370   // Type legalization might introduce new shuffles in the DAG.
14371   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
14372   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
14373   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
14374       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
14375       LHS.getOperand(1).isUndef() &&
14376       RHS.getOperand(1).isUndef()) {
14377     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
14378     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
14379 
14380     if (SVN0->getMask().equals(SVN1->getMask())) {
14381       EVT VT = N->getValueType(0);
14382       SDValue UndefVector = LHS.getOperand(1);
14383       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
14384                                      LHS.getOperand(0), RHS.getOperand(0),
14385                                      N->getFlags());
14386       AddUsersToWorklist(N);
14387       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
14388                                   SVN0->getMask());
14389     }
14390   }
14391 
14392   return SDValue();
14393 }
14394 
14395 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
14396                                     SDValue N2) {
14397   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
14398 
14399   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
14400                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
14401 
14402   // If we got a simplified select_cc node back from SimplifySelectCC, then
14403   // break it down into a new SETCC node, and a new SELECT node, and then return
14404   // the SELECT node, since we were called with a SELECT node.
14405   if (SCC.getNode()) {
14406     // Check to see if we got a select_cc back (to turn into setcc/select).
14407     // Otherwise, just return whatever node we got back, like fabs.
14408     if (SCC.getOpcode() == ISD::SELECT_CC) {
14409       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
14410                                   N0.getValueType(),
14411                                   SCC.getOperand(0), SCC.getOperand(1),
14412                                   SCC.getOperand(4));
14413       AddToWorklist(SETCC.getNode());
14414       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14415                            SCC.getOperand(2), SCC.getOperand(3));
14416     }
14417 
14418     return SCC;
14419   }
14420   return SDValue();
14421 }
14422 
14423 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14424 /// being selected between, see if we can simplify the select.  Callers of this
14425 /// should assume that TheSelect is deleted if this returns true.  As such, they
14426 /// should return the appropriate thing (e.g. the node) back to the top-level of
14427 /// the DAG combiner loop to avoid it being looked at.
14428 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14429                                     SDValue RHS) {
14430 
14431   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14432   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14433   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14434     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14435       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14436       SDValue Sqrt = RHS;
14437       ISD::CondCode CC;
14438       SDValue CmpLHS;
14439       const ConstantFPSDNode *Zero = nullptr;
14440 
14441       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14442         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14443         CmpLHS = TheSelect->getOperand(0);
14444         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14445       } else {
14446         // SELECT or VSELECT
14447         SDValue Cmp = TheSelect->getOperand(0);
14448         if (Cmp.getOpcode() == ISD::SETCC) {
14449           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14450           CmpLHS = Cmp.getOperand(0);
14451           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14452         }
14453       }
14454       if (Zero && Zero->isZero() &&
14455           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14456           CC == ISD::SETULT || CC == ISD::SETLT)) {
14457         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14458         CombineTo(TheSelect, Sqrt);
14459         return true;
14460       }
14461     }
14462   }
14463   // Cannot simplify select with vector condition
14464   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14465 
14466   // If this is a select from two identical things, try to pull the operation
14467   // through the select.
14468   if (LHS.getOpcode() != RHS.getOpcode() ||
14469       !LHS.hasOneUse() || !RHS.hasOneUse())
14470     return false;
14471 
14472   // If this is a load and the token chain is identical, replace the select
14473   // of two loads with a load through a select of the address to load from.
14474   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14475   // constants have been dropped into the constant pool.
14476   if (LHS.getOpcode() == ISD::LOAD) {
14477     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14478     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14479 
14480     // Token chains must be identical.
14481     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14482         // Do not let this transformation reduce the number of volatile loads.
14483         LLD->isVolatile() || RLD->isVolatile() ||
14484         // FIXME: If either is a pre/post inc/dec load,
14485         // we'd need to split out the address adjustment.
14486         LLD->isIndexed() || RLD->isIndexed() ||
14487         // If this is an EXTLOAD, the VT's must match.
14488         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14489         // If this is an EXTLOAD, the kind of extension must match.
14490         (LLD->getExtensionType() != RLD->getExtensionType() &&
14491          // The only exception is if one of the extensions is anyext.
14492          LLD->getExtensionType() != ISD::EXTLOAD &&
14493          RLD->getExtensionType() != ISD::EXTLOAD) ||
14494         // FIXME: this discards src value information.  This is
14495         // over-conservative. It would be beneficial to be able to remember
14496         // both potential memory locations.  Since we are discarding
14497         // src value info, don't do the transformation if the memory
14498         // locations are not in the default address space.
14499         LLD->getPointerInfo().getAddrSpace() != 0 ||
14500         RLD->getPointerInfo().getAddrSpace() != 0 ||
14501         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14502                                       LLD->getBasePtr().getValueType()))
14503       return false;
14504 
14505     // Check that the select condition doesn't reach either load.  If so,
14506     // folding this will induce a cycle into the DAG.  If not, this is safe to
14507     // xform, so create a select of the addresses.
14508     SDValue Addr;
14509     if (TheSelect->getOpcode() == ISD::SELECT) {
14510       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14511       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14512           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14513         return false;
14514       // The loads must not depend on one another.
14515       if (LLD->isPredecessorOf(RLD) ||
14516           RLD->isPredecessorOf(LLD))
14517         return false;
14518       Addr = DAG.getSelect(SDLoc(TheSelect),
14519                            LLD->getBasePtr().getValueType(),
14520                            TheSelect->getOperand(0), LLD->getBasePtr(),
14521                            RLD->getBasePtr());
14522     } else {  // Otherwise SELECT_CC
14523       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14524       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14525 
14526       if ((LLD->hasAnyUseOfValue(1) &&
14527            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14528           (RLD->hasAnyUseOfValue(1) &&
14529            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14530         return false;
14531 
14532       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14533                          LLD->getBasePtr().getValueType(),
14534                          TheSelect->getOperand(0),
14535                          TheSelect->getOperand(1),
14536                          LLD->getBasePtr(), RLD->getBasePtr(),
14537                          TheSelect->getOperand(4));
14538     }
14539 
14540     SDValue Load;
14541     // It is safe to replace the two loads if they have different alignments,
14542     // but the new load must be the minimum (most restrictive) alignment of the
14543     // inputs.
14544     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14545     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
14546     if (!RLD->isInvariant())
14547       MMOFlags &= ~MachineMemOperand::MOInvariant;
14548     if (!RLD->isDereferenceable())
14549       MMOFlags &= ~MachineMemOperand::MODereferenceable;
14550     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14551       // FIXME: Discards pointer and AA info.
14552       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
14553                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
14554                          MMOFlags);
14555     } else {
14556       // FIXME: Discards pointer and AA info.
14557       Load = DAG.getExtLoad(
14558           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
14559                                                   : LLD->getExtensionType(),
14560           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
14561           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
14562     }
14563 
14564     // Users of the select now use the result of the load.
14565     CombineTo(TheSelect, Load);
14566 
14567     // Users of the old loads now use the new load's chain.  We know the
14568     // old-load value is dead now.
14569     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14570     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14571     return true;
14572   }
14573 
14574   return false;
14575 }
14576 
14577 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
14578 /// bitwise 'and'.
14579 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
14580                                             SDValue N1, SDValue N2, SDValue N3,
14581                                             ISD::CondCode CC) {
14582   // Check to see if we can perform the "gzip trick", transforming
14583   // (select_cc setlt X, 0, A, 0) -> (and (sra X, size(X)-1), A)
14584   EVT XType = N0.getValueType();
14585   EVT AType = N2.getValueType();
14586   if (!isNullConstant(N3) || CC != ISD::SETLT || !XType.bitsGE(AType))
14587     return SDValue();
14588 
14589   // (a < 0) ? b : 0
14590   // (a < 1) ? a : 0
14591   if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
14592     return SDValue();
14593 
14594   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
14595   // constant.
14596   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
14597   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14598   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14599     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
14600     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
14601     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
14602     AddToWorklist(Shift.getNode());
14603 
14604     if (XType.bitsGT(AType)) {
14605       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14606       AddToWorklist(Shift.getNode());
14607     }
14608 
14609     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14610   }
14611 
14612   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
14613   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
14614   AddToWorklist(Shift.getNode());
14615 
14616   if (XType.bitsGT(AType)) {
14617     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14618     AddToWorklist(Shift.getNode());
14619   }
14620 
14621   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14622 }
14623 
14624 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14625 /// where 'cond' is the comparison specified by CC.
14626 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
14627                                       SDValue N2, SDValue N3, ISD::CondCode CC,
14628                                       bool NotExtCompare) {
14629   // (x ? y : y) -> y.
14630   if (N2 == N3) return N2;
14631 
14632   EVT VT = N2.getValueType();
14633   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14634   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14635 
14636   // Determine if the condition we're dealing with is constant
14637   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14638                               N0, N1, CC, DL, false);
14639   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14640 
14641   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14642     // fold select_cc true, x, y -> x
14643     // fold select_cc false, x, y -> y
14644     return !SCCC->isNullValue() ? N2 : N3;
14645   }
14646 
14647   // Check to see if we can simplify the select into an fabs node
14648   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14649     // Allow either -0.0 or 0.0
14650     if (CFP->isZero()) {
14651       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14652       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14653           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14654           N2 == N3.getOperand(0))
14655         return DAG.getNode(ISD::FABS, DL, VT, N0);
14656 
14657       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14658       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14659           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14660           N2.getOperand(0) == N3)
14661         return DAG.getNode(ISD::FABS, DL, VT, N3);
14662     }
14663   }
14664 
14665   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14666   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14667   // in it.  This is a win when the constant is not otherwise available because
14668   // it replaces two constant pool loads with one.  We only do this if the FP
14669   // type is known to be legal, because if it isn't, then we are before legalize
14670   // types an we want the other legalization to happen first (e.g. to avoid
14671   // messing with soft float) and if the ConstantFP is not legal, because if
14672   // it is legal, we may not need to store the FP constant in a constant pool.
14673   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14674     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14675       if (TLI.isTypeLegal(N2.getValueType()) &&
14676           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14677                TargetLowering::Legal &&
14678            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14679            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14680           // If both constants have multiple uses, then we won't need to do an
14681           // extra load, they are likely around in registers for other users.
14682           (TV->hasOneUse() || FV->hasOneUse())) {
14683         Constant *Elts[] = {
14684           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14685           const_cast<ConstantFP*>(TV->getConstantFPValue())
14686         };
14687         Type *FPTy = Elts[0]->getType();
14688         const DataLayout &TD = DAG.getDataLayout();
14689 
14690         // Create a ConstantArray of the two constants.
14691         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14692         SDValue CPIdx =
14693             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14694                                 TD.getPrefTypeAlignment(FPTy));
14695         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14696 
14697         // Get the offsets to the 0 and 1 element of the array so that we can
14698         // select between them.
14699         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14700         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14701         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14702 
14703         SDValue Cond = DAG.getSetCC(DL,
14704                                     getSetCCResultType(N0.getValueType()),
14705                                     N0, N1, CC);
14706         AddToWorklist(Cond.getNode());
14707         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14708                                           Cond, One, Zero);
14709         AddToWorklist(CstOffset.getNode());
14710         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14711                             CstOffset);
14712         AddToWorklist(CPIdx.getNode());
14713         return DAG.getLoad(
14714             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14715             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14716             Alignment);
14717       }
14718     }
14719 
14720   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
14721     return V;
14722 
14723   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14724   // where y is has a single bit set.
14725   // A plaintext description would be, we can turn the SELECT_CC into an AND
14726   // when the condition can be materialized as an all-ones register.  Any
14727   // single bit-test can be materialized as an all-ones register with
14728   // shift-left and shift-right-arith.
14729   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14730       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14731     SDValue AndLHS = N0->getOperand(0);
14732     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14733     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14734       // Shift the tested bit over the sign bit.
14735       const APInt &AndMask = ConstAndRHS->getAPIntValue();
14736       SDValue ShlAmt =
14737         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14738                         getShiftAmountTy(AndLHS.getValueType()));
14739       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14740 
14741       // Now arithmetic right shift it all the way over, so the result is either
14742       // all-ones, or zero.
14743       SDValue ShrAmt =
14744         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14745                         getShiftAmountTy(Shl.getValueType()));
14746       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14747 
14748       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14749     }
14750   }
14751 
14752   // fold select C, 16, 0 -> shl C, 4
14753   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14754       TLI.getBooleanContents(N0.getValueType()) ==
14755           TargetLowering::ZeroOrOneBooleanContent) {
14756 
14757     // If the caller doesn't want us to simplify this into a zext of a compare,
14758     // don't do it.
14759     if (NotExtCompare && N2C->isOne())
14760       return SDValue();
14761 
14762     // Get a SetCC of the condition
14763     // NOTE: Don't create a SETCC if it's not legal on this target.
14764     if (!LegalOperations ||
14765         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14766       SDValue Temp, SCC;
14767       // cast from setcc result type to select result type
14768       if (LegalTypes) {
14769         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14770                             N0, N1, CC);
14771         if (N2.getValueType().bitsLT(SCC.getValueType()))
14772           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14773                                         N2.getValueType());
14774         else
14775           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14776                              N2.getValueType(), SCC);
14777       } else {
14778         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14779         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14780                            N2.getValueType(), SCC);
14781       }
14782 
14783       AddToWorklist(SCC.getNode());
14784       AddToWorklist(Temp.getNode());
14785 
14786       if (N2C->isOne())
14787         return Temp;
14788 
14789       // shl setcc result by log2 n2c
14790       return DAG.getNode(
14791           ISD::SHL, DL, N2.getValueType(), Temp,
14792           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14793                           getShiftAmountTy(Temp.getValueType())));
14794     }
14795   }
14796 
14797   // Check to see if this is an integer abs.
14798   // select_cc setg[te] X,  0,  X, -X ->
14799   // select_cc setgt    X, -1,  X, -X ->
14800   // select_cc setl[te] X,  0, -X,  X ->
14801   // select_cc setlt    X,  1, -X,  X ->
14802   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14803   if (N1C) {
14804     ConstantSDNode *SubC = nullptr;
14805     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14806          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14807         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14808       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14809     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14810               (N1C->isOne() && CC == ISD::SETLT)) &&
14811              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14812       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14813 
14814     EVT XType = N0.getValueType();
14815     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14816       SDLoc DL(N0);
14817       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14818                                   N0,
14819                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14820                                          getShiftAmountTy(N0.getValueType())));
14821       SDValue Add = DAG.getNode(ISD::ADD, DL,
14822                                 XType, N0, Shift);
14823       AddToWorklist(Shift.getNode());
14824       AddToWorklist(Add.getNode());
14825       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14826     }
14827   }
14828 
14829   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14830   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14831   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14832   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14833   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14834   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14835   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14836   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14837   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14838     SDValue ValueOnZero = N2;
14839     SDValue Count = N3;
14840     // If the condition is NE instead of E, swap the operands.
14841     if (CC == ISD::SETNE)
14842       std::swap(ValueOnZero, Count);
14843     // Check if the value on zero is a constant equal to the bits in the type.
14844     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14845       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14846         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14847         // legal, combine to just cttz.
14848         if ((Count.getOpcode() == ISD::CTTZ ||
14849              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14850             N0 == Count.getOperand(0) &&
14851             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14852           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14853         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14854         // legal, combine to just ctlz.
14855         if ((Count.getOpcode() == ISD::CTLZ ||
14856              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14857             N0 == Count.getOperand(0) &&
14858             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14859           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14860       }
14861     }
14862   }
14863 
14864   return SDValue();
14865 }
14866 
14867 /// This is a stub for TargetLowering::SimplifySetCC.
14868 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
14869                                    ISD::CondCode Cond, const SDLoc &DL,
14870                                    bool foldBooleans) {
14871   TargetLowering::DAGCombinerInfo
14872     DagCombineInfo(DAG, Level, false, this);
14873   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14874 }
14875 
14876 /// Given an ISD::SDIV node expressing a divide by constant, return
14877 /// a DAG expression to select that will generate the same value by multiplying
14878 /// by a magic number.
14879 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14880 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14881   // when optimising for minimum size, we don't want to expand a div to a mul
14882   // and a shift.
14883   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14884     return SDValue();
14885 
14886   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14887   if (!C)
14888     return SDValue();
14889 
14890   // Avoid division by zero.
14891   if (C->isNullValue())
14892     return SDValue();
14893 
14894   std::vector<SDNode*> Built;
14895   SDValue S =
14896       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14897 
14898   for (SDNode *N : Built)
14899     AddToWorklist(N);
14900   return S;
14901 }
14902 
14903 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14904 /// DAG expression that will generate the same value by right shifting.
14905 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14906   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14907   if (!C)
14908     return SDValue();
14909 
14910   // Avoid division by zero.
14911   if (C->isNullValue())
14912     return SDValue();
14913 
14914   std::vector<SDNode *> Built;
14915   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14916 
14917   for (SDNode *N : Built)
14918     AddToWorklist(N);
14919   return S;
14920 }
14921 
14922 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14923 /// expression that will generate the same value by multiplying by a magic
14924 /// number.
14925 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14926 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14927   // when optimising for minimum size, we don't want to expand a div to a mul
14928   // and a shift.
14929   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14930     return SDValue();
14931 
14932   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14933   if (!C)
14934     return SDValue();
14935 
14936   // Avoid division by zero.
14937   if (C->isNullValue())
14938     return SDValue();
14939 
14940   std::vector<SDNode*> Built;
14941   SDValue S =
14942       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14943 
14944   for (SDNode *N : Built)
14945     AddToWorklist(N);
14946   return S;
14947 }
14948 
14949 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14950 /// For the reciprocal, we need to find the zero of the function:
14951 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
14952 ///     =>
14953 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14954 ///     does not require additional intermediate precision]
14955 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14956   if (Level >= AfterLegalizeDAG)
14957     return SDValue();
14958 
14959   // TODO: Handle half and/or extended types?
14960   EVT VT = Op.getValueType();
14961   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
14962     return SDValue();
14963 
14964   // If estimates are explicitly disabled for this function, we're done.
14965   MachineFunction &MF = DAG.getMachineFunction();
14966   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
14967   if (Enabled == TLI.ReciprocalEstimate::Disabled)
14968     return SDValue();
14969 
14970   // Estimates may be explicitly enabled for this type with a custom number of
14971   // refinement steps.
14972   int Iterations = TLI.getDivRefinementSteps(VT, MF);
14973   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
14974     AddToWorklist(Est.getNode());
14975 
14976     if (Iterations) {
14977       EVT VT = Op.getValueType();
14978       SDLoc DL(Op);
14979       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14980 
14981       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14982       for (int i = 0; i < Iterations; ++i) {
14983         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14984         AddToWorklist(NewEst.getNode());
14985 
14986         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14987         AddToWorklist(NewEst.getNode());
14988 
14989         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14990         AddToWorklist(NewEst.getNode());
14991 
14992         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14993         AddToWorklist(Est.getNode());
14994       }
14995     }
14996     return Est;
14997   }
14998 
14999   return SDValue();
15000 }
15001 
15002 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15003 /// For the reciprocal sqrt, we need to find the zero of the function:
15004 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15005 ///     =>
15006 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
15007 /// As a result, we precompute A/2 prior to the iteration loop.
15008 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
15009                                          unsigned Iterations,
15010                                          SDNodeFlags *Flags, bool Reciprocal) {
15011   EVT VT = Arg.getValueType();
15012   SDLoc DL(Arg);
15013   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
15014 
15015   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
15016   // this entire sequence requires only one FP constant.
15017   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
15018   AddToWorklist(HalfArg.getNode());
15019 
15020   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
15021   AddToWorklist(HalfArg.getNode());
15022 
15023   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
15024   for (unsigned i = 0; i < Iterations; ++i) {
15025     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
15026     AddToWorklist(NewEst.getNode());
15027 
15028     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
15029     AddToWorklist(NewEst.getNode());
15030 
15031     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
15032     AddToWorklist(NewEst.getNode());
15033 
15034     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15035     AddToWorklist(Est.getNode());
15036   }
15037 
15038   // If non-reciprocal square root is requested, multiply the result by Arg.
15039   if (!Reciprocal) {
15040     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
15041     AddToWorklist(Est.getNode());
15042   }
15043 
15044   return Est;
15045 }
15046 
15047 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15048 /// For the reciprocal sqrt, we need to find the zero of the function:
15049 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15050 ///     =>
15051 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
15052 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
15053                                          unsigned Iterations,
15054                                          SDNodeFlags *Flags, bool Reciprocal) {
15055   EVT VT = Arg.getValueType();
15056   SDLoc DL(Arg);
15057   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
15058   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
15059 
15060   // This routine must enter the loop below to work correctly
15061   // when (Reciprocal == false).
15062   assert(Iterations > 0);
15063 
15064   // Newton iterations for reciprocal square root:
15065   // E = (E * -0.5) * ((A * E) * E + -3.0)
15066   for (unsigned i = 0; i < Iterations; ++i) {
15067     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
15068     AddToWorklist(AE.getNode());
15069 
15070     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
15071     AddToWorklist(AEE.getNode());
15072 
15073     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
15074     AddToWorklist(RHS.getNode());
15075 
15076     // When calculating a square root at the last iteration build:
15077     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
15078     // (notice a common subexpression)
15079     SDValue LHS;
15080     if (Reciprocal || (i + 1) < Iterations) {
15081       // RSQRT: LHS = (E * -0.5)
15082       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
15083     } else {
15084       // SQRT: LHS = (A * E) * -0.5
15085       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
15086     }
15087     AddToWorklist(LHS.getNode());
15088 
15089     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
15090     AddToWorklist(Est.getNode());
15091   }
15092 
15093   return Est;
15094 }
15095 
15096 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
15097 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
15098 /// Op can be zero.
15099 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
15100                                            bool Reciprocal) {
15101   if (Level >= AfterLegalizeDAG)
15102     return SDValue();
15103 
15104   // TODO: Handle half and/or extended types?
15105   EVT VT = Op.getValueType();
15106   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15107     return SDValue();
15108 
15109   // If estimates are explicitly disabled for this function, we're done.
15110   MachineFunction &MF = DAG.getMachineFunction();
15111   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
15112   if (Enabled == TLI.ReciprocalEstimate::Disabled)
15113     return SDValue();
15114 
15115   // Estimates may be explicitly enabled for this type with a custom number of
15116   // refinement steps.
15117   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
15118 
15119   bool UseOneConstNR = false;
15120   if (SDValue Est =
15121       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
15122                           Reciprocal)) {
15123     AddToWorklist(Est.getNode());
15124 
15125     if (Iterations) {
15126       Est = UseOneConstNR
15127             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
15128             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
15129 
15130       if (!Reciprocal) {
15131         // Unfortunately, Est is now NaN if the input was exactly 0.0.
15132         // Select out this case and force the answer to 0.0.
15133         EVT VT = Op.getValueType();
15134         SDLoc DL(Op);
15135 
15136         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
15137         EVT CCVT = getSetCCResultType(VT);
15138         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
15139         AddToWorklist(ZeroCmp.getNode());
15140 
15141         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
15142                           ZeroCmp, FPZero, Est);
15143         AddToWorklist(Est.getNode());
15144       }
15145     }
15146     return Est;
15147   }
15148 
15149   return SDValue();
15150 }
15151 
15152 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15153   return buildSqrtEstimateImpl(Op, Flags, true);
15154 }
15155 
15156 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15157   return buildSqrtEstimateImpl(Op, Flags, false);
15158 }
15159 
15160 /// Return true if base is a frame index, which is known not to alias with
15161 /// anything but itself.  Provides base object and offset as results.
15162 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
15163                            const GlobalValue *&GV, const void *&CV) {
15164   // Assume it is a primitive operation.
15165   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
15166 
15167   // If it's an adding a simple constant then integrate the offset.
15168   if (Base.getOpcode() == ISD::ADD) {
15169     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
15170       Base = Base.getOperand(0);
15171       Offset += C->getZExtValue();
15172     }
15173   }
15174 
15175   // Return the underlying GlobalValue, and update the Offset.  Return false
15176   // for GlobalAddressSDNode since the same GlobalAddress may be represented
15177   // by multiple nodes with different offsets.
15178   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
15179     GV = G->getGlobal();
15180     Offset += G->getOffset();
15181     return false;
15182   }
15183 
15184   // Return the underlying Constant value, and update the Offset.  Return false
15185   // for ConstantSDNodes since the same constant pool entry may be represented
15186   // by multiple nodes with different offsets.
15187   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
15188     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
15189                                          : (const void *)C->getConstVal();
15190     Offset += C->getOffset();
15191     return false;
15192   }
15193   // If it's any of the following then it can't alias with anything but itself.
15194   return isa<FrameIndexSDNode>(Base);
15195 }
15196 
15197 /// Return true if there is any possibility that the two addresses overlap.
15198 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
15199   // If they are the same then they must be aliases.
15200   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
15201 
15202   // If they are both volatile then they cannot be reordered.
15203   if (Op0->isVolatile() && Op1->isVolatile()) return true;
15204 
15205   // If one operation reads from invariant memory, and the other may store, they
15206   // cannot alias. These should really be checking the equivalent of mayWrite,
15207   // but it only matters for memory nodes other than load /store.
15208   if (Op0->isInvariant() && Op1->writeMem())
15209     return false;
15210 
15211   if (Op1->isInvariant() && Op0->writeMem())
15212     return false;
15213 
15214   // Gather base node and offset information.
15215   SDValue Base1, Base2;
15216   int64_t Offset1, Offset2;
15217   const GlobalValue *GV1, *GV2;
15218   const void *CV1, *CV2;
15219   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
15220                                       Base1, Offset1, GV1, CV1);
15221   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
15222                                       Base2, Offset2, GV2, CV2);
15223 
15224   // If they have a same base address then check to see if they overlap.
15225   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
15226     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15227              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15228 
15229   // It is possible for different frame indices to alias each other, mostly
15230   // when tail call optimization reuses return address slots for arguments.
15231   // To catch this case, look up the actual index of frame indices to compute
15232   // the real alias relationship.
15233   if (isFrameIndex1 && isFrameIndex2) {
15234     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
15235     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
15236     Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
15237     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15238              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15239   }
15240 
15241   // Otherwise, if we know what the bases are, and they aren't identical, then
15242   // we know they cannot alias.
15243   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
15244     return false;
15245 
15246   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
15247   // compared to the size and offset of the access, we may be able to prove they
15248   // do not alias.  This check is conservative for now to catch cases created by
15249   // splitting vector types.
15250   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
15251       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
15252       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
15253        Op1->getMemoryVT().getSizeInBits() >> 3) &&
15254       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
15255     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
15256     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
15257 
15258     // There is no overlap between these relatively aligned accesses of similar
15259     // size, return no alias.
15260     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
15261         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
15262       return false;
15263   }
15264 
15265   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
15266                    ? CombinerGlobalAA
15267                    : DAG.getSubtarget().useAA();
15268 #ifndef NDEBUG
15269   if (CombinerAAOnlyFunc.getNumOccurrences() &&
15270       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
15271     UseAA = false;
15272 #endif
15273   if (UseAA &&
15274       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
15275     // Use alias analysis information.
15276     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
15277                                  Op1->getSrcValueOffset());
15278     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
15279         Op0->getSrcValueOffset() - MinOffset;
15280     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
15281         Op1->getSrcValueOffset() - MinOffset;
15282     AliasResult AAResult =
15283         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
15284                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
15285                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
15286                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
15287     if (AAResult == NoAlias)
15288       return false;
15289   }
15290 
15291   // Otherwise we have to assume they alias.
15292   return true;
15293 }
15294 
15295 /// Walk up chain skipping non-aliasing memory nodes,
15296 /// looking for aliasing nodes and adding them to the Aliases vector.
15297 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
15298                                    SmallVectorImpl<SDValue> &Aliases) {
15299   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
15300   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
15301 
15302   // Get alias information for node.
15303   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
15304 
15305   // Starting off.
15306   Chains.push_back(OriginalChain);
15307   unsigned Depth = 0;
15308 
15309   // Look at each chain and determine if it is an alias.  If so, add it to the
15310   // aliases list.  If not, then continue up the chain looking for the next
15311   // candidate.
15312   while (!Chains.empty()) {
15313     SDValue Chain = Chains.pop_back_val();
15314 
15315     // For TokenFactor nodes, look at each operand and only continue up the
15316     // chain until we reach the depth limit.
15317     //
15318     // FIXME: The depth check could be made to return the last non-aliasing
15319     // chain we found before we hit a tokenfactor rather than the original
15320     // chain.
15321     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
15322       Aliases.clear();
15323       Aliases.push_back(OriginalChain);
15324       return;
15325     }
15326 
15327     // Don't bother if we've been before.
15328     if (!Visited.insert(Chain.getNode()).second)
15329       continue;
15330 
15331     switch (Chain.getOpcode()) {
15332     case ISD::EntryToken:
15333       // Entry token is ideal chain operand, but handled in FindBetterChain.
15334       break;
15335 
15336     case ISD::LOAD:
15337     case ISD::STORE: {
15338       // Get alias information for Chain.
15339       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
15340           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
15341 
15342       // If chain is alias then stop here.
15343       if (!(IsLoad && IsOpLoad) &&
15344           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
15345         Aliases.push_back(Chain);
15346       } else {
15347         // Look further up the chain.
15348         Chains.push_back(Chain.getOperand(0));
15349         ++Depth;
15350       }
15351       break;
15352     }
15353 
15354     case ISD::TokenFactor:
15355       // We have to check each of the operands of the token factor for "small"
15356       // token factors, so we queue them up.  Adding the operands to the queue
15357       // (stack) in reverse order maintains the original order and increases the
15358       // likelihood that getNode will find a matching token factor (CSE.)
15359       if (Chain.getNumOperands() > 16) {
15360         Aliases.push_back(Chain);
15361         break;
15362       }
15363       for (unsigned n = Chain.getNumOperands(); n;)
15364         Chains.push_back(Chain.getOperand(--n));
15365       ++Depth;
15366       break;
15367 
15368     default:
15369       // For all other instructions we will just have to take what we can get.
15370       Aliases.push_back(Chain);
15371       break;
15372     }
15373   }
15374 }
15375 
15376 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
15377 /// (aliasing node.)
15378 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
15379   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
15380 
15381   // Accumulate all the aliases to this node.
15382   GatherAllAliases(N, OldChain, Aliases);
15383 
15384   // If no operands then chain to entry token.
15385   if (Aliases.size() == 0)
15386     return DAG.getEntryNode();
15387 
15388   // If a single operand then chain to it.  We don't need to revisit it.
15389   if (Aliases.size() == 1)
15390     return Aliases[0];
15391 
15392   // Construct a custom tailored token factor.
15393   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
15394 }
15395 
15396 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
15397   // This holds the base pointer, index, and the offset in bytes from the base
15398   // pointer.
15399   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
15400 
15401   // We must have a base and an offset.
15402   if (!BasePtr.Base.getNode())
15403     return false;
15404 
15405   // Do not handle stores to undef base pointers.
15406   if (BasePtr.Base.isUndef())
15407     return false;
15408 
15409   SmallVector<StoreSDNode *, 8> ChainedStores;
15410   ChainedStores.push_back(St);
15411 
15412   // Walk up the chain and look for nodes with offsets from the same
15413   // base pointer. Stop when reaching an instruction with a different kind
15414   // or instruction which has a different base pointer.
15415   StoreSDNode *Index = St;
15416   while (Index) {
15417     // If the chain has more than one use, then we can't reorder the mem ops.
15418     if (Index != St && !SDValue(Index, 0)->hasOneUse())
15419       break;
15420 
15421     if (Index->isVolatile() || Index->isIndexed())
15422       break;
15423 
15424     // Find the base pointer and offset for this memory node.
15425     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
15426 
15427     // Check that the base pointer is the same as the original one.
15428     if (!Ptr.equalBaseIndex(BasePtr))
15429       break;
15430 
15431     // Find the next memory operand in the chain. If the next operand in the
15432     // chain is a store then move up and continue the scan with the next
15433     // memory operand. If the next operand is a load save it and use alias
15434     // information to check if it interferes with anything.
15435     SDNode *NextInChain = Index->getChain().getNode();
15436     while (true) {
15437       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
15438         // We found a store node. Use it for the next iteration.
15439         if (STn->isVolatile() || STn->isIndexed()) {
15440           Index = nullptr;
15441           break;
15442         }
15443         ChainedStores.push_back(STn);
15444         Index = STn;
15445         break;
15446       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
15447         NextInChain = Ldn->getChain().getNode();
15448         continue;
15449       } else {
15450         Index = nullptr;
15451         break;
15452       }
15453     }
15454   }
15455 
15456   bool MadeChangeToSt = false;
15457   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
15458 
15459   for (StoreSDNode *ChainedStore : ChainedStores) {
15460     SDValue Chain = ChainedStore->getChain();
15461     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15462 
15463     if (Chain != BetterChain) {
15464       if (ChainedStore == St)
15465         MadeChangeToSt = true;
15466       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15467     }
15468   }
15469 
15470   // Do all replacements after finding the replacements to make to avoid making
15471   // the chains more complicated by introducing new TokenFactors.
15472   for (auto Replacement : BetterChains)
15473     replaceStoreChain(Replacement.first, Replacement.second);
15474 
15475   return MadeChangeToSt;
15476 }
15477 
15478 /// This is the entry point for the file.
15479 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15480                            CodeGenOpt::Level OptLevel) {
15481   /// This is the main entry point to this class.
15482   DAGCombiner(*this, AA, OptLevel).Run(Level);
15483 }
15484