1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
29 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/KnownBits.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
44 #include <algorithm>
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "dagcombine"
48 
49 STATISTIC(NodesCombined   , "Number of dag nodes combined");
50 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
51 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
52 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
53 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
54 STATISTIC(SlicedLoads, "Number of load sliced");
55 
56 namespace {
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60 
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64 
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71 
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79 
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83 
84 //------------------------------ DAGCombiner ---------------------------------//
85 
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94 
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103 
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110 
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 32> CombinedNodes;
116 
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis *AA;
119 
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126 
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129 
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       assert(N->getOpcode() != ISD::DELETED_NODE &&
135              "Deleted Node added to Worklist");
136 
137       // Skip handle nodes as they can't usefully be combined and confuse the
138       // zero-use deletion strategy.
139       if (N->getOpcode() == ISD::HANDLENODE)
140         return;
141 
142       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
143         Worklist.push_back(N);
144     }
145 
146     /// Remove all instances of N from the worklist.
147     void removeFromWorklist(SDNode *N) {
148       CombinedNodes.erase(N);
149 
150       auto It = WorklistMap.find(N);
151       if (It == WorklistMap.end())
152         return; // Not in the worklist.
153 
154       // Null out the entry rather than erasing it to avoid a linear operation.
155       Worklist[It->second] = nullptr;
156       WorklistMap.erase(It);
157     }
158 
159     void deleteAndRecombine(SDNode *N);
160     bool recursivelyDeleteUnusedNodes(SDNode *N);
161 
162     /// Replaces all uses of the results of one DAG node with new values.
163     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
164                       bool AddTo = true);
165 
166     /// Replaces all uses of the results of one DAG node with new values.
167     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
168       return CombineTo(N, &Res, 1, AddTo);
169     }
170 
171     /// Replaces all uses of the results of one DAG node with new values.
172     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
173                       bool AddTo = true) {
174       SDValue To[] = { Res0, Res1 };
175       return CombineTo(N, To, 2, AddTo);
176     }
177 
178     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
179 
180   private:
181     unsigned MaximumLegalStoreInBits;
182 
183     /// Check the specified integer node value to see if it can be simplified or
184     /// if things it uses can be simplified by bit propagation.
185     /// If so, return true.
186     bool SimplifyDemandedBits(SDValue Op) {
187       unsigned BitWidth = Op.getScalarValueSizeInBits();
188       APInt Demanded = APInt::getAllOnesValue(BitWidth);
189       return SimplifyDemandedBits(Op, Demanded);
190     }
191 
192     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
193 
194     bool CombineToPreIndexedLoadStore(SDNode *N);
195     bool CombineToPostIndexedLoadStore(SDNode *N);
196     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
197     bool SliceUpLoad(SDNode *N);
198 
199     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
200     ///   load.
201     ///
202     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
203     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
204     /// \param EltNo index of the vector element to load.
205     /// \param OriginalLoad load that EVE came from to be replaced.
206     /// \returns EVE on success SDValue() on failure.
207     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
208         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
209     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
210     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
211     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
212     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
213     SDValue PromoteIntBinOp(SDValue Op);
214     SDValue PromoteIntShiftOp(SDValue Op);
215     SDValue PromoteExtend(SDValue Op);
216     bool PromoteLoad(SDValue Op);
217 
218     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
219                          SDValue ExtLoad, const SDLoc &DL,
220                          ISD::NodeType ExtType);
221 
222     /// Call the node-specific routine that knows how to fold each
223     /// particular type of node. If that doesn't do anything, try the
224     /// target-specific DAG combines.
225     SDValue combine(SDNode *N);
226 
227     // Visitation implementation - Implement dag node combining for different
228     // node types.  The semantics are as follows:
229     // Return Value:
230     //   SDValue.getNode() == 0 - No change was made
231     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
232     //   otherwise              - N should be replaced by the returned Operand.
233     //
234     SDValue visitTokenFactor(SDNode *N);
235     SDValue visitMERGE_VALUES(SDNode *N);
236     SDValue visitADD(SDNode *N);
237     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
238     SDValue visitSUB(SDNode *N);
239     SDValue visitADDC(SDNode *N);
240     SDValue visitUADDO(SDNode *N);
241     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
242     SDValue visitSUBC(SDNode *N);
243     SDValue visitUSUBO(SDNode *N);
244     SDValue visitADDE(SDNode *N);
245     SDValue visitADDCARRY(SDNode *N);
246     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
247     SDValue visitSUBE(SDNode *N);
248     SDValue visitSUBCARRY(SDNode *N);
249     SDValue visitMUL(SDNode *N);
250     SDValue useDivRem(SDNode *N);
251     SDValue visitSDIV(SDNode *N);
252     SDValue visitUDIV(SDNode *N);
253     SDValue visitREM(SDNode *N);
254     SDValue visitMULHU(SDNode *N);
255     SDValue visitMULHS(SDNode *N);
256     SDValue visitSMUL_LOHI(SDNode *N);
257     SDValue visitUMUL_LOHI(SDNode *N);
258     SDValue visitSMULO(SDNode *N);
259     SDValue visitUMULO(SDNode *N);
260     SDValue visitIMINMAX(SDNode *N);
261     SDValue visitAND(SDNode *N);
262     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
263     SDValue visitOR(SDNode *N);
264     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
265     SDValue visitXOR(SDNode *N);
266     SDValue SimplifyVBinOp(SDNode *N);
267     SDValue visitSHL(SDNode *N);
268     SDValue visitSRA(SDNode *N);
269     SDValue visitSRL(SDNode *N);
270     SDValue visitRotate(SDNode *N);
271     SDValue visitABS(SDNode *N);
272     SDValue visitBSWAP(SDNode *N);
273     SDValue visitBITREVERSE(SDNode *N);
274     SDValue visitCTLZ(SDNode *N);
275     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
276     SDValue visitCTTZ(SDNode *N);
277     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
278     SDValue visitCTPOP(SDNode *N);
279     SDValue visitSELECT(SDNode *N);
280     SDValue visitVSELECT(SDNode *N);
281     SDValue visitSELECT_CC(SDNode *N);
282     SDValue visitSETCC(SDNode *N);
283     SDValue visitSETCCE(SDNode *N);
284     SDValue visitSETCCCARRY(SDNode *N);
285     SDValue visitSIGN_EXTEND(SDNode *N);
286     SDValue visitZERO_EXTEND(SDNode *N);
287     SDValue visitANY_EXTEND(SDNode *N);
288     SDValue visitAssertZext(SDNode *N);
289     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
290     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
291     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
292     SDValue visitTRUNCATE(SDNode *N);
293     SDValue visitBITCAST(SDNode *N);
294     SDValue visitBUILD_PAIR(SDNode *N);
295     SDValue visitFADD(SDNode *N);
296     SDValue visitFSUB(SDNode *N);
297     SDValue visitFMUL(SDNode *N);
298     SDValue visitFMA(SDNode *N);
299     SDValue visitFDIV(SDNode *N);
300     SDValue visitFREM(SDNode *N);
301     SDValue visitFSQRT(SDNode *N);
302     SDValue visitFCOPYSIGN(SDNode *N);
303     SDValue visitSINT_TO_FP(SDNode *N);
304     SDValue visitUINT_TO_FP(SDNode *N);
305     SDValue visitFP_TO_SINT(SDNode *N);
306     SDValue visitFP_TO_UINT(SDNode *N);
307     SDValue visitFP_ROUND(SDNode *N);
308     SDValue visitFP_ROUND_INREG(SDNode *N);
309     SDValue visitFP_EXTEND(SDNode *N);
310     SDValue visitFNEG(SDNode *N);
311     SDValue visitFABS(SDNode *N);
312     SDValue visitFCEIL(SDNode *N);
313     SDValue visitFTRUNC(SDNode *N);
314     SDValue visitFFLOOR(SDNode *N);
315     SDValue visitFMINNUM(SDNode *N);
316     SDValue visitFMAXNUM(SDNode *N);
317     SDValue visitBRCOND(SDNode *N);
318     SDValue visitBR_CC(SDNode *N);
319     SDValue visitLOAD(SDNode *N);
320 
321     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
322     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
323 
324     SDValue visitSTORE(SDNode *N);
325     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
326     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
327     SDValue visitBUILD_VECTOR(SDNode *N);
328     SDValue visitCONCAT_VECTORS(SDNode *N);
329     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
330     SDValue visitVECTOR_SHUFFLE(SDNode *N);
331     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
332     SDValue visitINSERT_SUBVECTOR(SDNode *N);
333     SDValue visitMLOAD(SDNode *N);
334     SDValue visitMSTORE(SDNode *N);
335     SDValue visitMGATHER(SDNode *N);
336     SDValue visitMSCATTER(SDNode *N);
337     SDValue visitFP_TO_FP16(SDNode *N);
338     SDValue visitFP16_TO_FP(SDNode *N);
339 
340     SDValue visitFADDForFMACombine(SDNode *N);
341     SDValue visitFSUBForFMACombine(SDNode *N);
342     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
343 
344     SDValue XformToShuffleWithZero(SDNode *N);
345     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
346                            SDValue RHS);
347 
348     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
349 
350     SDValue foldSelectOfConstants(SDNode *N);
351     SDValue foldVSelectOfConstants(SDNode *N);
352     SDValue foldBinOpIntoSelect(SDNode *BO);
353     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
354     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
355     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
356     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
357                              SDValue N2, SDValue N3, ISD::CondCode CC,
358                              bool NotExtCompare = false);
359     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
360                                    SDValue N2, SDValue N3, ISD::CondCode CC);
361     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
362                               const SDLoc &DL);
363     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
364                           const SDLoc &DL, bool foldBooleans = true);
365 
366     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
367                            SDValue &CC) const;
368     bool isOneUseSetCC(SDValue N) const;
369 
370     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
371                                          unsigned HiOp);
372     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
373     SDValue CombineExtLoad(SDNode *N);
374     SDValue combineRepeatedFPDivisors(SDNode *N);
375     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
376     SDValue BuildSDIV(SDNode *N);
377     SDValue BuildSDIVPow2(SDNode *N);
378     SDValue BuildUDIV(SDNode *N);
379     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
380     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
381     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
382     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
383     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
384     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
385                                 SDNodeFlags Flags, bool Reciprocal);
386     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
387                                 SDNodeFlags Flags, bool Reciprocal);
388     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
389                                bool DemandHighBits = true);
390     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
391     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
392                               SDValue InnerPos, SDValue InnerNeg,
393                               unsigned PosOpcode, unsigned NegOpcode,
394                               const SDLoc &DL);
395     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
396     SDValue MatchLoadCombine(SDNode *N);
397     SDValue ReduceLoadWidth(SDNode *N);
398     SDValue ReduceLoadOpStoreWidth(SDNode *N);
399     SDValue splitMergedValStore(StoreSDNode *ST);
400     SDValue TransformFPLoadStorePair(SDNode *N);
401     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
402     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
403     SDValue reduceBuildVecToShuffle(SDNode *N);
404     SDValue reduceBuildVecToTrunc(SDNode *N);
405     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
406                                   ArrayRef<int> VectorMask, SDValue VecIn1,
407                                   SDValue VecIn2, unsigned LeftIdx);
408     SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
409 
410     /// Walk up chain skipping non-aliasing memory nodes,
411     /// looking for aliasing nodes and adding them to the Aliases vector.
412     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
413                           SmallVectorImpl<SDValue> &Aliases);
414 
415     /// Return true if there is any possibility that the two addresses overlap.
416     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
417 
418     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
419     /// chain (aliasing node.)
420     SDValue FindBetterChain(SDNode *N, SDValue Chain);
421 
422     /// Try to replace a store and any possibly adjacent stores on
423     /// consecutive chains with better chains. Return true only if St is
424     /// replaced.
425     ///
426     /// Notice that other chains may still be replaced even if the function
427     /// returns false.
428     bool findBetterNeighborChains(StoreSDNode *St);
429 
430     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
431     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
432 
433     /// Holds a pointer to an LSBaseSDNode as well as information on where it
434     /// is located in a sequence of memory operations connected by a chain.
435     struct MemOpLink {
436       MemOpLink(LSBaseSDNode *N, int64_t Offset)
437           : MemNode(N), OffsetFromBase(Offset) {}
438       // Ptr to the mem node.
439       LSBaseSDNode *MemNode;
440       // Offset from the base ptr.
441       int64_t OffsetFromBase;
442     };
443 
444     /// This is a helper function for visitMUL to check the profitability
445     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
446     /// MulNode is the original multiply, AddNode is (add x, c1),
447     /// and ConstNode is c2.
448     bool isMulAddWithConstProfitable(SDNode *MulNode,
449                                      SDValue &AddNode,
450                                      SDValue &ConstNode);
451 
452 
453     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
454     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
455     /// the type of the loaded value to be extended.  LoadedVT returns the type
456     /// of the original loaded value.  NarrowLoad returns whether the load would
457     /// need to be narrowed in order to match.
458     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
459                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
460                           bool &NarrowLoad);
461 
462     /// Helper function for MergeConsecutiveStores which merges the
463     /// component store chains.
464     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
465                                 unsigned NumStores);
466 
467     /// This is a helper function for MergeConsecutiveStores. When the
468     /// source elements of the consecutive stores are all constants or
469     /// all extracted vector elements, try to merge them into one
470     /// larger store introducing bitcasts if necessary.  \return True
471     /// if a merged store was created.
472     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
473                                          EVT MemVT, unsigned NumStores,
474                                          bool IsConstantSrc, bool UseVector,
475                                          bool UseTrunc);
476 
477     /// This is a helper function for MergeConsecutiveStores. Stores
478     /// that potentially may be merged with St are placed in
479     /// StoreNodes.
480     void getStoreMergeCandidates(StoreSDNode *St,
481                                  SmallVectorImpl<MemOpLink> &StoreNodes);
482 
483     /// Helper function for MergeConsecutiveStores. Checks if
484     /// candidate stores have indirect dependency through their
485     /// operands. \return True if safe to merge.
486     bool checkMergeStoreCandidatesForDependencies(
487         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
488 
489     /// Merge consecutive store operations into a wide store.
490     /// This optimization uses wide integers or vectors when possible.
491     /// \return number of stores that were merged into a merged store (the
492     /// affected nodes are stored as a prefix in \p StoreNodes).
493     bool MergeConsecutiveStores(StoreSDNode *N);
494 
495     /// \brief Try to transform a truncation where C is a constant:
496     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
497     ///
498     /// \p N needs to be a truncation and its first operand an AND. Other
499     /// requirements are checked by the function (e.g. that trunc is
500     /// single-use) and if missed an empty SDValue is returned.
501     SDValue distributeTruncateThroughAnd(SDNode *N);
502 
503   public:
504     DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
505         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
506           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(AA) {
507       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
508 
509       MaximumLegalStoreInBits = 0;
510       for (MVT VT : MVT::all_valuetypes())
511         if (EVT(VT).isSimple() && VT != MVT::Other &&
512             TLI.isTypeLegal(EVT(VT)) &&
513             VT.getSizeInBits() >= MaximumLegalStoreInBits)
514           MaximumLegalStoreInBits = VT.getSizeInBits();
515     }
516 
517     /// Runs the dag combiner on all nodes in the work list
518     void Run(CombineLevel AtLevel);
519 
520     SelectionDAG &getDAG() const { return DAG; }
521 
522     /// Returns a type large enough to hold any valid shift amount - before type
523     /// legalization these can be huge.
524     EVT getShiftAmountTy(EVT LHSTy) {
525       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
526       if (LHSTy.isVector())
527         return LHSTy;
528       auto &DL = DAG.getDataLayout();
529       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
530                         : TLI.getPointerTy(DL);
531     }
532 
533     /// This method returns true if we are running before type legalization or
534     /// if the specified VT is legal.
535     bool isTypeLegal(const EVT &VT) {
536       if (!LegalTypes) return true;
537       return TLI.isTypeLegal(VT);
538     }
539 
540     /// Convenience wrapper around TargetLowering::getSetCCResultType
541     EVT getSetCCResultType(EVT VT) const {
542       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
543     }
544   };
545 }
546 
547 
548 namespace {
549 /// This class is a DAGUpdateListener that removes any deleted
550 /// nodes from the worklist.
551 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
552   DAGCombiner &DC;
553 public:
554   explicit WorklistRemover(DAGCombiner &dc)
555     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
556 
557   void NodeDeleted(SDNode *N, SDNode *E) override {
558     DC.removeFromWorklist(N);
559   }
560 };
561 }
562 
563 //===----------------------------------------------------------------------===//
564 //  TargetLowering::DAGCombinerInfo implementation
565 //===----------------------------------------------------------------------===//
566 
567 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
568   ((DAGCombiner*)DC)->AddToWorklist(N);
569 }
570 
571 SDValue TargetLowering::DAGCombinerInfo::
572 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
573   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
574 }
575 
576 SDValue TargetLowering::DAGCombinerInfo::
577 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
578   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
579 }
580 
581 
582 SDValue TargetLowering::DAGCombinerInfo::
583 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
584   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
585 }
586 
587 void TargetLowering::DAGCombinerInfo::
588 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
589   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
590 }
591 
592 //===----------------------------------------------------------------------===//
593 // Helper Functions
594 //===----------------------------------------------------------------------===//
595 
596 void DAGCombiner::deleteAndRecombine(SDNode *N) {
597   removeFromWorklist(N);
598 
599   // If the operands of this node are only used by the node, they will now be
600   // dead. Make sure to re-visit them and recursively delete dead nodes.
601   for (const SDValue &Op : N->ops())
602     // For an operand generating multiple values, one of the values may
603     // become dead allowing further simplification (e.g. split index
604     // arithmetic from an indexed load).
605     if (Op->hasOneUse() || Op->getNumValues() > 1)
606       AddToWorklist(Op.getNode());
607 
608   DAG.DeleteNode(N);
609 }
610 
611 /// Return 1 if we can compute the negated form of the specified expression for
612 /// the same cost as the expression itself, or 2 if we can compute the negated
613 /// form more cheaply than the expression itself.
614 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
615                                const TargetLowering &TLI,
616                                const TargetOptions *Options,
617                                unsigned Depth = 0) {
618   // fneg is removable even if it has multiple uses.
619   if (Op.getOpcode() == ISD::FNEG) return 2;
620 
621   // Don't allow anything with multiple uses.
622   if (!Op.hasOneUse()) return 0;
623 
624   // Don't recurse exponentially.
625   if (Depth > 6) return 0;
626 
627   switch (Op.getOpcode()) {
628   default: return false;
629   case ISD::ConstantFP: {
630     if (!LegalOperations)
631       return 1;
632 
633     // Don't invert constant FP values after legalization unless the target says
634     // the negated constant is legal.
635     EVT VT = Op.getValueType();
636     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
637       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
638   }
639   case ISD::FADD:
640     // FIXME: determine better conditions for this xform.
641     if (!Options->UnsafeFPMath) return 0;
642 
643     // After operation legalization, it might not be legal to create new FSUBs.
644     if (LegalOperations &&
645         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
646       return 0;
647 
648     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
649     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
650                                     Options, Depth + 1))
651       return V;
652     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
653     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
654                               Depth + 1);
655   case ISD::FSUB:
656     // We can't turn -(A-B) into B-A when we honor signed zeros.
657     if (!Options->NoSignedZerosFPMath &&
658         !Op.getNode()->getFlags().hasNoSignedZeros())
659       return 0;
660 
661     // fold (fneg (fsub A, B)) -> (fsub B, A)
662     return 1;
663 
664   case ISD::FMUL:
665   case ISD::FDIV:
666     if (Options->HonorSignDependentRoundingFPMath()) return 0;
667 
668     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
669     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
670                                     Options, Depth + 1))
671       return V;
672 
673     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
674                               Depth + 1);
675 
676   case ISD::FP_EXTEND:
677   case ISD::FP_ROUND:
678   case ISD::FSIN:
679     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
680                               Depth + 1);
681   }
682 }
683 
684 /// If isNegatibleForFree returns true, return the newly negated expression.
685 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
686                                     bool LegalOperations, unsigned Depth = 0) {
687   const TargetOptions &Options = DAG.getTarget().Options;
688   // fneg is removable even if it has multiple uses.
689   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
690 
691   // Don't allow anything with multiple uses.
692   assert(Op.hasOneUse() && "Unknown reuse!");
693 
694   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
695 
696   const SDNodeFlags Flags = Op.getNode()->getFlags();
697 
698   switch (Op.getOpcode()) {
699   default: llvm_unreachable("Unknown code");
700   case ISD::ConstantFP: {
701     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
702     V.changeSign();
703     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
704   }
705   case ISD::FADD:
706     // FIXME: determine better conditions for this xform.
707     assert(Options.UnsafeFPMath);
708 
709     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
710     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
711                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
712       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
713                          GetNegatedExpression(Op.getOperand(0), DAG,
714                                               LegalOperations, Depth+1),
715                          Op.getOperand(1), Flags);
716     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
717     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
718                        GetNegatedExpression(Op.getOperand(1), DAG,
719                                             LegalOperations, Depth+1),
720                        Op.getOperand(0), Flags);
721   case ISD::FSUB:
722     // fold (fneg (fsub 0, B)) -> B
723     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
724       if (N0CFP->isZero())
725         return Op.getOperand(1);
726 
727     // fold (fneg (fsub A, B)) -> (fsub B, A)
728     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
729                        Op.getOperand(1), Op.getOperand(0), Flags);
730 
731   case ISD::FMUL:
732   case ISD::FDIV:
733     assert(!Options.HonorSignDependentRoundingFPMath());
734 
735     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
736     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
737                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
738       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
739                          GetNegatedExpression(Op.getOperand(0), DAG,
740                                               LegalOperations, Depth+1),
741                          Op.getOperand(1), Flags);
742 
743     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
744     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
745                        Op.getOperand(0),
746                        GetNegatedExpression(Op.getOperand(1), DAG,
747                                             LegalOperations, Depth+1), Flags);
748 
749   case ISD::FP_EXTEND:
750   case ISD::FSIN:
751     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
752                        GetNegatedExpression(Op.getOperand(0), DAG,
753                                             LegalOperations, Depth+1));
754   case ISD::FP_ROUND:
755       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
756                          GetNegatedExpression(Op.getOperand(0), DAG,
757                                               LegalOperations, Depth+1),
758                          Op.getOperand(1));
759   }
760 }
761 
762 // APInts must be the same size for most operations, this helper
763 // function zero extends the shorter of the pair so that they match.
764 // We provide an Offset so that we can create bitwidths that won't overflow.
765 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
766   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
767   LHS = LHS.zextOrSelf(Bits);
768   RHS = RHS.zextOrSelf(Bits);
769 }
770 
771 // Return true if this node is a setcc, or is a select_cc
772 // that selects between the target values used for true and false, making it
773 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
774 // the appropriate nodes based on the type of node we are checking. This
775 // simplifies life a bit for the callers.
776 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
777                                     SDValue &CC) const {
778   if (N.getOpcode() == ISD::SETCC) {
779     LHS = N.getOperand(0);
780     RHS = N.getOperand(1);
781     CC  = N.getOperand(2);
782     return true;
783   }
784 
785   if (N.getOpcode() != ISD::SELECT_CC ||
786       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
787       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
788     return false;
789 
790   if (TLI.getBooleanContents(N.getValueType()) ==
791       TargetLowering::UndefinedBooleanContent)
792     return false;
793 
794   LHS = N.getOperand(0);
795   RHS = N.getOperand(1);
796   CC  = N.getOperand(4);
797   return true;
798 }
799 
800 /// Return true if this is a SetCC-equivalent operation with only one use.
801 /// If this is true, it allows the users to invert the operation for free when
802 /// it is profitable to do so.
803 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
804   SDValue N0, N1, N2;
805   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
806     return true;
807   return false;
808 }
809 
810 // \brief Returns the SDNode if it is a constant float BuildVector
811 // or constant float.
812 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
813   if (isa<ConstantFPSDNode>(N))
814     return N.getNode();
815   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
816     return N.getNode();
817   return nullptr;
818 }
819 
820 // Determines if it is a constant integer or a build vector of constant
821 // integers (and undefs).
822 // Do not permit build vector implicit truncation.
823 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
824   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
825     return !(Const->isOpaque() && NoOpaques);
826   if (N.getOpcode() != ISD::BUILD_VECTOR)
827     return false;
828   unsigned BitWidth = N.getScalarValueSizeInBits();
829   for (const SDValue &Op : N->op_values()) {
830     if (Op.isUndef())
831       continue;
832     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
833     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
834         (Const->isOpaque() && NoOpaques))
835       return false;
836   }
837   return true;
838 }
839 
840 // Determines if it is a constant null integer or a splatted vector of a
841 // constant null integer (with no undefs).
842 // Build vector implicit truncation is not an issue for null values.
843 static bool isNullConstantOrNullSplatConstant(SDValue N) {
844   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
845     return Splat->isNullValue();
846   return false;
847 }
848 
849 // Determines if it is a constant integer of one or a splatted vector of a
850 // constant integer of one (with no undefs).
851 // Do not permit build vector implicit truncation.
852 static bool isOneConstantOrOneSplatConstant(SDValue N) {
853   unsigned BitWidth = N.getScalarValueSizeInBits();
854   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
855     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
856   return false;
857 }
858 
859 // Determines if it is a constant integer of all ones or a splatted vector of a
860 // constant integer of all ones (with no undefs).
861 // Do not permit build vector implicit truncation.
862 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
863   unsigned BitWidth = N.getScalarValueSizeInBits();
864   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
865     return Splat->isAllOnesValue() &&
866            Splat->getAPIntValue().getBitWidth() == BitWidth;
867   return false;
868 }
869 
870 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
871 // undef's.
872 static bool isAnyConstantBuildVector(const SDNode *N) {
873   return ISD::isBuildVectorOfConstantSDNodes(N) ||
874          ISD::isBuildVectorOfConstantFPSDNodes(N);
875 }
876 
877 // Attempt to match a unary predicate against a scalar/splat constant or
878 // every element of a constant BUILD_VECTOR.
879 static bool matchUnaryPredicate(SDValue Op,
880                                 std::function<bool(ConstantSDNode *)> Match) {
881   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
882     return Match(Cst);
883 
884   if (ISD::BUILD_VECTOR != Op.getOpcode())
885     return false;
886 
887   EVT SVT = Op.getValueType().getScalarType();
888   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
889     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
890     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
891       return false;
892   }
893   return true;
894 }
895 
896 // Attempt to match a binary predicate against a pair of scalar/splat constants
897 // or every element of a pair of constant BUILD_VECTORs.
898 static bool matchBinaryPredicate(
899     SDValue LHS, SDValue RHS,
900     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match) {
901   if (LHS.getValueType() != RHS.getValueType())
902     return false;
903 
904   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
905     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
906       return Match(LHSCst, RHSCst);
907 
908   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
909       ISD::BUILD_VECTOR != RHS.getOpcode())
910     return false;
911 
912   EVT SVT = LHS.getValueType().getScalarType();
913   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
914     auto *LHSCst = dyn_cast<ConstantSDNode>(LHS.getOperand(i));
915     auto *RHSCst = dyn_cast<ConstantSDNode>(RHS.getOperand(i));
916     if (!LHSCst || !RHSCst)
917       return false;
918     if (LHSCst->getValueType(0) != SVT ||
919         LHSCst->getValueType(0) != RHSCst->getValueType(0))
920       return false;
921     if (!Match(LHSCst, RHSCst))
922       return false;
923   }
924   return true;
925 }
926 
927 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
928                                     SDValue N1) {
929   EVT VT = N0.getValueType();
930   if (N0.getOpcode() == Opc) {
931     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
932       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
933         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
934         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
935           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
936         return SDValue();
937       }
938       if (N0.hasOneUse()) {
939         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
940         // use
941         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
942         if (!OpNode.getNode())
943           return SDValue();
944         AddToWorklist(OpNode.getNode());
945         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
946       }
947     }
948   }
949 
950   if (N1.getOpcode() == Opc) {
951     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
952       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
953         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
954         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
955           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
956         return SDValue();
957       }
958       if (N1.hasOneUse()) {
959         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
960         // use
961         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
962         if (!OpNode.getNode())
963           return SDValue();
964         AddToWorklist(OpNode.getNode());
965         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
966       }
967     }
968   }
969 
970   return SDValue();
971 }
972 
973 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
974                                bool AddTo) {
975   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
976   ++NodesCombined;
977   DEBUG(dbgs() << "\nReplacing.1 ";
978         N->dump(&DAG);
979         dbgs() << "\nWith: ";
980         To[0].getNode()->dump(&DAG);
981         dbgs() << " and " << NumTo-1 << " other values\n");
982   for (unsigned i = 0, e = NumTo; i != e; ++i)
983     assert((!To[i].getNode() ||
984             N->getValueType(i) == To[i].getValueType()) &&
985            "Cannot combine value to value of different type!");
986 
987   WorklistRemover DeadNodes(*this);
988   DAG.ReplaceAllUsesWith(N, To);
989   if (AddTo) {
990     // Push the new nodes and any users onto the worklist
991     for (unsigned i = 0, e = NumTo; i != e; ++i) {
992       if (To[i].getNode()) {
993         AddToWorklist(To[i].getNode());
994         AddUsersToWorklist(To[i].getNode());
995       }
996     }
997   }
998 
999   // Finally, if the node is now dead, remove it from the graph.  The node
1000   // may not be dead if the replacement process recursively simplified to
1001   // something else needing this node.
1002   if (N->use_empty())
1003     deleteAndRecombine(N);
1004   return SDValue(N, 0);
1005 }
1006 
1007 void DAGCombiner::
1008 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1009   // Replace all uses.  If any nodes become isomorphic to other nodes and
1010   // are deleted, make sure to remove them from our worklist.
1011   WorklistRemover DeadNodes(*this);
1012   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1013 
1014   // Push the new node and any (possibly new) users onto the worklist.
1015   AddToWorklist(TLO.New.getNode());
1016   AddUsersToWorklist(TLO.New.getNode());
1017 
1018   // Finally, if the node is now dead, remove it from the graph.  The node
1019   // may not be dead if the replacement process recursively simplified to
1020   // something else needing this node.
1021   if (TLO.Old.getNode()->use_empty())
1022     deleteAndRecombine(TLO.Old.getNode());
1023 }
1024 
1025 /// Check the specified integer node value to see if it can be simplified or if
1026 /// things it uses can be simplified by bit propagation. If so, return true.
1027 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
1028   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1029   KnownBits Known;
1030   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
1031     return false;
1032 
1033   // Revisit the node.
1034   AddToWorklist(Op.getNode());
1035 
1036   // Replace the old value with the new one.
1037   ++NodesCombined;
1038   DEBUG(dbgs() << "\nReplacing.2 ";
1039         TLO.Old.getNode()->dump(&DAG);
1040         dbgs() << "\nWith: ";
1041         TLO.New.getNode()->dump(&DAG);
1042         dbgs() << '\n');
1043 
1044   CommitTargetLoweringOpt(TLO);
1045   return true;
1046 }
1047 
1048 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1049   SDLoc DL(Load);
1050   EVT VT = Load->getValueType(0);
1051   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1052 
1053   DEBUG(dbgs() << "\nReplacing.9 ";
1054         Load->dump(&DAG);
1055         dbgs() << "\nWith: ";
1056         Trunc.getNode()->dump(&DAG);
1057         dbgs() << '\n');
1058   WorklistRemover DeadNodes(*this);
1059   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1060   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1061   deleteAndRecombine(Load);
1062   AddToWorklist(Trunc.getNode());
1063 }
1064 
1065 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1066   Replace = false;
1067   SDLoc DL(Op);
1068   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1069     LoadSDNode *LD = cast<LoadSDNode>(Op);
1070     EVT MemVT = LD->getMemoryVT();
1071     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1072       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1073                                                        : ISD::EXTLOAD)
1074       : LD->getExtensionType();
1075     Replace = true;
1076     return DAG.getExtLoad(ExtType, DL, PVT,
1077                           LD->getChain(), LD->getBasePtr(),
1078                           MemVT, LD->getMemOperand());
1079   }
1080 
1081   unsigned Opc = Op.getOpcode();
1082   switch (Opc) {
1083   default: break;
1084   case ISD::AssertSext:
1085     if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1086       return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1087     break;
1088   case ISD::AssertZext:
1089     if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1090       return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1091     break;
1092   case ISD::Constant: {
1093     unsigned ExtOpc =
1094       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1095     return DAG.getNode(ExtOpc, DL, PVT, Op);
1096   }
1097   }
1098 
1099   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1100     return SDValue();
1101   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1102 }
1103 
1104 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1105   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1106     return SDValue();
1107   EVT OldVT = Op.getValueType();
1108   SDLoc DL(Op);
1109   bool Replace = false;
1110   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1111   if (!NewOp.getNode())
1112     return SDValue();
1113   AddToWorklist(NewOp.getNode());
1114 
1115   if (Replace)
1116     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1117   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1118                      DAG.getValueType(OldVT));
1119 }
1120 
1121 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1122   EVT OldVT = Op.getValueType();
1123   SDLoc DL(Op);
1124   bool Replace = false;
1125   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1126   if (!NewOp.getNode())
1127     return SDValue();
1128   AddToWorklist(NewOp.getNode());
1129 
1130   if (Replace)
1131     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1132   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1133 }
1134 
1135 /// Promote the specified integer binary operation if the target indicates it is
1136 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1137 /// i32 since i16 instructions are longer.
1138 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1139   if (!LegalOperations)
1140     return SDValue();
1141 
1142   EVT VT = Op.getValueType();
1143   if (VT.isVector() || !VT.isInteger())
1144     return SDValue();
1145 
1146   // If operation type is 'undesirable', e.g. i16 on x86, consider
1147   // promoting it.
1148   unsigned Opc = Op.getOpcode();
1149   if (TLI.isTypeDesirableForOp(Opc, VT))
1150     return SDValue();
1151 
1152   EVT PVT = VT;
1153   // Consult target whether it is a good idea to promote this operation and
1154   // what's the right type to promote it to.
1155   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1156     assert(PVT != VT && "Don't know what type to promote to!");
1157 
1158     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1159 
1160     bool Replace0 = false;
1161     SDValue N0 = Op.getOperand(0);
1162     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1163 
1164     bool Replace1 = false;
1165     SDValue N1 = Op.getOperand(1);
1166     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1167     SDLoc DL(Op);
1168 
1169     SDValue RV =
1170         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1171 
1172     // We are always replacing N0/N1's use in N and only need
1173     // additional replacements if there are additional uses.
1174     Replace0 &= !N0->hasOneUse();
1175     Replace1 &= (N0 != N1) && !N1->hasOneUse();
1176 
1177     // Combine Op here so it is presreved past replacements.
1178     CombineTo(Op.getNode(), RV);
1179 
1180     // If operands have a use ordering, make sur we deal with
1181     // predecessor first.
1182     if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1183       std::swap(N0, N1);
1184       std::swap(NN0, NN1);
1185     }
1186 
1187     if (Replace0) {
1188       AddToWorklist(NN0.getNode());
1189       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1190     }
1191     if (Replace1) {
1192       AddToWorklist(NN1.getNode());
1193       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1194     }
1195     return Op;
1196   }
1197   return SDValue();
1198 }
1199 
1200 /// Promote the specified integer shift operation if the target indicates it is
1201 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1202 /// i32 since i16 instructions are longer.
1203 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1204   if (!LegalOperations)
1205     return SDValue();
1206 
1207   EVT VT = Op.getValueType();
1208   if (VT.isVector() || !VT.isInteger())
1209     return SDValue();
1210 
1211   // If operation type is 'undesirable', e.g. i16 on x86, consider
1212   // promoting it.
1213   unsigned Opc = Op.getOpcode();
1214   if (TLI.isTypeDesirableForOp(Opc, VT))
1215     return SDValue();
1216 
1217   EVT PVT = VT;
1218   // Consult target whether it is a good idea to promote this operation and
1219   // what's the right type to promote it to.
1220   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1221     assert(PVT != VT && "Don't know what type to promote to!");
1222 
1223     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1224 
1225     bool Replace = false;
1226     SDValue N0 = Op.getOperand(0);
1227     SDValue N1 = Op.getOperand(1);
1228     if (Opc == ISD::SRA)
1229       N0 = SExtPromoteOperand(N0, PVT);
1230     else if (Opc == ISD::SRL)
1231       N0 = ZExtPromoteOperand(N0, PVT);
1232     else
1233       N0 = PromoteOperand(N0, PVT, Replace);
1234 
1235     if (!N0.getNode())
1236       return SDValue();
1237 
1238     SDLoc DL(Op);
1239     SDValue RV =
1240         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1241 
1242     AddToWorklist(N0.getNode());
1243     if (Replace)
1244       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1245 
1246     // Deal with Op being deleted.
1247     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1248       return RV;
1249   }
1250   return SDValue();
1251 }
1252 
1253 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1254   if (!LegalOperations)
1255     return SDValue();
1256 
1257   EVT VT = Op.getValueType();
1258   if (VT.isVector() || !VT.isInteger())
1259     return SDValue();
1260 
1261   // If operation type is 'undesirable', e.g. i16 on x86, consider
1262   // promoting it.
1263   unsigned Opc = Op.getOpcode();
1264   if (TLI.isTypeDesirableForOp(Opc, VT))
1265     return SDValue();
1266 
1267   EVT PVT = VT;
1268   // Consult target whether it is a good idea to promote this operation and
1269   // what's the right type to promote it to.
1270   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1271     assert(PVT != VT && "Don't know what type to promote to!");
1272     // fold (aext (aext x)) -> (aext x)
1273     // fold (aext (zext x)) -> (zext x)
1274     // fold (aext (sext x)) -> (sext x)
1275     DEBUG(dbgs() << "\nPromoting ";
1276           Op.getNode()->dump(&DAG));
1277     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1278   }
1279   return SDValue();
1280 }
1281 
1282 bool DAGCombiner::PromoteLoad(SDValue Op) {
1283   if (!LegalOperations)
1284     return false;
1285 
1286   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1287     return false;
1288 
1289   EVT VT = Op.getValueType();
1290   if (VT.isVector() || !VT.isInteger())
1291     return false;
1292 
1293   // If operation type is 'undesirable', e.g. i16 on x86, consider
1294   // promoting it.
1295   unsigned Opc = Op.getOpcode();
1296   if (TLI.isTypeDesirableForOp(Opc, VT))
1297     return false;
1298 
1299   EVT PVT = VT;
1300   // Consult target whether it is a good idea to promote this operation and
1301   // what's the right type to promote it to.
1302   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1303     assert(PVT != VT && "Don't know what type to promote to!");
1304 
1305     SDLoc DL(Op);
1306     SDNode *N = Op.getNode();
1307     LoadSDNode *LD = cast<LoadSDNode>(N);
1308     EVT MemVT = LD->getMemoryVT();
1309     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1310       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1311                                                        : ISD::EXTLOAD)
1312       : LD->getExtensionType();
1313     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1314                                    LD->getChain(), LD->getBasePtr(),
1315                                    MemVT, LD->getMemOperand());
1316     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1317 
1318     DEBUG(dbgs() << "\nPromoting ";
1319           N->dump(&DAG);
1320           dbgs() << "\nTo: ";
1321           Result.getNode()->dump(&DAG);
1322           dbgs() << '\n');
1323     WorklistRemover DeadNodes(*this);
1324     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1325     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1326     deleteAndRecombine(N);
1327     AddToWorklist(Result.getNode());
1328     return true;
1329   }
1330   return false;
1331 }
1332 
1333 /// \brief Recursively delete a node which has no uses and any operands for
1334 /// which it is the only use.
1335 ///
1336 /// Note that this both deletes the nodes and removes them from the worklist.
1337 /// It also adds any nodes who have had a user deleted to the worklist as they
1338 /// may now have only one use and subject to other combines.
1339 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1340   if (!N->use_empty())
1341     return false;
1342 
1343   SmallSetVector<SDNode *, 16> Nodes;
1344   Nodes.insert(N);
1345   do {
1346     N = Nodes.pop_back_val();
1347     if (!N)
1348       continue;
1349 
1350     if (N->use_empty()) {
1351       for (const SDValue &ChildN : N->op_values())
1352         Nodes.insert(ChildN.getNode());
1353 
1354       removeFromWorklist(N);
1355       DAG.DeleteNode(N);
1356     } else {
1357       AddToWorklist(N);
1358     }
1359   } while (!Nodes.empty());
1360   return true;
1361 }
1362 
1363 //===----------------------------------------------------------------------===//
1364 //  Main DAG Combiner implementation
1365 //===----------------------------------------------------------------------===//
1366 
1367 void DAGCombiner::Run(CombineLevel AtLevel) {
1368   // set the instance variables, so that the various visit routines may use it.
1369   Level = AtLevel;
1370   LegalOperations = Level >= AfterLegalizeVectorOps;
1371   LegalTypes = Level >= AfterLegalizeTypes;
1372 
1373   // Add all the dag nodes to the worklist.
1374   for (SDNode &Node : DAG.allnodes())
1375     AddToWorklist(&Node);
1376 
1377   // Create a dummy node (which is not added to allnodes), that adds a reference
1378   // to the root node, preventing it from being deleted, and tracking any
1379   // changes of the root.
1380   HandleSDNode Dummy(DAG.getRoot());
1381 
1382   // While the worklist isn't empty, find a node and try to combine it.
1383   while (!WorklistMap.empty()) {
1384     SDNode *N;
1385     // The Worklist holds the SDNodes in order, but it may contain null entries.
1386     do {
1387       N = Worklist.pop_back_val();
1388     } while (!N);
1389 
1390     bool GoodWorklistEntry = WorklistMap.erase(N);
1391     (void)GoodWorklistEntry;
1392     assert(GoodWorklistEntry &&
1393            "Found a worklist entry without a corresponding map entry!");
1394 
1395     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1396     // N is deleted from the DAG, since they too may now be dead or may have a
1397     // reduced number of uses, allowing other xforms.
1398     if (recursivelyDeleteUnusedNodes(N))
1399       continue;
1400 
1401     WorklistRemover DeadNodes(*this);
1402 
1403     // If this combine is running after legalizing the DAG, re-legalize any
1404     // nodes pulled off the worklist.
1405     if (Level == AfterLegalizeDAG) {
1406       SmallSetVector<SDNode *, 16> UpdatedNodes;
1407       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1408 
1409       for (SDNode *LN : UpdatedNodes) {
1410         AddToWorklist(LN);
1411         AddUsersToWorklist(LN);
1412       }
1413       if (!NIsValid)
1414         continue;
1415     }
1416 
1417     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1418 
1419     // Add any operands of the new node which have not yet been combined to the
1420     // worklist as well. Because the worklist uniques things already, this
1421     // won't repeatedly process the same operand.
1422     CombinedNodes.insert(N);
1423     for (const SDValue &ChildN : N->op_values())
1424       if (!CombinedNodes.count(ChildN.getNode()))
1425         AddToWorklist(ChildN.getNode());
1426 
1427     SDValue RV = combine(N);
1428 
1429     if (!RV.getNode())
1430       continue;
1431 
1432     ++NodesCombined;
1433 
1434     // If we get back the same node we passed in, rather than a new node or
1435     // zero, we know that the node must have defined multiple values and
1436     // CombineTo was used.  Since CombineTo takes care of the worklist
1437     // mechanics for us, we have no work to do in this case.
1438     if (RV.getNode() == N)
1439       continue;
1440 
1441     assert(N->getOpcode() != ISD::DELETED_NODE &&
1442            RV.getOpcode() != ISD::DELETED_NODE &&
1443            "Node was deleted but visit returned new node!");
1444 
1445     DEBUG(dbgs() << " ... into: ";
1446           RV.getNode()->dump(&DAG));
1447 
1448     if (N->getNumValues() == RV.getNode()->getNumValues())
1449       DAG.ReplaceAllUsesWith(N, RV.getNode());
1450     else {
1451       assert(N->getValueType(0) == RV.getValueType() &&
1452              N->getNumValues() == 1 && "Type mismatch");
1453       DAG.ReplaceAllUsesWith(N, &RV);
1454     }
1455 
1456     // Push the new node and any users onto the worklist
1457     AddToWorklist(RV.getNode());
1458     AddUsersToWorklist(RV.getNode());
1459 
1460     // Finally, if the node is now dead, remove it from the graph.  The node
1461     // may not be dead if the replacement process recursively simplified to
1462     // something else needing this node. This will also take care of adding any
1463     // operands which have lost a user to the worklist.
1464     recursivelyDeleteUnusedNodes(N);
1465   }
1466 
1467   // If the root changed (e.g. it was a dead load, update the root).
1468   DAG.setRoot(Dummy.getValue());
1469   DAG.RemoveDeadNodes();
1470 }
1471 
1472 SDValue DAGCombiner::visit(SDNode *N) {
1473   switch (N->getOpcode()) {
1474   default: break;
1475   case ISD::TokenFactor:        return visitTokenFactor(N);
1476   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1477   case ISD::ADD:                return visitADD(N);
1478   case ISD::SUB:                return visitSUB(N);
1479   case ISD::ADDC:               return visitADDC(N);
1480   case ISD::UADDO:              return visitUADDO(N);
1481   case ISD::SUBC:               return visitSUBC(N);
1482   case ISD::USUBO:              return visitUSUBO(N);
1483   case ISD::ADDE:               return visitADDE(N);
1484   case ISD::ADDCARRY:           return visitADDCARRY(N);
1485   case ISD::SUBE:               return visitSUBE(N);
1486   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1487   case ISD::MUL:                return visitMUL(N);
1488   case ISD::SDIV:               return visitSDIV(N);
1489   case ISD::UDIV:               return visitUDIV(N);
1490   case ISD::SREM:
1491   case ISD::UREM:               return visitREM(N);
1492   case ISD::MULHU:              return visitMULHU(N);
1493   case ISD::MULHS:              return visitMULHS(N);
1494   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1495   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1496   case ISD::SMULO:              return visitSMULO(N);
1497   case ISD::UMULO:              return visitUMULO(N);
1498   case ISD::SMIN:
1499   case ISD::SMAX:
1500   case ISD::UMIN:
1501   case ISD::UMAX:               return visitIMINMAX(N);
1502   case ISD::AND:                return visitAND(N);
1503   case ISD::OR:                 return visitOR(N);
1504   case ISD::XOR:                return visitXOR(N);
1505   case ISD::SHL:                return visitSHL(N);
1506   case ISD::SRA:                return visitSRA(N);
1507   case ISD::SRL:                return visitSRL(N);
1508   case ISD::ROTR:
1509   case ISD::ROTL:               return visitRotate(N);
1510   case ISD::ABS:                return visitABS(N);
1511   case ISD::BSWAP:              return visitBSWAP(N);
1512   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1513   case ISD::CTLZ:               return visitCTLZ(N);
1514   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1515   case ISD::CTTZ:               return visitCTTZ(N);
1516   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1517   case ISD::CTPOP:              return visitCTPOP(N);
1518   case ISD::SELECT:             return visitSELECT(N);
1519   case ISD::VSELECT:            return visitVSELECT(N);
1520   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1521   case ISD::SETCC:              return visitSETCC(N);
1522   case ISD::SETCCE:             return visitSETCCE(N);
1523   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1524   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1525   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1526   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1527   case ISD::AssertZext:         return visitAssertZext(N);
1528   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1529   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1530   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1531   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1532   case ISD::BITCAST:            return visitBITCAST(N);
1533   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1534   case ISD::FADD:               return visitFADD(N);
1535   case ISD::FSUB:               return visitFSUB(N);
1536   case ISD::FMUL:               return visitFMUL(N);
1537   case ISD::FMA:                return visitFMA(N);
1538   case ISD::FDIV:               return visitFDIV(N);
1539   case ISD::FREM:               return visitFREM(N);
1540   case ISD::FSQRT:              return visitFSQRT(N);
1541   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1542   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1543   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1544   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1545   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1546   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1547   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1548   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1549   case ISD::FNEG:               return visitFNEG(N);
1550   case ISD::FABS:               return visitFABS(N);
1551   case ISD::FFLOOR:             return visitFFLOOR(N);
1552   case ISD::FMINNUM:            return visitFMINNUM(N);
1553   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1554   case ISD::FCEIL:              return visitFCEIL(N);
1555   case ISD::FTRUNC:             return visitFTRUNC(N);
1556   case ISD::BRCOND:             return visitBRCOND(N);
1557   case ISD::BR_CC:              return visitBR_CC(N);
1558   case ISD::LOAD:               return visitLOAD(N);
1559   case ISD::STORE:              return visitSTORE(N);
1560   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1561   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1562   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1563   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1564   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1565   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1566   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1567   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1568   case ISD::MGATHER:            return visitMGATHER(N);
1569   case ISD::MLOAD:              return visitMLOAD(N);
1570   case ISD::MSCATTER:           return visitMSCATTER(N);
1571   case ISD::MSTORE:             return visitMSTORE(N);
1572   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1573   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1574   }
1575   return SDValue();
1576 }
1577 
1578 SDValue DAGCombiner::combine(SDNode *N) {
1579   SDValue RV = visit(N);
1580 
1581   // If nothing happened, try a target-specific DAG combine.
1582   if (!RV.getNode()) {
1583     assert(N->getOpcode() != ISD::DELETED_NODE &&
1584            "Node was deleted but visit returned NULL!");
1585 
1586     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1587         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1588 
1589       // Expose the DAG combiner to the target combiner impls.
1590       TargetLowering::DAGCombinerInfo
1591         DagCombineInfo(DAG, Level, false, this);
1592 
1593       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1594     }
1595   }
1596 
1597   // If nothing happened still, try promoting the operation.
1598   if (!RV.getNode()) {
1599     switch (N->getOpcode()) {
1600     default: break;
1601     case ISD::ADD:
1602     case ISD::SUB:
1603     case ISD::MUL:
1604     case ISD::AND:
1605     case ISD::OR:
1606     case ISD::XOR:
1607       RV = PromoteIntBinOp(SDValue(N, 0));
1608       break;
1609     case ISD::SHL:
1610     case ISD::SRA:
1611     case ISD::SRL:
1612       RV = PromoteIntShiftOp(SDValue(N, 0));
1613       break;
1614     case ISD::SIGN_EXTEND:
1615     case ISD::ZERO_EXTEND:
1616     case ISD::ANY_EXTEND:
1617       RV = PromoteExtend(SDValue(N, 0));
1618       break;
1619     case ISD::LOAD:
1620       if (PromoteLoad(SDValue(N, 0)))
1621         RV = SDValue(N, 0);
1622       break;
1623     }
1624   }
1625 
1626   // If N is a commutative binary node, try eliminate it if the commuted
1627   // version is already present in the DAG.
1628   if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1629       N->getNumValues() == 1) {
1630     SDValue N0 = N->getOperand(0);
1631     SDValue N1 = N->getOperand(1);
1632 
1633     // Constant operands are canonicalized to RHS.
1634     if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1635       SDValue Ops[] = {N1, N0};
1636       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1637                                             N->getFlags());
1638       if (CSENode)
1639         return SDValue(CSENode, 0);
1640     }
1641   }
1642 
1643   return RV;
1644 }
1645 
1646 /// Given a node, return its input chain if it has one, otherwise return a null
1647 /// sd operand.
1648 static SDValue getInputChainForNode(SDNode *N) {
1649   if (unsigned NumOps = N->getNumOperands()) {
1650     if (N->getOperand(0).getValueType() == MVT::Other)
1651       return N->getOperand(0);
1652     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1653       return N->getOperand(NumOps-1);
1654     for (unsigned i = 1; i < NumOps-1; ++i)
1655       if (N->getOperand(i).getValueType() == MVT::Other)
1656         return N->getOperand(i);
1657   }
1658   return SDValue();
1659 }
1660 
1661 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1662   // If N has two operands, where one has an input chain equal to the other,
1663   // the 'other' chain is redundant.
1664   if (N->getNumOperands() == 2) {
1665     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1666       return N->getOperand(0);
1667     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1668       return N->getOperand(1);
1669   }
1670 
1671   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1672   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1673   SmallPtrSet<SDNode*, 16> SeenOps;
1674   bool Changed = false;             // If we should replace this token factor.
1675 
1676   // Start out with this token factor.
1677   TFs.push_back(N);
1678 
1679   // Iterate through token factors.  The TFs grows when new token factors are
1680   // encountered.
1681   for (unsigned i = 0; i < TFs.size(); ++i) {
1682     SDNode *TF = TFs[i];
1683 
1684     // Check each of the operands.
1685     for (const SDValue &Op : TF->op_values()) {
1686 
1687       switch (Op.getOpcode()) {
1688       case ISD::EntryToken:
1689         // Entry tokens don't need to be added to the list. They are
1690         // redundant.
1691         Changed = true;
1692         break;
1693 
1694       case ISD::TokenFactor:
1695         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1696           // Queue up for processing.
1697           TFs.push_back(Op.getNode());
1698           // Clean up in case the token factor is removed.
1699           AddToWorklist(Op.getNode());
1700           Changed = true;
1701           break;
1702         }
1703         LLVM_FALLTHROUGH;
1704 
1705       default:
1706         // Only add if it isn't already in the list.
1707         if (SeenOps.insert(Op.getNode()).second)
1708           Ops.push_back(Op);
1709         else
1710           Changed = true;
1711         break;
1712       }
1713     }
1714   }
1715 
1716   // Remove Nodes that are chained to another node in the list. Do so
1717   // by walking up chains breath-first stopping when we've seen
1718   // another operand. In general we must climb to the EntryNode, but we can exit
1719   // early if we find all remaining work is associated with just one operand as
1720   // no further pruning is possible.
1721 
1722   // List of nodes to search through and original Ops from which they originate.
1723   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1724   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1725   SmallPtrSet<SDNode *, 16> SeenChains;
1726   bool DidPruneOps = false;
1727 
1728   unsigned NumLeftToConsider = 0;
1729   for (const SDValue &Op : Ops) {
1730     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1731     OpWorkCount.push_back(1);
1732   }
1733 
1734   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1735     // If this is an Op, we can remove the op from the list. Remark any
1736     // search associated with it as from the current OpNumber.
1737     if (SeenOps.count(Op) != 0) {
1738       Changed = true;
1739       DidPruneOps = true;
1740       unsigned OrigOpNumber = 0;
1741       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1742         OrigOpNumber++;
1743       assert((OrigOpNumber != Ops.size()) &&
1744              "expected to find TokenFactor Operand");
1745       // Re-mark worklist from OrigOpNumber to OpNumber
1746       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1747         if (Worklist[i].second == OrigOpNumber) {
1748           Worklist[i].second = OpNumber;
1749         }
1750       }
1751       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1752       OpWorkCount[OrigOpNumber] = 0;
1753       NumLeftToConsider--;
1754     }
1755     // Add if it's a new chain
1756     if (SeenChains.insert(Op).second) {
1757       OpWorkCount[OpNumber]++;
1758       Worklist.push_back(std::make_pair(Op, OpNumber));
1759     }
1760   };
1761 
1762   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1763     // We need at least be consider at least 2 Ops to prune.
1764     if (NumLeftToConsider <= 1)
1765       break;
1766     auto CurNode = Worklist[i].first;
1767     auto CurOpNumber = Worklist[i].second;
1768     assert((OpWorkCount[CurOpNumber] > 0) &&
1769            "Node should not appear in worklist");
1770     switch (CurNode->getOpcode()) {
1771     case ISD::EntryToken:
1772       // Hitting EntryToken is the only way for the search to terminate without
1773       // hitting
1774       // another operand's search. Prevent us from marking this operand
1775       // considered.
1776       NumLeftToConsider++;
1777       break;
1778     case ISD::TokenFactor:
1779       for (const SDValue &Op : CurNode->op_values())
1780         AddToWorklist(i, Op.getNode(), CurOpNumber);
1781       break;
1782     case ISD::CopyFromReg:
1783     case ISD::CopyToReg:
1784       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1785       break;
1786     default:
1787       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1788         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1789       break;
1790     }
1791     OpWorkCount[CurOpNumber]--;
1792     if (OpWorkCount[CurOpNumber] == 0)
1793       NumLeftToConsider--;
1794   }
1795 
1796   // If we've changed things around then replace token factor.
1797   if (Changed) {
1798     SDValue Result;
1799     if (Ops.empty()) {
1800       // The entry token is the only possible outcome.
1801       Result = DAG.getEntryNode();
1802     } else {
1803       if (DidPruneOps) {
1804         SmallVector<SDValue, 8> PrunedOps;
1805         //
1806         for (const SDValue &Op : Ops) {
1807           if (SeenChains.count(Op.getNode()) == 0)
1808             PrunedOps.push_back(Op);
1809         }
1810         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1811       } else {
1812         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1813       }
1814     }
1815     return Result;
1816   }
1817   return SDValue();
1818 }
1819 
1820 /// MERGE_VALUES can always be eliminated.
1821 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1822   WorklistRemover DeadNodes(*this);
1823   // Replacing results may cause a different MERGE_VALUES to suddenly
1824   // be CSE'd with N, and carry its uses with it. Iterate until no
1825   // uses remain, to ensure that the node can be safely deleted.
1826   // First add the users of this node to the work list so that they
1827   // can be tried again once they have new operands.
1828   AddUsersToWorklist(N);
1829   do {
1830     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1831       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1832   } while (!N->use_empty());
1833   deleteAndRecombine(N);
1834   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1835 }
1836 
1837 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1838 /// ConstantSDNode pointer else nullptr.
1839 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1840   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1841   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1842 }
1843 
1844 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1845   auto BinOpcode = BO->getOpcode();
1846   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1847           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1848           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1849           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1850           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1851           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1852           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1853           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1854           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1855          "Unexpected binary operator");
1856 
1857   // Bail out if any constants are opaque because we can't constant fold those.
1858   SDValue C1 = BO->getOperand(1);
1859   if (!isConstantOrConstantVector(C1, true) &&
1860       !isConstantFPBuildVectorOrConstantFP(C1))
1861     return SDValue();
1862 
1863   // Don't do this unless the old select is going away. We want to eliminate the
1864   // binary operator, not replace a binop with a select.
1865   // TODO: Handle ISD::SELECT_CC.
1866   SDValue Sel = BO->getOperand(0);
1867   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1868     return SDValue();
1869 
1870   SDValue CT = Sel.getOperand(1);
1871   if (!isConstantOrConstantVector(CT, true) &&
1872       !isConstantFPBuildVectorOrConstantFP(CT))
1873     return SDValue();
1874 
1875   SDValue CF = Sel.getOperand(2);
1876   if (!isConstantOrConstantVector(CF, true) &&
1877       !isConstantFPBuildVectorOrConstantFP(CF))
1878     return SDValue();
1879 
1880   // We have a select-of-constants followed by a binary operator with a
1881   // constant. Eliminate the binop by pulling the constant math into the select.
1882   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1883   EVT VT = Sel.getValueType();
1884   SDLoc DL(Sel);
1885   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1886   assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1887           isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1888          "Failed to constant fold a binop with constant operands");
1889 
1890   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1891   assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1892           isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1893          "Failed to constant fold a binop with constant operands");
1894 
1895   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1896 }
1897 
1898 SDValue DAGCombiner::visitADD(SDNode *N) {
1899   SDValue N0 = N->getOperand(0);
1900   SDValue N1 = N->getOperand(1);
1901   EVT VT = N0.getValueType();
1902   SDLoc DL(N);
1903 
1904   // fold vector ops
1905   if (VT.isVector()) {
1906     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1907       return FoldedVOp;
1908 
1909     // fold (add x, 0) -> x, vector edition
1910     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1911       return N0;
1912     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1913       return N1;
1914   }
1915 
1916   // fold (add x, undef) -> undef
1917   if (N0.isUndef())
1918     return N0;
1919 
1920   if (N1.isUndef())
1921     return N1;
1922 
1923   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1924     // canonicalize constant to RHS
1925     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1926       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1927     // fold (add c1, c2) -> c1+c2
1928     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1929                                       N1.getNode());
1930   }
1931 
1932   // fold (add x, 0) -> x
1933   if (isNullConstant(N1))
1934     return N0;
1935 
1936   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1937     // fold ((c1-A)+c2) -> (c1+c2)-A
1938     if (N0.getOpcode() == ISD::SUB &&
1939         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1940       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1941       return DAG.getNode(ISD::SUB, DL, VT,
1942                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1943                          N0.getOperand(1));
1944     }
1945 
1946     // add (sext i1 X), 1 -> zext (not i1 X)
1947     // We don't transform this pattern:
1948     //   add (zext i1 X), -1 -> sext (not i1 X)
1949     // because most (?) targets generate better code for the zext form.
1950     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1951         isOneConstantOrOneSplatConstant(N1)) {
1952       SDValue X = N0.getOperand(0);
1953       if ((!LegalOperations ||
1954            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1955             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1956           X.getScalarValueSizeInBits() == 1) {
1957         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1958         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1959       }
1960     }
1961 
1962     // Undo the add -> or combine to merge constant offsets from a frame index.
1963     if (N0.getOpcode() == ISD::OR &&
1964         isa<FrameIndexSDNode>(N0.getOperand(0)) &&
1965         isa<ConstantSDNode>(N0.getOperand(1)) &&
1966         DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
1967       SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
1968       return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
1969     }
1970   }
1971 
1972   if (SDValue NewSel = foldBinOpIntoSelect(N))
1973     return NewSel;
1974 
1975   // reassociate add
1976   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1977     return RADD;
1978 
1979   // fold ((0-A) + B) -> B-A
1980   if (N0.getOpcode() == ISD::SUB &&
1981       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1982     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1983 
1984   // fold (A + (0-B)) -> A-B
1985   if (N1.getOpcode() == ISD::SUB &&
1986       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1987     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1988 
1989   // fold (A+(B-A)) -> B
1990   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1991     return N1.getOperand(0);
1992 
1993   // fold ((B-A)+A) -> B
1994   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1995     return N0.getOperand(0);
1996 
1997   // fold (A+(B-(A+C))) to (B-C)
1998   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1999       N0 == N1.getOperand(1).getOperand(0))
2000     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2001                        N1.getOperand(1).getOperand(1));
2002 
2003   // fold (A+(B-(C+A))) to (B-C)
2004   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2005       N0 == N1.getOperand(1).getOperand(1))
2006     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2007                        N1.getOperand(1).getOperand(0));
2008 
2009   // fold (A+((B-A)+or-C)) to (B+or-C)
2010   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2011       N1.getOperand(0).getOpcode() == ISD::SUB &&
2012       N0 == N1.getOperand(0).getOperand(1))
2013     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2014                        N1.getOperand(1));
2015 
2016   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2017   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2018     SDValue N00 = N0.getOperand(0);
2019     SDValue N01 = N0.getOperand(1);
2020     SDValue N10 = N1.getOperand(0);
2021     SDValue N11 = N1.getOperand(1);
2022 
2023     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2024       return DAG.getNode(ISD::SUB, DL, VT,
2025                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2026                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2027   }
2028 
2029   if (SimplifyDemandedBits(SDValue(N, 0)))
2030     return SDValue(N, 0);
2031 
2032   // fold (a+b) -> (a|b) iff a and b share no bits.
2033   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2034       DAG.haveNoCommonBitsSet(N0, N1))
2035     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2036 
2037   if (SDValue Combined = visitADDLike(N0, N1, N))
2038     return Combined;
2039 
2040   if (SDValue Combined = visitADDLike(N1, N0, N))
2041     return Combined;
2042 
2043   return SDValue();
2044 }
2045 
2046 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2047   bool Masked = false;
2048 
2049   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2050   while (true) {
2051     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2052       V = V.getOperand(0);
2053       continue;
2054     }
2055 
2056     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2057       Masked = true;
2058       V = V.getOperand(0);
2059       continue;
2060     }
2061 
2062     break;
2063   }
2064 
2065   // If this is not a carry, return.
2066   if (V.getResNo() != 1)
2067     return SDValue();
2068 
2069   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2070       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2071     return SDValue();
2072 
2073   // If the result is masked, then no matter what kind of bool it is we can
2074   // return. If it isn't, then we need to make sure the bool type is either 0 or
2075   // 1 and not other values.
2076   if (Masked ||
2077       TLI.getBooleanContents(V.getValueType()) ==
2078           TargetLoweringBase::ZeroOrOneBooleanContent)
2079     return V;
2080 
2081   return SDValue();
2082 }
2083 
2084 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2085   EVT VT = N0.getValueType();
2086   SDLoc DL(LocReference);
2087 
2088   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2089   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2090       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2091     return DAG.getNode(ISD::SUB, DL, VT, N0,
2092                        DAG.getNode(ISD::SHL, DL, VT,
2093                                    N1.getOperand(0).getOperand(1),
2094                                    N1.getOperand(1)));
2095 
2096   if (N1.getOpcode() == ISD::AND) {
2097     SDValue AndOp0 = N1.getOperand(0);
2098     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2099     unsigned DestBits = VT.getScalarSizeInBits();
2100 
2101     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2102     // and similar xforms where the inner op is either ~0 or 0.
2103     if (NumSignBits == DestBits &&
2104         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2105       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2106   }
2107 
2108   // add (sext i1), X -> sub X, (zext i1)
2109   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2110       N0.getOperand(0).getValueType() == MVT::i1 &&
2111       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2112     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2113     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2114   }
2115 
2116   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2117   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2118     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2119     if (TN->getVT() == MVT::i1) {
2120       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2121                                  DAG.getConstant(1, DL, VT));
2122       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2123     }
2124   }
2125 
2126   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2127   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)))
2128     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2129                        N0, N1.getOperand(0), N1.getOperand(2));
2130 
2131   // (add X, Carry) -> (addcarry X, 0, Carry)
2132   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2133     if (SDValue Carry = getAsCarry(TLI, N1))
2134       return DAG.getNode(ISD::ADDCARRY, DL,
2135                          DAG.getVTList(VT, Carry.getValueType()), N0,
2136                          DAG.getConstant(0, DL, VT), Carry);
2137 
2138   return SDValue();
2139 }
2140 
2141 SDValue DAGCombiner::visitADDC(SDNode *N) {
2142   SDValue N0 = N->getOperand(0);
2143   SDValue N1 = N->getOperand(1);
2144   EVT VT = N0.getValueType();
2145   SDLoc DL(N);
2146 
2147   // If the flag result is dead, turn this into an ADD.
2148   if (!N->hasAnyUseOfValue(1))
2149     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2150                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2151 
2152   // canonicalize constant to RHS.
2153   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2154   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2155   if (N0C && !N1C)
2156     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2157 
2158   // fold (addc x, 0) -> x + no carry out
2159   if (isNullConstant(N1))
2160     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2161                                         DL, MVT::Glue));
2162 
2163   // If it cannot overflow, transform into an add.
2164   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2165     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2166                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2167 
2168   return SDValue();
2169 }
2170 
2171 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2172   SDValue N0 = N->getOperand(0);
2173   SDValue N1 = N->getOperand(1);
2174   EVT VT = N0.getValueType();
2175   if (VT.isVector())
2176     return SDValue();
2177 
2178   EVT CarryVT = N->getValueType(1);
2179   SDLoc DL(N);
2180 
2181   // If the flag result is dead, turn this into an ADD.
2182   if (!N->hasAnyUseOfValue(1))
2183     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2184                      DAG.getUNDEF(CarryVT));
2185 
2186   // canonicalize constant to RHS.
2187   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2188   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2189   if (N0C && !N1C)
2190     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2191 
2192   // fold (uaddo x, 0) -> x + no carry out
2193   if (isNullConstant(N1))
2194     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2195 
2196   // If it cannot overflow, transform into an add.
2197   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2198     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2199                      DAG.getConstant(0, DL, CarryVT));
2200 
2201   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2202     return Combined;
2203 
2204   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2205     return Combined;
2206 
2207   return SDValue();
2208 }
2209 
2210 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2211   auto VT = N0.getValueType();
2212 
2213   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2214   // If Y + 1 cannot overflow.
2215   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2216     SDValue Y = N1.getOperand(0);
2217     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2218     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2219       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2220                          N1.getOperand(2));
2221   }
2222 
2223   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2224   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2225     if (SDValue Carry = getAsCarry(TLI, N1))
2226       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2227                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2228 
2229   return SDValue();
2230 }
2231 
2232 SDValue DAGCombiner::visitADDE(SDNode *N) {
2233   SDValue N0 = N->getOperand(0);
2234   SDValue N1 = N->getOperand(1);
2235   SDValue CarryIn = N->getOperand(2);
2236 
2237   // canonicalize constant to RHS
2238   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2239   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2240   if (N0C && !N1C)
2241     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2242                        N1, N0, CarryIn);
2243 
2244   // fold (adde x, y, false) -> (addc x, y)
2245   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2246     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2247 
2248   return SDValue();
2249 }
2250 
2251 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2252   SDValue N0 = N->getOperand(0);
2253   SDValue N1 = N->getOperand(1);
2254   SDValue CarryIn = N->getOperand(2);
2255   SDLoc DL(N);
2256 
2257   // canonicalize constant to RHS
2258   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2259   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2260   if (N0C && !N1C)
2261     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2262 
2263   // fold (addcarry x, y, false) -> (uaddo x, y)
2264   if (isNullConstant(CarryIn))
2265     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2266 
2267   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2268   if (isNullConstant(N0) && isNullConstant(N1)) {
2269     EVT VT = N0.getValueType();
2270     EVT CarryVT = CarryIn.getValueType();
2271     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2272     AddToWorklist(CarryExt.getNode());
2273     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2274                                     DAG.getConstant(1, DL, VT)),
2275                      DAG.getConstant(0, DL, CarryVT));
2276   }
2277 
2278   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2279     return Combined;
2280 
2281   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2282     return Combined;
2283 
2284   return SDValue();
2285 }
2286 
2287 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2288                                        SDNode *N) {
2289   // Iff the flag result is dead:
2290   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2291   if ((N0.getOpcode() == ISD::ADD ||
2292        (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2293       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2294     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2295                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2296 
2297   /**
2298    * When one of the addcarry argument is itself a carry, we may be facing
2299    * a diamond carry propagation. In which case we try to transform the DAG
2300    * to ensure linear carry propagation if that is possible.
2301    *
2302    * We are trying to get:
2303    *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2304    */
2305   if (auto Y = getAsCarry(TLI, N1)) {
2306     /**
2307      *            (uaddo A, B)
2308      *             /       \
2309      *          Carry      Sum
2310      *            |          \
2311      *            | (addcarry *, 0, Z)
2312      *            |       /
2313      *             \   Carry
2314      *              |   /
2315      * (addcarry X, *, *)
2316      */
2317     if (Y.getOpcode() == ISD::UADDO &&
2318         CarryIn.getResNo() == 1 &&
2319         CarryIn.getOpcode() == ISD::ADDCARRY &&
2320         isNullConstant(CarryIn.getOperand(1)) &&
2321         CarryIn.getOperand(0) == Y.getValue(0)) {
2322       auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2323                               Y.getOperand(0), Y.getOperand(1),
2324                               CarryIn.getOperand(2));
2325       AddToWorklist(NewY.getNode());
2326       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2327                          DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2328                          NewY.getValue(1));
2329     }
2330   }
2331 
2332   return SDValue();
2333 }
2334 
2335 // Since it may not be valid to emit a fold to zero for vector initializers
2336 // check if we can before folding.
2337 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2338                              SelectionDAG &DAG, bool LegalOperations,
2339                              bool LegalTypes) {
2340   if (!VT.isVector())
2341     return DAG.getConstant(0, DL, VT);
2342   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2343     return DAG.getConstant(0, DL, VT);
2344   return SDValue();
2345 }
2346 
2347 SDValue DAGCombiner::visitSUB(SDNode *N) {
2348   SDValue N0 = N->getOperand(0);
2349   SDValue N1 = N->getOperand(1);
2350   EVT VT = N0.getValueType();
2351   SDLoc DL(N);
2352 
2353   // fold vector ops
2354   if (VT.isVector()) {
2355     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2356       return FoldedVOp;
2357 
2358     // fold (sub x, 0) -> x, vector edition
2359     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2360       return N0;
2361   }
2362 
2363   // fold (sub x, x) -> 0
2364   // FIXME: Refactor this and xor and other similar operations together.
2365   if (N0 == N1)
2366     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2367   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2368       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2369     // fold (sub c1, c2) -> c1-c2
2370     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2371                                       N1.getNode());
2372   }
2373 
2374   if (SDValue NewSel = foldBinOpIntoSelect(N))
2375     return NewSel;
2376 
2377   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2378 
2379   // fold (sub x, c) -> (add x, -c)
2380   if (N1C) {
2381     return DAG.getNode(ISD::ADD, DL, VT, N0,
2382                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2383   }
2384 
2385   if (isNullConstantOrNullSplatConstant(N0)) {
2386     unsigned BitWidth = VT.getScalarSizeInBits();
2387     // Right-shifting everything out but the sign bit followed by negation is
2388     // the same as flipping arithmetic/logical shift type without the negation:
2389     // -(X >>u 31) -> (X >>s 31)
2390     // -(X >>s 31) -> (X >>u 31)
2391     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2392       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2393       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2394         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2395         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2396           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2397       }
2398     }
2399 
2400     // 0 - X --> 0 if the sub is NUW.
2401     if (N->getFlags().hasNoUnsignedWrap())
2402       return N0;
2403 
2404     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2405       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2406       // N1 must be 0 because negating the minimum signed value is undefined.
2407       if (N->getFlags().hasNoSignedWrap())
2408         return N0;
2409 
2410       // 0 - X --> X if X is 0 or the minimum signed value.
2411       return N1;
2412     }
2413   }
2414 
2415   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2416   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2417     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2418 
2419   // fold A-(A-B) -> B
2420   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2421     return N1.getOperand(1);
2422 
2423   // fold (A+B)-A -> B
2424   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2425     return N0.getOperand(1);
2426 
2427   // fold (A+B)-B -> A
2428   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2429     return N0.getOperand(0);
2430 
2431   // fold C2-(A+C1) -> (C2-C1)-A
2432   if (N1.getOpcode() == ISD::ADD) {
2433     SDValue N11 = N1.getOperand(1);
2434     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2435         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2436       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2437       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2438     }
2439   }
2440 
2441   // fold ((A+(B+or-C))-B) -> A+or-C
2442   if (N0.getOpcode() == ISD::ADD &&
2443       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2444        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2445       N0.getOperand(1).getOperand(0) == N1)
2446     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2447                        N0.getOperand(1).getOperand(1));
2448 
2449   // fold ((A+(C+B))-B) -> A+C
2450   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2451       N0.getOperand(1).getOperand(1) == N1)
2452     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2453                        N0.getOperand(1).getOperand(0));
2454 
2455   // fold ((A-(B-C))-C) -> A-B
2456   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2457       N0.getOperand(1).getOperand(1) == N1)
2458     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2459                        N0.getOperand(1).getOperand(0));
2460 
2461   // If either operand of a sub is undef, the result is undef
2462   if (N0.isUndef())
2463     return N0;
2464   if (N1.isUndef())
2465     return N1;
2466 
2467   // If the relocation model supports it, consider symbol offsets.
2468   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2469     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2470       // fold (sub Sym, c) -> Sym-c
2471       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2472         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2473                                     GA->getOffset() -
2474                                         (uint64_t)N1C->getSExtValue());
2475       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2476       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2477         if (GA->getGlobal() == GB->getGlobal())
2478           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2479                                  DL, VT);
2480     }
2481 
2482   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2483   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2484     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2485     if (TN->getVT() == MVT::i1) {
2486       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2487                                  DAG.getConstant(1, DL, VT));
2488       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2489     }
2490   }
2491 
2492   return SDValue();
2493 }
2494 
2495 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2496   SDValue N0 = N->getOperand(0);
2497   SDValue N1 = N->getOperand(1);
2498   EVT VT = N0.getValueType();
2499   SDLoc DL(N);
2500 
2501   // If the flag result is dead, turn this into an SUB.
2502   if (!N->hasAnyUseOfValue(1))
2503     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2504                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2505 
2506   // fold (subc x, x) -> 0 + no borrow
2507   if (N0 == N1)
2508     return CombineTo(N, DAG.getConstant(0, DL, VT),
2509                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2510 
2511   // fold (subc x, 0) -> x + no borrow
2512   if (isNullConstant(N1))
2513     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2514 
2515   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2516   if (isAllOnesConstant(N0))
2517     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2518                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2519 
2520   return SDValue();
2521 }
2522 
2523 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2524   SDValue N0 = N->getOperand(0);
2525   SDValue N1 = N->getOperand(1);
2526   EVT VT = N0.getValueType();
2527   if (VT.isVector())
2528     return SDValue();
2529 
2530   EVT CarryVT = N->getValueType(1);
2531   SDLoc DL(N);
2532 
2533   // If the flag result is dead, turn this into an SUB.
2534   if (!N->hasAnyUseOfValue(1))
2535     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2536                      DAG.getUNDEF(CarryVT));
2537 
2538   // fold (usubo x, x) -> 0 + no borrow
2539   if (N0 == N1)
2540     return CombineTo(N, DAG.getConstant(0, DL, VT),
2541                      DAG.getConstant(0, DL, CarryVT));
2542 
2543   // fold (usubo x, 0) -> x + no borrow
2544   if (isNullConstant(N1))
2545     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2546 
2547   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2548   if (isAllOnesConstant(N0))
2549     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2550                      DAG.getConstant(0, DL, CarryVT));
2551 
2552   return SDValue();
2553 }
2554 
2555 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2556   SDValue N0 = N->getOperand(0);
2557   SDValue N1 = N->getOperand(1);
2558   SDValue CarryIn = N->getOperand(2);
2559 
2560   // fold (sube x, y, false) -> (subc x, y)
2561   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2562     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2563 
2564   return SDValue();
2565 }
2566 
2567 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2568   SDValue N0 = N->getOperand(0);
2569   SDValue N1 = N->getOperand(1);
2570   SDValue CarryIn = N->getOperand(2);
2571 
2572   // fold (subcarry x, y, false) -> (usubo x, y)
2573   if (isNullConstant(CarryIn))
2574     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2575 
2576   return SDValue();
2577 }
2578 
2579 SDValue DAGCombiner::visitMUL(SDNode *N) {
2580   SDValue N0 = N->getOperand(0);
2581   SDValue N1 = N->getOperand(1);
2582   EVT VT = N0.getValueType();
2583 
2584   // fold (mul x, undef) -> 0
2585   if (N0.isUndef() || N1.isUndef())
2586     return DAG.getConstant(0, SDLoc(N), VT);
2587 
2588   bool N0IsConst = false;
2589   bool N1IsConst = false;
2590   bool N1IsOpaqueConst = false;
2591   bool N0IsOpaqueConst = false;
2592   APInt ConstValue0, ConstValue1;
2593   // fold vector ops
2594   if (VT.isVector()) {
2595     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2596       return FoldedVOp;
2597 
2598     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2599     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2600     assert((!N0IsConst ||
2601             ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) &&
2602            "Splat APInt should be element width");
2603     assert((!N1IsConst ||
2604             ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
2605            "Splat APInt should be element width");
2606   } else {
2607     N0IsConst = isa<ConstantSDNode>(N0);
2608     if (N0IsConst) {
2609       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2610       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2611     }
2612     N1IsConst = isa<ConstantSDNode>(N1);
2613     if (N1IsConst) {
2614       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2615       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2616     }
2617   }
2618 
2619   // fold (mul c1, c2) -> c1*c2
2620   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2621     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2622                                       N0.getNode(), N1.getNode());
2623 
2624   // canonicalize constant to RHS (vector doesn't have to splat)
2625   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2626      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2627     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2628   // fold (mul x, 0) -> 0
2629   if (N1IsConst && ConstValue1.isNullValue())
2630     return N1;
2631   // fold (mul x, 1) -> x
2632   if (N1IsConst && ConstValue1.isOneValue())
2633     return N0;
2634 
2635   if (SDValue NewSel = foldBinOpIntoSelect(N))
2636     return NewSel;
2637 
2638   // fold (mul x, -1) -> 0-x
2639   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2640     SDLoc DL(N);
2641     return DAG.getNode(ISD::SUB, DL, VT,
2642                        DAG.getConstant(0, DL, VT), N0);
2643   }
2644   // fold (mul x, (1 << c)) -> x << c
2645   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2646       DAG.isKnownToBeAPowerOfTwo(N1)) {
2647     SDLoc DL(N);
2648     SDValue LogBase2 = BuildLogBase2(N1, DL);
2649     AddToWorklist(LogBase2.getNode());
2650 
2651     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2652     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2653     AddToWorklist(Trunc.getNode());
2654     return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
2655   }
2656   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2657   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
2658     unsigned Log2Val = (-ConstValue1).logBase2();
2659     SDLoc DL(N);
2660     // FIXME: If the input is something that is easily negated (e.g. a
2661     // single-use add), we should put the negate there.
2662     return DAG.getNode(ISD::SUB, DL, VT,
2663                        DAG.getConstant(0, DL, VT),
2664                        DAG.getNode(ISD::SHL, DL, VT, N0,
2665                             DAG.getConstant(Log2Val, DL,
2666                                       getShiftAmountTy(N0.getValueType()))));
2667   }
2668 
2669   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2670   if (N0.getOpcode() == ISD::SHL &&
2671       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2672       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2673     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2674     if (isConstantOrConstantVector(C3))
2675       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2676   }
2677 
2678   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2679   // use.
2680   {
2681     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2682 
2683     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2684     if (N0.getOpcode() == ISD::SHL &&
2685         isConstantOrConstantVector(N0.getOperand(1)) &&
2686         N0.getNode()->hasOneUse()) {
2687       Sh = N0; Y = N1;
2688     } else if (N1.getOpcode() == ISD::SHL &&
2689                isConstantOrConstantVector(N1.getOperand(1)) &&
2690                N1.getNode()->hasOneUse()) {
2691       Sh = N1; Y = N0;
2692     }
2693 
2694     if (Sh.getNode()) {
2695       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2696       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2697     }
2698   }
2699 
2700   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2701   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2702       N0.getOpcode() == ISD::ADD &&
2703       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2704       isMulAddWithConstProfitable(N, N0, N1))
2705       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2706                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2707                                      N0.getOperand(0), N1),
2708                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2709                                      N0.getOperand(1), N1));
2710 
2711   // reassociate mul
2712   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2713     return RMUL;
2714 
2715   return SDValue();
2716 }
2717 
2718 /// Return true if divmod libcall is available.
2719 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2720                                      const TargetLowering &TLI) {
2721   RTLIB::Libcall LC;
2722   EVT NodeType = Node->getValueType(0);
2723   if (!NodeType.isSimple())
2724     return false;
2725   switch (NodeType.getSimpleVT().SimpleTy) {
2726   default: return false; // No libcall for vector types.
2727   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2728   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2729   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2730   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2731   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2732   }
2733 
2734   return TLI.getLibcallName(LC) != nullptr;
2735 }
2736 
2737 /// Issue divrem if both quotient and remainder are needed.
2738 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2739   if (Node->use_empty())
2740     return SDValue(); // This is a dead node, leave it alone.
2741 
2742   unsigned Opcode = Node->getOpcode();
2743   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2744   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2745 
2746   // DivMod lib calls can still work on non-legal types if using lib-calls.
2747   EVT VT = Node->getValueType(0);
2748   if (VT.isVector() || !VT.isInteger())
2749     return SDValue();
2750 
2751   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2752     return SDValue();
2753 
2754   // If DIVREM is going to get expanded into a libcall,
2755   // but there is no libcall available, then don't combine.
2756   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2757       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2758     return SDValue();
2759 
2760   // If div is legal, it's better to do the normal expansion
2761   unsigned OtherOpcode = 0;
2762   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2763     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2764     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2765       return SDValue();
2766   } else {
2767     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2768     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2769       return SDValue();
2770   }
2771 
2772   SDValue Op0 = Node->getOperand(0);
2773   SDValue Op1 = Node->getOperand(1);
2774   SDValue combined;
2775   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2776          UE = Op0.getNode()->use_end(); UI != UE;) {
2777     SDNode *User = *UI++;
2778     if (User == Node || User->use_empty())
2779       continue;
2780     // Convert the other matching node(s), too;
2781     // otherwise, the DIVREM may get target-legalized into something
2782     // target-specific that we won't be able to recognize.
2783     unsigned UserOpc = User->getOpcode();
2784     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2785         User->getOperand(0) == Op0 &&
2786         User->getOperand(1) == Op1) {
2787       if (!combined) {
2788         if (UserOpc == OtherOpcode) {
2789           SDVTList VTs = DAG.getVTList(VT, VT);
2790           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2791         } else if (UserOpc == DivRemOpc) {
2792           combined = SDValue(User, 0);
2793         } else {
2794           assert(UserOpc == Opcode);
2795           continue;
2796         }
2797       }
2798       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2799         CombineTo(User, combined);
2800       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2801         CombineTo(User, combined.getValue(1));
2802     }
2803   }
2804   return combined;
2805 }
2806 
2807 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2808   SDValue N0 = N->getOperand(0);
2809   SDValue N1 = N->getOperand(1);
2810   EVT VT = N->getValueType(0);
2811   SDLoc DL(N);
2812 
2813   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2814     return DAG.getUNDEF(VT);
2815 
2816   // undef / X -> 0
2817   // undef % X -> 0
2818   if (N0.isUndef())
2819     return DAG.getConstant(0, DL, VT);
2820 
2821   return SDValue();
2822 }
2823 
2824 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2825   SDValue N0 = N->getOperand(0);
2826   SDValue N1 = N->getOperand(1);
2827   EVT VT = N->getValueType(0);
2828 
2829   // fold vector ops
2830   if (VT.isVector())
2831     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2832       return FoldedVOp;
2833 
2834   SDLoc DL(N);
2835 
2836   // fold (sdiv c1, c2) -> c1/c2
2837   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2838   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2839   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2840     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2841   // fold (sdiv X, 1) -> X
2842   if (N1C && N1C->isOne())
2843     return N0;
2844   // fold (sdiv X, -1) -> 0-X
2845   if (N1C && N1C->isAllOnesValue())
2846     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2847 
2848   if (SDValue V = simplifyDivRem(N, DAG))
2849     return V;
2850 
2851   if (SDValue NewSel = foldBinOpIntoSelect(N))
2852     return NewSel;
2853 
2854   // If we know the sign bits of both operands are zero, strength reduce to a
2855   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2856   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2857     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2858 
2859   // fold (sdiv X, pow2) -> simple ops after legalize
2860   // FIXME: We check for the exact bit here because the generic lowering gives
2861   // better results in that case. The target-specific lowering should learn how
2862   // to handle exact sdivs efficiently.
2863   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2864       !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2865                                     (-N1C->getAPIntValue()).isPowerOf2())) {
2866     // Target-specific implementation of sdiv x, pow2.
2867     if (SDValue Res = BuildSDIVPow2(N))
2868       return Res;
2869 
2870     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2871 
2872     // Splat the sign bit into the register
2873     SDValue SGN =
2874         DAG.getNode(ISD::SRA, DL, VT, N0,
2875                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2876                                     getShiftAmountTy(N0.getValueType())));
2877     AddToWorklist(SGN.getNode());
2878 
2879     // Add (N0 < 0) ? abs2 - 1 : 0;
2880     SDValue SRL =
2881         DAG.getNode(ISD::SRL, DL, VT, SGN,
2882                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2883                                     getShiftAmountTy(SGN.getValueType())));
2884     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2885     AddToWorklist(SRL.getNode());
2886     AddToWorklist(ADD.getNode());    // Divide by pow2
2887     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2888                   DAG.getConstant(lg2, DL,
2889                                   getShiftAmountTy(ADD.getValueType())));
2890 
2891     // If we're dividing by a positive value, we're done.  Otherwise, we must
2892     // negate the result.
2893     if (N1C->getAPIntValue().isNonNegative())
2894       return SRA;
2895 
2896     AddToWorklist(SRA.getNode());
2897     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2898   }
2899 
2900   // If integer divide is expensive and we satisfy the requirements, emit an
2901   // alternate sequence.  Targets may check function attributes for size/speed
2902   // trade-offs.
2903   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2904   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2905     if (SDValue Op = BuildSDIV(N))
2906       return Op;
2907 
2908   // sdiv, srem -> sdivrem
2909   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2910   // true.  Otherwise, we break the simplification logic in visitREM().
2911   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2912     if (SDValue DivRem = useDivRem(N))
2913         return DivRem;
2914 
2915   return SDValue();
2916 }
2917 
2918 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2919   SDValue N0 = N->getOperand(0);
2920   SDValue N1 = N->getOperand(1);
2921   EVT VT = N->getValueType(0);
2922 
2923   // fold vector ops
2924   if (VT.isVector())
2925     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2926       return FoldedVOp;
2927 
2928   SDLoc DL(N);
2929 
2930   // fold (udiv c1, c2) -> c1/c2
2931   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2932   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2933   if (N0C && N1C)
2934     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2935                                                     N0C, N1C))
2936       return Folded;
2937 
2938   if (SDValue V = simplifyDivRem(N, DAG))
2939     return V;
2940 
2941   if (SDValue NewSel = foldBinOpIntoSelect(N))
2942     return NewSel;
2943 
2944   // fold (udiv x, (1 << c)) -> x >>u c
2945   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2946       DAG.isKnownToBeAPowerOfTwo(N1)) {
2947     SDValue LogBase2 = BuildLogBase2(N1, DL);
2948     AddToWorklist(LogBase2.getNode());
2949 
2950     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2951     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2952     AddToWorklist(Trunc.getNode());
2953     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2954   }
2955 
2956   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2957   if (N1.getOpcode() == ISD::SHL) {
2958     SDValue N10 = N1.getOperand(0);
2959     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2960         DAG.isKnownToBeAPowerOfTwo(N10)) {
2961       SDValue LogBase2 = BuildLogBase2(N10, DL);
2962       AddToWorklist(LogBase2.getNode());
2963 
2964       EVT ADDVT = N1.getOperand(1).getValueType();
2965       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2966       AddToWorklist(Trunc.getNode());
2967       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2968       AddToWorklist(Add.getNode());
2969       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2970     }
2971   }
2972 
2973   // fold (udiv x, c) -> alternate
2974   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2975   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2976     if (SDValue Op = BuildUDIV(N))
2977       return Op;
2978 
2979   // sdiv, srem -> sdivrem
2980   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2981   // true.  Otherwise, we break the simplification logic in visitREM().
2982   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2983     if (SDValue DivRem = useDivRem(N))
2984         return DivRem;
2985 
2986   return SDValue();
2987 }
2988 
2989 // handles ISD::SREM and ISD::UREM
2990 SDValue DAGCombiner::visitREM(SDNode *N) {
2991   unsigned Opcode = N->getOpcode();
2992   SDValue N0 = N->getOperand(0);
2993   SDValue N1 = N->getOperand(1);
2994   EVT VT = N->getValueType(0);
2995   bool isSigned = (Opcode == ISD::SREM);
2996   SDLoc DL(N);
2997 
2998   // fold (rem c1, c2) -> c1%c2
2999   ConstantSDNode *N0C = isConstOrConstSplat(N0);
3000   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3001   if (N0C && N1C)
3002     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
3003       return Folded;
3004 
3005   if (SDValue V = simplifyDivRem(N, DAG))
3006     return V;
3007 
3008   if (SDValue NewSel = foldBinOpIntoSelect(N))
3009     return NewSel;
3010 
3011   if (isSigned) {
3012     // If we know the sign bits of both operands are zero, strength reduce to a
3013     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
3014     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3015       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
3016   } else {
3017     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
3018     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
3019       // fold (urem x, pow2) -> (and x, pow2-1)
3020       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3021       AddToWorklist(Add.getNode());
3022       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3023     }
3024     if (N1.getOpcode() == ISD::SHL &&
3025         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
3026       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
3027       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3028       AddToWorklist(Add.getNode());
3029       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3030     }
3031   }
3032 
3033   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
3034 
3035   // If X/C can be simplified by the division-by-constant logic, lower
3036   // X%C to the equivalent of X-X/C*C.
3037   // To avoid mangling nodes, this simplification requires that the combine()
3038   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
3039   // against this by skipping the simplification if isIntDivCheap().  When
3040   // div is not cheap, combine will not return a DIVREM.  Regardless,
3041   // checking cheapness here makes sense since the simplification results in
3042   // fatter code.
3043   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
3044     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3045     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
3046     AddToWorklist(Div.getNode());
3047     SDValue OptimizedDiv = combine(Div.getNode());
3048     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
3049       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
3050              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
3051       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
3052       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3053       AddToWorklist(Mul.getNode());
3054       return Sub;
3055     }
3056   }
3057 
3058   // sdiv, srem -> sdivrem
3059   if (SDValue DivRem = useDivRem(N))
3060     return DivRem.getValue(1);
3061 
3062   return SDValue();
3063 }
3064 
3065 SDValue DAGCombiner::visitMULHS(SDNode *N) {
3066   SDValue N0 = N->getOperand(0);
3067   SDValue N1 = N->getOperand(1);
3068   EVT VT = N->getValueType(0);
3069   SDLoc DL(N);
3070 
3071   // fold (mulhs x, 0) -> 0
3072   if (isNullConstant(N1))
3073     return N1;
3074   // fold (mulhs x, 1) -> (sra x, size(x)-1)
3075   if (isOneConstant(N1)) {
3076     SDLoc DL(N);
3077     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3078                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3079                                        getShiftAmountTy(N0.getValueType())));
3080   }
3081   // fold (mulhs x, undef) -> 0
3082   if (N0.isUndef() || N1.isUndef())
3083     return DAG.getConstant(0, SDLoc(N), VT);
3084 
3085   // If the type twice as wide is legal, transform the mulhs to a wider multiply
3086   // plus a shift.
3087   if (VT.isSimple() && !VT.isVector()) {
3088     MVT Simple = VT.getSimpleVT();
3089     unsigned SimpleSize = Simple.getSizeInBits();
3090     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3091     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3092       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3093       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3094       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3095       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3096             DAG.getConstant(SimpleSize, DL,
3097                             getShiftAmountTy(N1.getValueType())));
3098       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3099     }
3100   }
3101 
3102   return SDValue();
3103 }
3104 
3105 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3106   SDValue N0 = N->getOperand(0);
3107   SDValue N1 = N->getOperand(1);
3108   EVT VT = N->getValueType(0);
3109   SDLoc DL(N);
3110 
3111   // fold (mulhu x, 0) -> 0
3112   if (isNullConstant(N1))
3113     return N1;
3114   // fold (mulhu x, 1) -> 0
3115   if (isOneConstant(N1))
3116     return DAG.getConstant(0, DL, N0.getValueType());
3117   // fold (mulhu x, undef) -> 0
3118   if (N0.isUndef() || N1.isUndef())
3119     return DAG.getConstant(0, DL, VT);
3120 
3121   // If the type twice as wide is legal, transform the mulhu to a wider multiply
3122   // plus a shift.
3123   if (VT.isSimple() && !VT.isVector()) {
3124     MVT Simple = VT.getSimpleVT();
3125     unsigned SimpleSize = Simple.getSizeInBits();
3126     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3127     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3128       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3129       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3130       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3131       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3132             DAG.getConstant(SimpleSize, DL,
3133                             getShiftAmountTy(N1.getValueType())));
3134       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3135     }
3136   }
3137 
3138   return SDValue();
3139 }
3140 
3141 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3142 /// give the opcodes for the two computations that are being performed. Return
3143 /// true if a simplification was made.
3144 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3145                                                 unsigned HiOp) {
3146   // If the high half is not needed, just compute the low half.
3147   bool HiExists = N->hasAnyUseOfValue(1);
3148   if (!HiExists &&
3149       (!LegalOperations ||
3150        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3151     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3152     return CombineTo(N, Res, Res);
3153   }
3154 
3155   // If the low half is not needed, just compute the high half.
3156   bool LoExists = N->hasAnyUseOfValue(0);
3157   if (!LoExists &&
3158       (!LegalOperations ||
3159        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3160     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3161     return CombineTo(N, Res, Res);
3162   }
3163 
3164   // If both halves are used, return as it is.
3165   if (LoExists && HiExists)
3166     return SDValue();
3167 
3168   // If the two computed results can be simplified separately, separate them.
3169   if (LoExists) {
3170     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3171     AddToWorklist(Lo.getNode());
3172     SDValue LoOpt = combine(Lo.getNode());
3173     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3174         (!LegalOperations ||
3175          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3176       return CombineTo(N, LoOpt, LoOpt);
3177   }
3178 
3179   if (HiExists) {
3180     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3181     AddToWorklist(Hi.getNode());
3182     SDValue HiOpt = combine(Hi.getNode());
3183     if (HiOpt.getNode() && HiOpt != Hi &&
3184         (!LegalOperations ||
3185          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3186       return CombineTo(N, HiOpt, HiOpt);
3187   }
3188 
3189   return SDValue();
3190 }
3191 
3192 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3193   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3194     return Res;
3195 
3196   EVT VT = N->getValueType(0);
3197   SDLoc DL(N);
3198 
3199   // If the type is twice as wide is legal, transform the mulhu to a wider
3200   // multiply plus a shift.
3201   if (VT.isSimple() && !VT.isVector()) {
3202     MVT Simple = VT.getSimpleVT();
3203     unsigned SimpleSize = Simple.getSizeInBits();
3204     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3205     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3206       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3207       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3208       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3209       // Compute the high part as N1.
3210       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3211             DAG.getConstant(SimpleSize, DL,
3212                             getShiftAmountTy(Lo.getValueType())));
3213       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3214       // Compute the low part as N0.
3215       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3216       return CombineTo(N, Lo, Hi);
3217     }
3218   }
3219 
3220   return SDValue();
3221 }
3222 
3223 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3224   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3225     return Res;
3226 
3227   EVT VT = N->getValueType(0);
3228   SDLoc DL(N);
3229 
3230   // If the type is twice as wide is legal, transform the mulhu to a wider
3231   // multiply plus a shift.
3232   if (VT.isSimple() && !VT.isVector()) {
3233     MVT Simple = VT.getSimpleVT();
3234     unsigned SimpleSize = Simple.getSizeInBits();
3235     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3236     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3237       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3238       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3239       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3240       // Compute the high part as N1.
3241       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3242             DAG.getConstant(SimpleSize, DL,
3243                             getShiftAmountTy(Lo.getValueType())));
3244       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3245       // Compute the low part as N0.
3246       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3247       return CombineTo(N, Lo, Hi);
3248     }
3249   }
3250 
3251   return SDValue();
3252 }
3253 
3254 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3255   // (smulo x, 2) -> (saddo x, x)
3256   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3257     if (C2->getAPIntValue() == 2)
3258       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3259                          N->getOperand(0), N->getOperand(0));
3260 
3261   return SDValue();
3262 }
3263 
3264 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3265   // (umulo x, 2) -> (uaddo x, x)
3266   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3267     if (C2->getAPIntValue() == 2)
3268       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3269                          N->getOperand(0), N->getOperand(0));
3270 
3271   return SDValue();
3272 }
3273 
3274 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3275   SDValue N0 = N->getOperand(0);
3276   SDValue N1 = N->getOperand(1);
3277   EVT VT = N0.getValueType();
3278 
3279   // fold vector ops
3280   if (VT.isVector())
3281     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3282       return FoldedVOp;
3283 
3284   // fold operation with constant operands.
3285   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3286   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3287   if (N0C && N1C)
3288     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3289 
3290   // canonicalize constant to RHS
3291   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3292      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3293     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3294 
3295   return SDValue();
3296 }
3297 
3298 /// If this is a binary operator with two operands of the same opcode, try to
3299 /// simplify it.
3300 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3301   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3302   EVT VT = N0.getValueType();
3303   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3304 
3305   // Bail early if none of these transforms apply.
3306   if (N0.getNumOperands() == 0) return SDValue();
3307 
3308   // For each of OP in AND/OR/XOR:
3309   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3310   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3311   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3312   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3313   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3314   //
3315   // do not sink logical op inside of a vector extend, since it may combine
3316   // into a vsetcc.
3317   EVT Op0VT = N0.getOperand(0).getValueType();
3318   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3319        N0.getOpcode() == ISD::SIGN_EXTEND ||
3320        N0.getOpcode() == ISD::BSWAP ||
3321        // Avoid infinite looping with PromoteIntBinOp.
3322        (N0.getOpcode() == ISD::ANY_EXTEND &&
3323         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3324        (N0.getOpcode() == ISD::TRUNCATE &&
3325         (!TLI.isZExtFree(VT, Op0VT) ||
3326          !TLI.isTruncateFree(Op0VT, VT)) &&
3327         TLI.isTypeLegal(Op0VT))) &&
3328       !VT.isVector() &&
3329       Op0VT == N1.getOperand(0).getValueType() &&
3330       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3331     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3332                                  N0.getOperand(0).getValueType(),
3333                                  N0.getOperand(0), N1.getOperand(0));
3334     AddToWorklist(ORNode.getNode());
3335     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3336   }
3337 
3338   // For each of OP in SHL/SRL/SRA/AND...
3339   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3340   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3341   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3342   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3343        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3344       N0.getOperand(1) == N1.getOperand(1)) {
3345     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3346                                  N0.getOperand(0).getValueType(),
3347                                  N0.getOperand(0), N1.getOperand(0));
3348     AddToWorklist(ORNode.getNode());
3349     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3350                        ORNode, N0.getOperand(1));
3351   }
3352 
3353   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3354   // Only perform this optimization up until type legalization, before
3355   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3356   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3357   // we don't want to undo this promotion.
3358   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3359   // on scalars.
3360   if ((N0.getOpcode() == ISD::BITCAST ||
3361        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3362        Level <= AfterLegalizeTypes) {
3363     SDValue In0 = N0.getOperand(0);
3364     SDValue In1 = N1.getOperand(0);
3365     EVT In0Ty = In0.getValueType();
3366     EVT In1Ty = In1.getValueType();
3367     SDLoc DL(N);
3368     // If both incoming values are integers, and the original types are the
3369     // same.
3370     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3371       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3372       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3373       AddToWorklist(Op.getNode());
3374       return BC;
3375     }
3376   }
3377 
3378   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3379   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3380   // If both shuffles use the same mask, and both shuffle within a single
3381   // vector, then it is worthwhile to move the swizzle after the operation.
3382   // The type-legalizer generates this pattern when loading illegal
3383   // vector types from memory. In many cases this allows additional shuffle
3384   // optimizations.
3385   // There are other cases where moving the shuffle after the xor/and/or
3386   // is profitable even if shuffles don't perform a swizzle.
3387   // If both shuffles use the same mask, and both shuffles have the same first
3388   // or second operand, then it might still be profitable to move the shuffle
3389   // after the xor/and/or operation.
3390   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3391     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3392     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3393 
3394     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3395            "Inputs to shuffles are not the same type");
3396 
3397     // Check that both shuffles use the same mask. The masks are known to be of
3398     // the same length because the result vector type is the same.
3399     // Check also that shuffles have only one use to avoid introducing extra
3400     // instructions.
3401     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3402         SVN0->getMask().equals(SVN1->getMask())) {
3403       SDValue ShOp = N0->getOperand(1);
3404 
3405       // Don't try to fold this node if it requires introducing a
3406       // build vector of all zeros that might be illegal at this stage.
3407       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3408         if (!LegalTypes)
3409           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3410         else
3411           ShOp = SDValue();
3412       }
3413 
3414       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3415       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3416       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3417       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3418         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3419                                       N0->getOperand(0), N1->getOperand(0));
3420         AddToWorklist(NewNode.getNode());
3421         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3422                                     SVN0->getMask());
3423       }
3424 
3425       // Don't try to fold this node if it requires introducing a
3426       // build vector of all zeros that might be illegal at this stage.
3427       ShOp = N0->getOperand(0);
3428       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3429         if (!LegalTypes)
3430           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3431         else
3432           ShOp = SDValue();
3433       }
3434 
3435       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3436       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3437       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3438       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3439         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3440                                       N0->getOperand(1), N1->getOperand(1));
3441         AddToWorklist(NewNode.getNode());
3442         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3443                                     SVN0->getMask());
3444       }
3445     }
3446   }
3447 
3448   return SDValue();
3449 }
3450 
3451 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3452 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3453                                        const SDLoc &DL) {
3454   SDValue LL, LR, RL, RR, N0CC, N1CC;
3455   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3456       !isSetCCEquivalent(N1, RL, RR, N1CC))
3457     return SDValue();
3458 
3459   assert(N0.getValueType() == N1.getValueType() &&
3460          "Unexpected operand types for bitwise logic op");
3461   assert(LL.getValueType() == LR.getValueType() &&
3462          RL.getValueType() == RR.getValueType() &&
3463          "Unexpected operand types for setcc");
3464 
3465   // If we're here post-legalization or the logic op type is not i1, the logic
3466   // op type must match a setcc result type. Also, all folds require new
3467   // operations on the left and right operands, so those types must match.
3468   EVT VT = N0.getValueType();
3469   EVT OpVT = LL.getValueType();
3470   if (LegalOperations || VT != MVT::i1)
3471     if (VT != getSetCCResultType(OpVT))
3472       return SDValue();
3473   if (OpVT != RL.getValueType())
3474     return SDValue();
3475 
3476   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3477   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3478   bool IsInteger = OpVT.isInteger();
3479   if (LR == RR && CC0 == CC1 && IsInteger) {
3480     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3481     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3482 
3483     // All bits clear?
3484     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3485     // All sign bits clear?
3486     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3487     // Any bits set?
3488     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3489     // Any sign bits set?
3490     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3491 
3492     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3493     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3494     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3495     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3496     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3497       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3498       AddToWorklist(Or.getNode());
3499       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3500     }
3501 
3502     // All bits set?
3503     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3504     // All sign bits set?
3505     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3506     // Any bits clear?
3507     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3508     // Any sign bits clear?
3509     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3510 
3511     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3512     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3513     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3514     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3515     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3516       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3517       AddToWorklist(And.getNode());
3518       return DAG.getSetCC(DL, VT, And, LR, CC1);
3519     }
3520   }
3521 
3522   // TODO: What is the 'or' equivalent of this fold?
3523   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3524   if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3525       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3526        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3527     SDValue One = DAG.getConstant(1, DL, OpVT);
3528     SDValue Two = DAG.getConstant(2, DL, OpVT);
3529     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3530     AddToWorklist(Add.getNode());
3531     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3532   }
3533 
3534   // Try more general transforms if the predicates match and the only user of
3535   // the compares is the 'and' or 'or'.
3536   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3537       N0.hasOneUse() && N1.hasOneUse()) {
3538     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3539     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3540     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3541       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3542       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3543       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3544       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3545       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3546     }
3547   }
3548 
3549   // Canonicalize equivalent operands to LL == RL.
3550   if (LL == RR && LR == RL) {
3551     CC1 = ISD::getSetCCSwappedOperands(CC1);
3552     std::swap(RL, RR);
3553   }
3554 
3555   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3556   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3557   if (LL == RL && LR == RR) {
3558     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3559                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3560     if (NewCC != ISD::SETCC_INVALID &&
3561         (!LegalOperations ||
3562          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3563           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3564       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3565   }
3566 
3567   return SDValue();
3568 }
3569 
3570 /// This contains all DAGCombine rules which reduce two values combined by
3571 /// an And operation to a single value. This makes them reusable in the context
3572 /// of visitSELECT(). Rules involving constants are not included as
3573 /// visitSELECT() already handles those cases.
3574 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3575   EVT VT = N1.getValueType();
3576   SDLoc DL(N);
3577 
3578   // fold (and x, undef) -> 0
3579   if (N0.isUndef() || N1.isUndef())
3580     return DAG.getConstant(0, DL, VT);
3581 
3582   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3583     return V;
3584 
3585   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3586       VT.getSizeInBits() <= 64) {
3587     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3588       APInt ADDC = ADDI->getAPIntValue();
3589       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3590         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3591         // immediate for an add, but it is legal if its top c2 bits are set,
3592         // transform the ADD so the immediate doesn't need to be materialized
3593         // in a register.
3594         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3595           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3596                                              SRLI->getZExtValue());
3597           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3598             ADDC |= Mask;
3599             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3600               SDLoc DL0(N0);
3601               SDValue NewAdd =
3602                 DAG.getNode(ISD::ADD, DL0, VT,
3603                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3604               CombineTo(N0.getNode(), NewAdd);
3605               // Return N so it doesn't get rechecked!
3606               return SDValue(N, 0);
3607             }
3608           }
3609         }
3610       }
3611     }
3612   }
3613 
3614   // Reduce bit extract of low half of an integer to the narrower type.
3615   // (and (srl i64:x, K), KMask) ->
3616   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3617   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3618     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3619       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3620         unsigned Size = VT.getSizeInBits();
3621         const APInt &AndMask = CAnd->getAPIntValue();
3622         unsigned ShiftBits = CShift->getZExtValue();
3623 
3624         // Bail out, this node will probably disappear anyway.
3625         if (ShiftBits == 0)
3626           return SDValue();
3627 
3628         unsigned MaskBits = AndMask.countTrailingOnes();
3629         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3630 
3631         if (AndMask.isMask() &&
3632             // Required bits must not span the two halves of the integer and
3633             // must fit in the half size type.
3634             (ShiftBits + MaskBits <= Size / 2) &&
3635             TLI.isNarrowingProfitable(VT, HalfVT) &&
3636             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3637             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3638             TLI.isTruncateFree(VT, HalfVT) &&
3639             TLI.isZExtFree(HalfVT, VT)) {
3640           // The isNarrowingProfitable is to avoid regressions on PPC and
3641           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3642           // on downstream users of this. Those patterns could probably be
3643           // extended to handle extensions mixed in.
3644 
3645           SDValue SL(N0);
3646           assert(MaskBits <= Size);
3647 
3648           // Extracting the highest bit of the low half.
3649           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3650           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3651                                       N0.getOperand(0));
3652 
3653           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3654           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3655           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3656           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3657           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3658         }
3659       }
3660     }
3661   }
3662 
3663   return SDValue();
3664 }
3665 
3666 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3667                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3668                                    bool &NarrowLoad) {
3669   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3670 
3671   if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3672     return false;
3673 
3674   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3675   LoadedVT = LoadN->getMemoryVT();
3676 
3677   if (ExtVT == LoadedVT &&
3678       (!LegalOperations ||
3679        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3680     // ZEXTLOAD will match without needing to change the size of the value being
3681     // loaded.
3682     NarrowLoad = false;
3683     return true;
3684   }
3685 
3686   // Do not change the width of a volatile load.
3687   if (LoadN->isVolatile())
3688     return false;
3689 
3690   // Do not generate loads of non-round integer types since these can
3691   // be expensive (and would be wrong if the type is not byte sized).
3692   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3693     return false;
3694 
3695   if (LegalOperations &&
3696       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3697     return false;
3698 
3699   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3700     return false;
3701 
3702   NarrowLoad = true;
3703   return true;
3704 }
3705 
3706 SDValue DAGCombiner::visitAND(SDNode *N) {
3707   SDValue N0 = N->getOperand(0);
3708   SDValue N1 = N->getOperand(1);
3709   EVT VT = N1.getValueType();
3710 
3711   // x & x --> x
3712   if (N0 == N1)
3713     return N0;
3714 
3715   // fold vector ops
3716   if (VT.isVector()) {
3717     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3718       return FoldedVOp;
3719 
3720     // fold (and x, 0) -> 0, vector edition
3721     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3722       // do not return N0, because undef node may exist in N0
3723       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3724                              SDLoc(N), N0.getValueType());
3725     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3726       // do not return N1, because undef node may exist in N1
3727       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3728                              SDLoc(N), N1.getValueType());
3729 
3730     // fold (and x, -1) -> x, vector edition
3731     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3732       return N1;
3733     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3734       return N0;
3735   }
3736 
3737   // fold (and c1, c2) -> c1&c2
3738   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3739   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3740   if (N0C && N1C && !N1C->isOpaque())
3741     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3742   // canonicalize constant to RHS
3743   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3744      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3745     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3746   // fold (and x, -1) -> x
3747   if (isAllOnesConstant(N1))
3748     return N0;
3749   // if (and x, c) is known to be zero, return 0
3750   unsigned BitWidth = VT.getScalarSizeInBits();
3751   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3752                                    APInt::getAllOnesValue(BitWidth)))
3753     return DAG.getConstant(0, SDLoc(N), VT);
3754 
3755   if (SDValue NewSel = foldBinOpIntoSelect(N))
3756     return NewSel;
3757 
3758   // reassociate and
3759   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3760     return RAND;
3761   // fold (and (or x, C), D) -> D if (C & D) == D
3762   if (N1C && N0.getOpcode() == ISD::OR)
3763     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3764       if (N1C->getAPIntValue().isSubsetOf(ORI->getAPIntValue()))
3765         return N1;
3766   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3767   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3768     SDValue N0Op0 = N0.getOperand(0);
3769     APInt Mask = ~N1C->getAPIntValue();
3770     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3771     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3772       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3773                                  N0.getValueType(), N0Op0);
3774 
3775       // Replace uses of the AND with uses of the Zero extend node.
3776       CombineTo(N, Zext);
3777 
3778       // We actually want to replace all uses of the any_extend with the
3779       // zero_extend, to avoid duplicating things.  This will later cause this
3780       // AND to be folded.
3781       CombineTo(N0.getNode(), Zext);
3782       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3783     }
3784   }
3785   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3786   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3787   // already be zero by virtue of the width of the base type of the load.
3788   //
3789   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3790   // more cases.
3791   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3792        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3793        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3794        N0.getOperand(0).getResNo() == 0) ||
3795       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3796     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3797                                          N0 : N0.getOperand(0) );
3798 
3799     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3800     // This can be a pure constant or a vector splat, in which case we treat the
3801     // vector as a scalar and use the splat value.
3802     APInt Constant = APInt::getNullValue(1);
3803     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3804       Constant = C->getAPIntValue();
3805     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3806       APInt SplatValue, SplatUndef;
3807       unsigned SplatBitSize;
3808       bool HasAnyUndefs;
3809       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3810                                              SplatBitSize, HasAnyUndefs);
3811       if (IsSplat) {
3812         // Undef bits can contribute to a possible optimisation if set, so
3813         // set them.
3814         SplatValue |= SplatUndef;
3815 
3816         // The splat value may be something like "0x00FFFFFF", which means 0 for
3817         // the first vector value and FF for the rest, repeating. We need a mask
3818         // that will apply equally to all members of the vector, so AND all the
3819         // lanes of the constant together.
3820         EVT VT = Vector->getValueType(0);
3821         unsigned BitWidth = VT.getScalarSizeInBits();
3822 
3823         // If the splat value has been compressed to a bitlength lower
3824         // than the size of the vector lane, we need to re-expand it to
3825         // the lane size.
3826         if (BitWidth > SplatBitSize)
3827           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3828                SplatBitSize < BitWidth;
3829                SplatBitSize = SplatBitSize * 2)
3830             SplatValue |= SplatValue.shl(SplatBitSize);
3831 
3832         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3833         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3834         if (SplatBitSize % BitWidth == 0) {
3835           Constant = APInt::getAllOnesValue(BitWidth);
3836           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3837             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3838         }
3839       }
3840     }
3841 
3842     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3843     // actually legal and isn't going to get expanded, else this is a false
3844     // optimisation.
3845     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3846                                                     Load->getValueType(0),
3847                                                     Load->getMemoryVT());
3848 
3849     // Resize the constant to the same size as the original memory access before
3850     // extension. If it is still the AllOnesValue then this AND is completely
3851     // unneeded.
3852     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3853 
3854     bool B;
3855     switch (Load->getExtensionType()) {
3856     default: B = false; break;
3857     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3858     case ISD::ZEXTLOAD:
3859     case ISD::NON_EXTLOAD: B = true; break;
3860     }
3861 
3862     if (B && Constant.isAllOnesValue()) {
3863       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3864       // preserve semantics once we get rid of the AND.
3865       SDValue NewLoad(Load, 0);
3866 
3867       // Fold the AND away. NewLoad may get replaced immediately.
3868       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3869 
3870       if (Load->getExtensionType() == ISD::EXTLOAD) {
3871         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3872                               Load->getValueType(0), SDLoc(Load),
3873                               Load->getChain(), Load->getBasePtr(),
3874                               Load->getOffset(), Load->getMemoryVT(),
3875                               Load->getMemOperand());
3876         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3877         if (Load->getNumValues() == 3) {
3878           // PRE/POST_INC loads have 3 values.
3879           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3880                            NewLoad.getValue(2) };
3881           CombineTo(Load, To, 3, true);
3882         } else {
3883           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3884         }
3885       }
3886 
3887       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3888     }
3889   }
3890 
3891   // fold (and (load x), 255) -> (zextload x, i8)
3892   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3893   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3894   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3895                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3896                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3897     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3898     LoadSDNode *LN0 = HasAnyExt
3899       ? cast<LoadSDNode>(N0.getOperand(0))
3900       : cast<LoadSDNode>(N0);
3901     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3902         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3903       auto NarrowLoad = false;
3904       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3905       EVT ExtVT, LoadedVT;
3906       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3907                            NarrowLoad)) {
3908         if (!NarrowLoad) {
3909           SDValue NewLoad =
3910             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3911                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3912                            LN0->getMemOperand());
3913           AddToWorklist(N);
3914           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3915           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3916         } else {
3917           EVT PtrType = LN0->getOperand(1).getValueType();
3918 
3919           unsigned Alignment = LN0->getAlignment();
3920           SDValue NewPtr = LN0->getBasePtr();
3921 
3922           // For big endian targets, we need to add an offset to the pointer
3923           // to load the correct bytes.  For little endian systems, we merely
3924           // need to read fewer bytes from the same pointer.
3925           if (DAG.getDataLayout().isBigEndian()) {
3926             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3927             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3928             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3929             SDLoc DL(LN0);
3930             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3931                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3932             Alignment = MinAlign(Alignment, PtrOff);
3933           }
3934 
3935           AddToWorklist(NewPtr.getNode());
3936 
3937           SDValue Load = DAG.getExtLoad(
3938               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3939               LN0->getPointerInfo(), ExtVT, Alignment,
3940               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3941           AddToWorklist(N);
3942           CombineTo(LN0, Load, Load.getValue(1));
3943           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3944         }
3945       }
3946     }
3947   }
3948 
3949   if (SDValue Combined = visitANDLike(N0, N1, N))
3950     return Combined;
3951 
3952   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3953   if (N0.getOpcode() == N1.getOpcode())
3954     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3955       return Tmp;
3956 
3957   // Masking the negated extension of a boolean is just the zero-extended
3958   // boolean:
3959   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3960   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3961   //
3962   // Note: the SimplifyDemandedBits fold below can make an information-losing
3963   // transform, and then we have no way to find this better fold.
3964   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3965     if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
3966       SDValue SubRHS = N0.getOperand(1);
3967       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3968           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3969         return SubRHS;
3970       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3971           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3972         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3973     }
3974   }
3975 
3976   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3977   // fold (and (sra)) -> (and (srl)) when possible.
3978   if (SimplifyDemandedBits(SDValue(N, 0)))
3979     return SDValue(N, 0);
3980 
3981   // fold (zext_inreg (extload x)) -> (zextload x)
3982   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3983     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3984     EVT MemVT = LN0->getMemoryVT();
3985     // If we zero all the possible extended bits, then we can turn this into
3986     // a zextload if we are running before legalize or the operation is legal.
3987     unsigned BitWidth = N1.getScalarValueSizeInBits();
3988     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3989                            BitWidth - MemVT.getScalarSizeInBits())) &&
3990         ((!LegalOperations && !LN0->isVolatile()) ||
3991          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3992       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3993                                        LN0->getChain(), LN0->getBasePtr(),
3994                                        MemVT, LN0->getMemOperand());
3995       AddToWorklist(N);
3996       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3997       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3998     }
3999   }
4000   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
4001   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4002       N0.hasOneUse()) {
4003     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4004     EVT MemVT = LN0->getMemoryVT();
4005     // If we zero all the possible extended bits, then we can turn this into
4006     // a zextload if we are running before legalize or the operation is legal.
4007     unsigned BitWidth = N1.getScalarValueSizeInBits();
4008     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4009                            BitWidth - MemVT.getScalarSizeInBits())) &&
4010         ((!LegalOperations && !LN0->isVolatile()) ||
4011          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4012       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4013                                        LN0->getChain(), LN0->getBasePtr(),
4014                                        MemVT, LN0->getMemOperand());
4015       AddToWorklist(N);
4016       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4017       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4018     }
4019   }
4020   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
4021   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
4022     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
4023                                            N0.getOperand(1), false))
4024       return BSwap;
4025   }
4026 
4027   return SDValue();
4028 }
4029 
4030 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
4031 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
4032                                         bool DemandHighBits) {
4033   if (!LegalOperations)
4034     return SDValue();
4035 
4036   EVT VT = N->getValueType(0);
4037   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
4038     return SDValue();
4039   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4040     return SDValue();
4041 
4042   // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
4043   bool LookPassAnd0 = false;
4044   bool LookPassAnd1 = false;
4045   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
4046       std::swap(N0, N1);
4047   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
4048       std::swap(N0, N1);
4049   if (N0.getOpcode() == ISD::AND) {
4050     if (!N0.getNode()->hasOneUse())
4051       return SDValue();
4052     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4053     if (!N01C || N01C->getZExtValue() != 0xFF00)
4054       return SDValue();
4055     N0 = N0.getOperand(0);
4056     LookPassAnd0 = true;
4057   }
4058 
4059   if (N1.getOpcode() == ISD::AND) {
4060     if (!N1.getNode()->hasOneUse())
4061       return SDValue();
4062     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4063     if (!N11C || N11C->getZExtValue() != 0xFF)
4064       return SDValue();
4065     N1 = N1.getOperand(0);
4066     LookPassAnd1 = true;
4067   }
4068 
4069   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
4070     std::swap(N0, N1);
4071   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
4072     return SDValue();
4073   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4074     return SDValue();
4075 
4076   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4077   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4078   if (!N01C || !N11C)
4079     return SDValue();
4080   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4081     return SDValue();
4082 
4083   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4084   SDValue N00 = N0->getOperand(0);
4085   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4086     if (!N00.getNode()->hasOneUse())
4087       return SDValue();
4088     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4089     if (!N001C || N001C->getZExtValue() != 0xFF)
4090       return SDValue();
4091     N00 = N00.getOperand(0);
4092     LookPassAnd0 = true;
4093   }
4094 
4095   SDValue N10 = N1->getOperand(0);
4096   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4097     if (!N10.getNode()->hasOneUse())
4098       return SDValue();
4099     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4100     if (!N101C || N101C->getZExtValue() != 0xFF00)
4101       return SDValue();
4102     N10 = N10.getOperand(0);
4103     LookPassAnd1 = true;
4104   }
4105 
4106   if (N00 != N10)
4107     return SDValue();
4108 
4109   // Make sure everything beyond the low halfword gets set to zero since the SRL
4110   // 16 will clear the top bits.
4111   unsigned OpSizeInBits = VT.getSizeInBits();
4112   if (DemandHighBits && OpSizeInBits > 16) {
4113     // If the left-shift isn't masked out then the only way this is a bswap is
4114     // if all bits beyond the low 8 are 0. In that case the entire pattern
4115     // reduces to a left shift anyway: leave it for other parts of the combiner.
4116     if (!LookPassAnd0)
4117       return SDValue();
4118 
4119     // However, if the right shift isn't masked out then it might be because
4120     // it's not needed. See if we can spot that too.
4121     if (!LookPassAnd1 &&
4122         !DAG.MaskedValueIsZero(
4123             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4124       return SDValue();
4125   }
4126 
4127   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4128   if (OpSizeInBits > 16) {
4129     SDLoc DL(N);
4130     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4131                       DAG.getConstant(OpSizeInBits - 16, DL,
4132                                       getShiftAmountTy(VT)));
4133   }
4134   return Res;
4135 }
4136 
4137 /// Return true if the specified node is an element that makes up a 32-bit
4138 /// packed halfword byteswap.
4139 /// ((x & 0x000000ff) << 8) |
4140 /// ((x & 0x0000ff00) >> 8) |
4141 /// ((x & 0x00ff0000) << 8) |
4142 /// ((x & 0xff000000) >> 8)
4143 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4144   if (!N.getNode()->hasOneUse())
4145     return false;
4146 
4147   unsigned Opc = N.getOpcode();
4148   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4149     return false;
4150 
4151   SDValue N0 = N.getOperand(0);
4152   unsigned Opc0 = N0.getOpcode();
4153   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4154     return false;
4155 
4156   ConstantSDNode *N1C = nullptr;
4157   // SHL or SRL: look upstream for AND mask operand
4158   if (Opc == ISD::AND)
4159     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4160   else if (Opc0 == ISD::AND)
4161     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4162   if (!N1C)
4163     return false;
4164 
4165   unsigned MaskByteOffset;
4166   switch (N1C->getZExtValue()) {
4167   default:
4168     return false;
4169   case 0xFF:       MaskByteOffset = 0; break;
4170   case 0xFF00:     MaskByteOffset = 1; break;
4171   case 0xFF0000:   MaskByteOffset = 2; break;
4172   case 0xFF000000: MaskByteOffset = 3; break;
4173   }
4174 
4175   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4176   if (Opc == ISD::AND) {
4177     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4178       // (x >> 8) & 0xff
4179       // (x >> 8) & 0xff0000
4180       if (Opc0 != ISD::SRL)
4181         return false;
4182       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4183       if (!C || C->getZExtValue() != 8)
4184         return false;
4185     } else {
4186       // (x << 8) & 0xff00
4187       // (x << 8) & 0xff000000
4188       if (Opc0 != ISD::SHL)
4189         return false;
4190       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4191       if (!C || C->getZExtValue() != 8)
4192         return false;
4193     }
4194   } else if (Opc == ISD::SHL) {
4195     // (x & 0xff) << 8
4196     // (x & 0xff0000) << 8
4197     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4198       return false;
4199     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4200     if (!C || C->getZExtValue() != 8)
4201       return false;
4202   } else { // Opc == ISD::SRL
4203     // (x & 0xff00) >> 8
4204     // (x & 0xff000000) >> 8
4205     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4206       return false;
4207     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4208     if (!C || C->getZExtValue() != 8)
4209       return false;
4210   }
4211 
4212   if (Parts[MaskByteOffset])
4213     return false;
4214 
4215   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4216   return true;
4217 }
4218 
4219 /// Match a 32-bit packed halfword bswap. That is
4220 /// ((x & 0x000000ff) << 8) |
4221 /// ((x & 0x0000ff00) >> 8) |
4222 /// ((x & 0x00ff0000) << 8) |
4223 /// ((x & 0xff000000) >> 8)
4224 /// => (rotl (bswap x), 16)
4225 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4226   if (!LegalOperations)
4227     return SDValue();
4228 
4229   EVT VT = N->getValueType(0);
4230   if (VT != MVT::i32)
4231     return SDValue();
4232   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4233     return SDValue();
4234 
4235   // Look for either
4236   // (or (or (and), (and)), (or (and), (and)))
4237   // (or (or (or (and), (and)), (and)), (and))
4238   if (N0.getOpcode() != ISD::OR)
4239     return SDValue();
4240   SDValue N00 = N0.getOperand(0);
4241   SDValue N01 = N0.getOperand(1);
4242   SDNode *Parts[4] = {};
4243 
4244   if (N1.getOpcode() == ISD::OR &&
4245       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4246     // (or (or (and), (and)), (or (and), (and)))
4247     if (!isBSwapHWordElement(N00, Parts))
4248       return SDValue();
4249 
4250     if (!isBSwapHWordElement(N01, Parts))
4251       return SDValue();
4252     SDValue N10 = N1.getOperand(0);
4253     if (!isBSwapHWordElement(N10, Parts))
4254       return SDValue();
4255     SDValue N11 = N1.getOperand(1);
4256     if (!isBSwapHWordElement(N11, Parts))
4257       return SDValue();
4258   } else {
4259     // (or (or (or (and), (and)), (and)), (and))
4260     if (!isBSwapHWordElement(N1, Parts))
4261       return SDValue();
4262     if (!isBSwapHWordElement(N01, Parts))
4263       return SDValue();
4264     if (N00.getOpcode() != ISD::OR)
4265       return SDValue();
4266     SDValue N000 = N00.getOperand(0);
4267     if (!isBSwapHWordElement(N000, Parts))
4268       return SDValue();
4269     SDValue N001 = N00.getOperand(1);
4270     if (!isBSwapHWordElement(N001, Parts))
4271       return SDValue();
4272   }
4273 
4274   // Make sure the parts are all coming from the same node.
4275   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4276     return SDValue();
4277 
4278   SDLoc DL(N);
4279   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4280                               SDValue(Parts[0], 0));
4281 
4282   // Result of the bswap should be rotated by 16. If it's not legal, then
4283   // do  (x << 16) | (x >> 16).
4284   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4285   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4286     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4287   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4288     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4289   return DAG.getNode(ISD::OR, DL, VT,
4290                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4291                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4292 }
4293 
4294 /// This contains all DAGCombine rules which reduce two values combined by
4295 /// an Or operation to a single value \see visitANDLike().
4296 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4297   EVT VT = N1.getValueType();
4298   SDLoc DL(N);
4299 
4300   // fold (or x, undef) -> -1
4301   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4302     return DAG.getAllOnesConstant(DL, VT);
4303 
4304   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4305     return V;
4306 
4307   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4308   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4309       // Don't increase # computations.
4310       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4311     // We can only do this xform if we know that bits from X that are set in C2
4312     // but not in C1 are already zero.  Likewise for Y.
4313     if (const ConstantSDNode *N0O1C =
4314         getAsNonOpaqueConstant(N0.getOperand(1))) {
4315       if (const ConstantSDNode *N1O1C =
4316           getAsNonOpaqueConstant(N1.getOperand(1))) {
4317         // We can only do this xform if we know that bits from X that are set in
4318         // C2 but not in C1 are already zero.  Likewise for Y.
4319         const APInt &LHSMask = N0O1C->getAPIntValue();
4320         const APInt &RHSMask = N1O1C->getAPIntValue();
4321 
4322         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4323             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4324           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4325                                   N0.getOperand(0), N1.getOperand(0));
4326           return DAG.getNode(ISD::AND, DL, VT, X,
4327                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4328         }
4329       }
4330     }
4331   }
4332 
4333   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4334   if (N0.getOpcode() == ISD::AND &&
4335       N1.getOpcode() == ISD::AND &&
4336       N0.getOperand(0) == N1.getOperand(0) &&
4337       // Don't increase # computations.
4338       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4339     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4340                             N0.getOperand(1), N1.getOperand(1));
4341     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4342   }
4343 
4344   return SDValue();
4345 }
4346 
4347 SDValue DAGCombiner::visitOR(SDNode *N) {
4348   SDValue N0 = N->getOperand(0);
4349   SDValue N1 = N->getOperand(1);
4350   EVT VT = N1.getValueType();
4351 
4352   // x | x --> x
4353   if (N0 == N1)
4354     return N0;
4355 
4356   // fold vector ops
4357   if (VT.isVector()) {
4358     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4359       return FoldedVOp;
4360 
4361     // fold (or x, 0) -> x, vector edition
4362     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4363       return N1;
4364     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4365       return N0;
4366 
4367     // fold (or x, -1) -> -1, vector edition
4368     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4369       // do not return N0, because undef node may exist in N0
4370       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4371     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4372       // do not return N1, because undef node may exist in N1
4373       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4374 
4375     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4376     // Do this only if the resulting shuffle is legal.
4377     if (isa<ShuffleVectorSDNode>(N0) &&
4378         isa<ShuffleVectorSDNode>(N1) &&
4379         // Avoid folding a node with illegal type.
4380         TLI.isTypeLegal(VT)) {
4381       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4382       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4383       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4384       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4385       // Ensure both shuffles have a zero input.
4386       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4387         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4388         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4389         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4390         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4391         bool CanFold = true;
4392         int NumElts = VT.getVectorNumElements();
4393         SmallVector<int, 4> Mask(NumElts);
4394 
4395         for (int i = 0; i != NumElts; ++i) {
4396           int M0 = SV0->getMaskElt(i);
4397           int M1 = SV1->getMaskElt(i);
4398 
4399           // Determine if either index is pointing to a zero vector.
4400           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4401           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4402 
4403           // If one element is zero and the otherside is undef, keep undef.
4404           // This also handles the case that both are undef.
4405           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4406             Mask[i] = -1;
4407             continue;
4408           }
4409 
4410           // Make sure only one of the elements is zero.
4411           if (M0Zero == M1Zero) {
4412             CanFold = false;
4413             break;
4414           }
4415 
4416           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4417 
4418           // We have a zero and non-zero element. If the non-zero came from
4419           // SV0 make the index a LHS index. If it came from SV1, make it
4420           // a RHS index. We need to mod by NumElts because we don't care
4421           // which operand it came from in the original shuffles.
4422           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4423         }
4424 
4425         if (CanFold) {
4426           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4427           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4428 
4429           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4430           if (!LegalMask) {
4431             std::swap(NewLHS, NewRHS);
4432             ShuffleVectorSDNode::commuteMask(Mask);
4433             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4434           }
4435 
4436           if (LegalMask)
4437             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4438         }
4439       }
4440     }
4441   }
4442 
4443   // fold (or c1, c2) -> c1|c2
4444   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4445   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4446   if (N0C && N1C && !N1C->isOpaque())
4447     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4448   // canonicalize constant to RHS
4449   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4450      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4451     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4452   // fold (or x, 0) -> x
4453   if (isNullConstant(N1))
4454     return N0;
4455   // fold (or x, -1) -> -1
4456   if (isAllOnesConstant(N1))
4457     return N1;
4458 
4459   if (SDValue NewSel = foldBinOpIntoSelect(N))
4460     return NewSel;
4461 
4462   // fold (or x, c) -> c iff (x & ~c) == 0
4463   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4464     return N1;
4465 
4466   if (SDValue Combined = visitORLike(N0, N1, N))
4467     return Combined;
4468 
4469   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4470   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4471     return BSwap;
4472   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4473     return BSwap;
4474 
4475   // reassociate or
4476   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4477     return ROR;
4478 
4479   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4480   // iff (c1 & c2) != 0.
4481   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4482     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4483       if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4484         if (SDValue COR =
4485                 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4486           return DAG.getNode(
4487               ISD::AND, SDLoc(N), VT,
4488               DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4489         return SDValue();
4490       }
4491     }
4492   }
4493 
4494   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4495   if (N0.getOpcode() == N1.getOpcode())
4496     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4497       return Tmp;
4498 
4499   // See if this is some rotate idiom.
4500   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4501     return SDValue(Rot, 0);
4502 
4503   if (SDValue Load = MatchLoadCombine(N))
4504     return Load;
4505 
4506   // Simplify the operands using demanded-bits information.
4507   if (SimplifyDemandedBits(SDValue(N, 0)))
4508     return SDValue(N, 0);
4509 
4510   return SDValue();
4511 }
4512 
4513 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4514 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4515   if (Op.getOpcode() == ISD::AND) {
4516     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4517       Mask = Op.getOperand(1);
4518       Op = Op.getOperand(0);
4519     } else {
4520       return false;
4521     }
4522   }
4523 
4524   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4525     Shift = Op;
4526     return true;
4527   }
4528 
4529   return false;
4530 }
4531 
4532 // Return true if we can prove that, whenever Neg and Pos are both in the
4533 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4534 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4535 //
4536 //     (or (shift1 X, Neg), (shift2 X, Pos))
4537 //
4538 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4539 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4540 // to consider shift amounts with defined behavior.
4541 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4542   // If EltSize is a power of 2 then:
4543   //
4544   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4545   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4546   //
4547   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4548   // for the stronger condition:
4549   //
4550   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4551   //
4552   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4553   // we can just replace Neg with Neg' for the rest of the function.
4554   //
4555   // In other cases we check for the even stronger condition:
4556   //
4557   //     Neg == EltSize - Pos                                    [B]
4558   //
4559   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4560   // behavior if Pos == 0 (and consequently Neg == EltSize).
4561   //
4562   // We could actually use [A] whenever EltSize is a power of 2, but the
4563   // only extra cases that it would match are those uninteresting ones
4564   // where Neg and Pos are never in range at the same time.  E.g. for
4565   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4566   // as well as (sub 32, Pos), but:
4567   //
4568   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4569   //
4570   // always invokes undefined behavior for 32-bit X.
4571   //
4572   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4573   unsigned MaskLoBits = 0;
4574   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4575     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4576       if (NegC->getAPIntValue() == EltSize - 1) {
4577         Neg = Neg.getOperand(0);
4578         MaskLoBits = Log2_64(EltSize);
4579       }
4580     }
4581   }
4582 
4583   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4584   if (Neg.getOpcode() != ISD::SUB)
4585     return false;
4586   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4587   if (!NegC)
4588     return false;
4589   SDValue NegOp1 = Neg.getOperand(1);
4590 
4591   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4592   // Pos'.  The truncation is redundant for the purpose of the equality.
4593   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4594     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4595       if (PosC->getAPIntValue() == EltSize - 1)
4596         Pos = Pos.getOperand(0);
4597 
4598   // The condition we need is now:
4599   //
4600   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4601   //
4602   // If NegOp1 == Pos then we need:
4603   //
4604   //              EltSize & Mask == NegC & Mask
4605   //
4606   // (because "x & Mask" is a truncation and distributes through subtraction).
4607   APInt Width;
4608   if (Pos == NegOp1)
4609     Width = NegC->getAPIntValue();
4610 
4611   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4612   // Then the condition we want to prove becomes:
4613   //
4614   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4615   //
4616   // which, again because "x & Mask" is a truncation, becomes:
4617   //
4618   //                NegC & Mask == (EltSize - PosC) & Mask
4619   //             EltSize & Mask == (NegC + PosC) & Mask
4620   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4621     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4622       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4623     else
4624       return false;
4625   } else
4626     return false;
4627 
4628   // Now we just need to check that EltSize & Mask == Width & Mask.
4629   if (MaskLoBits)
4630     // EltSize & Mask is 0 since Mask is EltSize - 1.
4631     return Width.getLoBits(MaskLoBits) == 0;
4632   return Width == EltSize;
4633 }
4634 
4635 // A subroutine of MatchRotate used once we have found an OR of two opposite
4636 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4637 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4638 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4639 // Neg with outer conversions stripped away.
4640 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4641                                        SDValue Neg, SDValue InnerPos,
4642                                        SDValue InnerNeg, unsigned PosOpcode,
4643                                        unsigned NegOpcode, const SDLoc &DL) {
4644   // fold (or (shl x, (*ext y)),
4645   //          (srl x, (*ext (sub 32, y)))) ->
4646   //   (rotl x, y) or (rotr x, (sub 32, y))
4647   //
4648   // fold (or (shl x, (*ext (sub 32, y))),
4649   //          (srl x, (*ext y))) ->
4650   //   (rotr x, y) or (rotl x, (sub 32, y))
4651   EVT VT = Shifted.getValueType();
4652   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4653     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4654     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4655                        HasPos ? Pos : Neg).getNode();
4656   }
4657 
4658   return nullptr;
4659 }
4660 
4661 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4662 // idioms for rotate, and if the target supports rotation instructions, generate
4663 // a rot[lr].
4664 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4665   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4666   EVT VT = LHS.getValueType();
4667   if (!TLI.isTypeLegal(VT)) return nullptr;
4668 
4669   // The target must have at least one rotate flavor.
4670   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4671   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4672   if (!HasROTL && !HasROTR) return nullptr;
4673 
4674   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4675   SDValue LHSShift;   // The shift.
4676   SDValue LHSMask;    // AND value if any.
4677   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4678     return nullptr; // Not part of a rotate.
4679 
4680   SDValue RHSShift;   // The shift.
4681   SDValue RHSMask;    // AND value if any.
4682   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4683     return nullptr; // Not part of a rotate.
4684 
4685   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4686     return nullptr;   // Not shifting the same value.
4687 
4688   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4689     return nullptr;   // Shifts must disagree.
4690 
4691   // Canonicalize shl to left side in a shl/srl pair.
4692   if (RHSShift.getOpcode() == ISD::SHL) {
4693     std::swap(LHS, RHS);
4694     std::swap(LHSShift, RHSShift);
4695     std::swap(LHSMask, RHSMask);
4696   }
4697 
4698   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4699   SDValue LHSShiftArg = LHSShift.getOperand(0);
4700   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4701   SDValue RHSShiftArg = RHSShift.getOperand(0);
4702   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4703 
4704   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4705   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4706   auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
4707                                         ConstantSDNode *RHS) {
4708     return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
4709   };
4710   if (matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
4711     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4712                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4713 
4714     // If there is an AND of either shifted operand, apply it to the result.
4715     if (LHSMask.getNode() || RHSMask.getNode()) {
4716       SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
4717       SDValue Mask = AllOnes;
4718 
4719       if (LHSMask.getNode()) {
4720         SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
4721         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4722                            DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
4723       }
4724       if (RHSMask.getNode()) {
4725         SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
4726         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4727                            DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
4728       }
4729 
4730       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4731     }
4732 
4733     return Rot.getNode();
4734   }
4735 
4736   // If there is a mask here, and we have a variable shift, we can't be sure
4737   // that we're masking out the right stuff.
4738   if (LHSMask.getNode() || RHSMask.getNode())
4739     return nullptr;
4740 
4741   // If the shift amount is sign/zext/any-extended just peel it off.
4742   SDValue LExtOp0 = LHSShiftAmt;
4743   SDValue RExtOp0 = RHSShiftAmt;
4744   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4745        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4746        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4747        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4748       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4749        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4750        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4751        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4752     LExtOp0 = LHSShiftAmt.getOperand(0);
4753     RExtOp0 = RHSShiftAmt.getOperand(0);
4754   }
4755 
4756   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4757                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4758   if (TryL)
4759     return TryL;
4760 
4761   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4762                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4763   if (TryR)
4764     return TryR;
4765 
4766   return nullptr;
4767 }
4768 
4769 namespace {
4770 /// Represents known origin of an individual byte in load combine pattern. The
4771 /// value of the byte is either constant zero or comes from memory.
4772 struct ByteProvider {
4773   // For constant zero providers Load is set to nullptr. For memory providers
4774   // Load represents the node which loads the byte from memory.
4775   // ByteOffset is the offset of the byte in the value produced by the load.
4776   LoadSDNode *Load;
4777   unsigned ByteOffset;
4778 
4779   ByteProvider() : Load(nullptr), ByteOffset(0) {}
4780 
4781   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4782     return ByteProvider(Load, ByteOffset);
4783   }
4784   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4785 
4786   bool isConstantZero() const { return !Load; }
4787   bool isMemory() const { return Load; }
4788 
4789   bool operator==(const ByteProvider &Other) const {
4790     return Other.Load == Load && Other.ByteOffset == ByteOffset;
4791   }
4792 
4793 private:
4794   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4795       : Load(Load), ByteOffset(ByteOffset) {}
4796 };
4797 
4798 /// Recursively traverses the expression calculating the origin of the requested
4799 /// byte of the given value. Returns None if the provider can't be calculated.
4800 ///
4801 /// For all the values except the root of the expression verifies that the value
4802 /// has exactly one use and if it's not true return None. This way if the origin
4803 /// of the byte is returned it's guaranteed that the values which contribute to
4804 /// the byte are not used outside of this expression.
4805 ///
4806 /// Because the parts of the expression are not allowed to have more than one
4807 /// use this function iterates over trees, not DAGs. So it never visits the same
4808 /// node more than once.
4809 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4810                                                    unsigned Depth,
4811                                                    bool Root = false) {
4812   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4813   if (Depth == 10)
4814     return None;
4815 
4816   if (!Root && !Op.hasOneUse())
4817     return None;
4818 
4819   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4820   unsigned BitWidth = Op.getValueSizeInBits();
4821   if (BitWidth % 8 != 0)
4822     return None;
4823   unsigned ByteWidth = BitWidth / 8;
4824   assert(Index < ByteWidth && "invalid index requested");
4825   (void) ByteWidth;
4826 
4827   switch (Op.getOpcode()) {
4828   case ISD::OR: {
4829     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4830     if (!LHS)
4831       return None;
4832     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4833     if (!RHS)
4834       return None;
4835 
4836     if (LHS->isConstantZero())
4837       return RHS;
4838     if (RHS->isConstantZero())
4839       return LHS;
4840     return None;
4841   }
4842   case ISD::SHL: {
4843     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4844     if (!ShiftOp)
4845       return None;
4846 
4847     uint64_t BitShift = ShiftOp->getZExtValue();
4848     if (BitShift % 8 != 0)
4849       return None;
4850     uint64_t ByteShift = BitShift / 8;
4851 
4852     return Index < ByteShift
4853                ? ByteProvider::getConstantZero()
4854                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4855                                        Depth + 1);
4856   }
4857   case ISD::ANY_EXTEND:
4858   case ISD::SIGN_EXTEND:
4859   case ISD::ZERO_EXTEND: {
4860     SDValue NarrowOp = Op->getOperand(0);
4861     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4862     if (NarrowBitWidth % 8 != 0)
4863       return None;
4864     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4865 
4866     if (Index >= NarrowByteWidth)
4867       return Op.getOpcode() == ISD::ZERO_EXTEND
4868                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4869                  : None;
4870     return calculateByteProvider(NarrowOp, Index, Depth + 1);
4871   }
4872   case ISD::BSWAP:
4873     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4874                                  Depth + 1);
4875   case ISD::LOAD: {
4876     auto L = cast<LoadSDNode>(Op.getNode());
4877     if (L->isVolatile() || L->isIndexed())
4878       return None;
4879 
4880     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4881     if (NarrowBitWidth % 8 != 0)
4882       return None;
4883     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4884 
4885     if (Index >= NarrowByteWidth)
4886       return L->getExtensionType() == ISD::ZEXTLOAD
4887                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4888                  : None;
4889     return ByteProvider::getMemory(L, Index);
4890   }
4891   }
4892 
4893   return None;
4894 }
4895 } // namespace
4896 
4897 /// Match a pattern where a wide type scalar value is loaded by several narrow
4898 /// loads and combined by shifts and ors. Fold it into a single load or a load
4899 /// and a BSWAP if the targets supports it.
4900 ///
4901 /// Assuming little endian target:
4902 ///  i8 *a = ...
4903 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4904 /// =>
4905 ///  i32 val = *((i32)a)
4906 ///
4907 ///  i8 *a = ...
4908 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4909 /// =>
4910 ///  i32 val = BSWAP(*((i32)a))
4911 ///
4912 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4913 /// interact well with the worklist mechanism. When a part of the pattern is
4914 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4915 /// but the root node of the pattern which triggers the load combine is not
4916 /// necessarily a direct user of the changed node. For example, once the address
4917 /// of t28 load is reassociated load combine won't be triggered:
4918 ///             t25: i32 = add t4, Constant:i32<2>
4919 ///           t26: i64 = sign_extend t25
4920 ///        t27: i64 = add t2, t26
4921 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4922 ///     t29: i32 = zero_extend t28
4923 ///   t32: i32 = shl t29, Constant:i8<8>
4924 /// t33: i32 = or t23, t32
4925 /// As a possible fix visitLoad can check if the load can be a part of a load
4926 /// combine pattern and add corresponding OR roots to the worklist.
4927 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4928   assert(N->getOpcode() == ISD::OR &&
4929          "Can only match load combining against OR nodes");
4930 
4931   // Handles simple types only
4932   EVT VT = N->getValueType(0);
4933   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4934     return SDValue();
4935   unsigned ByteWidth = VT.getSizeInBits() / 8;
4936 
4937   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4938   // Before legalize we can introduce too wide illegal loads which will be later
4939   // split into legal sized loads. This enables us to combine i64 load by i8
4940   // patterns to a couple of i32 loads on 32 bit targets.
4941   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4942     return SDValue();
4943 
4944   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4945     unsigned BW, unsigned i) { return i; };
4946   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4947     unsigned BW, unsigned i) { return BW - i - 1; };
4948 
4949   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4950   auto MemoryByteOffset = [&] (ByteProvider P) {
4951     assert(P.isMemory() && "Must be a memory byte provider");
4952     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4953     assert(LoadBitWidth % 8 == 0 &&
4954            "can only analyze providers for individual bytes not bit");
4955     unsigned LoadByteWidth = LoadBitWidth / 8;
4956     return IsBigEndianTarget
4957             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4958             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4959   };
4960 
4961   Optional<BaseIndexOffset> Base;
4962   SDValue Chain;
4963 
4964   SmallSet<LoadSDNode *, 8> Loads;
4965   Optional<ByteProvider> FirstByteProvider;
4966   int64_t FirstOffset = INT64_MAX;
4967 
4968   // Check if all the bytes of the OR we are looking at are loaded from the same
4969   // base address. Collect bytes offsets from Base address in ByteOffsets.
4970   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4971   for (unsigned i = 0; i < ByteWidth; i++) {
4972     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4973     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4974       return SDValue();
4975 
4976     LoadSDNode *L = P->Load;
4977     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4978            "Must be enforced by calculateByteProvider");
4979     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4980 
4981     // All loads must share the same chain
4982     SDValue LChain = L->getChain();
4983     if (!Chain)
4984       Chain = LChain;
4985     else if (Chain != LChain)
4986       return SDValue();
4987 
4988     // Loads must share the same base address
4989     BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4990     int64_t ByteOffsetFromBase = 0;
4991     if (!Base)
4992       Base = Ptr;
4993     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
4994       return SDValue();
4995 
4996     // Calculate the offset of the current byte from the base address
4997     ByteOffsetFromBase += MemoryByteOffset(*P);
4998     ByteOffsets[i] = ByteOffsetFromBase;
4999 
5000     // Remember the first byte load
5001     if (ByteOffsetFromBase < FirstOffset) {
5002       FirstByteProvider = P;
5003       FirstOffset = ByteOffsetFromBase;
5004     }
5005 
5006     Loads.insert(L);
5007   }
5008   assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
5009          "memory, so there must be at least one load which produces the value");
5010   assert(Base && "Base address of the accessed memory location must be set");
5011   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
5012 
5013   // Check if the bytes of the OR we are looking at match with either big or
5014   // little endian value load
5015   bool BigEndian = true, LittleEndian = true;
5016   for (unsigned i = 0; i < ByteWidth; i++) {
5017     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
5018     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
5019     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
5020     if (!BigEndian && !LittleEndian)
5021       return SDValue();
5022   }
5023   assert((BigEndian != LittleEndian) && "should be either or");
5024   assert(FirstByteProvider && "must be set");
5025 
5026   // Ensure that the first byte is loaded from zero offset of the first load.
5027   // So the combined value can be loaded from the first load address.
5028   if (MemoryByteOffset(*FirstByteProvider) != 0)
5029     return SDValue();
5030   LoadSDNode *FirstLoad = FirstByteProvider->Load;
5031 
5032   // The node we are looking at matches with the pattern, check if we can
5033   // replace it with a single load and bswap if needed.
5034 
5035   // If the load needs byte swap check if the target supports it
5036   bool NeedsBswap = IsBigEndianTarget != BigEndian;
5037 
5038   // Before legalize we can introduce illegal bswaps which will be later
5039   // converted to an explicit bswap sequence. This way we end up with a single
5040   // load and byte shuffling instead of several loads and byte shuffling.
5041   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
5042     return SDValue();
5043 
5044   // Check that a load of the wide type is both allowed and fast on the target
5045   bool Fast = false;
5046   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
5047                                         VT, FirstLoad->getAddressSpace(),
5048                                         FirstLoad->getAlignment(), &Fast);
5049   if (!Allowed || !Fast)
5050     return SDValue();
5051 
5052   SDValue NewLoad =
5053       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
5054                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
5055 
5056   // Transfer chain users from old loads to the new load.
5057   for (LoadSDNode *L : Loads)
5058     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
5059 
5060   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5061 }
5062 
5063 SDValue DAGCombiner::visitXOR(SDNode *N) {
5064   SDValue N0 = N->getOperand(0);
5065   SDValue N1 = N->getOperand(1);
5066   EVT VT = N0.getValueType();
5067 
5068   // fold vector ops
5069   if (VT.isVector()) {
5070     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5071       return FoldedVOp;
5072 
5073     // fold (xor x, 0) -> x, vector edition
5074     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5075       return N1;
5076     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5077       return N0;
5078   }
5079 
5080   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5081   if (N0.isUndef() && N1.isUndef())
5082     return DAG.getConstant(0, SDLoc(N), VT);
5083   // fold (xor x, undef) -> undef
5084   if (N0.isUndef())
5085     return N0;
5086   if (N1.isUndef())
5087     return N1;
5088   // fold (xor c1, c2) -> c1^c2
5089   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5090   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5091   if (N0C && N1C)
5092     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5093   // canonicalize constant to RHS
5094   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5095      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5096     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5097   // fold (xor x, 0) -> x
5098   if (isNullConstant(N1))
5099     return N0;
5100 
5101   if (SDValue NewSel = foldBinOpIntoSelect(N))
5102     return NewSel;
5103 
5104   // reassociate xor
5105   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5106     return RXOR;
5107 
5108   // fold !(x cc y) -> (x !cc y)
5109   SDValue LHS, RHS, CC;
5110   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5111     bool isInt = LHS.getValueType().isInteger();
5112     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5113                                                isInt);
5114 
5115     if (!LegalOperations ||
5116         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5117       switch (N0.getOpcode()) {
5118       default:
5119         llvm_unreachable("Unhandled SetCC Equivalent!");
5120       case ISD::SETCC:
5121         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5122       case ISD::SELECT_CC:
5123         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5124                                N0.getOperand(3), NotCC);
5125       }
5126     }
5127   }
5128 
5129   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5130   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5131       N0.getNode()->hasOneUse() &&
5132       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5133     SDValue V = N0.getOperand(0);
5134     SDLoc DL(N0);
5135     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5136                     DAG.getConstant(1, DL, V.getValueType()));
5137     AddToWorklist(V.getNode());
5138     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5139   }
5140 
5141   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5142   if (isOneConstant(N1) && VT == MVT::i1 &&
5143       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5144     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5145     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5146       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5147       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5148       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5149       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5150       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5151     }
5152   }
5153   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5154   if (isAllOnesConstant(N1) &&
5155       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5156     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5157     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5158       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5159       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5160       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5161       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5162       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5163     }
5164   }
5165   // fold (xor (and x, y), y) -> (and (not x), y)
5166   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5167       N0->getOperand(1) == N1) {
5168     SDValue X = N0->getOperand(0);
5169     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5170     AddToWorklist(NotX.getNode());
5171     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5172   }
5173   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5174   if (N1C && N0.getOpcode() == ISD::XOR) {
5175     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5176       SDLoc DL(N);
5177       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5178                          DAG.getConstant(N1C->getAPIntValue() ^
5179                                          N00C->getAPIntValue(), DL, VT));
5180     }
5181     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5182       SDLoc DL(N);
5183       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5184                          DAG.getConstant(N1C->getAPIntValue() ^
5185                                          N01C->getAPIntValue(), DL, VT));
5186     }
5187   }
5188 
5189   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5190   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5191   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5192       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5193       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5194     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5195       if (C->getAPIntValue() == (OpSizeInBits - 1))
5196         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5197   }
5198 
5199   // fold (xor x, x) -> 0
5200   if (N0 == N1)
5201     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5202 
5203   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5204   // Here is a concrete example of this equivalence:
5205   // i16   x ==  14
5206   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5207   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5208   //
5209   // =>
5210   //
5211   // i16     ~1      == 0b1111111111111110
5212   // i16 rol(~1, 14) == 0b1011111111111111
5213   //
5214   // Some additional tips to help conceptualize this transform:
5215   // - Try to see the operation as placing a single zero in a value of all ones.
5216   // - There exists no value for x which would allow the result to contain zero.
5217   // - Values of x larger than the bitwidth are undefined and do not require a
5218   //   consistent result.
5219   // - Pushing the zero left requires shifting one bits in from the right.
5220   // A rotate left of ~1 is a nice way of achieving the desired result.
5221   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5222       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5223     SDLoc DL(N);
5224     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5225                        N0.getOperand(1));
5226   }
5227 
5228   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5229   if (N0.getOpcode() == N1.getOpcode())
5230     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5231       return Tmp;
5232 
5233   // Simplify the expression using non-local knowledge.
5234   if (SimplifyDemandedBits(SDValue(N, 0)))
5235     return SDValue(N, 0);
5236 
5237   return SDValue();
5238 }
5239 
5240 /// Handle transforms common to the three shifts, when the shift amount is a
5241 /// constant.
5242 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5243   SDNode *LHS = N->getOperand(0).getNode();
5244   if (!LHS->hasOneUse()) return SDValue();
5245 
5246   // We want to pull some binops through shifts, so that we have (and (shift))
5247   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5248   // thing happens with address calculations, so it's important to canonicalize
5249   // it.
5250   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5251 
5252   switch (LHS->getOpcode()) {
5253   default: return SDValue();
5254   case ISD::OR:
5255   case ISD::XOR:
5256     HighBitSet = false; // We can only transform sra if the high bit is clear.
5257     break;
5258   case ISD::AND:
5259     HighBitSet = true;  // We can only transform sra if the high bit is set.
5260     break;
5261   case ISD::ADD:
5262     if (N->getOpcode() != ISD::SHL)
5263       return SDValue(); // only shl(add) not sr[al](add).
5264     HighBitSet = false; // We can only transform sra if the high bit is clear.
5265     break;
5266   }
5267 
5268   // We require the RHS of the binop to be a constant and not opaque as well.
5269   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5270   if (!BinOpCst) return SDValue();
5271 
5272   // FIXME: disable this unless the input to the binop is a shift by a constant
5273   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5274   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5275   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5276                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5277                  BinOpLHSVal->getOpcode() == ISD::SRL;
5278   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5279                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5280 
5281   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5282       !isCopyOrSelect)
5283     return SDValue();
5284 
5285   if (isCopyOrSelect && N->hasOneUse())
5286     return SDValue();
5287 
5288   EVT VT = N->getValueType(0);
5289 
5290   // If this is a signed shift right, and the high bit is modified by the
5291   // logical operation, do not perform the transformation. The highBitSet
5292   // boolean indicates the value of the high bit of the constant which would
5293   // cause it to be modified for this operation.
5294   if (N->getOpcode() == ISD::SRA) {
5295     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5296     if (BinOpRHSSignSet != HighBitSet)
5297       return SDValue();
5298   }
5299 
5300   if (!TLI.isDesirableToCommuteWithShift(LHS))
5301     return SDValue();
5302 
5303   // Fold the constants, shifting the binop RHS by the shift amount.
5304   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5305                                N->getValueType(0),
5306                                LHS->getOperand(1), N->getOperand(1));
5307   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5308 
5309   // Create the new shift.
5310   SDValue NewShift = DAG.getNode(N->getOpcode(),
5311                                  SDLoc(LHS->getOperand(0)),
5312                                  VT, LHS->getOperand(0), N->getOperand(1));
5313 
5314   // Create the new binop.
5315   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5316 }
5317 
5318 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5319   assert(N->getOpcode() == ISD::TRUNCATE);
5320   assert(N->getOperand(0).getOpcode() == ISD::AND);
5321 
5322   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5323   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5324     SDValue N01 = N->getOperand(0).getOperand(1);
5325     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5326       SDLoc DL(N);
5327       EVT TruncVT = N->getValueType(0);
5328       SDValue N00 = N->getOperand(0).getOperand(0);
5329       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5330       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5331       AddToWorklist(Trunc00.getNode());
5332       AddToWorklist(Trunc01.getNode());
5333       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5334     }
5335   }
5336 
5337   return SDValue();
5338 }
5339 
5340 SDValue DAGCombiner::visitRotate(SDNode *N) {
5341   SDLoc dl(N);
5342   SDValue N0 = N->getOperand(0);
5343   SDValue N1 = N->getOperand(1);
5344   EVT VT = N->getValueType(0);
5345   unsigned Bitsize = VT.getScalarSizeInBits();
5346 
5347   // fold (rot x, 0) -> x
5348   if (isNullConstantOrNullSplatConstant(N1))
5349     return N0;
5350 
5351   // fold (rot x, c) -> (rot x, c % BitSize)
5352   if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
5353     if (Cst->getAPIntValue().uge(Bitsize)) {
5354       uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
5355       return DAG.getNode(N->getOpcode(), dl, VT, N0,
5356                          DAG.getConstant(RotAmt, dl, N1.getValueType()));
5357     }
5358   }
5359 
5360   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5361   if (N1.getOpcode() == ISD::TRUNCATE &&
5362       N1.getOperand(0).getOpcode() == ISD::AND) {
5363     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5364       return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
5365   }
5366 
5367   unsigned NextOp = N0.getOpcode();
5368   // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
5369   if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
5370     SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
5371     SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
5372     if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
5373       EVT ShiftVT = C1->getValueType(0);
5374       bool SameSide = (N->getOpcode() == NextOp);
5375       unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
5376       if (SDValue CombinedShift =
5377               DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
5378         SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
5379         SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
5380             ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
5381             BitsizeC.getNode());
5382         return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
5383                            CombinedShiftNorm);
5384       }
5385     }
5386   }
5387   return SDValue();
5388 }
5389 
5390 SDValue DAGCombiner::visitSHL(SDNode *N) {
5391   SDValue N0 = N->getOperand(0);
5392   SDValue N1 = N->getOperand(1);
5393   EVT VT = N0.getValueType();
5394   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5395 
5396   // fold vector ops
5397   if (VT.isVector()) {
5398     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5399       return FoldedVOp;
5400 
5401     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5402     // If setcc produces all-one true value then:
5403     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5404     if (N1CV && N1CV->isConstant()) {
5405       if (N0.getOpcode() == ISD::AND) {
5406         SDValue N00 = N0->getOperand(0);
5407         SDValue N01 = N0->getOperand(1);
5408         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5409 
5410         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5411             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5412                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5413           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5414                                                      N01CV, N1CV))
5415             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5416         }
5417       }
5418     }
5419   }
5420 
5421   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5422 
5423   // fold (shl c1, c2) -> c1<<c2
5424   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5425   if (N0C && N1C && !N1C->isOpaque())
5426     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5427   // fold (shl 0, x) -> 0
5428   if (isNullConstantOrNullSplatConstant(N0))
5429     return N0;
5430   // fold (shl x, c >= size(x)) -> undef
5431   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5432   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5433     return Val->getAPIntValue().uge(OpSizeInBits);
5434   };
5435   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5436     return DAG.getUNDEF(VT);
5437   // fold (shl x, 0) -> x
5438   if (N1C && N1C->isNullValue())
5439     return N0;
5440   // fold (shl undef, x) -> 0
5441   if (N0.isUndef())
5442     return DAG.getConstant(0, SDLoc(N), VT);
5443 
5444   if (SDValue NewSel = foldBinOpIntoSelect(N))
5445     return NewSel;
5446 
5447   // if (shl x, c) is known to be zero, return 0
5448   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5449                             APInt::getAllOnesValue(OpSizeInBits)))
5450     return DAG.getConstant(0, SDLoc(N), VT);
5451   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5452   if (N1.getOpcode() == ISD::TRUNCATE &&
5453       N1.getOperand(0).getOpcode() == ISD::AND) {
5454     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5455       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5456   }
5457 
5458   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5459     return SDValue(N, 0);
5460 
5461   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5462   if (N0.getOpcode() == ISD::SHL) {
5463     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5464                                           ConstantSDNode *RHS) {
5465       APInt c1 = LHS->getAPIntValue();
5466       APInt c2 = RHS->getAPIntValue();
5467       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5468       return (c1 + c2).uge(OpSizeInBits);
5469     };
5470     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5471       return DAG.getConstant(0, SDLoc(N), VT);
5472 
5473     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5474                                        ConstantSDNode *RHS) {
5475       APInt c1 = LHS->getAPIntValue();
5476       APInt c2 = RHS->getAPIntValue();
5477       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5478       return (c1 + c2).ult(OpSizeInBits);
5479     };
5480     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5481       SDLoc DL(N);
5482       EVT ShiftVT = N1.getValueType();
5483       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5484       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
5485     }
5486   }
5487 
5488   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5489   // For this to be valid, the second form must not preserve any of the bits
5490   // that are shifted out by the inner shift in the first form.  This means
5491   // the outer shift size must be >= the number of bits added by the ext.
5492   // As a corollary, we don't care what kind of ext it is.
5493   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5494               N0.getOpcode() == ISD::ANY_EXTEND ||
5495               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5496       N0.getOperand(0).getOpcode() == ISD::SHL) {
5497     SDValue N0Op0 = N0.getOperand(0);
5498     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5499       APInt c1 = N0Op0C1->getAPIntValue();
5500       APInt c2 = N1C->getAPIntValue();
5501       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5502 
5503       EVT InnerShiftVT = N0Op0.getValueType();
5504       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5505       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5506         SDLoc DL(N0);
5507         APInt Sum = c1 + c2;
5508         if (Sum.uge(OpSizeInBits))
5509           return DAG.getConstant(0, DL, VT);
5510 
5511         return DAG.getNode(
5512             ISD::SHL, DL, VT,
5513             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5514             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5515       }
5516     }
5517   }
5518 
5519   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5520   // Only fold this if the inner zext has no other uses to avoid increasing
5521   // the total number of instructions.
5522   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5523       N0.getOperand(0).getOpcode() == ISD::SRL) {
5524     SDValue N0Op0 = N0.getOperand(0);
5525     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5526       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5527         uint64_t c1 = N0Op0C1->getZExtValue();
5528         uint64_t c2 = N1C->getZExtValue();
5529         if (c1 == c2) {
5530           SDValue NewOp0 = N0.getOperand(0);
5531           EVT CountVT = NewOp0.getOperand(1).getValueType();
5532           SDLoc DL(N);
5533           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5534                                        NewOp0,
5535                                        DAG.getConstant(c2, DL, CountVT));
5536           AddToWorklist(NewSHL.getNode());
5537           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5538         }
5539       }
5540     }
5541   }
5542 
5543   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5544   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5545   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5546       N0->getFlags().hasExact()) {
5547     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5548       uint64_t C1 = N0C1->getZExtValue();
5549       uint64_t C2 = N1C->getZExtValue();
5550       SDLoc DL(N);
5551       if (C1 <= C2)
5552         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5553                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5554       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5555                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5556     }
5557   }
5558 
5559   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5560   //                               (and (srl x, (sub c1, c2), MASK)
5561   // Only fold this if the inner shift has no other uses -- if it does, folding
5562   // this will increase the total number of instructions.
5563   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5564     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5565       uint64_t c1 = N0C1->getZExtValue();
5566       if (c1 < OpSizeInBits) {
5567         uint64_t c2 = N1C->getZExtValue();
5568         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5569         SDValue Shift;
5570         if (c2 > c1) {
5571           Mask <<= c2 - c1;
5572           SDLoc DL(N);
5573           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5574                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5575         } else {
5576           Mask.lshrInPlace(c1 - c2);
5577           SDLoc DL(N);
5578           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5579                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5580         }
5581         SDLoc DL(N0);
5582         return DAG.getNode(ISD::AND, DL, VT, Shift,
5583                            DAG.getConstant(Mask, DL, VT));
5584       }
5585     }
5586   }
5587 
5588   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5589   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5590       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5591     SDLoc DL(N);
5592     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5593     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5594     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5595   }
5596 
5597   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5598   // Variant of version done on multiply, except mul by a power of 2 is turned
5599   // into a shift.
5600   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5601       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5602       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5603     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5604     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5605     AddToWorklist(Shl0.getNode());
5606     AddToWorklist(Shl1.getNode());
5607     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5608   }
5609 
5610   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5611   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5612       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5613       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5614     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5615     if (isConstantOrConstantVector(Shl))
5616       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5617   }
5618 
5619   if (N1C && !N1C->isOpaque())
5620     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5621       return NewSHL;
5622 
5623   return SDValue();
5624 }
5625 
5626 SDValue DAGCombiner::visitSRA(SDNode *N) {
5627   SDValue N0 = N->getOperand(0);
5628   SDValue N1 = N->getOperand(1);
5629   EVT VT = N0.getValueType();
5630   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5631 
5632   // Arithmetic shifting an all-sign-bit value is a no-op.
5633   // fold (sra 0, x) -> 0
5634   // fold (sra -1, x) -> -1
5635   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5636     return N0;
5637 
5638   // fold vector ops
5639   if (VT.isVector())
5640     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5641       return FoldedVOp;
5642 
5643   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5644 
5645   // fold (sra c1, c2) -> (sra c1, c2)
5646   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5647   if (N0C && N1C && !N1C->isOpaque())
5648     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5649   // fold (sra x, c >= size(x)) -> undef
5650   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5651   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5652     return Val->getAPIntValue().uge(OpSizeInBits);
5653   };
5654   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5655     return DAG.getUNDEF(VT);
5656   // fold (sra x, 0) -> x
5657   if (N1C && N1C->isNullValue())
5658     return N0;
5659 
5660   if (SDValue NewSel = foldBinOpIntoSelect(N))
5661     return NewSel;
5662 
5663   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5664   // sext_inreg.
5665   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5666     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5667     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5668     if (VT.isVector())
5669       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5670                                ExtVT, VT.getVectorNumElements());
5671     if ((!LegalOperations ||
5672          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5673       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5674                          N0.getOperand(0), DAG.getValueType(ExtVT));
5675   }
5676 
5677   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5678   if (N0.getOpcode() == ISD::SRA) {
5679     SDLoc DL(N);
5680     EVT ShiftVT = N1.getValueType();
5681 
5682     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5683                                           ConstantSDNode *RHS) {
5684       APInt c1 = LHS->getAPIntValue();
5685       APInt c2 = RHS->getAPIntValue();
5686       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5687       return (c1 + c2).uge(OpSizeInBits);
5688     };
5689     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5690       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
5691                          DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT));
5692 
5693     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5694                                        ConstantSDNode *RHS) {
5695       APInt c1 = LHS->getAPIntValue();
5696       APInt c2 = RHS->getAPIntValue();
5697       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5698       return (c1 + c2).ult(OpSizeInBits);
5699     };
5700     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5701       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5702       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum);
5703     }
5704   }
5705 
5706   // fold (sra (shl X, m), (sub result_size, n))
5707   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5708   // result_size - n != m.
5709   // If truncate is free for the target sext(shl) is likely to result in better
5710   // code.
5711   if (N0.getOpcode() == ISD::SHL && N1C) {
5712     // Get the two constanst of the shifts, CN0 = m, CN = n.
5713     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5714     if (N01C) {
5715       LLVMContext &Ctx = *DAG.getContext();
5716       // Determine what the truncate's result bitsize and type would be.
5717       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5718 
5719       if (VT.isVector())
5720         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5721 
5722       // Determine the residual right-shift amount.
5723       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5724 
5725       // If the shift is not a no-op (in which case this should be just a sign
5726       // extend already), the truncated to type is legal, sign_extend is legal
5727       // on that type, and the truncate to that type is both legal and free,
5728       // perform the transform.
5729       if ((ShiftAmt > 0) &&
5730           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5731           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5732           TLI.isTruncateFree(VT, TruncVT)) {
5733 
5734         SDLoc DL(N);
5735         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5736             getShiftAmountTy(N0.getOperand(0).getValueType()));
5737         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5738                                     N0.getOperand(0), Amt);
5739         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5740                                     Shift);
5741         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5742                            N->getValueType(0), Trunc);
5743       }
5744     }
5745   }
5746 
5747   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5748   if (N1.getOpcode() == ISD::TRUNCATE &&
5749       N1.getOperand(0).getOpcode() == ISD::AND) {
5750     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5751       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5752   }
5753 
5754   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5755   //      if c1 is equal to the number of bits the trunc removes
5756   if (N0.getOpcode() == ISD::TRUNCATE &&
5757       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5758        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5759       N0.getOperand(0).hasOneUse() &&
5760       N0.getOperand(0).getOperand(1).hasOneUse() &&
5761       N1C) {
5762     SDValue N0Op0 = N0.getOperand(0);
5763     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5764       unsigned LargeShiftVal = LargeShift->getZExtValue();
5765       EVT LargeVT = N0Op0.getValueType();
5766 
5767       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5768         SDLoc DL(N);
5769         SDValue Amt =
5770           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5771                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5772         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5773                                   N0Op0.getOperand(0), Amt);
5774         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5775       }
5776     }
5777   }
5778 
5779   // Simplify, based on bits shifted out of the LHS.
5780   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5781     return SDValue(N, 0);
5782 
5783 
5784   // If the sign bit is known to be zero, switch this to a SRL.
5785   if (DAG.SignBitIsZero(N0))
5786     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5787 
5788   if (N1C && !N1C->isOpaque())
5789     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5790       return NewSRA;
5791 
5792   return SDValue();
5793 }
5794 
5795 SDValue DAGCombiner::visitSRL(SDNode *N) {
5796   SDValue N0 = N->getOperand(0);
5797   SDValue N1 = N->getOperand(1);
5798   EVT VT = N0.getValueType();
5799   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5800 
5801   // fold vector ops
5802   if (VT.isVector())
5803     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5804       return FoldedVOp;
5805 
5806   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5807 
5808   // fold (srl c1, c2) -> c1 >>u c2
5809   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5810   if (N0C && N1C && !N1C->isOpaque())
5811     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5812   // fold (srl 0, x) -> 0
5813   if (isNullConstantOrNullSplatConstant(N0))
5814     return N0;
5815   // fold (srl x, c >= size(x)) -> undef
5816   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5817   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5818     return Val->getAPIntValue().uge(OpSizeInBits);
5819   };
5820   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5821     return DAG.getUNDEF(VT);
5822   // fold (srl x, 0) -> x
5823   if (N1C && N1C->isNullValue())
5824     return N0;
5825 
5826   if (SDValue NewSel = foldBinOpIntoSelect(N))
5827     return NewSel;
5828 
5829   // if (srl x, c) is known to be zero, return 0
5830   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5831                                    APInt::getAllOnesValue(OpSizeInBits)))
5832     return DAG.getConstant(0, SDLoc(N), VT);
5833 
5834   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5835   if (N0.getOpcode() == ISD::SRL) {
5836     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5837                                           ConstantSDNode *RHS) {
5838       APInt c1 = LHS->getAPIntValue();
5839       APInt c2 = RHS->getAPIntValue();
5840       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5841       return (c1 + c2).uge(OpSizeInBits);
5842     };
5843     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5844       return DAG.getConstant(0, SDLoc(N), VT);
5845 
5846     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5847                                        ConstantSDNode *RHS) {
5848       APInt c1 = LHS->getAPIntValue();
5849       APInt c2 = RHS->getAPIntValue();
5850       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5851       return (c1 + c2).ult(OpSizeInBits);
5852     };
5853     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5854       SDLoc DL(N);
5855       EVT ShiftVT = N1.getValueType();
5856       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5857       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
5858     }
5859   }
5860 
5861   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5862   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5863       N0.getOperand(0).getOpcode() == ISD::SRL) {
5864     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5865       uint64_t c1 = N001C->getZExtValue();
5866       uint64_t c2 = N1C->getZExtValue();
5867       EVT InnerShiftVT = N0.getOperand(0).getValueType();
5868       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5869       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5870       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5871       if (c1 + OpSizeInBits == InnerShiftSize) {
5872         SDLoc DL(N0);
5873         if (c1 + c2 >= InnerShiftSize)
5874           return DAG.getConstant(0, DL, VT);
5875         return DAG.getNode(ISD::TRUNCATE, DL, VT,
5876                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5877                                        N0.getOperand(0).getOperand(0),
5878                                        DAG.getConstant(c1 + c2, DL,
5879                                                        ShiftCountVT)));
5880       }
5881     }
5882   }
5883 
5884   // fold (srl (shl x, c), c) -> (and x, cst2)
5885   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5886       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5887     SDLoc DL(N);
5888     SDValue Mask =
5889         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5890     AddToWorklist(Mask.getNode());
5891     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5892   }
5893 
5894   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5895   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5896     // Shifting in all undef bits?
5897     EVT SmallVT = N0.getOperand(0).getValueType();
5898     unsigned BitSize = SmallVT.getScalarSizeInBits();
5899     if (N1C->getZExtValue() >= BitSize)
5900       return DAG.getUNDEF(VT);
5901 
5902     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5903       uint64_t ShiftAmt = N1C->getZExtValue();
5904       SDLoc DL0(N0);
5905       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5906                                        N0.getOperand(0),
5907                           DAG.getConstant(ShiftAmt, DL0,
5908                                           getShiftAmountTy(SmallVT)));
5909       AddToWorklist(SmallShift.getNode());
5910       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5911       SDLoc DL(N);
5912       return DAG.getNode(ISD::AND, DL, VT,
5913                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5914                          DAG.getConstant(Mask, DL, VT));
5915     }
5916   }
5917 
5918   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
5919   // bit, which is unmodified by sra.
5920   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5921     if (N0.getOpcode() == ISD::SRA)
5922       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5923   }
5924 
5925   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5926   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5927       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5928     KnownBits Known;
5929     DAG.computeKnownBits(N0.getOperand(0), Known);
5930 
5931     // If any of the input bits are KnownOne, then the input couldn't be all
5932     // zeros, thus the result of the srl will always be zero.
5933     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5934 
5935     // If all of the bits input the to ctlz node are known to be zero, then
5936     // the result of the ctlz is "32" and the result of the shift is one.
5937     APInt UnknownBits = ~Known.Zero;
5938     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5939 
5940     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5941     if (UnknownBits.isPowerOf2()) {
5942       // Okay, we know that only that the single bit specified by UnknownBits
5943       // could be set on input to the CTLZ node. If this bit is set, the SRL
5944       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5945       // to an SRL/XOR pair, which is likely to simplify more.
5946       unsigned ShAmt = UnknownBits.countTrailingZeros();
5947       SDValue Op = N0.getOperand(0);
5948 
5949       if (ShAmt) {
5950         SDLoc DL(N0);
5951         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5952                   DAG.getConstant(ShAmt, DL,
5953                                   getShiftAmountTy(Op.getValueType())));
5954         AddToWorklist(Op.getNode());
5955       }
5956 
5957       SDLoc DL(N);
5958       return DAG.getNode(ISD::XOR, DL, VT,
5959                          Op, DAG.getConstant(1, DL, VT));
5960     }
5961   }
5962 
5963   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5964   if (N1.getOpcode() == ISD::TRUNCATE &&
5965       N1.getOperand(0).getOpcode() == ISD::AND) {
5966     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5967       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5968   }
5969 
5970   // fold operands of srl based on knowledge that the low bits are not
5971   // demanded.
5972   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5973     return SDValue(N, 0);
5974 
5975   if (N1C && !N1C->isOpaque())
5976     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5977       return NewSRL;
5978 
5979   // Attempt to convert a srl of a load into a narrower zero-extending load.
5980   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5981     return NarrowLoad;
5982 
5983   // Here is a common situation. We want to optimize:
5984   //
5985   //   %a = ...
5986   //   %b = and i32 %a, 2
5987   //   %c = srl i32 %b, 1
5988   //   brcond i32 %c ...
5989   //
5990   // into
5991   //
5992   //   %a = ...
5993   //   %b = and %a, 2
5994   //   %c = setcc eq %b, 0
5995   //   brcond %c ...
5996   //
5997   // However when after the source operand of SRL is optimized into AND, the SRL
5998   // itself may not be optimized further. Look for it and add the BRCOND into
5999   // the worklist.
6000   if (N->hasOneUse()) {
6001     SDNode *Use = *N->use_begin();
6002     if (Use->getOpcode() == ISD::BRCOND)
6003       AddToWorklist(Use);
6004     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
6005       // Also look pass the truncate.
6006       Use = *Use->use_begin();
6007       if (Use->getOpcode() == ISD::BRCOND)
6008         AddToWorklist(Use);
6009     }
6010   }
6011 
6012   return SDValue();
6013 }
6014 
6015 SDValue DAGCombiner::visitABS(SDNode *N) {
6016   SDValue N0 = N->getOperand(0);
6017   EVT VT = N->getValueType(0);
6018 
6019   // fold (abs c1) -> c2
6020   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6021     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
6022   // fold (abs (abs x)) -> (abs x)
6023   if (N0.getOpcode() == ISD::ABS)
6024     return N0;
6025   // fold (abs x) -> x iff not-negative
6026   if (DAG.SignBitIsZero(N0))
6027     return N0;
6028   return SDValue();
6029 }
6030 
6031 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
6032   SDValue N0 = N->getOperand(0);
6033   EVT VT = N->getValueType(0);
6034 
6035   // fold (bswap c1) -> c2
6036   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6037     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
6038   // fold (bswap (bswap x)) -> x
6039   if (N0.getOpcode() == ISD::BSWAP)
6040     return N0->getOperand(0);
6041   return SDValue();
6042 }
6043 
6044 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
6045   SDValue N0 = N->getOperand(0);
6046   EVT VT = N->getValueType(0);
6047 
6048   // fold (bitreverse c1) -> c2
6049   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6050     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
6051   // fold (bitreverse (bitreverse x)) -> x
6052   if (N0.getOpcode() == ISD::BITREVERSE)
6053     return N0.getOperand(0);
6054   return SDValue();
6055 }
6056 
6057 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
6058   SDValue N0 = N->getOperand(0);
6059   EVT VT = N->getValueType(0);
6060 
6061   // fold (ctlz c1) -> c2
6062   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6063     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
6064   return SDValue();
6065 }
6066 
6067 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
6068   SDValue N0 = N->getOperand(0);
6069   EVT VT = N->getValueType(0);
6070 
6071   // fold (ctlz_zero_undef c1) -> c2
6072   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6073     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6074   return SDValue();
6075 }
6076 
6077 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
6078   SDValue N0 = N->getOperand(0);
6079   EVT VT = N->getValueType(0);
6080 
6081   // fold (cttz c1) -> c2
6082   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6083     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
6084   return SDValue();
6085 }
6086 
6087 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
6088   SDValue N0 = N->getOperand(0);
6089   EVT VT = N->getValueType(0);
6090 
6091   // fold (cttz_zero_undef c1) -> c2
6092   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6093     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6094   return SDValue();
6095 }
6096 
6097 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
6098   SDValue N0 = N->getOperand(0);
6099   EVT VT = N->getValueType(0);
6100 
6101   // fold (ctpop c1) -> c2
6102   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6103     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6104   return SDValue();
6105 }
6106 
6107 
6108 /// \brief Generate Min/Max node
6109 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6110                                    SDValue RHS, SDValue True, SDValue False,
6111                                    ISD::CondCode CC, const TargetLowering &TLI,
6112                                    SelectionDAG &DAG) {
6113   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6114     return SDValue();
6115 
6116   switch (CC) {
6117   case ISD::SETOLT:
6118   case ISD::SETOLE:
6119   case ISD::SETLT:
6120   case ISD::SETLE:
6121   case ISD::SETULT:
6122   case ISD::SETULE: {
6123     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6124     if (TLI.isOperationLegal(Opcode, VT))
6125       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6126     return SDValue();
6127   }
6128   case ISD::SETOGT:
6129   case ISD::SETOGE:
6130   case ISD::SETGT:
6131   case ISD::SETGE:
6132   case ISD::SETUGT:
6133   case ISD::SETUGE: {
6134     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6135     if (TLI.isOperationLegal(Opcode, VT))
6136       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6137     return SDValue();
6138   }
6139   default:
6140     return SDValue();
6141   }
6142 }
6143 
6144 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6145   SDValue Cond = N->getOperand(0);
6146   SDValue N1 = N->getOperand(1);
6147   SDValue N2 = N->getOperand(2);
6148   EVT VT = N->getValueType(0);
6149   EVT CondVT = Cond.getValueType();
6150   SDLoc DL(N);
6151 
6152   if (!VT.isInteger())
6153     return SDValue();
6154 
6155   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6156   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6157   if (!C1 || !C2)
6158     return SDValue();
6159 
6160   // Only do this before legalization to avoid conflicting with target-specific
6161   // transforms in the other direction (create a select from a zext/sext). There
6162   // is also a target-independent combine here in DAGCombiner in the other
6163   // direction for (select Cond, -1, 0) when the condition is not i1.
6164   if (CondVT == MVT::i1 && !LegalOperations) {
6165     if (C1->isNullValue() && C2->isOne()) {
6166       // select Cond, 0, 1 --> zext (!Cond)
6167       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6168       if (VT != MVT::i1)
6169         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6170       return NotCond;
6171     }
6172     if (C1->isNullValue() && C2->isAllOnesValue()) {
6173       // select Cond, 0, -1 --> sext (!Cond)
6174       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6175       if (VT != MVT::i1)
6176         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6177       return NotCond;
6178     }
6179     if (C1->isOne() && C2->isNullValue()) {
6180       // select Cond, 1, 0 --> zext (Cond)
6181       if (VT != MVT::i1)
6182         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6183       return Cond;
6184     }
6185     if (C1->isAllOnesValue() && C2->isNullValue()) {
6186       // select Cond, -1, 0 --> sext (Cond)
6187       if (VT != MVT::i1)
6188         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6189       return Cond;
6190     }
6191 
6192     // For any constants that differ by 1, we can transform the select into an
6193     // extend and add. Use a target hook because some targets may prefer to
6194     // transform in the other direction.
6195     if (TLI.convertSelectOfConstantsToMath(VT)) {
6196       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6197         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6198         if (VT != MVT::i1)
6199           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6200         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6201       }
6202       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6203         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6204         if (VT != MVT::i1)
6205           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6206         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6207       }
6208     }
6209 
6210     return SDValue();
6211   }
6212 
6213   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6214   // We can't do this reliably if integer based booleans have different contents
6215   // to floating point based booleans. This is because we can't tell whether we
6216   // have an integer-based boolean or a floating-point-based boolean unless we
6217   // can find the SETCC that produced it and inspect its operands. This is
6218   // fairly easy if C is the SETCC node, but it can potentially be
6219   // undiscoverable (or not reasonably discoverable). For example, it could be
6220   // in another basic block or it could require searching a complicated
6221   // expression.
6222   if (CondVT.isInteger() &&
6223       TLI.getBooleanContents(false, true) ==
6224           TargetLowering::ZeroOrOneBooleanContent &&
6225       TLI.getBooleanContents(false, false) ==
6226           TargetLowering::ZeroOrOneBooleanContent &&
6227       C1->isNullValue() && C2->isOne()) {
6228     SDValue NotCond =
6229         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6230     if (VT.bitsEq(CondVT))
6231       return NotCond;
6232     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6233   }
6234 
6235   return SDValue();
6236 }
6237 
6238 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6239   SDValue N0 = N->getOperand(0);
6240   SDValue N1 = N->getOperand(1);
6241   SDValue N2 = N->getOperand(2);
6242   EVT VT = N->getValueType(0);
6243   EVT VT0 = N0.getValueType();
6244   SDLoc DL(N);
6245 
6246   // fold (select C, X, X) -> X
6247   if (N1 == N2)
6248     return N1;
6249 
6250   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6251     // fold (select true, X, Y) -> X
6252     // fold (select false, X, Y) -> Y
6253     return !N0C->isNullValue() ? N1 : N2;
6254   }
6255 
6256   // fold (select X, X, Y) -> (or X, Y)
6257   // fold (select X, 1, Y) -> (or C, Y)
6258   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6259     return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6260 
6261   if (SDValue V = foldSelectOfConstants(N))
6262     return V;
6263 
6264   // fold (select C, 0, X) -> (and (not C), X)
6265   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6266     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6267     AddToWorklist(NOTNode.getNode());
6268     return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6269   }
6270   // fold (select C, X, 1) -> (or (not C), X)
6271   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6272     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6273     AddToWorklist(NOTNode.getNode());
6274     return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6275   }
6276   // fold (select X, Y, X) -> (and X, Y)
6277   // fold (select X, Y, 0) -> (and X, Y)
6278   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6279     return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6280 
6281   // If we can fold this based on the true/false value, do so.
6282   if (SimplifySelectOps(N, N1, N2))
6283     return SDValue(N, 0); // Don't revisit N.
6284 
6285   if (VT0 == MVT::i1) {
6286     // The code in this block deals with the following 2 equivalences:
6287     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6288     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6289     // The target can specify its preferred form with the
6290     // shouldNormalizeToSelectSequence() callback. However we always transform
6291     // to the right anyway if we find the inner select exists in the DAG anyway
6292     // and we always transform to the left side if we know that we can further
6293     // optimize the combination of the conditions.
6294     bool normalizeToSequence =
6295         TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6296     // select (and Cond0, Cond1), X, Y
6297     //   -> select Cond0, (select Cond1, X, Y), Y
6298     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6299       SDValue Cond0 = N0->getOperand(0);
6300       SDValue Cond1 = N0->getOperand(1);
6301       SDValue InnerSelect =
6302           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6303       if (normalizeToSequence || !InnerSelect.use_empty())
6304         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6305                            InnerSelect, N2);
6306     }
6307     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6308     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6309       SDValue Cond0 = N0->getOperand(0);
6310       SDValue Cond1 = N0->getOperand(1);
6311       SDValue InnerSelect =
6312           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6313       if (normalizeToSequence || !InnerSelect.use_empty())
6314         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
6315                            InnerSelect);
6316     }
6317 
6318     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6319     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6320       SDValue N1_0 = N1->getOperand(0);
6321       SDValue N1_1 = N1->getOperand(1);
6322       SDValue N1_2 = N1->getOperand(2);
6323       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6324         // Create the actual and node if we can generate good code for it.
6325         if (!normalizeToSequence) {
6326           SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
6327           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
6328         }
6329         // Otherwise see if we can optimize the "and" to a better pattern.
6330         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6331           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
6332                              N2);
6333       }
6334     }
6335     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6336     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6337       SDValue N2_0 = N2->getOperand(0);
6338       SDValue N2_1 = N2->getOperand(1);
6339       SDValue N2_2 = N2->getOperand(2);
6340       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6341         // Create the actual or node if we can generate good code for it.
6342         if (!normalizeToSequence) {
6343           SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
6344           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
6345         }
6346         // Otherwise see if we can optimize to a better pattern.
6347         if (SDValue Combined = visitORLike(N0, N2_0, N))
6348           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
6349                              N2_2);
6350       }
6351     }
6352   }
6353 
6354   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6355   if (VT0 == MVT::i1) {
6356     if (N0->getOpcode() == ISD::XOR) {
6357       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6358         SDValue Cond0 = N0->getOperand(0);
6359         if (C->isOne())
6360           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1);
6361       }
6362     }
6363   }
6364 
6365   // fold selects based on a setcc into other things, such as min/max/abs
6366   if (N0.getOpcode() == ISD::SETCC) {
6367     // select x, y (fcmp lt x, y) -> fminnum x, y
6368     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6369     //
6370     // This is OK if we don't care about what happens if either operand is a
6371     // NaN.
6372     //
6373 
6374     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6375     // no signed zeros as well as no nans.
6376     const TargetOptions &Options = DAG.getTarget().Options;
6377     if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
6378         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6379       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6380 
6381       if (SDValue FMinMax = combineMinNumMaxNum(
6382               DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
6383         return FMinMax;
6384     }
6385 
6386     if ((!LegalOperations &&
6387          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6388         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6389       return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
6390                          N0.getOperand(1), N1, N2, N0.getOperand(2));
6391     return SimplifySelect(DL, N0, N1, N2);
6392   }
6393 
6394   return SDValue();
6395 }
6396 
6397 static
6398 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6399   SDLoc DL(N);
6400   EVT LoVT, HiVT;
6401   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6402 
6403   // Split the inputs.
6404   SDValue Lo, Hi, LL, LH, RL, RH;
6405   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6406   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6407 
6408   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6409   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6410 
6411   return std::make_pair(Lo, Hi);
6412 }
6413 
6414 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6415 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6416 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6417   SDLoc DL(N);
6418   SDValue Cond = N->getOperand(0);
6419   SDValue LHS = N->getOperand(1);
6420   SDValue RHS = N->getOperand(2);
6421   EVT VT = N->getValueType(0);
6422   int NumElems = VT.getVectorNumElements();
6423   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6424          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6425          Cond.getOpcode() == ISD::BUILD_VECTOR);
6426 
6427   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6428   // binary ones here.
6429   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6430     return SDValue();
6431 
6432   // We're sure we have an even number of elements due to the
6433   // concat_vectors we have as arguments to vselect.
6434   // Skip BV elements until we find one that's not an UNDEF
6435   // After we find an UNDEF element, keep looping until we get to half the
6436   // length of the BV and see if all the non-undef nodes are the same.
6437   ConstantSDNode *BottomHalf = nullptr;
6438   for (int i = 0; i < NumElems / 2; ++i) {
6439     if (Cond->getOperand(i)->isUndef())
6440       continue;
6441 
6442     if (BottomHalf == nullptr)
6443       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6444     else if (Cond->getOperand(i).getNode() != BottomHalf)
6445       return SDValue();
6446   }
6447 
6448   // Do the same for the second half of the BuildVector
6449   ConstantSDNode *TopHalf = nullptr;
6450   for (int i = NumElems / 2; i < NumElems; ++i) {
6451     if (Cond->getOperand(i)->isUndef())
6452       continue;
6453 
6454     if (TopHalf == nullptr)
6455       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6456     else if (Cond->getOperand(i).getNode() != TopHalf)
6457       return SDValue();
6458   }
6459 
6460   assert(TopHalf && BottomHalf &&
6461          "One half of the selector was all UNDEFs and the other was all the "
6462          "same value. This should have been addressed before this function.");
6463   return DAG.getNode(
6464       ISD::CONCAT_VECTORS, DL, VT,
6465       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6466       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6467 }
6468 
6469 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6470 
6471   if (Level >= AfterLegalizeTypes)
6472     return SDValue();
6473 
6474   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6475   SDValue Mask = MSC->getMask();
6476   SDValue Data  = MSC->getValue();
6477   SDLoc DL(N);
6478 
6479   // If the MSCATTER data type requires splitting and the mask is provided by a
6480   // SETCC, then split both nodes and its operands before legalization. This
6481   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6482   // and enables future optimizations (e.g. min/max pattern matching on X86).
6483   if (Mask.getOpcode() != ISD::SETCC)
6484     return SDValue();
6485 
6486   // Check if any splitting is required.
6487   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6488       TargetLowering::TypeSplitVector)
6489     return SDValue();
6490   SDValue MaskLo, MaskHi, Lo, Hi;
6491   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6492 
6493   EVT LoVT, HiVT;
6494   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6495 
6496   SDValue Chain = MSC->getChain();
6497 
6498   EVT MemoryVT = MSC->getMemoryVT();
6499   unsigned Alignment = MSC->getOriginalAlignment();
6500 
6501   EVT LoMemVT, HiMemVT;
6502   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6503 
6504   SDValue DataLo, DataHi;
6505   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6506 
6507   SDValue BasePtr = MSC->getBasePtr();
6508   SDValue IndexLo, IndexHi;
6509   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6510 
6511   MachineMemOperand *MMO = DAG.getMachineFunction().
6512     getMachineMemOperand(MSC->getPointerInfo(),
6513                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6514                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6515 
6516   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6517   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6518                             DL, OpsLo, MMO);
6519 
6520   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6521   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6522                             DL, OpsHi, MMO);
6523 
6524   AddToWorklist(Lo.getNode());
6525   AddToWorklist(Hi.getNode());
6526 
6527   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6528 }
6529 
6530 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6531 
6532   if (Level >= AfterLegalizeTypes)
6533     return SDValue();
6534 
6535   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6536   SDValue Mask = MST->getMask();
6537   SDValue Data  = MST->getValue();
6538   EVT VT = Data.getValueType();
6539   SDLoc DL(N);
6540 
6541   // If the MSTORE data type requires splitting and the mask is provided by a
6542   // SETCC, then split both nodes and its operands before legalization. This
6543   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6544   // and enables future optimizations (e.g. min/max pattern matching on X86).
6545   if (Mask.getOpcode() == ISD::SETCC) {
6546 
6547     // Check if any splitting is required.
6548     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6549         TargetLowering::TypeSplitVector)
6550       return SDValue();
6551 
6552     SDValue MaskLo, MaskHi, Lo, Hi;
6553     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6554 
6555     SDValue Chain = MST->getChain();
6556     SDValue Ptr   = MST->getBasePtr();
6557 
6558     EVT MemoryVT = MST->getMemoryVT();
6559     unsigned Alignment = MST->getOriginalAlignment();
6560 
6561     // if Alignment is equal to the vector size,
6562     // take the half of it for the second part
6563     unsigned SecondHalfAlignment =
6564       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6565 
6566     EVT LoMemVT, HiMemVT;
6567     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6568 
6569     SDValue DataLo, DataHi;
6570     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6571 
6572     MachineMemOperand *MMO = DAG.getMachineFunction().
6573       getMachineMemOperand(MST->getPointerInfo(),
6574                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6575                            Alignment, MST->getAAInfo(), MST->getRanges());
6576 
6577     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6578                             MST->isTruncatingStore(),
6579                             MST->isCompressingStore());
6580 
6581     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6582                                      MST->isCompressingStore());
6583 
6584     MMO = DAG.getMachineFunction().
6585       getMachineMemOperand(MST->getPointerInfo(),
6586                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6587                            SecondHalfAlignment, MST->getAAInfo(),
6588                            MST->getRanges());
6589 
6590     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6591                             MST->isTruncatingStore(),
6592                             MST->isCompressingStore());
6593 
6594     AddToWorklist(Lo.getNode());
6595     AddToWorklist(Hi.getNode());
6596 
6597     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6598   }
6599   return SDValue();
6600 }
6601 
6602 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6603 
6604   if (Level >= AfterLegalizeTypes)
6605     return SDValue();
6606 
6607   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6608   SDValue Mask = MGT->getMask();
6609   SDLoc DL(N);
6610 
6611   // If the MGATHER result requires splitting and the mask is provided by a
6612   // SETCC, then split both nodes and its operands before legalization. This
6613   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6614   // and enables future optimizations (e.g. min/max pattern matching on X86).
6615 
6616   if (Mask.getOpcode() != ISD::SETCC)
6617     return SDValue();
6618 
6619   EVT VT = N->getValueType(0);
6620 
6621   // Check if any splitting is required.
6622   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6623       TargetLowering::TypeSplitVector)
6624     return SDValue();
6625 
6626   SDValue MaskLo, MaskHi, Lo, Hi;
6627   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6628 
6629   SDValue Src0 = MGT->getValue();
6630   SDValue Src0Lo, Src0Hi;
6631   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6632 
6633   EVT LoVT, HiVT;
6634   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6635 
6636   SDValue Chain = MGT->getChain();
6637   EVT MemoryVT = MGT->getMemoryVT();
6638   unsigned Alignment = MGT->getOriginalAlignment();
6639 
6640   EVT LoMemVT, HiMemVT;
6641   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6642 
6643   SDValue BasePtr = MGT->getBasePtr();
6644   SDValue Index = MGT->getIndex();
6645   SDValue IndexLo, IndexHi;
6646   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6647 
6648   MachineMemOperand *MMO = DAG.getMachineFunction().
6649     getMachineMemOperand(MGT->getPointerInfo(),
6650                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6651                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6652 
6653   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6654   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6655                             MMO);
6656 
6657   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6658   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6659                             MMO);
6660 
6661   AddToWorklist(Lo.getNode());
6662   AddToWorklist(Hi.getNode());
6663 
6664   // Build a factor node to remember that this load is independent of the
6665   // other one.
6666   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6667                       Hi.getValue(1));
6668 
6669   // Legalized the chain result - switch anything that used the old chain to
6670   // use the new one.
6671   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6672 
6673   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6674 
6675   SDValue RetOps[] = { GatherRes, Chain };
6676   return DAG.getMergeValues(RetOps, DL);
6677 }
6678 
6679 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6680 
6681   if (Level >= AfterLegalizeTypes)
6682     return SDValue();
6683 
6684   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6685   SDValue Mask = MLD->getMask();
6686   SDLoc DL(N);
6687 
6688   // If the MLOAD result requires splitting and the mask is provided by a
6689   // SETCC, then split both nodes and its operands before legalization. This
6690   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6691   // and enables future optimizations (e.g. min/max pattern matching on X86).
6692 
6693   if (Mask.getOpcode() == ISD::SETCC) {
6694     EVT VT = N->getValueType(0);
6695 
6696     // Check if any splitting is required.
6697     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6698         TargetLowering::TypeSplitVector)
6699       return SDValue();
6700 
6701     SDValue MaskLo, MaskHi, Lo, Hi;
6702     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6703 
6704     SDValue Src0 = MLD->getSrc0();
6705     SDValue Src0Lo, Src0Hi;
6706     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6707 
6708     EVT LoVT, HiVT;
6709     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6710 
6711     SDValue Chain = MLD->getChain();
6712     SDValue Ptr   = MLD->getBasePtr();
6713     EVT MemoryVT = MLD->getMemoryVT();
6714     unsigned Alignment = MLD->getOriginalAlignment();
6715 
6716     // if Alignment is equal to the vector size,
6717     // take the half of it for the second part
6718     unsigned SecondHalfAlignment =
6719       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6720          Alignment/2 : Alignment;
6721 
6722     EVT LoMemVT, HiMemVT;
6723     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6724 
6725     MachineMemOperand *MMO = DAG.getMachineFunction().
6726     getMachineMemOperand(MLD->getPointerInfo(),
6727                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6728                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6729 
6730     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6731                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6732 
6733     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6734                                      MLD->isExpandingLoad());
6735 
6736     MMO = DAG.getMachineFunction().
6737     getMachineMemOperand(MLD->getPointerInfo(),
6738                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6739                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6740 
6741     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6742                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6743 
6744     AddToWorklist(Lo.getNode());
6745     AddToWorklist(Hi.getNode());
6746 
6747     // Build a factor node to remember that this load is independent of the
6748     // other one.
6749     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6750                         Hi.getValue(1));
6751 
6752     // Legalized the chain result - switch anything that used the old chain to
6753     // use the new one.
6754     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6755 
6756     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6757 
6758     SDValue RetOps[] = { LoadRes, Chain };
6759     return DAG.getMergeValues(RetOps, DL);
6760   }
6761   return SDValue();
6762 }
6763 
6764 /// A vector select of 2 constant vectors can be simplified to math/logic to
6765 /// avoid a variable select instruction and possibly avoid constant loads.
6766 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
6767   SDValue Cond = N->getOperand(0);
6768   SDValue N1 = N->getOperand(1);
6769   SDValue N2 = N->getOperand(2);
6770   EVT VT = N->getValueType(0);
6771   if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
6772       !TLI.convertSelectOfConstantsToMath(VT) ||
6773       !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
6774       !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
6775     return SDValue();
6776 
6777   // Check if we can use the condition value to increment/decrement a single
6778   // constant value. This simplifies a select to an add and removes a constant
6779   // load/materialization from the general case.
6780   bool AllAddOne = true;
6781   bool AllSubOne = true;
6782   unsigned Elts = VT.getVectorNumElements();
6783   for (unsigned i = 0; i != Elts; ++i) {
6784     SDValue N1Elt = N1.getOperand(i);
6785     SDValue N2Elt = N2.getOperand(i);
6786     if (N1Elt.isUndef() || N2Elt.isUndef())
6787       continue;
6788 
6789     const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
6790     const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
6791     if (C1 != C2 + 1)
6792       AllAddOne = false;
6793     if (C1 != C2 - 1)
6794       AllSubOne = false;
6795   }
6796 
6797   // Further simplifications for the extra-special cases where the constants are
6798   // all 0 or all -1 should be implemented as folds of these patterns.
6799   SDLoc DL(N);
6800   if (AllAddOne || AllSubOne) {
6801     // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
6802     // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
6803     auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
6804     SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
6805     return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
6806   }
6807 
6808   // The general case for select-of-constants:
6809   // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
6810   // ...but that only makes sense if a vselect is slower than 2 logic ops, so
6811   // leave that to a machine-specific pass.
6812   return SDValue();
6813 }
6814 
6815 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6816   SDValue N0 = N->getOperand(0);
6817   SDValue N1 = N->getOperand(1);
6818   SDValue N2 = N->getOperand(2);
6819   SDLoc DL(N);
6820 
6821   // fold (vselect C, X, X) -> X
6822   if (N1 == N2)
6823     return N1;
6824 
6825   // Canonicalize integer abs.
6826   // vselect (setg[te] X,  0),  X, -X ->
6827   // vselect (setgt    X, -1),  X, -X ->
6828   // vselect (setl[te] X,  0), -X,  X ->
6829   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6830   if (N0.getOpcode() == ISD::SETCC) {
6831     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6832     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6833     bool isAbs = false;
6834     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6835 
6836     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6837          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6838         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6839       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6840     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6841              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6842       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6843 
6844     if (isAbs) {
6845       EVT VT = LHS.getValueType();
6846       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
6847         return DAG.getNode(ISD::ABS, DL, VT, LHS);
6848 
6849       SDValue Shift = DAG.getNode(
6850           ISD::SRA, DL, VT, LHS,
6851           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6852       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6853       AddToWorklist(Shift.getNode());
6854       AddToWorklist(Add.getNode());
6855       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6856     }
6857   }
6858 
6859   if (SimplifySelectOps(N, N1, N2))
6860     return SDValue(N, 0);  // Don't revisit N.
6861 
6862   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6863   if (ISD::isBuildVectorAllOnes(N0.getNode()))
6864     return N1;
6865   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6866   if (ISD::isBuildVectorAllZeros(N0.getNode()))
6867     return N2;
6868 
6869   // The ConvertSelectToConcatVector function is assuming both the above
6870   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6871   // and addressed.
6872   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6873       N2.getOpcode() == ISD::CONCAT_VECTORS &&
6874       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6875     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6876       return CV;
6877   }
6878 
6879   if (SDValue V = foldVSelectOfConstants(N))
6880     return V;
6881 
6882   return SDValue();
6883 }
6884 
6885 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6886   SDValue N0 = N->getOperand(0);
6887   SDValue N1 = N->getOperand(1);
6888   SDValue N2 = N->getOperand(2);
6889   SDValue N3 = N->getOperand(3);
6890   SDValue N4 = N->getOperand(4);
6891   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6892 
6893   // fold select_cc lhs, rhs, x, x, cc -> x
6894   if (N2 == N3)
6895     return N2;
6896 
6897   // Determine if the condition we're dealing with is constant
6898   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6899                                   CC, SDLoc(N), false)) {
6900     AddToWorklist(SCC.getNode());
6901 
6902     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6903       if (!SCCC->isNullValue())
6904         return N2;    // cond always true -> true val
6905       else
6906         return N3;    // cond always false -> false val
6907     } else if (SCC->isUndef()) {
6908       // When the condition is UNDEF, just return the first operand. This is
6909       // coherent the DAG creation, no setcc node is created in this case
6910       return N2;
6911     } else if (SCC.getOpcode() == ISD::SETCC) {
6912       // Fold to a simpler select_cc
6913       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6914                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6915                          SCC.getOperand(2));
6916     }
6917   }
6918 
6919   // If we can fold this based on the true/false value, do so.
6920   if (SimplifySelectOps(N, N2, N3))
6921     return SDValue(N, 0);  // Don't revisit N.
6922 
6923   // fold select_cc into other things, such as min/max/abs
6924   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6925 }
6926 
6927 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6928   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6929                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
6930                        SDLoc(N));
6931 }
6932 
6933 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6934   SDValue LHS = N->getOperand(0);
6935   SDValue RHS = N->getOperand(1);
6936   SDValue Carry = N->getOperand(2);
6937   SDValue Cond = N->getOperand(3);
6938 
6939   // If Carry is false, fold to a regular SETCC.
6940   if (Carry.getOpcode() == ISD::CARRY_FALSE)
6941     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6942 
6943   return SDValue();
6944 }
6945 
6946 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
6947   SDValue LHS = N->getOperand(0);
6948   SDValue RHS = N->getOperand(1);
6949   SDValue Carry = N->getOperand(2);
6950   SDValue Cond = N->getOperand(3);
6951 
6952   // If Carry is false, fold to a regular SETCC.
6953   if (isNullConstant(Carry))
6954     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6955 
6956   return SDValue();
6957 }
6958 
6959 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6960 /// a build_vector of constants.
6961 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6962 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6963 /// Vector extends are not folded if operations are legal; this is to
6964 /// avoid introducing illegal build_vector dag nodes.
6965 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6966                                          SelectionDAG &DAG, bool LegalTypes,
6967                                          bool LegalOperations) {
6968   unsigned Opcode = N->getOpcode();
6969   SDValue N0 = N->getOperand(0);
6970   EVT VT = N->getValueType(0);
6971 
6972   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6973          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6974          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6975          && "Expected EXTEND dag node in input!");
6976 
6977   // fold (sext c1) -> c1
6978   // fold (zext c1) -> c1
6979   // fold (aext c1) -> c1
6980   if (isa<ConstantSDNode>(N0))
6981     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6982 
6983   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6984   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6985   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6986   EVT SVT = VT.getScalarType();
6987   if (!(VT.isVector() &&
6988       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6989       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6990     return nullptr;
6991 
6992   // We can fold this node into a build_vector.
6993   unsigned VTBits = SVT.getSizeInBits();
6994   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6995   SmallVector<SDValue, 8> Elts;
6996   unsigned NumElts = VT.getVectorNumElements();
6997   SDLoc DL(N);
6998 
6999   for (unsigned i=0; i != NumElts; ++i) {
7000     SDValue Op = N0->getOperand(i);
7001     if (Op->isUndef()) {
7002       Elts.push_back(DAG.getUNDEF(SVT));
7003       continue;
7004     }
7005 
7006     SDLoc DL(Op);
7007     // Get the constant value and if needed trunc it to the size of the type.
7008     // Nodes like build_vector might have constants wider than the scalar type.
7009     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
7010     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
7011       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
7012     else
7013       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
7014   }
7015 
7016   return DAG.getBuildVector(VT, DL, Elts).getNode();
7017 }
7018 
7019 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
7020 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
7021 // transformation. Returns true if extension are possible and the above
7022 // mentioned transformation is profitable.
7023 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
7024                                     unsigned ExtOpc,
7025                                     SmallVectorImpl<SDNode *> &ExtendNodes,
7026                                     const TargetLowering &TLI) {
7027   bool HasCopyToRegUses = false;
7028   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
7029   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
7030                             UE = N0.getNode()->use_end();
7031        UI != UE; ++UI) {
7032     SDNode *User = *UI;
7033     if (User == N)
7034       continue;
7035     if (UI.getUse().getResNo() != N0.getResNo())
7036       continue;
7037     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
7038     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
7039       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
7040       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
7041         // Sign bits will be lost after a zext.
7042         return false;
7043       bool Add = false;
7044       for (unsigned i = 0; i != 2; ++i) {
7045         SDValue UseOp = User->getOperand(i);
7046         if (UseOp == N0)
7047           continue;
7048         if (!isa<ConstantSDNode>(UseOp))
7049           return false;
7050         Add = true;
7051       }
7052       if (Add)
7053         ExtendNodes.push_back(User);
7054       continue;
7055     }
7056     // If truncates aren't free and there are users we can't
7057     // extend, it isn't worthwhile.
7058     if (!isTruncFree)
7059       return false;
7060     // Remember if this value is live-out.
7061     if (User->getOpcode() == ISD::CopyToReg)
7062       HasCopyToRegUses = true;
7063   }
7064 
7065   if (HasCopyToRegUses) {
7066     bool BothLiveOut = false;
7067     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7068          UI != UE; ++UI) {
7069       SDUse &Use = UI.getUse();
7070       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
7071         BothLiveOut = true;
7072         break;
7073       }
7074     }
7075     if (BothLiveOut)
7076       // Both unextended and extended values are live out. There had better be
7077       // a good reason for the transformation.
7078       return ExtendNodes.size();
7079   }
7080   return true;
7081 }
7082 
7083 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
7084                                   SDValue Trunc, SDValue ExtLoad,
7085                                   const SDLoc &DL, ISD::NodeType ExtType) {
7086   // Extend SetCC uses if necessary.
7087   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
7088     SDNode *SetCC = SetCCs[i];
7089     SmallVector<SDValue, 4> Ops;
7090 
7091     for (unsigned j = 0; j != 2; ++j) {
7092       SDValue SOp = SetCC->getOperand(j);
7093       if (SOp == Trunc)
7094         Ops.push_back(ExtLoad);
7095       else
7096         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
7097     }
7098 
7099     Ops.push_back(SetCC->getOperand(2));
7100     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7101   }
7102 }
7103 
7104 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
7105 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
7106   SDValue N0 = N->getOperand(0);
7107   EVT DstVT = N->getValueType(0);
7108   EVT SrcVT = N0.getValueType();
7109 
7110   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
7111           N->getOpcode() == ISD::ZERO_EXTEND) &&
7112          "Unexpected node type (not an extend)!");
7113 
7114   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
7115   // For example, on a target with legal v4i32, but illegal v8i32, turn:
7116   //   (v8i32 (sext (v8i16 (load x))))
7117   // into:
7118   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
7119   //                          (v4i32 (sextload (x + 16)))))
7120   // Where uses of the original load, i.e.:
7121   //   (v8i16 (load x))
7122   // are replaced with:
7123   //   (v8i16 (truncate
7124   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
7125   //                            (v4i32 (sextload (x + 16)))))))
7126   //
7127   // This combine is only applicable to illegal, but splittable, vectors.
7128   // All legal types, and illegal non-vector types, are handled elsewhere.
7129   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
7130   //
7131   if (N0->getOpcode() != ISD::LOAD)
7132     return SDValue();
7133 
7134   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7135 
7136   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
7137       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
7138       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
7139     return SDValue();
7140 
7141   SmallVector<SDNode *, 4> SetCCs;
7142   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
7143     return SDValue();
7144 
7145   ISD::LoadExtType ExtType =
7146       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
7147 
7148   // Try to split the vector types to get down to legal types.
7149   EVT SplitSrcVT = SrcVT;
7150   EVT SplitDstVT = DstVT;
7151   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
7152          SplitSrcVT.getVectorNumElements() > 1) {
7153     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
7154     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
7155   }
7156 
7157   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7158     return SDValue();
7159 
7160   SDLoc DL(N);
7161   const unsigned NumSplits =
7162       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7163   const unsigned Stride = SplitSrcVT.getStoreSize();
7164   SmallVector<SDValue, 4> Loads;
7165   SmallVector<SDValue, 4> Chains;
7166 
7167   SDValue BasePtr = LN0->getBasePtr();
7168   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7169     const unsigned Offset = Idx * Stride;
7170     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7171 
7172     SDValue SplitLoad = DAG.getExtLoad(
7173         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7174         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7175         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7176 
7177     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7178                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7179 
7180     Loads.push_back(SplitLoad.getValue(0));
7181     Chains.push_back(SplitLoad.getValue(1));
7182   }
7183 
7184   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7185   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7186 
7187   // Simplify TF.
7188   AddToWorklist(NewChain.getNode());
7189 
7190   CombineTo(N, NewValue);
7191 
7192   // Replace uses of the original load (before extension)
7193   // with a truncate of the concatenated sextloaded vectors.
7194   SDValue Trunc =
7195       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7196   CombineTo(N0.getNode(), Trunc, NewChain);
7197   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
7198                   (ISD::NodeType)N->getOpcode());
7199   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7200 }
7201 
7202 /// If we're narrowing or widening the result of a vector select and the final
7203 /// size is the same size as a setcc (compare) feeding the select, then try to
7204 /// apply the cast operation to the select's operands because matching vector
7205 /// sizes for a select condition and other operands should be more efficient.
7206 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7207   unsigned CastOpcode = Cast->getOpcode();
7208   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7209           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7210           CastOpcode == ISD::FP_ROUND) &&
7211          "Unexpected opcode for vector select narrowing/widening");
7212 
7213   // We only do this transform before legal ops because the pattern may be
7214   // obfuscated by target-specific operations after legalization. Do not create
7215   // an illegal select op, however, because that may be difficult to lower.
7216   EVT VT = Cast->getValueType(0);
7217   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7218     return SDValue();
7219 
7220   SDValue VSel = Cast->getOperand(0);
7221   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7222       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7223     return SDValue();
7224 
7225   // Does the setcc have the same vector size as the casted select?
7226   SDValue SetCC = VSel.getOperand(0);
7227   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7228   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7229     return SDValue();
7230 
7231   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7232   SDValue A = VSel.getOperand(1);
7233   SDValue B = VSel.getOperand(2);
7234   SDValue CastA, CastB;
7235   SDLoc DL(Cast);
7236   if (CastOpcode == ISD::FP_ROUND) {
7237     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7238     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7239     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7240   } else {
7241     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7242     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7243   }
7244   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7245 }
7246 
7247 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7248   SDValue N0 = N->getOperand(0);
7249   EVT VT = N->getValueType(0);
7250   SDLoc DL(N);
7251 
7252   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7253                                               LegalOperations))
7254     return SDValue(Res, 0);
7255 
7256   // fold (sext (sext x)) -> (sext x)
7257   // fold (sext (aext x)) -> (sext x)
7258   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7259     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7260 
7261   if (N0.getOpcode() == ISD::TRUNCATE) {
7262     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7263     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7264     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7265       SDNode *oye = N0.getOperand(0).getNode();
7266       if (NarrowLoad.getNode() != N0.getNode()) {
7267         CombineTo(N0.getNode(), NarrowLoad);
7268         // CombineTo deleted the truncate, if needed, but not what's under it.
7269         AddToWorklist(oye);
7270       }
7271       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7272     }
7273 
7274     // See if the value being truncated is already sign extended.  If so, just
7275     // eliminate the trunc/sext pair.
7276     SDValue Op = N0.getOperand(0);
7277     unsigned OpBits   = Op.getScalarValueSizeInBits();
7278     unsigned MidBits  = N0.getScalarValueSizeInBits();
7279     unsigned DestBits = VT.getScalarSizeInBits();
7280     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7281 
7282     if (OpBits == DestBits) {
7283       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7284       // bits, it is already ready.
7285       if (NumSignBits > DestBits-MidBits)
7286         return Op;
7287     } else if (OpBits < DestBits) {
7288       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7289       // bits, just sext from i32.
7290       if (NumSignBits > OpBits-MidBits)
7291         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7292     } else {
7293       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7294       // bits, just truncate to i32.
7295       if (NumSignBits > OpBits-MidBits)
7296         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7297     }
7298 
7299     // fold (sext (truncate x)) -> (sextinreg x).
7300     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7301                                                  N0.getValueType())) {
7302       if (OpBits < DestBits)
7303         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7304       else if (OpBits > DestBits)
7305         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7306       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7307                          DAG.getValueType(N0.getValueType()));
7308     }
7309   }
7310 
7311   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7312   // Only generate vector extloads when 1) they're legal, and 2) they are
7313   // deemed desirable by the target.
7314   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7315       ((!LegalOperations && !VT.isVector() &&
7316         !cast<LoadSDNode>(N0)->isVolatile()) ||
7317        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7318     bool DoXform = true;
7319     SmallVector<SDNode*, 4> SetCCs;
7320     if (!N0.hasOneUse())
7321       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7322     if (VT.isVector())
7323       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7324     if (DoXform) {
7325       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7326       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7327                                        LN0->getBasePtr(), N0.getValueType(),
7328                                        LN0->getMemOperand());
7329       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7330                                   N0.getValueType(), ExtLoad);
7331       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7332       // If the load value is used only by N, replace it via CombineTo N.
7333       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7334       CombineTo(N, ExtLoad);
7335       if (NoReplaceTrunc)
7336         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7337       else
7338         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7339       return SDValue(N, 0);
7340     }
7341   }
7342 
7343   // fold (sext (load x)) to multiple smaller sextloads.
7344   // Only on illegal but splittable vectors.
7345   if (SDValue ExtLoad = CombineExtLoad(N))
7346     return ExtLoad;
7347 
7348   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7349   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7350   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7351       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7352     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7353     EVT MemVT = LN0->getMemoryVT();
7354     if ((!LegalOperations && !LN0->isVolatile()) ||
7355         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7356       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7357                                        LN0->getBasePtr(), MemVT,
7358                                        LN0->getMemOperand());
7359       CombineTo(N, ExtLoad);
7360       CombineTo(N0.getNode(),
7361                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7362                             N0.getValueType(), ExtLoad),
7363                 ExtLoad.getValue(1));
7364       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7365     }
7366   }
7367 
7368   // fold (sext (and/or/xor (load x), cst)) ->
7369   //      (and/or/xor (sextload x), (sext cst))
7370   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7371        N0.getOpcode() == ISD::XOR) &&
7372       isa<LoadSDNode>(N0.getOperand(0)) &&
7373       N0.getOperand(1).getOpcode() == ISD::Constant &&
7374       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7375       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7376     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7377     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7378       bool DoXform = true;
7379       SmallVector<SDNode*, 4> SetCCs;
7380       if (!N0.hasOneUse())
7381         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7382                                           SetCCs, TLI);
7383       if (DoXform) {
7384         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7385                                          LN0->getChain(), LN0->getBasePtr(),
7386                                          LN0->getMemoryVT(),
7387                                          LN0->getMemOperand());
7388         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7389         Mask = Mask.sext(VT.getSizeInBits());
7390         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7391                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7392         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7393                                     SDLoc(N0.getOperand(0)),
7394                                     N0.getOperand(0).getValueType(), ExtLoad);
7395         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7396         bool NoReplaceTruncAnd = !N0.hasOneUse();
7397         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7398         CombineTo(N, And);
7399         // If N0 has multiple uses, change other uses as well.
7400         if (NoReplaceTruncAnd) {
7401           SDValue TruncAnd =
7402               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7403           CombineTo(N0.getNode(), TruncAnd);
7404         }
7405         if (NoReplaceTrunc)
7406           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7407         else
7408           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7409         return SDValue(N,0); // Return N so it doesn't get rechecked!
7410       }
7411     }
7412   }
7413 
7414   if (N0.getOpcode() == ISD::SETCC) {
7415     SDValue N00 = N0.getOperand(0);
7416     SDValue N01 = N0.getOperand(1);
7417     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7418     EVT N00VT = N0.getOperand(0).getValueType();
7419 
7420     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7421     // Only do this before legalize for now.
7422     if (VT.isVector() && !LegalOperations &&
7423         TLI.getBooleanContents(N00VT) ==
7424             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7425       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7426       // of the same size as the compared operands. Only optimize sext(setcc())
7427       // if this is the case.
7428       EVT SVT = getSetCCResultType(N00VT);
7429 
7430       // We know that the # elements of the results is the same as the
7431       // # elements of the compare (and the # elements of the compare result
7432       // for that matter).  Check to see that they are the same size.  If so,
7433       // we know that the element size of the sext'd result matches the
7434       // element size of the compare operands.
7435       if (VT.getSizeInBits() == SVT.getSizeInBits())
7436         return DAG.getSetCC(DL, VT, N00, N01, CC);
7437 
7438       // If the desired elements are smaller or larger than the source
7439       // elements, we can use a matching integer vector type and then
7440       // truncate/sign extend.
7441       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7442       if (SVT == MatchingVecType) {
7443         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7444         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7445       }
7446     }
7447 
7448     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7449     // Here, T can be 1 or -1, depending on the type of the setcc and
7450     // getBooleanContents().
7451     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7452 
7453     // To determine the "true" side of the select, we need to know the high bit
7454     // of the value returned by the setcc if it evaluates to true.
7455     // If the type of the setcc is i1, then the true case of the select is just
7456     // sext(i1 1), that is, -1.
7457     // If the type of the setcc is larger (say, i8) then the value of the high
7458     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7459     // of the appropriate width.
7460     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7461                                            : TLI.getConstTrueVal(DAG, VT, DL);
7462     SDValue Zero = DAG.getConstant(0, DL, VT);
7463     if (SDValue SCC =
7464             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7465       return SCC;
7466 
7467     if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) {
7468       EVT SetCCVT = getSetCCResultType(N00VT);
7469       // Don't do this transform for i1 because there's a select transform
7470       // that would reverse it.
7471       // TODO: We should not do this transform at all without a target hook
7472       // because a sext is likely cheaper than a select?
7473       if (SetCCVT.getScalarSizeInBits() != 1 &&
7474           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7475         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7476         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7477       }
7478     }
7479   }
7480 
7481   // fold (sext x) -> (zext x) if the sign bit is known zero.
7482   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7483       DAG.SignBitIsZero(N0))
7484     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7485 
7486   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7487     return NewVSel;
7488 
7489   return SDValue();
7490 }
7491 
7492 // isTruncateOf - If N is a truncate of some other value, return true, record
7493 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7494 // This function computes KnownBits to avoid a duplicated call to
7495 // computeKnownBits in the caller.
7496 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7497                          KnownBits &Known) {
7498   if (N->getOpcode() == ISD::TRUNCATE) {
7499     Op = N->getOperand(0);
7500     DAG.computeKnownBits(Op, Known);
7501     return true;
7502   }
7503 
7504   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7505       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7506     return false;
7507 
7508   SDValue Op0 = N->getOperand(0);
7509   SDValue Op1 = N->getOperand(1);
7510   assert(Op0.getValueType() == Op1.getValueType());
7511 
7512   if (isNullConstant(Op0))
7513     Op = Op1;
7514   else if (isNullConstant(Op1))
7515     Op = Op0;
7516   else
7517     return false;
7518 
7519   DAG.computeKnownBits(Op, Known);
7520 
7521   if (!(Known.Zero | 1).isAllOnesValue())
7522     return false;
7523 
7524   return true;
7525 }
7526 
7527 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7528   SDValue N0 = N->getOperand(0);
7529   EVT VT = N->getValueType(0);
7530 
7531   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7532                                               LegalOperations))
7533     return SDValue(Res, 0);
7534 
7535   // fold (zext (zext x)) -> (zext x)
7536   // fold (zext (aext x)) -> (zext x)
7537   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7538     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7539                        N0.getOperand(0));
7540 
7541   // fold (zext (truncate x)) -> (zext x) or
7542   //      (zext (truncate x)) -> (truncate x)
7543   // This is valid when the truncated bits of x are already zero.
7544   // FIXME: We should extend this to work for vectors too.
7545   SDValue Op;
7546   KnownBits Known;
7547   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7548     APInt TruncatedBits =
7549       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7550       APInt(Op.getValueSizeInBits(), 0) :
7551       APInt::getBitsSet(Op.getValueSizeInBits(),
7552                         N0.getValueSizeInBits(),
7553                         std::min(Op.getValueSizeInBits(),
7554                                  VT.getSizeInBits()));
7555     if (TruncatedBits.isSubsetOf(Known.Zero))
7556       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7557   }
7558 
7559   // fold (zext (truncate (load x))) -> (zext (smaller load x))
7560   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7561   if (N0.getOpcode() == ISD::TRUNCATE) {
7562     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7563       SDNode *oye = N0.getOperand(0).getNode();
7564       if (NarrowLoad.getNode() != N0.getNode()) {
7565         CombineTo(N0.getNode(), NarrowLoad);
7566         // CombineTo deleted the truncate, if needed, but not what's under it.
7567         AddToWorklist(oye);
7568       }
7569       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7570     }
7571   }
7572 
7573   // fold (zext (truncate x)) -> (and x, mask)
7574   if (N0.getOpcode() == ISD::TRUNCATE) {
7575     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7576     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7577     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7578       SDNode *oye = N0.getOperand(0).getNode();
7579       if (NarrowLoad.getNode() != N0.getNode()) {
7580         CombineTo(N0.getNode(), NarrowLoad);
7581         // CombineTo deleted the truncate, if needed, but not what's under it.
7582         AddToWorklist(oye);
7583       }
7584       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7585     }
7586 
7587     EVT SrcVT = N0.getOperand(0).getValueType();
7588     EVT MinVT = N0.getValueType();
7589 
7590     // Try to mask before the extension to avoid having to generate a larger mask,
7591     // possibly over several sub-vectors.
7592     if (SrcVT.bitsLT(VT)) {
7593       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7594                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7595         SDValue Op = N0.getOperand(0);
7596         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7597         AddToWorklist(Op.getNode());
7598         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7599       }
7600     }
7601 
7602     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7603       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7604       AddToWorklist(Op.getNode());
7605       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7606     }
7607   }
7608 
7609   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7610   // if either of the casts is not free.
7611   if (N0.getOpcode() == ISD::AND &&
7612       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7613       N0.getOperand(1).getOpcode() == ISD::Constant &&
7614       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7615                            N0.getValueType()) ||
7616        !TLI.isZExtFree(N0.getValueType(), VT))) {
7617     SDValue X = N0.getOperand(0).getOperand(0);
7618     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7619     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7620     Mask = Mask.zext(VT.getSizeInBits());
7621     SDLoc DL(N);
7622     return DAG.getNode(ISD::AND, DL, VT,
7623                        X, DAG.getConstant(Mask, DL, VT));
7624   }
7625 
7626   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7627   // Only generate vector extloads when 1) they're legal, and 2) they are
7628   // deemed desirable by the target.
7629   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7630       ((!LegalOperations && !VT.isVector() &&
7631         !cast<LoadSDNode>(N0)->isVolatile()) ||
7632        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7633     bool DoXform = true;
7634     SmallVector<SDNode*, 4> SetCCs;
7635     if (!N0.hasOneUse())
7636       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7637     if (VT.isVector())
7638       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7639     if (DoXform) {
7640       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7641       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7642                                        LN0->getChain(),
7643                                        LN0->getBasePtr(), N0.getValueType(),
7644                                        LN0->getMemOperand());
7645 
7646       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7647                                   N0.getValueType(), ExtLoad);
7648       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
7649       // If the load value is used only by N, replace it via CombineTo N.
7650       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7651       CombineTo(N, ExtLoad);
7652       if (NoReplaceTrunc)
7653         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7654       else
7655         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7656       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7657     }
7658   }
7659 
7660   // fold (zext (load x)) to multiple smaller zextloads.
7661   // Only on illegal but splittable vectors.
7662   if (SDValue ExtLoad = CombineExtLoad(N))
7663     return ExtLoad;
7664 
7665   // fold (zext (and/or/xor (load x), cst)) ->
7666   //      (and/or/xor (zextload x), (zext cst))
7667   // Unless (and (load x) cst) will match as a zextload already and has
7668   // additional users.
7669   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7670        N0.getOpcode() == ISD::XOR) &&
7671       isa<LoadSDNode>(N0.getOperand(0)) &&
7672       N0.getOperand(1).getOpcode() == ISD::Constant &&
7673       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7674       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7675     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7676     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7677       bool DoXform = true;
7678       SmallVector<SDNode*, 4> SetCCs;
7679       if (!N0.hasOneUse()) {
7680         if (N0.getOpcode() == ISD::AND) {
7681           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7682           auto NarrowLoad = false;
7683           EVT LoadResultTy = AndC->getValueType(0);
7684           EVT ExtVT, LoadedVT;
7685           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7686                                NarrowLoad))
7687             DoXform = false;
7688         }
7689         if (DoXform)
7690           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7691                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7692       }
7693       if (DoXform) {
7694         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7695                                          LN0->getChain(), LN0->getBasePtr(),
7696                                          LN0->getMemoryVT(),
7697                                          LN0->getMemOperand());
7698         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7699         Mask = Mask.zext(VT.getSizeInBits());
7700         SDLoc DL(N);
7701         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7702                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7703         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7704                                     SDLoc(N0.getOperand(0)),
7705                                     N0.getOperand(0).getValueType(), ExtLoad);
7706         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND);
7707         bool NoReplaceTruncAnd = !N0.hasOneUse();
7708         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7709         CombineTo(N, And);
7710         // If N0 has multiple uses, change other uses as well.
7711         if (NoReplaceTruncAnd) {
7712           SDValue TruncAnd =
7713               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7714           CombineTo(N0.getNode(), TruncAnd);
7715         }
7716         if (NoReplaceTrunc)
7717           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7718         else
7719           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7720         return SDValue(N,0); // Return N so it doesn't get rechecked!
7721       }
7722     }
7723   }
7724 
7725   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7726   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7727   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7728       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7729     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7730     EVT MemVT = LN0->getMemoryVT();
7731     if ((!LegalOperations && !LN0->isVolatile()) ||
7732         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7733       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7734                                        LN0->getChain(),
7735                                        LN0->getBasePtr(), MemVT,
7736                                        LN0->getMemOperand());
7737       CombineTo(N, ExtLoad);
7738       CombineTo(N0.getNode(),
7739                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7740                             ExtLoad),
7741                 ExtLoad.getValue(1));
7742       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7743     }
7744   }
7745 
7746   if (N0.getOpcode() == ISD::SETCC) {
7747     // Only do this before legalize for now.
7748     if (!LegalOperations && VT.isVector() &&
7749         N0.getValueType().getVectorElementType() == MVT::i1) {
7750       EVT N00VT = N0.getOperand(0).getValueType();
7751       if (getSetCCResultType(N00VT) == N0.getValueType())
7752         return SDValue();
7753 
7754       // We know that the # elements of the results is the same as the #
7755       // elements of the compare (and the # elements of the compare result for
7756       // that matter). Check to see that they are the same size. If so, we know
7757       // that the element size of the sext'd result matches the element size of
7758       // the compare operands.
7759       SDLoc DL(N);
7760       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7761       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7762         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7763         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7764                                      N0.getOperand(1), N0.getOperand(2));
7765         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7766       }
7767 
7768       // If the desired elements are smaller or larger than the source
7769       // elements we can use a matching integer vector type and then
7770       // truncate/sign extend.
7771       EVT MatchingElementType = EVT::getIntegerVT(
7772           *DAG.getContext(), N00VT.getScalarSizeInBits());
7773       EVT MatchingVectorType = EVT::getVectorVT(
7774           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7775       SDValue VsetCC =
7776           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7777                       N0.getOperand(1), N0.getOperand(2));
7778       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7779                          VecOnes);
7780     }
7781 
7782     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7783     SDLoc DL(N);
7784     if (SDValue SCC = SimplifySelectCC(
7785             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7786             DAG.getConstant(0, DL, VT),
7787             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7788       return SCC;
7789   }
7790 
7791   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7792   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7793       isa<ConstantSDNode>(N0.getOperand(1)) &&
7794       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7795       N0.hasOneUse()) {
7796     SDValue ShAmt = N0.getOperand(1);
7797     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7798     if (N0.getOpcode() == ISD::SHL) {
7799       SDValue InnerZExt = N0.getOperand(0);
7800       // If the original shl may be shifting out bits, do not perform this
7801       // transformation.
7802       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7803         InnerZExt.getOperand(0).getValueSizeInBits();
7804       if (ShAmtVal > KnownZeroBits)
7805         return SDValue();
7806     }
7807 
7808     SDLoc DL(N);
7809 
7810     // Ensure that the shift amount is wide enough for the shifted value.
7811     if (VT.getSizeInBits() >= 256)
7812       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7813 
7814     return DAG.getNode(N0.getOpcode(), DL, VT,
7815                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7816                        ShAmt);
7817   }
7818 
7819   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7820     return NewVSel;
7821 
7822   return SDValue();
7823 }
7824 
7825 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7826   SDValue N0 = N->getOperand(0);
7827   EVT VT = N->getValueType(0);
7828 
7829   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7830                                               LegalOperations))
7831     return SDValue(Res, 0);
7832 
7833   // fold (aext (aext x)) -> (aext x)
7834   // fold (aext (zext x)) -> (zext x)
7835   // fold (aext (sext x)) -> (sext x)
7836   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
7837       N0.getOpcode() == ISD::ZERO_EXTEND ||
7838       N0.getOpcode() == ISD::SIGN_EXTEND)
7839     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7840 
7841   // fold (aext (truncate (load x))) -> (aext (smaller load x))
7842   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7843   if (N0.getOpcode() == ISD::TRUNCATE) {
7844     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7845       SDNode *oye = N0.getOperand(0).getNode();
7846       if (NarrowLoad.getNode() != N0.getNode()) {
7847         CombineTo(N0.getNode(), NarrowLoad);
7848         // CombineTo deleted the truncate, if needed, but not what's under it.
7849         AddToWorklist(oye);
7850       }
7851       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7852     }
7853   }
7854 
7855   // fold (aext (truncate x))
7856   if (N0.getOpcode() == ISD::TRUNCATE)
7857     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7858 
7859   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7860   // if the trunc is not free.
7861   if (N0.getOpcode() == ISD::AND &&
7862       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7863       N0.getOperand(1).getOpcode() == ISD::Constant &&
7864       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7865                           N0.getValueType())) {
7866     SDLoc DL(N);
7867     SDValue X = N0.getOperand(0).getOperand(0);
7868     X = DAG.getAnyExtOrTrunc(X, DL, VT);
7869     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7870     Mask = Mask.zext(VT.getSizeInBits());
7871     return DAG.getNode(ISD::AND, DL, VT,
7872                        X, DAG.getConstant(Mask, DL, VT));
7873   }
7874 
7875   // fold (aext (load x)) -> (aext (truncate (extload x)))
7876   // None of the supported targets knows how to perform load and any_ext
7877   // on vectors in one instruction.  We only perform this transformation on
7878   // scalars.
7879   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7880       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7881       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7882     bool DoXform = true;
7883     SmallVector<SDNode*, 4> SetCCs;
7884     if (!N0.hasOneUse())
7885       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7886     if (DoXform) {
7887       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7888       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7889                                        LN0->getChain(),
7890                                        LN0->getBasePtr(), N0.getValueType(),
7891                                        LN0->getMemOperand());
7892       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7893                                   N0.getValueType(), ExtLoad);
7894       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7895                       ISD::ANY_EXTEND);
7896       // If the load value is used only by N, replace it via CombineTo N.
7897       bool NoReplaceTrunc = N0.hasOneUse();
7898       CombineTo(N, ExtLoad);
7899       if (NoReplaceTrunc)
7900         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7901       else
7902         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7903       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7904     }
7905   }
7906 
7907   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7908   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7909   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
7910   if (N0.getOpcode() == ISD::LOAD &&
7911       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7912       N0.hasOneUse()) {
7913     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7914     ISD::LoadExtType ExtType = LN0->getExtensionType();
7915     EVT MemVT = LN0->getMemoryVT();
7916     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7917       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7918                                        VT, LN0->getChain(), LN0->getBasePtr(),
7919                                        MemVT, LN0->getMemOperand());
7920       CombineTo(N, ExtLoad);
7921       CombineTo(N0.getNode(),
7922                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7923                             N0.getValueType(), ExtLoad),
7924                 ExtLoad.getValue(1));
7925       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7926     }
7927   }
7928 
7929   if (N0.getOpcode() == ISD::SETCC) {
7930     // For vectors:
7931     // aext(setcc) -> vsetcc
7932     // aext(setcc) -> truncate(vsetcc)
7933     // aext(setcc) -> aext(vsetcc)
7934     // Only do this before legalize for now.
7935     if (VT.isVector() && !LegalOperations) {
7936       EVT N0VT = N0.getOperand(0).getValueType();
7937         // We know that the # elements of the results is the same as the
7938         // # elements of the compare (and the # elements of the compare result
7939         // for that matter).  Check to see that they are the same size.  If so,
7940         // we know that the element size of the sext'd result matches the
7941         // element size of the compare operands.
7942       if (VT.getSizeInBits() == N0VT.getSizeInBits())
7943         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7944                              N0.getOperand(1),
7945                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
7946       // If the desired elements are smaller or larger than the source
7947       // elements we can use a matching integer vector type and then
7948       // truncate/any extend
7949       else {
7950         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7951         SDValue VsetCC =
7952           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7953                         N0.getOperand(1),
7954                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
7955         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7956       }
7957     }
7958 
7959     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7960     SDLoc DL(N);
7961     if (SDValue SCC = SimplifySelectCC(
7962             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7963             DAG.getConstant(0, DL, VT),
7964             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7965       return SCC;
7966   }
7967 
7968   return SDValue();
7969 }
7970 
7971 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7972   SDValue N0 = N->getOperand(0);
7973   SDValue N1 = N->getOperand(1);
7974   EVT EVT = cast<VTSDNode>(N1)->getVT();
7975 
7976   // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7977   if (N0.getOpcode() == ISD::AssertZext &&
7978       EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7979     return N0;
7980 
7981   return SDValue();
7982 }
7983 
7984 /// If the result of a wider load is shifted to right of N  bits and then
7985 /// truncated to a narrower type and where N is a multiple of number of bits of
7986 /// the narrower type, transform it to a narrower load from address + N / num of
7987 /// bits of new type. If the result is to be extended, also fold the extension
7988 /// to form a extending load.
7989 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7990   unsigned Opc = N->getOpcode();
7991 
7992   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7993   SDValue N0 = N->getOperand(0);
7994   EVT VT = N->getValueType(0);
7995   EVT ExtVT = VT;
7996 
7997   // This transformation isn't valid for vector loads.
7998   if (VT.isVector())
7999     return SDValue();
8000 
8001   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
8002   // extended to VT.
8003   if (Opc == ISD::SIGN_EXTEND_INREG) {
8004     ExtType = ISD::SEXTLOAD;
8005     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8006   } else if (Opc == ISD::SRL) {
8007     // Another special-case: SRL is basically zero-extending a narrower value.
8008     ExtType = ISD::ZEXTLOAD;
8009     N0 = SDValue(N, 0);
8010     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8011     if (!N01) return SDValue();
8012     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
8013                               VT.getSizeInBits() - N01->getZExtValue());
8014   }
8015   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
8016     return SDValue();
8017 
8018   unsigned EVTBits = ExtVT.getSizeInBits();
8019 
8020   // Do not generate loads of non-round integer types since these can
8021   // be expensive (and would be wrong if the type is not byte sized).
8022   if (!ExtVT.isRound())
8023     return SDValue();
8024 
8025   unsigned ShAmt = 0;
8026   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
8027     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8028       ShAmt = N01->getZExtValue();
8029       // Is the shift amount a multiple of size of VT?
8030       if ((ShAmt & (EVTBits-1)) == 0) {
8031         N0 = N0.getOperand(0);
8032         // Is the load width a multiple of size of VT?
8033         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
8034           return SDValue();
8035       }
8036 
8037       // At this point, we must have a load or else we can't do the transform.
8038       if (!isa<LoadSDNode>(N0)) return SDValue();
8039 
8040       // Because a SRL must be assumed to *need* to zero-extend the high bits
8041       // (as opposed to anyext the high bits), we can't combine the zextload
8042       // lowering of SRL and an sextload.
8043       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
8044         return SDValue();
8045 
8046       // If the shift amount is larger than the input type then we're not
8047       // accessing any of the loaded bytes.  If the load was a zextload/extload
8048       // then the result of the shift+trunc is zero/undef (handled elsewhere).
8049       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
8050         return SDValue();
8051     }
8052   }
8053 
8054   // If the load is shifted left (and the result isn't shifted back right),
8055   // we can fold the truncate through the shift.
8056   unsigned ShLeftAmt = 0;
8057   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8058       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
8059     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8060       ShLeftAmt = N01->getZExtValue();
8061       N0 = N0.getOperand(0);
8062     }
8063   }
8064 
8065   // If we haven't found a load, we can't narrow it.  Don't transform one with
8066   // multiple uses, this would require adding a new load.
8067   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
8068     return SDValue();
8069 
8070   // Don't change the width of a volatile load.
8071   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8072   if (LN0->isVolatile())
8073     return SDValue();
8074 
8075   // Verify that we are actually reducing a load width here.
8076   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
8077     return SDValue();
8078 
8079   // For the transform to be legal, the load must produce only two values
8080   // (the value loaded and the chain).  Don't transform a pre-increment
8081   // load, for example, which produces an extra value.  Otherwise the
8082   // transformation is not equivalent, and the downstream logic to replace
8083   // uses gets things wrong.
8084   if (LN0->getNumValues() > 2)
8085     return SDValue();
8086 
8087   // If the load that we're shrinking is an extload and we're not just
8088   // discarding the extension we can't simply shrink the load. Bail.
8089   // TODO: It would be possible to merge the extensions in some cases.
8090   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
8091       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
8092     return SDValue();
8093 
8094   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
8095     return SDValue();
8096 
8097   EVT PtrType = N0.getOperand(1).getValueType();
8098 
8099   if (PtrType == MVT::Untyped || PtrType.isExtended())
8100     // It's not possible to generate a constant of extended or untyped type.
8101     return SDValue();
8102 
8103   // For big endian targets, we need to adjust the offset to the pointer to
8104   // load the correct bytes.
8105   if (DAG.getDataLayout().isBigEndian()) {
8106     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
8107     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
8108     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
8109   }
8110 
8111   uint64_t PtrOff = ShAmt / 8;
8112   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
8113   SDLoc DL(LN0);
8114   // The original load itself didn't wrap, so an offset within it doesn't.
8115   SDNodeFlags Flags;
8116   Flags.setNoUnsignedWrap(true);
8117   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
8118                                PtrType, LN0->getBasePtr(),
8119                                DAG.getConstant(PtrOff, DL, PtrType),
8120                                Flags);
8121   AddToWorklist(NewPtr.getNode());
8122 
8123   SDValue Load;
8124   if (ExtType == ISD::NON_EXTLOAD)
8125     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8126                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8127                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8128   else
8129     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8130                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8131                           NewAlign, LN0->getMemOperand()->getFlags(),
8132                           LN0->getAAInfo());
8133 
8134   // Replace the old load's chain with the new load's chain.
8135   WorklistRemover DeadNodes(*this);
8136   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8137 
8138   // Shift the result left, if we've swallowed a left shift.
8139   SDValue Result = Load;
8140   if (ShLeftAmt != 0) {
8141     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8142     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8143       ShImmTy = VT;
8144     // If the shift amount is as large as the result size (but, presumably,
8145     // no larger than the source) then the useful bits of the result are
8146     // zero; we can't simply return the shortened shift, because the result
8147     // of that operation is undefined.
8148     SDLoc DL(N0);
8149     if (ShLeftAmt >= VT.getSizeInBits())
8150       Result = DAG.getConstant(0, DL, VT);
8151     else
8152       Result = DAG.getNode(ISD::SHL, DL, VT,
8153                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8154   }
8155 
8156   // Return the new loaded value.
8157   return Result;
8158 }
8159 
8160 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8161   SDValue N0 = N->getOperand(0);
8162   SDValue N1 = N->getOperand(1);
8163   EVT VT = N->getValueType(0);
8164   EVT EVT = cast<VTSDNode>(N1)->getVT();
8165   unsigned VTBits = VT.getScalarSizeInBits();
8166   unsigned EVTBits = EVT.getScalarSizeInBits();
8167 
8168   if (N0.isUndef())
8169     return DAG.getUNDEF(VT);
8170 
8171   // fold (sext_in_reg c1) -> c1
8172   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8173     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8174 
8175   // If the input is already sign extended, just drop the extension.
8176   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8177     return N0;
8178 
8179   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8180   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8181       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8182     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8183                        N0.getOperand(0), N1);
8184 
8185   // fold (sext_in_reg (sext x)) -> (sext x)
8186   // fold (sext_in_reg (aext x)) -> (sext x)
8187   // if x is small enough.
8188   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8189     SDValue N00 = N0.getOperand(0);
8190     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8191         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8192       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8193   }
8194 
8195   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8196   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8197        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8198        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8199       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8200     if (!LegalOperations ||
8201         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8202       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8203   }
8204 
8205   // fold (sext_in_reg (zext x)) -> (sext x)
8206   // iff we are extending the source sign bit.
8207   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8208     SDValue N00 = N0.getOperand(0);
8209     if (N00.getScalarValueSizeInBits() == EVTBits &&
8210         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8211       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8212   }
8213 
8214   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8215   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8216     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8217 
8218   // fold operands of sext_in_reg based on knowledge that the top bits are not
8219   // demanded.
8220   if (SimplifyDemandedBits(SDValue(N, 0)))
8221     return SDValue(N, 0);
8222 
8223   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8224   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8225   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8226     return NarrowLoad;
8227 
8228   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8229   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8230   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8231   if (N0.getOpcode() == ISD::SRL) {
8232     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8233       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8234         // We can turn this into an SRA iff the input to the SRL is already sign
8235         // extended enough.
8236         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8237         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8238           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8239                              N0.getOperand(0), N0.getOperand(1));
8240       }
8241   }
8242 
8243   // fold (sext_inreg (extload x)) -> (sextload x)
8244   if (ISD::isEXTLoad(N0.getNode()) &&
8245       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8246       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8247       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8248        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8249     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8250     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8251                                      LN0->getChain(),
8252                                      LN0->getBasePtr(), EVT,
8253                                      LN0->getMemOperand());
8254     CombineTo(N, ExtLoad);
8255     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8256     AddToWorklist(ExtLoad.getNode());
8257     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8258   }
8259   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8260   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8261       N0.hasOneUse() &&
8262       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8263       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8264        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8265     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8266     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8267                                      LN0->getChain(),
8268                                      LN0->getBasePtr(), EVT,
8269                                      LN0->getMemOperand());
8270     CombineTo(N, ExtLoad);
8271     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8272     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8273   }
8274 
8275   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8276   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8277     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8278                                            N0.getOperand(1), false))
8279       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8280                          BSwap, N1);
8281   }
8282 
8283   return SDValue();
8284 }
8285 
8286 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8287   SDValue N0 = N->getOperand(0);
8288   EVT VT = N->getValueType(0);
8289 
8290   if (N0.isUndef())
8291     return DAG.getUNDEF(VT);
8292 
8293   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8294                                               LegalOperations))
8295     return SDValue(Res, 0);
8296 
8297   return SDValue();
8298 }
8299 
8300 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8301   SDValue N0 = N->getOperand(0);
8302   EVT VT = N->getValueType(0);
8303 
8304   if (N0.isUndef())
8305     return DAG.getUNDEF(VT);
8306 
8307   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8308                                               LegalOperations))
8309     return SDValue(Res, 0);
8310 
8311   return SDValue();
8312 }
8313 
8314 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8315   SDValue N0 = N->getOperand(0);
8316   EVT VT = N->getValueType(0);
8317   bool isLE = DAG.getDataLayout().isLittleEndian();
8318 
8319   // noop truncate
8320   if (N0.getValueType() == N->getValueType(0))
8321     return N0;
8322   // fold (truncate c1) -> c1
8323   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8324     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8325   // fold (truncate (truncate x)) -> (truncate x)
8326   if (N0.getOpcode() == ISD::TRUNCATE)
8327     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8328   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8329   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8330       N0.getOpcode() == ISD::SIGN_EXTEND ||
8331       N0.getOpcode() == ISD::ANY_EXTEND) {
8332     // if the source is smaller than the dest, we still need an extend.
8333     if (N0.getOperand(0).getValueType().bitsLT(VT))
8334       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8335     // if the source is larger than the dest, than we just need the truncate.
8336     if (N0.getOperand(0).getValueType().bitsGT(VT))
8337       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8338     // if the source and dest are the same type, we can drop both the extend
8339     // and the truncate.
8340     return N0.getOperand(0);
8341   }
8342 
8343   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8344   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8345     return SDValue();
8346 
8347   // Fold extract-and-trunc into a narrow extract. For example:
8348   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8349   //   i32 y = TRUNCATE(i64 x)
8350   //        -- becomes --
8351   //   v16i8 b = BITCAST (v2i64 val)
8352   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8353   //
8354   // Note: We only run this optimization after type legalization (which often
8355   // creates this pattern) and before operation legalization after which
8356   // we need to be more careful about the vector instructions that we generate.
8357   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8358       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8359 
8360     EVT VecTy = N0.getOperand(0).getValueType();
8361     EVT ExTy = N0.getValueType();
8362     EVT TrTy = N->getValueType(0);
8363 
8364     unsigned NumElem = VecTy.getVectorNumElements();
8365     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8366 
8367     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8368     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8369 
8370     SDValue EltNo = N0->getOperand(1);
8371     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8372       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8373       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8374       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8375 
8376       SDLoc DL(N);
8377       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8378                          DAG.getBitcast(NVT, N0.getOperand(0)),
8379                          DAG.getConstant(Index, DL, IndexTy));
8380     }
8381   }
8382 
8383   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8384   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8385     EVT SrcVT = N0.getValueType();
8386     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8387         TLI.isTruncateFree(SrcVT, VT)) {
8388       SDLoc SL(N0);
8389       SDValue Cond = N0.getOperand(0);
8390       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8391       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8392       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8393     }
8394   }
8395 
8396   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8397   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8398       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8399       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8400     SDValue Amt = N0.getOperand(1);
8401     KnownBits Known;
8402     DAG.computeKnownBits(Amt, Known);
8403     unsigned Size = VT.getScalarSizeInBits();
8404     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8405       SDLoc SL(N);
8406       EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8407 
8408       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8409       if (AmtVT != Amt.getValueType()) {
8410         Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8411         AddToWorklist(Amt.getNode());
8412       }
8413       return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8414     }
8415   }
8416 
8417   // Fold a series of buildvector, bitcast, and truncate if possible.
8418   // For example fold
8419   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8420   //   (2xi32 (buildvector x, y)).
8421   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8422       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8423       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8424       N0.getOperand(0).hasOneUse()) {
8425 
8426     SDValue BuildVect = N0.getOperand(0);
8427     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8428     EVT TruncVecEltTy = VT.getVectorElementType();
8429 
8430     // Check that the element types match.
8431     if (BuildVectEltTy == TruncVecEltTy) {
8432       // Now we only need to compute the offset of the truncated elements.
8433       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8434       unsigned TruncVecNumElts = VT.getVectorNumElements();
8435       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8436 
8437       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8438              "Invalid number of elements");
8439 
8440       SmallVector<SDValue, 8> Opnds;
8441       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8442         Opnds.push_back(BuildVect.getOperand(i));
8443 
8444       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8445     }
8446   }
8447 
8448   // See if we can simplify the input to this truncate through knowledge that
8449   // only the low bits are being used.
8450   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8451   // Currently we only perform this optimization on scalars because vectors
8452   // may have different active low bits.
8453   if (!VT.isVector()) {
8454     APInt Mask =
8455         APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
8456     if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
8457       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8458   }
8459 
8460   // fold (truncate (load x)) -> (smaller load x)
8461   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8462   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8463     if (SDValue Reduced = ReduceLoadWidth(N))
8464       return Reduced;
8465 
8466     // Handle the case where the load remains an extending load even
8467     // after truncation.
8468     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8469       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8470       if (!LN0->isVolatile() &&
8471           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8472         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8473                                          VT, LN0->getChain(), LN0->getBasePtr(),
8474                                          LN0->getMemoryVT(),
8475                                          LN0->getMemOperand());
8476         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8477         return NewLoad;
8478       }
8479     }
8480   }
8481 
8482   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8483   // where ... are all 'undef'.
8484   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8485     SmallVector<EVT, 8> VTs;
8486     SDValue V;
8487     unsigned Idx = 0;
8488     unsigned NumDefs = 0;
8489 
8490     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8491       SDValue X = N0.getOperand(i);
8492       if (!X.isUndef()) {
8493         V = X;
8494         Idx = i;
8495         NumDefs++;
8496       }
8497       // Stop if more than one members are non-undef.
8498       if (NumDefs > 1)
8499         break;
8500       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8501                                      VT.getVectorElementType(),
8502                                      X.getValueType().getVectorNumElements()));
8503     }
8504 
8505     if (NumDefs == 0)
8506       return DAG.getUNDEF(VT);
8507 
8508     if (NumDefs == 1) {
8509       assert(V.getNode() && "The single defined operand is empty!");
8510       SmallVector<SDValue, 8> Opnds;
8511       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8512         if (i != Idx) {
8513           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8514           continue;
8515         }
8516         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8517         AddToWorklist(NV.getNode());
8518         Opnds.push_back(NV);
8519       }
8520       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8521     }
8522   }
8523 
8524   // Fold truncate of a bitcast of a vector to an extract of the low vector
8525   // element.
8526   //
8527   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
8528   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8529     SDValue VecSrc = N0.getOperand(0);
8530     EVT SrcVT = VecSrc.getValueType();
8531     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8532         (!LegalOperations ||
8533          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8534       SDLoc SL(N);
8535 
8536       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8537       unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1;
8538       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8539                          VecSrc, DAG.getConstant(Idx, SL, IdxVT));
8540     }
8541   }
8542 
8543   // Simplify the operands using demanded-bits information.
8544   if (!VT.isVector() &&
8545       SimplifyDemandedBits(SDValue(N, 0)))
8546     return SDValue(N, 0);
8547 
8548   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8549   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8550   // When the adde's carry is not used.
8551   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8552       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8553       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8554     SDLoc SL(N);
8555     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8556     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8557     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8558     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8559   }
8560 
8561   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8562     return NewVSel;
8563 
8564   return SDValue();
8565 }
8566 
8567 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8568   SDValue Elt = N->getOperand(i);
8569   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8570     return Elt.getNode();
8571   return Elt.getOperand(Elt.getResNo()).getNode();
8572 }
8573 
8574 /// build_pair (load, load) -> load
8575 /// if load locations are consecutive.
8576 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8577   assert(N->getOpcode() == ISD::BUILD_PAIR);
8578 
8579   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8580   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8581   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8582       LD1->getAddressSpace() != LD2->getAddressSpace())
8583     return SDValue();
8584   EVT LD1VT = LD1->getValueType(0);
8585   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8586   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8587       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8588     unsigned Align = LD1->getAlignment();
8589     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8590         VT.getTypeForEVT(*DAG.getContext()));
8591 
8592     if (NewAlign <= Align &&
8593         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8594       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8595                          LD1->getPointerInfo(), Align);
8596   }
8597 
8598   return SDValue();
8599 }
8600 
8601 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8602   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8603   // and Lo parts; on big-endian machines it doesn't.
8604   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8605 }
8606 
8607 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8608                                     const TargetLowering &TLI) {
8609   // If this is not a bitcast to an FP type or if the target doesn't have
8610   // IEEE754-compliant FP logic, we're done.
8611   EVT VT = N->getValueType(0);
8612   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8613     return SDValue();
8614 
8615   // TODO: Use splat values for the constant-checking below and remove this
8616   // restriction.
8617   SDValue N0 = N->getOperand(0);
8618   EVT SourceVT = N0.getValueType();
8619   if (SourceVT.isVector())
8620     return SDValue();
8621 
8622   unsigned FPOpcode;
8623   APInt SignMask;
8624   switch (N0.getOpcode()) {
8625   case ISD::AND:
8626     FPOpcode = ISD::FABS;
8627     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8628     break;
8629   case ISD::XOR:
8630     FPOpcode = ISD::FNEG;
8631     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8632     break;
8633   // TODO: ISD::OR --> ISD::FNABS?
8634   default:
8635     return SDValue();
8636   }
8637 
8638   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8639   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8640   SDValue LogicOp0 = N0.getOperand(0);
8641   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8642   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8643       LogicOp0.getOpcode() == ISD::BITCAST &&
8644       LogicOp0->getOperand(0).getValueType() == VT)
8645     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8646 
8647   return SDValue();
8648 }
8649 
8650 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8651   SDValue N0 = N->getOperand(0);
8652   EVT VT = N->getValueType(0);
8653 
8654   if (N0.isUndef())
8655     return DAG.getUNDEF(VT);
8656 
8657   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8658   // Only do this before legalize, since afterward the target may be depending
8659   // on the bitconvert.
8660   // First check to see if this is all constant.
8661   if (!LegalTypes &&
8662       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8663       VT.isVector()) {
8664     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8665 
8666     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8667     assert(!DestEltVT.isVector() &&
8668            "Element type of vector ValueType must not be vector!");
8669     if (isSimple)
8670       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8671   }
8672 
8673   // If the input is a constant, let getNode fold it.
8674   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8675     // If we can't allow illegal operations, we need to check that this is just
8676     // a fp -> int or int -> conversion and that the resulting operation will
8677     // be legal.
8678     if (!LegalOperations ||
8679         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8680          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8681         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8682          TLI.isOperationLegal(ISD::Constant, VT)))
8683       return DAG.getBitcast(VT, N0);
8684   }
8685 
8686   // (conv (conv x, t1), t2) -> (conv x, t2)
8687   if (N0.getOpcode() == ISD::BITCAST)
8688     return DAG.getBitcast(VT, N0.getOperand(0));
8689 
8690   // fold (conv (load x)) -> (load (conv*)x)
8691   // If the resultant load doesn't need a higher alignment than the original!
8692   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8693       // Do not change the width of a volatile load.
8694       !cast<LoadSDNode>(N0)->isVolatile() &&
8695       // Do not remove the cast if the types differ in endian layout.
8696       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8697           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8698       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8699       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8700     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8701     unsigned OrigAlign = LN0->getAlignment();
8702 
8703     bool Fast = false;
8704     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8705                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8706         Fast) {
8707       SDValue Load =
8708           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8709                       LN0->getPointerInfo(), OrigAlign,
8710                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8711       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8712       return Load;
8713     }
8714   }
8715 
8716   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8717     return V;
8718 
8719   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8720   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8721   //
8722   // For ppc_fp128:
8723   // fold (bitcast (fneg x)) ->
8724   //     flipbit = signbit
8725   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8726   //
8727   // fold (bitcast (fabs x)) ->
8728   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8729   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8730   // This often reduces constant pool loads.
8731   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8732        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8733       N0.getNode()->hasOneUse() && VT.isInteger() &&
8734       !VT.isVector() && !N0.getValueType().isVector()) {
8735     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8736     AddToWorklist(NewConv.getNode());
8737 
8738     SDLoc DL(N);
8739     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8740       assert(VT.getSizeInBits() == 128);
8741       SDValue SignBit = DAG.getConstant(
8742           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8743       SDValue FlipBit;
8744       if (N0.getOpcode() == ISD::FNEG) {
8745         FlipBit = SignBit;
8746         AddToWorklist(FlipBit.getNode());
8747       } else {
8748         assert(N0.getOpcode() == ISD::FABS);
8749         SDValue Hi =
8750             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8751                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8752                                               SDLoc(NewConv)));
8753         AddToWorklist(Hi.getNode());
8754         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8755         AddToWorklist(FlipBit.getNode());
8756       }
8757       SDValue FlipBits =
8758           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8759       AddToWorklist(FlipBits.getNode());
8760       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8761     }
8762     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8763     if (N0.getOpcode() == ISD::FNEG)
8764       return DAG.getNode(ISD::XOR, DL, VT,
8765                          NewConv, DAG.getConstant(SignBit, DL, VT));
8766     assert(N0.getOpcode() == ISD::FABS);
8767     return DAG.getNode(ISD::AND, DL, VT,
8768                        NewConv, DAG.getConstant(~SignBit, DL, VT));
8769   }
8770 
8771   // fold (bitconvert (fcopysign cst, x)) ->
8772   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
8773   // Note that we don't handle (copysign x, cst) because this can always be
8774   // folded to an fneg or fabs.
8775   //
8776   // For ppc_fp128:
8777   // fold (bitcast (fcopysign cst, x)) ->
8778   //     flipbit = (and (extract_element
8779   //                     (xor (bitcast cst), (bitcast x)), 0),
8780   //                    signbit)
8781   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
8782   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8783       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8784       VT.isInteger() && !VT.isVector()) {
8785     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8786     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8787     if (isTypeLegal(IntXVT)) {
8788       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8789       AddToWorklist(X.getNode());
8790 
8791       // If X has a different width than the result/lhs, sext it or truncate it.
8792       unsigned VTWidth = VT.getSizeInBits();
8793       if (OrigXWidth < VTWidth) {
8794         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8795         AddToWorklist(X.getNode());
8796       } else if (OrigXWidth > VTWidth) {
8797         // To get the sign bit in the right place, we have to shift it right
8798         // before truncating.
8799         SDLoc DL(X);
8800         X = DAG.getNode(ISD::SRL, DL,
8801                         X.getValueType(), X,
8802                         DAG.getConstant(OrigXWidth-VTWidth, DL,
8803                                         X.getValueType()));
8804         AddToWorklist(X.getNode());
8805         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8806         AddToWorklist(X.getNode());
8807       }
8808 
8809       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8810         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8811         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8812         AddToWorklist(Cst.getNode());
8813         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8814         AddToWorklist(X.getNode());
8815         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8816         AddToWorklist(XorResult.getNode());
8817         SDValue XorResult64 = DAG.getNode(
8818             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8819             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8820                                   SDLoc(XorResult)));
8821         AddToWorklist(XorResult64.getNode());
8822         SDValue FlipBit =
8823             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8824                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8825         AddToWorklist(FlipBit.getNode());
8826         SDValue FlipBits =
8827             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8828         AddToWorklist(FlipBits.getNode());
8829         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8830       }
8831       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8832       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8833                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
8834       AddToWorklist(X.getNode());
8835 
8836       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8837       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8838                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8839       AddToWorklist(Cst.getNode());
8840 
8841       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8842     }
8843   }
8844 
8845   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8846   if (N0.getOpcode() == ISD::BUILD_PAIR)
8847     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8848       return CombineLD;
8849 
8850   // Remove double bitcasts from shuffles - this is often a legacy of
8851   // XformToShuffleWithZero being used to combine bitmaskings (of
8852   // float vectors bitcast to integer vectors) into shuffles.
8853   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8854   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8855       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8856       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8857       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8858     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8859 
8860     // If operands are a bitcast, peek through if it casts the original VT.
8861     // If operands are a constant, just bitcast back to original VT.
8862     auto PeekThroughBitcast = [&](SDValue Op) {
8863       if (Op.getOpcode() == ISD::BITCAST &&
8864           Op.getOperand(0).getValueType() == VT)
8865         return SDValue(Op.getOperand(0));
8866       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8867           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8868         return DAG.getBitcast(VT, Op);
8869       return SDValue();
8870     };
8871 
8872     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8873     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8874     if (!(SV0 && SV1))
8875       return SDValue();
8876 
8877     int MaskScale =
8878         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8879     SmallVector<int, 8> NewMask;
8880     for (int M : SVN->getMask())
8881       for (int i = 0; i != MaskScale; ++i)
8882         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8883 
8884     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8885     if (!LegalMask) {
8886       std::swap(SV0, SV1);
8887       ShuffleVectorSDNode::commuteMask(NewMask);
8888       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8889     }
8890 
8891     if (LegalMask)
8892       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8893   }
8894 
8895   return SDValue();
8896 }
8897 
8898 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8899   EVT VT = N->getValueType(0);
8900   return CombineConsecutiveLoads(N, VT);
8901 }
8902 
8903 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8904 /// operands. DstEltVT indicates the destination element value type.
8905 SDValue DAGCombiner::
8906 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8907   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8908 
8909   // If this is already the right type, we're done.
8910   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8911 
8912   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8913   unsigned DstBitSize = DstEltVT.getSizeInBits();
8914 
8915   // If this is a conversion of N elements of one type to N elements of another
8916   // type, convert each element.  This handles FP<->INT cases.
8917   if (SrcBitSize == DstBitSize) {
8918     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8919                               BV->getValueType(0).getVectorNumElements());
8920 
8921     // Due to the FP element handling below calling this routine recursively,
8922     // we can end up with a scalar-to-vector node here.
8923     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8924       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8925                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8926 
8927     SmallVector<SDValue, 8> Ops;
8928     for (SDValue Op : BV->op_values()) {
8929       // If the vector element type is not legal, the BUILD_VECTOR operands
8930       // are promoted and implicitly truncated.  Make that explicit here.
8931       if (Op.getValueType() != SrcEltVT)
8932         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8933       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8934       AddToWorklist(Ops.back().getNode());
8935     }
8936     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8937   }
8938 
8939   // Otherwise, we're growing or shrinking the elements.  To avoid having to
8940   // handle annoying details of growing/shrinking FP values, we convert them to
8941   // int first.
8942   if (SrcEltVT.isFloatingPoint()) {
8943     // Convert the input float vector to a int vector where the elements are the
8944     // same sizes.
8945     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8946     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8947     SrcEltVT = IntVT;
8948   }
8949 
8950   // Now we know the input is an integer vector.  If the output is a FP type,
8951   // convert to integer first, then to FP of the right size.
8952   if (DstEltVT.isFloatingPoint()) {
8953     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8954     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8955 
8956     // Next, convert to FP elements of the same size.
8957     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8958   }
8959 
8960   SDLoc DL(BV);
8961 
8962   // Okay, we know the src/dst types are both integers of differing types.
8963   // Handling growing first.
8964   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8965   if (SrcBitSize < DstBitSize) {
8966     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8967 
8968     SmallVector<SDValue, 8> Ops;
8969     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8970          i += NumInputsPerOutput) {
8971       bool isLE = DAG.getDataLayout().isLittleEndian();
8972       APInt NewBits = APInt(DstBitSize, 0);
8973       bool EltIsUndef = true;
8974       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8975         // Shift the previously computed bits over.
8976         NewBits <<= SrcBitSize;
8977         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8978         if (Op.isUndef()) continue;
8979         EltIsUndef = false;
8980 
8981         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8982                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
8983       }
8984 
8985       if (EltIsUndef)
8986         Ops.push_back(DAG.getUNDEF(DstEltVT));
8987       else
8988         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8989     }
8990 
8991     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8992     return DAG.getBuildVector(VT, DL, Ops);
8993   }
8994 
8995   // Finally, this must be the case where we are shrinking elements: each input
8996   // turns into multiple outputs.
8997   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8998   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8999                             NumOutputsPerInput*BV->getNumOperands());
9000   SmallVector<SDValue, 8> Ops;
9001 
9002   for (const SDValue &Op : BV->op_values()) {
9003     if (Op.isUndef()) {
9004       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
9005       continue;
9006     }
9007 
9008     APInt OpVal = cast<ConstantSDNode>(Op)->
9009                   getAPIntValue().zextOrTrunc(SrcBitSize);
9010 
9011     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
9012       APInt ThisVal = OpVal.trunc(DstBitSize);
9013       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
9014       OpVal.lshrInPlace(DstBitSize);
9015     }
9016 
9017     // For big endian targets, swap the order of the pieces of each element.
9018     if (DAG.getDataLayout().isBigEndian())
9019       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
9020   }
9021 
9022   return DAG.getBuildVector(VT, DL, Ops);
9023 }
9024 
9025 static bool isContractable(SDNode *N) {
9026   SDNodeFlags F = N->getFlags();
9027   return F.hasAllowContract() || F.hasUnsafeAlgebra();
9028 }
9029 
9030 /// Try to perform FMA combining on a given FADD node.
9031 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
9032   SDValue N0 = N->getOperand(0);
9033   SDValue N1 = N->getOperand(1);
9034   EVT VT = N->getValueType(0);
9035   SDLoc SL(N);
9036 
9037   const TargetOptions &Options = DAG.getTarget().Options;
9038 
9039   // Floating-point multiply-add with intermediate rounding.
9040   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9041 
9042   // Floating-point multiply-add without intermediate rounding.
9043   bool HasFMA =
9044       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9045       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9046 
9047   // No valid opcode, do not combine.
9048   if (!HasFMAD && !HasFMA)
9049     return SDValue();
9050 
9051   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9052                               Options.UnsafeFPMath || HasFMAD);
9053   // If the addition is not contractable, do not combine.
9054   if (!AllowFusionGlobally && !isContractable(N))
9055     return SDValue();
9056 
9057   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9058   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9059     return SDValue();
9060 
9061   // Always prefer FMAD to FMA for precision.
9062   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9063   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9064   bool LookThroughFPExt = TLI.isFPExtFree(VT);
9065 
9066   // Is the node an FMUL and contractable either due to global flags or
9067   // SDNodeFlags.
9068   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9069     if (N.getOpcode() != ISD::FMUL)
9070       return false;
9071     return AllowFusionGlobally || isContractable(N.getNode());
9072   };
9073   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
9074   // prefer to fold the multiply with fewer uses.
9075   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
9076     if (N0.getNode()->use_size() > N1.getNode()->use_size())
9077       std::swap(N0, N1);
9078   }
9079 
9080   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
9081   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9082     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9083                        N0.getOperand(0), N0.getOperand(1), N1);
9084   }
9085 
9086   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
9087   // Note: Commutes FADD operands.
9088   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
9089     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9090                        N1.getOperand(0), N1.getOperand(1), N0);
9091   }
9092 
9093   // Look through FP_EXTEND nodes to do more combining.
9094   if (LookThroughFPExt) {
9095     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
9096     if (N0.getOpcode() == ISD::FP_EXTEND) {
9097       SDValue N00 = N0.getOperand(0);
9098       if (isContractableFMUL(N00))
9099         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9100                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9101                                        N00.getOperand(0)),
9102                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9103                                        N00.getOperand(1)), N1);
9104     }
9105 
9106     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
9107     // Note: Commutes FADD operands.
9108     if (N1.getOpcode() == ISD::FP_EXTEND) {
9109       SDValue N10 = N1.getOperand(0);
9110       if (isContractableFMUL(N10))
9111         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9112                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9113                                        N10.getOperand(0)),
9114                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9115                                        N10.getOperand(1)), N0);
9116     }
9117   }
9118 
9119   // More folding opportunities when target permits.
9120   if (Aggressive) {
9121     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9122     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9123     // are currently only supported on binary nodes.
9124     if (Options.UnsafeFPMath &&
9125         N0.getOpcode() == PreferredFusedOpcode &&
9126         N0.getOperand(2).getOpcode() == ISD::FMUL &&
9127         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9128       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9129                          N0.getOperand(0), N0.getOperand(1),
9130                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9131                                      N0.getOperand(2).getOperand(0),
9132                                      N0.getOperand(2).getOperand(1),
9133                                      N1));
9134     }
9135 
9136     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9137     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9138     // are currently only supported on binary nodes.
9139     if (Options.UnsafeFPMath &&
9140         N1->getOpcode() == PreferredFusedOpcode &&
9141         N1.getOperand(2).getOpcode() == ISD::FMUL &&
9142         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9143       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9144                          N1.getOperand(0), N1.getOperand(1),
9145                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9146                                      N1.getOperand(2).getOperand(0),
9147                                      N1.getOperand(2).getOperand(1),
9148                                      N0));
9149     }
9150 
9151     if (LookThroughFPExt) {
9152       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9153       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
9154       auto FoldFAddFMAFPExtFMul = [&] (
9155           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9156         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9157                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9158                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9159                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9160                                        Z));
9161       };
9162       if (N0.getOpcode() == PreferredFusedOpcode) {
9163         SDValue N02 = N0.getOperand(2);
9164         if (N02.getOpcode() == ISD::FP_EXTEND) {
9165           SDValue N020 = N02.getOperand(0);
9166           if (isContractableFMUL(N020))
9167             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9168                                         N020.getOperand(0), N020.getOperand(1),
9169                                         N1);
9170         }
9171       }
9172 
9173       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9174       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9175       // FIXME: This turns two single-precision and one double-precision
9176       // operation into two double-precision operations, which might not be
9177       // interesting for all targets, especially GPUs.
9178       auto FoldFAddFPExtFMAFMul = [&] (
9179           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9180         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9181                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9182                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9183                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9184                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9185                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9186                                        Z));
9187       };
9188       if (N0.getOpcode() == ISD::FP_EXTEND) {
9189         SDValue N00 = N0.getOperand(0);
9190         if (N00.getOpcode() == PreferredFusedOpcode) {
9191           SDValue N002 = N00.getOperand(2);
9192           if (isContractableFMUL(N002))
9193             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9194                                         N002.getOperand(0), N002.getOperand(1),
9195                                         N1);
9196         }
9197       }
9198 
9199       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9200       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9201       if (N1.getOpcode() == PreferredFusedOpcode) {
9202         SDValue N12 = N1.getOperand(2);
9203         if (N12.getOpcode() == ISD::FP_EXTEND) {
9204           SDValue N120 = N12.getOperand(0);
9205           if (isContractableFMUL(N120))
9206             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9207                                         N120.getOperand(0), N120.getOperand(1),
9208                                         N0);
9209         }
9210       }
9211 
9212       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9213       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9214       // FIXME: This turns two single-precision and one double-precision
9215       // operation into two double-precision operations, which might not be
9216       // interesting for all targets, especially GPUs.
9217       if (N1.getOpcode() == ISD::FP_EXTEND) {
9218         SDValue N10 = N1.getOperand(0);
9219         if (N10.getOpcode() == PreferredFusedOpcode) {
9220           SDValue N102 = N10.getOperand(2);
9221           if (isContractableFMUL(N102))
9222             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9223                                         N102.getOperand(0), N102.getOperand(1),
9224                                         N0);
9225         }
9226       }
9227     }
9228   }
9229 
9230   return SDValue();
9231 }
9232 
9233 /// Try to perform FMA combining on a given FSUB node.
9234 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9235   SDValue N0 = N->getOperand(0);
9236   SDValue N1 = N->getOperand(1);
9237   EVT VT = N->getValueType(0);
9238   SDLoc SL(N);
9239 
9240   const TargetOptions &Options = DAG.getTarget().Options;
9241   // Floating-point multiply-add with intermediate rounding.
9242   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9243 
9244   // Floating-point multiply-add without intermediate rounding.
9245   bool HasFMA =
9246       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9247       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9248 
9249   // No valid opcode, do not combine.
9250   if (!HasFMAD && !HasFMA)
9251     return SDValue();
9252 
9253   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9254                               Options.UnsafeFPMath || HasFMAD);
9255   // If the subtraction is not contractable, do not combine.
9256   if (!AllowFusionGlobally && !isContractable(N))
9257     return SDValue();
9258 
9259   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9260   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9261     return SDValue();
9262 
9263   // Always prefer FMAD to FMA for precision.
9264   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9265   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9266   bool LookThroughFPExt = TLI.isFPExtFree(VT);
9267 
9268   // Is the node an FMUL and contractable either due to global flags or
9269   // SDNodeFlags.
9270   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9271     if (N.getOpcode() != ISD::FMUL)
9272       return false;
9273     return AllowFusionGlobally || isContractable(N.getNode());
9274   };
9275 
9276   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9277   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9278     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9279                        N0.getOperand(0), N0.getOperand(1),
9280                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9281   }
9282 
9283   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9284   // Note: Commutes FSUB operands.
9285   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9286     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9287                        DAG.getNode(ISD::FNEG, SL, VT,
9288                                    N1.getOperand(0)),
9289                        N1.getOperand(1), N0);
9290 
9291   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9292   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9293       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9294     SDValue N00 = N0.getOperand(0).getOperand(0);
9295     SDValue N01 = N0.getOperand(0).getOperand(1);
9296     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9297                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9298                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9299   }
9300 
9301   // Look through FP_EXTEND nodes to do more combining.
9302   if (LookThroughFPExt) {
9303     // fold (fsub (fpext (fmul x, y)), z)
9304     //   -> (fma (fpext x), (fpext y), (fneg z))
9305     if (N0.getOpcode() == ISD::FP_EXTEND) {
9306       SDValue N00 = N0.getOperand(0);
9307       if (isContractableFMUL(N00))
9308         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9309                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9310                                        N00.getOperand(0)),
9311                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9312                                        N00.getOperand(1)),
9313                            DAG.getNode(ISD::FNEG, SL, VT, N1));
9314     }
9315 
9316     // fold (fsub x, (fpext (fmul y, z)))
9317     //   -> (fma (fneg (fpext y)), (fpext z), x)
9318     // Note: Commutes FSUB operands.
9319     if (N1.getOpcode() == ISD::FP_EXTEND) {
9320       SDValue N10 = N1.getOperand(0);
9321       if (isContractableFMUL(N10))
9322         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9323                            DAG.getNode(ISD::FNEG, SL, VT,
9324                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9325                                                    N10.getOperand(0))),
9326                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9327                                        N10.getOperand(1)),
9328                            N0);
9329     }
9330 
9331     // fold (fsub (fpext (fneg (fmul, x, y))), z)
9332     //   -> (fneg (fma (fpext x), (fpext y), z))
9333     // Note: This could be removed with appropriate canonicalization of the
9334     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9335     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9336     // from implementing the canonicalization in visitFSUB.
9337     if (N0.getOpcode() == ISD::FP_EXTEND) {
9338       SDValue N00 = N0.getOperand(0);
9339       if (N00.getOpcode() == ISD::FNEG) {
9340         SDValue N000 = N00.getOperand(0);
9341         if (isContractableFMUL(N000)) {
9342           return DAG.getNode(ISD::FNEG, SL, VT,
9343                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9344                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9345                                                      N000.getOperand(0)),
9346                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9347                                                      N000.getOperand(1)),
9348                                          N1));
9349         }
9350       }
9351     }
9352 
9353     // fold (fsub (fneg (fpext (fmul, x, y))), z)
9354     //   -> (fneg (fma (fpext x)), (fpext y), z)
9355     // Note: This could be removed with appropriate canonicalization of the
9356     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9357     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9358     // from implementing the canonicalization in visitFSUB.
9359     if (N0.getOpcode() == ISD::FNEG) {
9360       SDValue N00 = N0.getOperand(0);
9361       if (N00.getOpcode() == ISD::FP_EXTEND) {
9362         SDValue N000 = N00.getOperand(0);
9363         if (isContractableFMUL(N000)) {
9364           return DAG.getNode(ISD::FNEG, SL, VT,
9365                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9366                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9367                                                      N000.getOperand(0)),
9368                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9369                                                      N000.getOperand(1)),
9370                                          N1));
9371         }
9372       }
9373     }
9374 
9375   }
9376 
9377   // More folding opportunities when target permits.
9378   if (Aggressive) {
9379     // fold (fsub (fma x, y, (fmul u, v)), z)
9380     //   -> (fma x, y (fma u, v, (fneg z)))
9381     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9382     // are currently only supported on binary nodes.
9383     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9384         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9385         N0.getOperand(2)->hasOneUse()) {
9386       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9387                          N0.getOperand(0), N0.getOperand(1),
9388                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9389                                      N0.getOperand(2).getOperand(0),
9390                                      N0.getOperand(2).getOperand(1),
9391                                      DAG.getNode(ISD::FNEG, SL, VT,
9392                                                  N1)));
9393     }
9394 
9395     // fold (fsub x, (fma y, z, (fmul u, v)))
9396     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9397     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9398     // are currently only supported on binary nodes.
9399     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9400         isContractableFMUL(N1.getOperand(2))) {
9401       SDValue N20 = N1.getOperand(2).getOperand(0);
9402       SDValue N21 = N1.getOperand(2).getOperand(1);
9403       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9404                          DAG.getNode(ISD::FNEG, SL, VT,
9405                                      N1.getOperand(0)),
9406                          N1.getOperand(1),
9407                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9408                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9409 
9410                                      N21, N0));
9411     }
9412 
9413     if (LookThroughFPExt) {
9414       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9415       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9416       if (N0.getOpcode() == PreferredFusedOpcode) {
9417         SDValue N02 = N0.getOperand(2);
9418         if (N02.getOpcode() == ISD::FP_EXTEND) {
9419           SDValue N020 = N02.getOperand(0);
9420           if (isContractableFMUL(N020))
9421             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9422                                N0.getOperand(0), N0.getOperand(1),
9423                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9424                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9425                                                        N020.getOperand(0)),
9426                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9427                                                        N020.getOperand(1)),
9428                                            DAG.getNode(ISD::FNEG, SL, VT,
9429                                                        N1)));
9430         }
9431       }
9432 
9433       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9434       //   -> (fma (fpext x), (fpext y),
9435       //           (fma (fpext u), (fpext v), (fneg z)))
9436       // FIXME: This turns two single-precision and one double-precision
9437       // operation into two double-precision operations, which might not be
9438       // interesting for all targets, especially GPUs.
9439       if (N0.getOpcode() == ISD::FP_EXTEND) {
9440         SDValue N00 = N0.getOperand(0);
9441         if (N00.getOpcode() == PreferredFusedOpcode) {
9442           SDValue N002 = N00.getOperand(2);
9443           if (isContractableFMUL(N002))
9444             return DAG.getNode(PreferredFusedOpcode, SL, VT,
9445                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9446                                            N00.getOperand(0)),
9447                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
9448                                            N00.getOperand(1)),
9449                                DAG.getNode(PreferredFusedOpcode, SL, VT,
9450                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9451                                                        N002.getOperand(0)),
9452                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
9453                                                        N002.getOperand(1)),
9454                                            DAG.getNode(ISD::FNEG, SL, VT,
9455                                                        N1)));
9456         }
9457       }
9458 
9459       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9460       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9461       if (N1.getOpcode() == PreferredFusedOpcode &&
9462         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9463         SDValue N120 = N1.getOperand(2).getOperand(0);
9464         if (isContractableFMUL(N120)) {
9465           SDValue N1200 = N120.getOperand(0);
9466           SDValue N1201 = N120.getOperand(1);
9467           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9468                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9469                              N1.getOperand(1),
9470                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9471                                          DAG.getNode(ISD::FNEG, SL, VT,
9472                                              DAG.getNode(ISD::FP_EXTEND, SL,
9473                                                          VT, N1200)),
9474                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9475                                                      N1201),
9476                                          N0));
9477         }
9478       }
9479 
9480       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9481       //   -> (fma (fneg (fpext y)), (fpext z),
9482       //           (fma (fneg (fpext u)), (fpext v), x))
9483       // FIXME: This turns two single-precision and one double-precision
9484       // operation into two double-precision operations, which might not be
9485       // interesting for all targets, especially GPUs.
9486       if (N1.getOpcode() == ISD::FP_EXTEND &&
9487         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9488         SDValue N100 = N1.getOperand(0).getOperand(0);
9489         SDValue N101 = N1.getOperand(0).getOperand(1);
9490         SDValue N102 = N1.getOperand(0).getOperand(2);
9491         if (isContractableFMUL(N102)) {
9492           SDValue N1020 = N102.getOperand(0);
9493           SDValue N1021 = N102.getOperand(1);
9494           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9495                              DAG.getNode(ISD::FNEG, SL, VT,
9496                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9497                                                      N100)),
9498                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9499                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9500                                          DAG.getNode(ISD::FNEG, SL, VT,
9501                                              DAG.getNode(ISD::FP_EXTEND, SL,
9502                                                          VT, N1020)),
9503                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9504                                                      N1021),
9505                                          N0));
9506         }
9507       }
9508     }
9509   }
9510 
9511   return SDValue();
9512 }
9513 
9514 /// Try to perform FMA combining on a given FMUL node based on the distributive
9515 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9516 /// subtraction instead of addition).
9517 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9518   SDValue N0 = N->getOperand(0);
9519   SDValue N1 = N->getOperand(1);
9520   EVT VT = N->getValueType(0);
9521   SDLoc SL(N);
9522 
9523   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9524 
9525   const TargetOptions &Options = DAG.getTarget().Options;
9526 
9527   // The transforms below are incorrect when x == 0 and y == inf, because the
9528   // intermediate multiplication produces a nan.
9529   if (!Options.NoInfsFPMath)
9530     return SDValue();
9531 
9532   // Floating-point multiply-add without intermediate rounding.
9533   bool HasFMA =
9534       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9535       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9536       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9537 
9538   // Floating-point multiply-add with intermediate rounding. This can result
9539   // in a less precise result due to the changed rounding order.
9540   bool HasFMAD = Options.UnsafeFPMath &&
9541                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9542 
9543   // No valid opcode, do not combine.
9544   if (!HasFMAD && !HasFMA)
9545     return SDValue();
9546 
9547   // Always prefer FMAD to FMA for precision.
9548   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9549   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9550 
9551   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9552   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9553   auto FuseFADD = [&](SDValue X, SDValue Y) {
9554     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9555       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9556       if (XC1 && XC1->isExactlyValue(+1.0))
9557         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9558       if (XC1 && XC1->isExactlyValue(-1.0))
9559         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9560                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9561     }
9562     return SDValue();
9563   };
9564 
9565   if (SDValue FMA = FuseFADD(N0, N1))
9566     return FMA;
9567   if (SDValue FMA = FuseFADD(N1, N0))
9568     return FMA;
9569 
9570   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9571   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9572   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9573   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9574   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9575     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9576       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9577       if (XC0 && XC0->isExactlyValue(+1.0))
9578         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9579                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9580                            Y);
9581       if (XC0 && XC0->isExactlyValue(-1.0))
9582         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9583                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9584                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9585 
9586       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9587       if (XC1 && XC1->isExactlyValue(+1.0))
9588         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9589                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9590       if (XC1 && XC1->isExactlyValue(-1.0))
9591         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9592     }
9593     return SDValue();
9594   };
9595 
9596   if (SDValue FMA = FuseFSUB(N0, N1))
9597     return FMA;
9598   if (SDValue FMA = FuseFSUB(N1, N0))
9599     return FMA;
9600 
9601   return SDValue();
9602 }
9603 
9604 static bool isFMulNegTwo(SDValue &N) {
9605   if (N.getOpcode() != ISD::FMUL)
9606     return false;
9607   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9608     return CFP->isExactlyValue(-2.0);
9609   return false;
9610 }
9611 
9612 SDValue DAGCombiner::visitFADD(SDNode *N) {
9613   SDValue N0 = N->getOperand(0);
9614   SDValue N1 = N->getOperand(1);
9615   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9616   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9617   EVT VT = N->getValueType(0);
9618   SDLoc DL(N);
9619   const TargetOptions &Options = DAG.getTarget().Options;
9620   const SDNodeFlags Flags = N->getFlags();
9621 
9622   // fold vector ops
9623   if (VT.isVector())
9624     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9625       return FoldedVOp;
9626 
9627   // fold (fadd c1, c2) -> c1 + c2
9628   if (N0CFP && N1CFP)
9629     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9630 
9631   // canonicalize constant to RHS
9632   if (N0CFP && !N1CFP)
9633     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9634 
9635   if (SDValue NewSel = foldBinOpIntoSelect(N))
9636     return NewSel;
9637 
9638   // fold (fadd A, (fneg B)) -> (fsub A, B)
9639   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9640       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9641     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9642                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9643 
9644   // fold (fadd (fneg A), B) -> (fsub B, A)
9645   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9646       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9647     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9648                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9649 
9650   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9651   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9652   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9653       (isFMulNegTwo(N1) && N1.hasOneUse())) {
9654     bool N1IsFMul = isFMulNegTwo(N1);
9655     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9656     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9657     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9658   }
9659 
9660   // FIXME: Auto-upgrade the target/function-level option.
9661   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9662     // fold (fadd A, 0) -> A
9663     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9664       if (N1C->isZero())
9665         return N0;
9666   }
9667 
9668   // If 'unsafe math' is enabled, fold lots of things.
9669   if (Options.UnsafeFPMath) {
9670     // No FP constant should be created after legalization as Instruction
9671     // Selection pass has a hard time dealing with FP constants.
9672     bool AllowNewConst = (Level < AfterLegalizeDAG);
9673 
9674     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9675     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9676         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9677       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9678                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9679                                      Flags),
9680                          Flags);
9681 
9682     // If allowed, fold (fadd (fneg x), x) -> 0.0
9683     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9684       return DAG.getConstantFP(0.0, DL, VT);
9685 
9686     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9687     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9688       return DAG.getConstantFP(0.0, DL, VT);
9689 
9690     // We can fold chains of FADD's of the same value into multiplications.
9691     // This transform is not safe in general because we are reducing the number
9692     // of rounding steps.
9693     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9694       if (N0.getOpcode() == ISD::FMUL) {
9695         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9696         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9697 
9698         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9699         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9700           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9701                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9702           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9703         }
9704 
9705         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9706         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9707             N1.getOperand(0) == N1.getOperand(1) &&
9708             N0.getOperand(0) == N1.getOperand(0)) {
9709           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9710                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9711           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9712         }
9713       }
9714 
9715       if (N1.getOpcode() == ISD::FMUL) {
9716         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9717         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9718 
9719         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9720         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9721           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9722                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9723           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9724         }
9725 
9726         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9727         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9728             N0.getOperand(0) == N0.getOperand(1) &&
9729             N1.getOperand(0) == N0.getOperand(0)) {
9730           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9731                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9732           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9733         }
9734       }
9735 
9736       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9737         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9738         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9739         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9740             (N0.getOperand(0) == N1)) {
9741           return DAG.getNode(ISD::FMUL, DL, VT,
9742                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9743         }
9744       }
9745 
9746       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9747         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9748         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9749         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9750             N1.getOperand(0) == N0) {
9751           return DAG.getNode(ISD::FMUL, DL, VT,
9752                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9753         }
9754       }
9755 
9756       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9757       if (AllowNewConst &&
9758           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9759           N0.getOperand(0) == N0.getOperand(1) &&
9760           N1.getOperand(0) == N1.getOperand(1) &&
9761           N0.getOperand(0) == N1.getOperand(0)) {
9762         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9763                            DAG.getConstantFP(4.0, DL, VT), Flags);
9764       }
9765     }
9766   } // enable-unsafe-fp-math
9767 
9768   // FADD -> FMA combines:
9769   if (SDValue Fused = visitFADDForFMACombine(N)) {
9770     AddToWorklist(Fused.getNode());
9771     return Fused;
9772   }
9773   return SDValue();
9774 }
9775 
9776 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9777   SDValue N0 = N->getOperand(0);
9778   SDValue N1 = N->getOperand(1);
9779   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9780   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9781   EVT VT = N->getValueType(0);
9782   SDLoc DL(N);
9783   const TargetOptions &Options = DAG.getTarget().Options;
9784   const SDNodeFlags Flags = N->getFlags();
9785 
9786   // fold vector ops
9787   if (VT.isVector())
9788     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9789       return FoldedVOp;
9790 
9791   // fold (fsub c1, c2) -> c1-c2
9792   if (N0CFP && N1CFP)
9793     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9794 
9795   if (SDValue NewSel = foldBinOpIntoSelect(N))
9796     return NewSel;
9797 
9798   // fold (fsub A, (fneg B)) -> (fadd A, B)
9799   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9800     return DAG.getNode(ISD::FADD, DL, VT, N0,
9801                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9802 
9803   // FIXME: Auto-upgrade the target/function-level option.
9804   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
9805     // (fsub 0, B) -> -B
9806     if (N0CFP && N0CFP->isZero()) {
9807       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9808         return GetNegatedExpression(N1, DAG, LegalOperations);
9809       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9810         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9811     }
9812   }
9813 
9814   // If 'unsafe math' is enabled, fold lots of things.
9815   if (Options.UnsafeFPMath) {
9816     // (fsub A, 0) -> A
9817     if (N1CFP && N1CFP->isZero())
9818       return N0;
9819 
9820     // (fsub x, x) -> 0.0
9821     if (N0 == N1)
9822       return DAG.getConstantFP(0.0f, DL, VT);
9823 
9824     // (fsub x, (fadd x, y)) -> (fneg y)
9825     // (fsub x, (fadd y, x)) -> (fneg y)
9826     if (N1.getOpcode() == ISD::FADD) {
9827       SDValue N10 = N1->getOperand(0);
9828       SDValue N11 = N1->getOperand(1);
9829 
9830       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9831         return GetNegatedExpression(N11, DAG, LegalOperations);
9832 
9833       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9834         return GetNegatedExpression(N10, DAG, LegalOperations);
9835     }
9836   }
9837 
9838   // FSUB -> FMA combines:
9839   if (SDValue Fused = visitFSUBForFMACombine(N)) {
9840     AddToWorklist(Fused.getNode());
9841     return Fused;
9842   }
9843 
9844   return SDValue();
9845 }
9846 
9847 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9848   SDValue N0 = N->getOperand(0);
9849   SDValue N1 = N->getOperand(1);
9850   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9851   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9852   EVT VT = N->getValueType(0);
9853   SDLoc DL(N);
9854   const TargetOptions &Options = DAG.getTarget().Options;
9855   const SDNodeFlags Flags = N->getFlags();
9856 
9857   // fold vector ops
9858   if (VT.isVector()) {
9859     // This just handles C1 * C2 for vectors. Other vector folds are below.
9860     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9861       return FoldedVOp;
9862   }
9863 
9864   // fold (fmul c1, c2) -> c1*c2
9865   if (N0CFP && N1CFP)
9866     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9867 
9868   // canonicalize constant to RHS
9869   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9870      !isConstantFPBuildVectorOrConstantFP(N1))
9871     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9872 
9873   // fold (fmul A, 1.0) -> A
9874   if (N1CFP && N1CFP->isExactlyValue(1.0))
9875     return N0;
9876 
9877   if (SDValue NewSel = foldBinOpIntoSelect(N))
9878     return NewSel;
9879 
9880   if (Options.UnsafeFPMath) {
9881     // fold (fmul A, 0) -> 0
9882     if (N1CFP && N1CFP->isZero())
9883       return N1;
9884 
9885     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9886     if (N0.getOpcode() == ISD::FMUL) {
9887       // Fold scalars or any vector constants (not just splats).
9888       // This fold is done in general by InstCombine, but extra fmul insts
9889       // may have been generated during lowering.
9890       SDValue N00 = N0.getOperand(0);
9891       SDValue N01 = N0.getOperand(1);
9892       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9893       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9894       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9895 
9896       // Check 1: Make sure that the first operand of the inner multiply is NOT
9897       // a constant. Otherwise, we may induce infinite looping.
9898       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9899         // Check 2: Make sure that the second operand of the inner multiply and
9900         // the second operand of the outer multiply are constants.
9901         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9902             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9903           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9904           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9905         }
9906       }
9907     }
9908 
9909     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9910     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9911     // during an early run of DAGCombiner can prevent folding with fmuls
9912     // inserted during lowering.
9913     if (N0.getOpcode() == ISD::FADD &&
9914         (N0.getOperand(0) == N0.getOperand(1)) &&
9915         N0.hasOneUse()) {
9916       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9917       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9918       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9919     }
9920   }
9921 
9922   // fold (fmul X, 2.0) -> (fadd X, X)
9923   if (N1CFP && N1CFP->isExactlyValue(+2.0))
9924     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9925 
9926   // fold (fmul X, -1.0) -> (fneg X)
9927   if (N1CFP && N1CFP->isExactlyValue(-1.0))
9928     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9929       return DAG.getNode(ISD::FNEG, DL, VT, N0);
9930 
9931   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9932   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9933     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9934       // Both can be negated for free, check to see if at least one is cheaper
9935       // negated.
9936       if (LHSNeg == 2 || RHSNeg == 2)
9937         return DAG.getNode(ISD::FMUL, DL, VT,
9938                            GetNegatedExpression(N0, DAG, LegalOperations),
9939                            GetNegatedExpression(N1, DAG, LegalOperations),
9940                            Flags);
9941     }
9942   }
9943 
9944   // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
9945   // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
9946   if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
9947       (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
9948       TLI.isOperationLegal(ISD::FABS, VT)) {
9949     SDValue Select = N0, X = N1;
9950     if (Select.getOpcode() != ISD::SELECT)
9951       std::swap(Select, X);
9952 
9953     SDValue Cond = Select.getOperand(0);
9954     auto TrueOpnd  = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
9955     auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
9956 
9957     if (TrueOpnd && FalseOpnd &&
9958         Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
9959         isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
9960         cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
9961       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9962       switch (CC) {
9963       default: break;
9964       case ISD::SETOLT:
9965       case ISD::SETULT:
9966       case ISD::SETOLE:
9967       case ISD::SETULE:
9968       case ISD::SETLT:
9969       case ISD::SETLE:
9970         std::swap(TrueOpnd, FalseOpnd);
9971         // Fall through
9972       case ISD::SETOGT:
9973       case ISD::SETUGT:
9974       case ISD::SETOGE:
9975       case ISD::SETUGE:
9976       case ISD::SETGT:
9977       case ISD::SETGE:
9978         if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
9979             TLI.isOperationLegal(ISD::FNEG, VT))
9980           return DAG.getNode(ISD::FNEG, DL, VT,
9981                    DAG.getNode(ISD::FABS, DL, VT, X));
9982         if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
9983           return DAG.getNode(ISD::FABS, DL, VT, X);
9984 
9985         break;
9986       }
9987     }
9988   }
9989 
9990   // FMUL -> FMA combines:
9991   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9992     AddToWorklist(Fused.getNode());
9993     return Fused;
9994   }
9995 
9996   return SDValue();
9997 }
9998 
9999 SDValue DAGCombiner::visitFMA(SDNode *N) {
10000   SDValue N0 = N->getOperand(0);
10001   SDValue N1 = N->getOperand(1);
10002   SDValue N2 = N->getOperand(2);
10003   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10004   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10005   EVT VT = N->getValueType(0);
10006   SDLoc DL(N);
10007   const TargetOptions &Options = DAG.getTarget().Options;
10008 
10009   // Constant fold FMA.
10010   if (isa<ConstantFPSDNode>(N0) &&
10011       isa<ConstantFPSDNode>(N1) &&
10012       isa<ConstantFPSDNode>(N2)) {
10013     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
10014   }
10015 
10016   if (Options.UnsafeFPMath) {
10017     if (N0CFP && N0CFP->isZero())
10018       return N2;
10019     if (N1CFP && N1CFP->isZero())
10020       return N2;
10021   }
10022   // TODO: The FMA node should have flags that propagate to these nodes.
10023   if (N0CFP && N0CFP->isExactlyValue(1.0))
10024     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
10025   if (N1CFP && N1CFP->isExactlyValue(1.0))
10026     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
10027 
10028   // Canonicalize (fma c, x, y) -> (fma x, c, y)
10029   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10030      !isConstantFPBuildVectorOrConstantFP(N1))
10031     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
10032 
10033   // TODO: FMA nodes should have flags that propagate to the created nodes.
10034   // For now, create a Flags object for use with all unsafe math transforms.
10035   SDNodeFlags Flags;
10036   Flags.setUnsafeAlgebra(true);
10037 
10038   if (Options.UnsafeFPMath) {
10039     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
10040     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
10041         isConstantFPBuildVectorOrConstantFP(N1) &&
10042         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
10043       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10044                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
10045                                      Flags), Flags);
10046     }
10047 
10048     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
10049     if (N0.getOpcode() == ISD::FMUL &&
10050         isConstantFPBuildVectorOrConstantFP(N1) &&
10051         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
10052       return DAG.getNode(ISD::FMA, DL, VT,
10053                          N0.getOperand(0),
10054                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
10055                                      Flags),
10056                          N2);
10057     }
10058   }
10059 
10060   // (fma x, 1, y) -> (fadd x, y)
10061   // (fma x, -1, y) -> (fadd (fneg x), y)
10062   if (N1CFP) {
10063     if (N1CFP->isExactlyValue(1.0))
10064       // TODO: The FMA node should have flags that propagate to this node.
10065       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
10066 
10067     if (N1CFP->isExactlyValue(-1.0) &&
10068         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
10069       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
10070       AddToWorklist(RHSNeg.getNode());
10071       // TODO: The FMA node should have flags that propagate to this node.
10072       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
10073     }
10074   }
10075 
10076   if (Options.UnsafeFPMath) {
10077     // (fma x, c, x) -> (fmul x, (c+1))
10078     if (N1CFP && N0 == N2) {
10079       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10080                          DAG.getNode(ISD::FADD, DL, VT, N1,
10081                                      DAG.getConstantFP(1.0, DL, VT), Flags),
10082                          Flags);
10083     }
10084 
10085     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
10086     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
10087       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10088                          DAG.getNode(ISD::FADD, DL, VT, N1,
10089                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
10090                          Flags);
10091     }
10092   }
10093 
10094   return SDValue();
10095 }
10096 
10097 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10098 // reciprocal.
10099 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
10100 // Notice that this is not always beneficial. One reason is different targets
10101 // may have different costs for FDIV and FMUL, so sometimes the cost of two
10102 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
10103 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
10104 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
10105   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
10106   const SDNodeFlags Flags = N->getFlags();
10107   if (!UnsafeMath && !Flags.hasAllowReciprocal())
10108     return SDValue();
10109 
10110   // Skip if current node is a reciprocal.
10111   SDValue N0 = N->getOperand(0);
10112   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10113   if (N0CFP && N0CFP->isExactlyValue(1.0))
10114     return SDValue();
10115 
10116   // Exit early if the target does not want this transform or if there can't
10117   // possibly be enough uses of the divisor to make the transform worthwhile.
10118   SDValue N1 = N->getOperand(1);
10119   unsigned MinUses = TLI.combineRepeatedFPDivisors();
10120   if (!MinUses || N1->use_size() < MinUses)
10121     return SDValue();
10122 
10123   // Find all FDIV users of the same divisor.
10124   // Use a set because duplicates may be present in the user list.
10125   SetVector<SDNode *> Users;
10126   for (auto *U : N1->uses()) {
10127     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
10128       // This division is eligible for optimization only if global unsafe math
10129       // is enabled or if this division allows reciprocal formation.
10130       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
10131         Users.insert(U);
10132     }
10133   }
10134 
10135   // Now that we have the actual number of divisor uses, make sure it meets
10136   // the minimum threshold specified by the target.
10137   if (Users.size() < MinUses)
10138     return SDValue();
10139 
10140   EVT VT = N->getValueType(0);
10141   SDLoc DL(N);
10142   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10143   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10144 
10145   // Dividend / Divisor -> Dividend * Reciprocal
10146   for (auto *U : Users) {
10147     SDValue Dividend = U->getOperand(0);
10148     if (Dividend != FPOne) {
10149       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10150                                     Reciprocal, Flags);
10151       CombineTo(U, NewNode);
10152     } else if (U != Reciprocal.getNode()) {
10153       // In the absence of fast-math-flags, this user node is always the
10154       // same node as Reciprocal, but with FMF they may be different nodes.
10155       CombineTo(U, Reciprocal);
10156     }
10157   }
10158   return SDValue(N, 0);  // N was replaced.
10159 }
10160 
10161 SDValue DAGCombiner::visitFDIV(SDNode *N) {
10162   SDValue N0 = N->getOperand(0);
10163   SDValue N1 = N->getOperand(1);
10164   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10165   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10166   EVT VT = N->getValueType(0);
10167   SDLoc DL(N);
10168   const TargetOptions &Options = DAG.getTarget().Options;
10169   SDNodeFlags Flags = N->getFlags();
10170 
10171   // fold vector ops
10172   if (VT.isVector())
10173     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10174       return FoldedVOp;
10175 
10176   // fold (fdiv c1, c2) -> c1/c2
10177   if (N0CFP && N1CFP)
10178     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10179 
10180   if (SDValue NewSel = foldBinOpIntoSelect(N))
10181     return NewSel;
10182 
10183   if (Options.UnsafeFPMath) {
10184     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10185     if (N1CFP) {
10186       // Compute the reciprocal 1.0 / c2.
10187       const APFloat &N1APF = N1CFP->getValueAPF();
10188       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10189       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10190       // Only do the transform if the reciprocal is a legal fp immediate that
10191       // isn't too nasty (eg NaN, denormal, ...).
10192       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10193           (!LegalOperations ||
10194            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10195            // backend)... we should handle this gracefully after Legalize.
10196            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
10197            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
10198            TLI.isFPImmLegal(Recip, VT)))
10199         return DAG.getNode(ISD::FMUL, DL, VT, N0,
10200                            DAG.getConstantFP(Recip, DL, VT), Flags);
10201     }
10202 
10203     // If this FDIV is part of a reciprocal square root, it may be folded
10204     // into a target-specific square root estimate instruction.
10205     if (N1.getOpcode() == ISD::FSQRT) {
10206       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10207         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10208       }
10209     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10210                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10211       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10212                                           Flags)) {
10213         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10214         AddToWorklist(RV.getNode());
10215         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10216       }
10217     } else if (N1.getOpcode() == ISD::FP_ROUND &&
10218                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10219       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10220                                           Flags)) {
10221         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10222         AddToWorklist(RV.getNode());
10223         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10224       }
10225     } else if (N1.getOpcode() == ISD::FMUL) {
10226       // Look through an FMUL. Even though this won't remove the FDIV directly,
10227       // it's still worthwhile to get rid of the FSQRT if possible.
10228       SDValue SqrtOp;
10229       SDValue OtherOp;
10230       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10231         SqrtOp = N1.getOperand(0);
10232         OtherOp = N1.getOperand(1);
10233       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10234         SqrtOp = N1.getOperand(1);
10235         OtherOp = N1.getOperand(0);
10236       }
10237       if (SqrtOp.getNode()) {
10238         // We found a FSQRT, so try to make this fold:
10239         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10240         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10241           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10242           AddToWorklist(RV.getNode());
10243           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10244         }
10245       }
10246     }
10247 
10248     // Fold into a reciprocal estimate and multiply instead of a real divide.
10249     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10250       AddToWorklist(RV.getNode());
10251       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10252     }
10253   }
10254 
10255   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10256   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10257     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10258       // Both can be negated for free, check to see if at least one is cheaper
10259       // negated.
10260       if (LHSNeg == 2 || RHSNeg == 2)
10261         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10262                            GetNegatedExpression(N0, DAG, LegalOperations),
10263                            GetNegatedExpression(N1, DAG, LegalOperations),
10264                            Flags);
10265     }
10266   }
10267 
10268   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10269     return CombineRepeatedDivisors;
10270 
10271   return SDValue();
10272 }
10273 
10274 SDValue DAGCombiner::visitFREM(SDNode *N) {
10275   SDValue N0 = N->getOperand(0);
10276   SDValue N1 = N->getOperand(1);
10277   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10278   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10279   EVT VT = N->getValueType(0);
10280 
10281   // fold (frem c1, c2) -> fmod(c1,c2)
10282   if (N0CFP && N1CFP)
10283     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10284 
10285   if (SDValue NewSel = foldBinOpIntoSelect(N))
10286     return NewSel;
10287 
10288   return SDValue();
10289 }
10290 
10291 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10292   if (!DAG.getTarget().Options.UnsafeFPMath)
10293     return SDValue();
10294 
10295   SDValue N0 = N->getOperand(0);
10296   if (TLI.isFsqrtCheap(N0, DAG))
10297     return SDValue();
10298 
10299   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10300   // For now, create a Flags object for use with all unsafe math transforms.
10301   SDNodeFlags Flags;
10302   Flags.setUnsafeAlgebra(true);
10303   return buildSqrtEstimate(N0, Flags);
10304 }
10305 
10306 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10307 /// copysign(x, fp_round(y)) -> copysign(x, y)
10308 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10309   SDValue N1 = N->getOperand(1);
10310   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10311        N1.getOpcode() == ISD::FP_ROUND)) {
10312     // Do not optimize out type conversion of f128 type yet.
10313     // For some targets like x86_64, configuration is changed to keep one f128
10314     // value in one SSE register, but instruction selection cannot handle
10315     // FCOPYSIGN on SSE registers yet.
10316     EVT N1VT = N1->getValueType(0);
10317     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10318     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10319   }
10320   return false;
10321 }
10322 
10323 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10324   SDValue N0 = N->getOperand(0);
10325   SDValue N1 = N->getOperand(1);
10326   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10327   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10328   EVT VT = N->getValueType(0);
10329 
10330   if (N0CFP && N1CFP) // Constant fold
10331     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10332 
10333   if (N1CFP) {
10334     const APFloat &V = N1CFP->getValueAPF();
10335     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10336     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10337     if (!V.isNegative()) {
10338       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10339         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10340     } else {
10341       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10342         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10343                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10344     }
10345   }
10346 
10347   // copysign(fabs(x), y) -> copysign(x, y)
10348   // copysign(fneg(x), y) -> copysign(x, y)
10349   // copysign(copysign(x,z), y) -> copysign(x, y)
10350   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10351       N0.getOpcode() == ISD::FCOPYSIGN)
10352     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10353 
10354   // copysign(x, abs(y)) -> abs(x)
10355   if (N1.getOpcode() == ISD::FABS)
10356     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10357 
10358   // copysign(x, copysign(y,z)) -> copysign(x, z)
10359   if (N1.getOpcode() == ISD::FCOPYSIGN)
10360     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10361 
10362   // copysign(x, fp_extend(y)) -> copysign(x, y)
10363   // copysign(x, fp_round(y)) -> copysign(x, y)
10364   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10365     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10366 
10367   return SDValue();
10368 }
10369 
10370 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10371   SDValue N0 = N->getOperand(0);
10372   EVT VT = N->getValueType(0);
10373   EVT OpVT = N0.getValueType();
10374 
10375   // fold (sint_to_fp c1) -> c1fp
10376   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10377       // ...but only if the target supports immediate floating-point values
10378       (!LegalOperations ||
10379        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10380     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10381 
10382   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10383   // but UINT_TO_FP is legal on this target, try to convert.
10384   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10385       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10386     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10387     if (DAG.SignBitIsZero(N0))
10388       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10389   }
10390 
10391   // The next optimizations are desirable only if SELECT_CC can be lowered.
10392   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10393     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10394     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10395         !VT.isVector() &&
10396         (!LegalOperations ||
10397          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10398       SDLoc DL(N);
10399       SDValue Ops[] =
10400         { N0.getOperand(0), N0.getOperand(1),
10401           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10402           N0.getOperand(2) };
10403       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10404     }
10405 
10406     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10407     //      (select_cc x, y, 1.0, 0.0,, cc)
10408     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10409         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10410         (!LegalOperations ||
10411          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10412       SDLoc DL(N);
10413       SDValue Ops[] =
10414         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10415           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10416           N0.getOperand(0).getOperand(2) };
10417       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10418     }
10419   }
10420 
10421   return SDValue();
10422 }
10423 
10424 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10425   SDValue N0 = N->getOperand(0);
10426   EVT VT = N->getValueType(0);
10427   EVT OpVT = N0.getValueType();
10428 
10429   // fold (uint_to_fp c1) -> c1fp
10430   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10431       // ...but only if the target supports immediate floating-point values
10432       (!LegalOperations ||
10433        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10434     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10435 
10436   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10437   // but SINT_TO_FP is legal on this target, try to convert.
10438   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10439       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10440     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10441     if (DAG.SignBitIsZero(N0))
10442       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10443   }
10444 
10445   // The next optimizations are desirable only if SELECT_CC can be lowered.
10446   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10447     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10448 
10449     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10450         (!LegalOperations ||
10451          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10452       SDLoc DL(N);
10453       SDValue Ops[] =
10454         { N0.getOperand(0), N0.getOperand(1),
10455           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10456           N0.getOperand(2) };
10457       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10458     }
10459   }
10460 
10461   return SDValue();
10462 }
10463 
10464 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10465 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10466   SDValue N0 = N->getOperand(0);
10467   EVT VT = N->getValueType(0);
10468 
10469   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10470     return SDValue();
10471 
10472   SDValue Src = N0.getOperand(0);
10473   EVT SrcVT = Src.getValueType();
10474   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10475   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10476 
10477   // We can safely assume the conversion won't overflow the output range,
10478   // because (for example) (uint8_t)18293.f is undefined behavior.
10479 
10480   // Since we can assume the conversion won't overflow, our decision as to
10481   // whether the input will fit in the float should depend on the minimum
10482   // of the input range and output range.
10483 
10484   // This means this is also safe for a signed input and unsigned output, since
10485   // a negative input would lead to undefined behavior.
10486   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10487   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10488   unsigned ActualSize = std::min(InputSize, OutputSize);
10489   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10490 
10491   // We can only fold away the float conversion if the input range can be
10492   // represented exactly in the float range.
10493   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10494     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10495       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10496                                                        : ISD::ZERO_EXTEND;
10497       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10498     }
10499     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10500       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10501     return DAG.getBitcast(VT, Src);
10502   }
10503   return SDValue();
10504 }
10505 
10506 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10507   SDValue N0 = N->getOperand(0);
10508   EVT VT = N->getValueType(0);
10509 
10510   // fold (fp_to_sint c1fp) -> c1
10511   if (isConstantFPBuildVectorOrConstantFP(N0))
10512     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10513 
10514   return FoldIntToFPToInt(N, DAG);
10515 }
10516 
10517 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10518   SDValue N0 = N->getOperand(0);
10519   EVT VT = N->getValueType(0);
10520 
10521   // fold (fp_to_uint c1fp) -> c1
10522   if (isConstantFPBuildVectorOrConstantFP(N0))
10523     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10524 
10525   return FoldIntToFPToInt(N, DAG);
10526 }
10527 
10528 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10529   SDValue N0 = N->getOperand(0);
10530   SDValue N1 = N->getOperand(1);
10531   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10532   EVT VT = N->getValueType(0);
10533 
10534   // fold (fp_round c1fp) -> c1fp
10535   if (N0CFP)
10536     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10537 
10538   // fold (fp_round (fp_extend x)) -> x
10539   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10540     return N0.getOperand(0);
10541 
10542   // fold (fp_round (fp_round x)) -> (fp_round x)
10543   if (N0.getOpcode() == ISD::FP_ROUND) {
10544     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10545     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10546 
10547     // Skip this folding if it results in an fp_round from f80 to f16.
10548     //
10549     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10550     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10551     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10552     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10553     // x86.
10554     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10555       return SDValue();
10556 
10557     // If the first fp_round isn't a value preserving truncation, it might
10558     // introduce a tie in the second fp_round, that wouldn't occur in the
10559     // single-step fp_round we want to fold to.
10560     // In other words, double rounding isn't the same as rounding.
10561     // Also, this is a value preserving truncation iff both fp_round's are.
10562     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10563       SDLoc DL(N);
10564       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10565                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10566     }
10567   }
10568 
10569   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10570   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10571     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10572                               N0.getOperand(0), N1);
10573     AddToWorklist(Tmp.getNode());
10574     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10575                        Tmp, N0.getOperand(1));
10576   }
10577 
10578   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10579     return NewVSel;
10580 
10581   return SDValue();
10582 }
10583 
10584 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10585   SDValue N0 = N->getOperand(0);
10586   EVT VT = N->getValueType(0);
10587   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10588   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10589 
10590   // fold (fp_round_inreg c1fp) -> c1fp
10591   if (N0CFP && isTypeLegal(EVT)) {
10592     SDLoc DL(N);
10593     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10594     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10595   }
10596 
10597   return SDValue();
10598 }
10599 
10600 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10601   SDValue N0 = N->getOperand(0);
10602   EVT VT = N->getValueType(0);
10603 
10604   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10605   if (N->hasOneUse() &&
10606       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10607     return SDValue();
10608 
10609   // fold (fp_extend c1fp) -> c1fp
10610   if (isConstantFPBuildVectorOrConstantFP(N0))
10611     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10612 
10613   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10614   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10615       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10616     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10617 
10618   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10619   // value of X.
10620   if (N0.getOpcode() == ISD::FP_ROUND
10621       && N0.getConstantOperandVal(1) == 1) {
10622     SDValue In = N0.getOperand(0);
10623     if (In.getValueType() == VT) return In;
10624     if (VT.bitsLT(In.getValueType()))
10625       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10626                          In, N0.getOperand(1));
10627     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10628   }
10629 
10630   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10631   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10632        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10633     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10634     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10635                                      LN0->getChain(),
10636                                      LN0->getBasePtr(), N0.getValueType(),
10637                                      LN0->getMemOperand());
10638     CombineTo(N, ExtLoad);
10639     CombineTo(N0.getNode(),
10640               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10641                           N0.getValueType(), ExtLoad,
10642                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10643               ExtLoad.getValue(1));
10644     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10645   }
10646 
10647   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10648     return NewVSel;
10649 
10650   return SDValue();
10651 }
10652 
10653 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10654   SDValue N0 = N->getOperand(0);
10655   EVT VT = N->getValueType(0);
10656 
10657   // fold (fceil c1) -> fceil(c1)
10658   if (isConstantFPBuildVectorOrConstantFP(N0))
10659     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10660 
10661   return SDValue();
10662 }
10663 
10664 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10665   SDValue N0 = N->getOperand(0);
10666   EVT VT = N->getValueType(0);
10667 
10668   // fold (ftrunc c1) -> ftrunc(c1)
10669   if (isConstantFPBuildVectorOrConstantFP(N0))
10670     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10671 
10672   return SDValue();
10673 }
10674 
10675 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10676   SDValue N0 = N->getOperand(0);
10677   EVT VT = N->getValueType(0);
10678 
10679   // fold (ffloor c1) -> ffloor(c1)
10680   if (isConstantFPBuildVectorOrConstantFP(N0))
10681     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10682 
10683   return SDValue();
10684 }
10685 
10686 // FIXME: FNEG and FABS have a lot in common; refactor.
10687 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10688   SDValue N0 = N->getOperand(0);
10689   EVT VT = N->getValueType(0);
10690 
10691   // Constant fold FNEG.
10692   if (isConstantFPBuildVectorOrConstantFP(N0))
10693     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10694 
10695   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10696                          &DAG.getTarget().Options))
10697     return GetNegatedExpression(N0, DAG, LegalOperations);
10698 
10699   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10700   // constant pool values.
10701   if (!TLI.isFNegFree(VT) &&
10702       N0.getOpcode() == ISD::BITCAST &&
10703       N0.getNode()->hasOneUse()) {
10704     SDValue Int = N0.getOperand(0);
10705     EVT IntVT = Int.getValueType();
10706     if (IntVT.isInteger() && !IntVT.isVector()) {
10707       APInt SignMask;
10708       if (N0.getValueType().isVector()) {
10709         // For a vector, get a mask such as 0x80... per scalar element
10710         // and splat it.
10711         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10712         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10713       } else {
10714         // For a scalar, just generate 0x80...
10715         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10716       }
10717       SDLoc DL0(N0);
10718       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10719                         DAG.getConstant(SignMask, DL0, IntVT));
10720       AddToWorklist(Int.getNode());
10721       return DAG.getBitcast(VT, Int);
10722     }
10723   }
10724 
10725   // (fneg (fmul c, x)) -> (fmul -c, x)
10726   if (N0.getOpcode() == ISD::FMUL &&
10727       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10728     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10729     if (CFP1) {
10730       APFloat CVal = CFP1->getValueAPF();
10731       CVal.changeSign();
10732       if (Level >= AfterLegalizeDAG &&
10733           (TLI.isFPImmLegal(CVal, VT) ||
10734            TLI.isOperationLegal(ISD::ConstantFP, VT)))
10735         return DAG.getNode(
10736             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10737             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10738             N0->getFlags());
10739     }
10740   }
10741 
10742   return SDValue();
10743 }
10744 
10745 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10746   SDValue N0 = N->getOperand(0);
10747   SDValue N1 = N->getOperand(1);
10748   EVT VT = N->getValueType(0);
10749   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10750   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10751 
10752   if (N0CFP && N1CFP) {
10753     const APFloat &C0 = N0CFP->getValueAPF();
10754     const APFloat &C1 = N1CFP->getValueAPF();
10755     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10756   }
10757 
10758   // Canonicalize to constant on RHS.
10759   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10760      !isConstantFPBuildVectorOrConstantFP(N1))
10761     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10762 
10763   return SDValue();
10764 }
10765 
10766 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10767   SDValue N0 = N->getOperand(0);
10768   SDValue N1 = N->getOperand(1);
10769   EVT VT = N->getValueType(0);
10770   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10771   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10772 
10773   if (N0CFP && N1CFP) {
10774     const APFloat &C0 = N0CFP->getValueAPF();
10775     const APFloat &C1 = N1CFP->getValueAPF();
10776     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10777   }
10778 
10779   // Canonicalize to constant on RHS.
10780   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10781      !isConstantFPBuildVectorOrConstantFP(N1))
10782     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10783 
10784   return SDValue();
10785 }
10786 
10787 SDValue DAGCombiner::visitFABS(SDNode *N) {
10788   SDValue N0 = N->getOperand(0);
10789   EVT VT = N->getValueType(0);
10790 
10791   // fold (fabs c1) -> fabs(c1)
10792   if (isConstantFPBuildVectorOrConstantFP(N0))
10793     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10794 
10795   // fold (fabs (fabs x)) -> (fabs x)
10796   if (N0.getOpcode() == ISD::FABS)
10797     return N->getOperand(0);
10798 
10799   // fold (fabs (fneg x)) -> (fabs x)
10800   // fold (fabs (fcopysign x, y)) -> (fabs x)
10801   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10802     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10803 
10804   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10805   // constant pool values.
10806   if (!TLI.isFAbsFree(VT) &&
10807       N0.getOpcode() == ISD::BITCAST &&
10808       N0.getNode()->hasOneUse()) {
10809     SDValue Int = N0.getOperand(0);
10810     EVT IntVT = Int.getValueType();
10811     if (IntVT.isInteger() && !IntVT.isVector()) {
10812       APInt SignMask;
10813       if (N0.getValueType().isVector()) {
10814         // For a vector, get a mask such as 0x7f... per scalar element
10815         // and splat it.
10816         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10817         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10818       } else {
10819         // For a scalar, just generate 0x7f...
10820         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10821       }
10822       SDLoc DL(N0);
10823       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10824                         DAG.getConstant(SignMask, DL, IntVT));
10825       AddToWorklist(Int.getNode());
10826       return DAG.getBitcast(N->getValueType(0), Int);
10827     }
10828   }
10829 
10830   return SDValue();
10831 }
10832 
10833 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10834   SDValue Chain = N->getOperand(0);
10835   SDValue N1 = N->getOperand(1);
10836   SDValue N2 = N->getOperand(2);
10837 
10838   // If N is a constant we could fold this into a fallthrough or unconditional
10839   // branch. However that doesn't happen very often in normal code, because
10840   // Instcombine/SimplifyCFG should have handled the available opportunities.
10841   // If we did this folding here, it would be necessary to update the
10842   // MachineBasicBlock CFG, which is awkward.
10843 
10844   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10845   // on the target.
10846   if (N1.getOpcode() == ISD::SETCC &&
10847       TLI.isOperationLegalOrCustom(ISD::BR_CC,
10848                                    N1.getOperand(0).getValueType())) {
10849     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10850                        Chain, N1.getOperand(2),
10851                        N1.getOperand(0), N1.getOperand(1), N2);
10852   }
10853 
10854   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10855       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10856        (N1.getOperand(0).hasOneUse() &&
10857         N1.getOperand(0).getOpcode() == ISD::SRL))) {
10858     SDNode *Trunc = nullptr;
10859     if (N1.getOpcode() == ISD::TRUNCATE) {
10860       // Look pass the truncate.
10861       Trunc = N1.getNode();
10862       N1 = N1.getOperand(0);
10863     }
10864 
10865     // Match this pattern so that we can generate simpler code:
10866     //
10867     //   %a = ...
10868     //   %b = and i32 %a, 2
10869     //   %c = srl i32 %b, 1
10870     //   brcond i32 %c ...
10871     //
10872     // into
10873     //
10874     //   %a = ...
10875     //   %b = and i32 %a, 2
10876     //   %c = setcc eq %b, 0
10877     //   brcond %c ...
10878     //
10879     // This applies only when the AND constant value has one bit set and the
10880     // SRL constant is equal to the log2 of the AND constant. The back-end is
10881     // smart enough to convert the result into a TEST/JMP sequence.
10882     SDValue Op0 = N1.getOperand(0);
10883     SDValue Op1 = N1.getOperand(1);
10884 
10885     if (Op0.getOpcode() == ISD::AND &&
10886         Op1.getOpcode() == ISD::Constant) {
10887       SDValue AndOp1 = Op0.getOperand(1);
10888 
10889       if (AndOp1.getOpcode() == ISD::Constant) {
10890         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10891 
10892         if (AndConst.isPowerOf2() &&
10893             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10894           SDLoc DL(N);
10895           SDValue SetCC =
10896             DAG.getSetCC(DL,
10897                          getSetCCResultType(Op0.getValueType()),
10898                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10899                          ISD::SETNE);
10900 
10901           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10902                                           MVT::Other, Chain, SetCC, N2);
10903           // Don't add the new BRCond into the worklist or else SimplifySelectCC
10904           // will convert it back to (X & C1) >> C2.
10905           CombineTo(N, NewBRCond, false);
10906           // Truncate is dead.
10907           if (Trunc)
10908             deleteAndRecombine(Trunc);
10909           // Replace the uses of SRL with SETCC
10910           WorklistRemover DeadNodes(*this);
10911           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10912           deleteAndRecombine(N1.getNode());
10913           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10914         }
10915       }
10916     }
10917 
10918     if (Trunc)
10919       // Restore N1 if the above transformation doesn't match.
10920       N1 = N->getOperand(1);
10921   }
10922 
10923   // Transform br(xor(x, y)) -> br(x != y)
10924   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10925   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10926     SDNode *TheXor = N1.getNode();
10927     SDValue Op0 = TheXor->getOperand(0);
10928     SDValue Op1 = TheXor->getOperand(1);
10929     if (Op0.getOpcode() == Op1.getOpcode()) {
10930       // Avoid missing important xor optimizations.
10931       if (SDValue Tmp = visitXOR(TheXor)) {
10932         if (Tmp.getNode() != TheXor) {
10933           DEBUG(dbgs() << "\nReplacing.8 ";
10934                 TheXor->dump(&DAG);
10935                 dbgs() << "\nWith: ";
10936                 Tmp.getNode()->dump(&DAG);
10937                 dbgs() << '\n');
10938           WorklistRemover DeadNodes(*this);
10939           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10940           deleteAndRecombine(TheXor);
10941           return DAG.getNode(ISD::BRCOND, SDLoc(N),
10942                              MVT::Other, Chain, Tmp, N2);
10943         }
10944 
10945         // visitXOR has changed XOR's operands or replaced the XOR completely,
10946         // bail out.
10947         return SDValue(N, 0);
10948       }
10949     }
10950 
10951     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10952       bool Equal = false;
10953       if (isOneConstant(Op0) && Op0.hasOneUse() &&
10954           Op0.getOpcode() == ISD::XOR) {
10955         TheXor = Op0.getNode();
10956         Equal = true;
10957       }
10958 
10959       EVT SetCCVT = N1.getValueType();
10960       if (LegalTypes)
10961         SetCCVT = getSetCCResultType(SetCCVT);
10962       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10963                                    SetCCVT,
10964                                    Op0, Op1,
10965                                    Equal ? ISD::SETEQ : ISD::SETNE);
10966       // Replace the uses of XOR with SETCC
10967       WorklistRemover DeadNodes(*this);
10968       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10969       deleteAndRecombine(N1.getNode());
10970       return DAG.getNode(ISD::BRCOND, SDLoc(N),
10971                          MVT::Other, Chain, SetCC, N2);
10972     }
10973   }
10974 
10975   return SDValue();
10976 }
10977 
10978 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10979 //
10980 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10981   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10982   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10983 
10984   // If N is a constant we could fold this into a fallthrough or unconditional
10985   // branch. However that doesn't happen very often in normal code, because
10986   // Instcombine/SimplifyCFG should have handled the available opportunities.
10987   // If we did this folding here, it would be necessary to update the
10988   // MachineBasicBlock CFG, which is awkward.
10989 
10990   // Use SimplifySetCC to simplify SETCC's.
10991   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10992                                CondLHS, CondRHS, CC->get(), SDLoc(N),
10993                                false);
10994   if (Simp.getNode()) AddToWorklist(Simp.getNode());
10995 
10996   // fold to a simpler setcc
10997   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10998     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10999                        N->getOperand(0), Simp.getOperand(2),
11000                        Simp.getOperand(0), Simp.getOperand(1),
11001                        N->getOperand(4));
11002 
11003   return SDValue();
11004 }
11005 
11006 /// Return true if 'Use' is a load or a store that uses N as its base pointer
11007 /// and that N may be folded in the load / store addressing mode.
11008 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
11009                                     SelectionDAG &DAG,
11010                                     const TargetLowering &TLI) {
11011   EVT VT;
11012   unsigned AS;
11013 
11014   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
11015     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
11016       return false;
11017     VT = LD->getMemoryVT();
11018     AS = LD->getAddressSpace();
11019   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
11020     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
11021       return false;
11022     VT = ST->getMemoryVT();
11023     AS = ST->getAddressSpace();
11024   } else
11025     return false;
11026 
11027   TargetLowering::AddrMode AM;
11028   if (N->getOpcode() == ISD::ADD) {
11029     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11030     if (Offset)
11031       // [reg +/- imm]
11032       AM.BaseOffs = Offset->getSExtValue();
11033     else
11034       // [reg +/- reg]
11035       AM.Scale = 1;
11036   } else if (N->getOpcode() == ISD::SUB) {
11037     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11038     if (Offset)
11039       // [reg +/- imm]
11040       AM.BaseOffs = -Offset->getSExtValue();
11041     else
11042       // [reg +/- reg]
11043       AM.Scale = 1;
11044   } else
11045     return false;
11046 
11047   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
11048                                    VT.getTypeForEVT(*DAG.getContext()), AS);
11049 }
11050 
11051 /// Try turning a load/store into a pre-indexed load/store when the base
11052 /// pointer is an add or subtract and it has other uses besides the load/store.
11053 /// After the transformation, the new indexed load/store has effectively folded
11054 /// the add/subtract in and all of its other uses are redirected to the
11055 /// new load/store.
11056 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
11057   if (Level < AfterLegalizeDAG)
11058     return false;
11059 
11060   bool isLoad = true;
11061   SDValue Ptr;
11062   EVT VT;
11063   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11064     if (LD->isIndexed())
11065       return false;
11066     VT = LD->getMemoryVT();
11067     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
11068         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
11069       return false;
11070     Ptr = LD->getBasePtr();
11071   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11072     if (ST->isIndexed())
11073       return false;
11074     VT = ST->getMemoryVT();
11075     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
11076         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
11077       return false;
11078     Ptr = ST->getBasePtr();
11079     isLoad = false;
11080   } else {
11081     return false;
11082   }
11083 
11084   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
11085   // out.  There is no reason to make this a preinc/predec.
11086   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
11087       Ptr.getNode()->hasOneUse())
11088     return false;
11089 
11090   // Ask the target to do addressing mode selection.
11091   SDValue BasePtr;
11092   SDValue Offset;
11093   ISD::MemIndexedMode AM = ISD::UNINDEXED;
11094   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
11095     return false;
11096 
11097   // Backends without true r+i pre-indexed forms may need to pass a
11098   // constant base with a variable offset so that constant coercion
11099   // will work with the patterns in canonical form.
11100   bool Swapped = false;
11101   if (isa<ConstantSDNode>(BasePtr)) {
11102     std::swap(BasePtr, Offset);
11103     Swapped = true;
11104   }
11105 
11106   // Don't create a indexed load / store with zero offset.
11107   if (isNullConstant(Offset))
11108     return false;
11109 
11110   // Try turning it into a pre-indexed load / store except when:
11111   // 1) The new base ptr is a frame index.
11112   // 2) If N is a store and the new base ptr is either the same as or is a
11113   //    predecessor of the value being stored.
11114   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
11115   //    that would create a cycle.
11116   // 4) All uses are load / store ops that use it as old base ptr.
11117 
11118   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
11119   // (plus the implicit offset) to a register to preinc anyway.
11120   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11121     return false;
11122 
11123   // Check #2.
11124   if (!isLoad) {
11125     SDValue Val = cast<StoreSDNode>(N)->getValue();
11126     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
11127       return false;
11128   }
11129 
11130   // Caches for hasPredecessorHelper.
11131   SmallPtrSet<const SDNode *, 32> Visited;
11132   SmallVector<const SDNode *, 16> Worklist;
11133   Worklist.push_back(N);
11134 
11135   // If the offset is a constant, there may be other adds of constants that
11136   // can be folded with this one. We should do this to avoid having to keep
11137   // a copy of the original base pointer.
11138   SmallVector<SDNode *, 16> OtherUses;
11139   if (isa<ConstantSDNode>(Offset))
11140     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11141                               UE = BasePtr.getNode()->use_end();
11142          UI != UE; ++UI) {
11143       SDUse &Use = UI.getUse();
11144       // Skip the use that is Ptr and uses of other results from BasePtr's
11145       // node (important for nodes that return multiple results).
11146       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11147         continue;
11148 
11149       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11150         continue;
11151 
11152       if (Use.getUser()->getOpcode() != ISD::ADD &&
11153           Use.getUser()->getOpcode() != ISD::SUB) {
11154         OtherUses.clear();
11155         break;
11156       }
11157 
11158       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11159       if (!isa<ConstantSDNode>(Op1)) {
11160         OtherUses.clear();
11161         break;
11162       }
11163 
11164       // FIXME: In some cases, we can be smarter about this.
11165       if (Op1.getValueType() != Offset.getValueType()) {
11166         OtherUses.clear();
11167         break;
11168       }
11169 
11170       OtherUses.push_back(Use.getUser());
11171     }
11172 
11173   if (Swapped)
11174     std::swap(BasePtr, Offset);
11175 
11176   // Now check for #3 and #4.
11177   bool RealUse = false;
11178 
11179   for (SDNode *Use : Ptr.getNode()->uses()) {
11180     if (Use == N)
11181       continue;
11182     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11183       return false;
11184 
11185     // If Ptr may be folded in addressing mode of other use, then it's
11186     // not profitable to do this transformation.
11187     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11188       RealUse = true;
11189   }
11190 
11191   if (!RealUse)
11192     return false;
11193 
11194   SDValue Result;
11195   if (isLoad)
11196     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11197                                 BasePtr, Offset, AM);
11198   else
11199     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11200                                  BasePtr, Offset, AM);
11201   ++PreIndexedNodes;
11202   ++NodesCombined;
11203   DEBUG(dbgs() << "\nReplacing.4 ";
11204         N->dump(&DAG);
11205         dbgs() << "\nWith: ";
11206         Result.getNode()->dump(&DAG);
11207         dbgs() << '\n');
11208   WorklistRemover DeadNodes(*this);
11209   if (isLoad) {
11210     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11211     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11212   } else {
11213     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11214   }
11215 
11216   // Finally, since the node is now dead, remove it from the graph.
11217   deleteAndRecombine(N);
11218 
11219   if (Swapped)
11220     std::swap(BasePtr, Offset);
11221 
11222   // Replace other uses of BasePtr that can be updated to use Ptr
11223   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11224     unsigned OffsetIdx = 1;
11225     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11226       OffsetIdx = 0;
11227     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11228            BasePtr.getNode() && "Expected BasePtr operand");
11229 
11230     // We need to replace ptr0 in the following expression:
11231     //   x0 * offset0 + y0 * ptr0 = t0
11232     // knowing that
11233     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11234     //
11235     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11236     // indexed load/store and the expression that needs to be re-written.
11237     //
11238     // Therefore, we have:
11239     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11240 
11241     ConstantSDNode *CN =
11242       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11243     int X0, X1, Y0, Y1;
11244     const APInt &Offset0 = CN->getAPIntValue();
11245     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11246 
11247     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11248     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11249     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11250     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11251 
11252     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11253 
11254     APInt CNV = Offset0;
11255     if (X0 < 0) CNV = -CNV;
11256     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11257     else CNV = CNV - Offset1;
11258 
11259     SDLoc DL(OtherUses[i]);
11260 
11261     // We can now generate the new expression.
11262     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11263     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11264 
11265     SDValue NewUse = DAG.getNode(Opcode,
11266                                  DL,
11267                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11268     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11269     deleteAndRecombine(OtherUses[i]);
11270   }
11271 
11272   // Replace the uses of Ptr with uses of the updated base value.
11273   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11274   deleteAndRecombine(Ptr.getNode());
11275 
11276   return true;
11277 }
11278 
11279 /// Try to combine a load/store with a add/sub of the base pointer node into a
11280 /// post-indexed load/store. The transformation folded the add/subtract into the
11281 /// new indexed load/store effectively and all of its uses are redirected to the
11282 /// new load/store.
11283 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11284   if (Level < AfterLegalizeDAG)
11285     return false;
11286 
11287   bool isLoad = true;
11288   SDValue Ptr;
11289   EVT VT;
11290   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11291     if (LD->isIndexed())
11292       return false;
11293     VT = LD->getMemoryVT();
11294     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11295         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11296       return false;
11297     Ptr = LD->getBasePtr();
11298   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11299     if (ST->isIndexed())
11300       return false;
11301     VT = ST->getMemoryVT();
11302     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11303         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11304       return false;
11305     Ptr = ST->getBasePtr();
11306     isLoad = false;
11307   } else {
11308     return false;
11309   }
11310 
11311   if (Ptr.getNode()->hasOneUse())
11312     return false;
11313 
11314   for (SDNode *Op : Ptr.getNode()->uses()) {
11315     if (Op == N ||
11316         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11317       continue;
11318 
11319     SDValue BasePtr;
11320     SDValue Offset;
11321     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11322     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11323       // Don't create a indexed load / store with zero offset.
11324       if (isNullConstant(Offset))
11325         continue;
11326 
11327       // Try turning it into a post-indexed load / store except when
11328       // 1) All uses are load / store ops that use it as base ptr (and
11329       //    it may be folded as addressing mmode).
11330       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11331       //    nor a successor of N. Otherwise, if Op is folded that would
11332       //    create a cycle.
11333 
11334       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11335         continue;
11336 
11337       // Check for #1.
11338       bool TryNext = false;
11339       for (SDNode *Use : BasePtr.getNode()->uses()) {
11340         if (Use == Ptr.getNode())
11341           continue;
11342 
11343         // If all the uses are load / store addresses, then don't do the
11344         // transformation.
11345         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11346           bool RealUse = false;
11347           for (SDNode *UseUse : Use->uses()) {
11348             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11349               RealUse = true;
11350           }
11351 
11352           if (!RealUse) {
11353             TryNext = true;
11354             break;
11355           }
11356         }
11357       }
11358 
11359       if (TryNext)
11360         continue;
11361 
11362       // Check for #2
11363       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11364         SDValue Result = isLoad
11365           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11366                                BasePtr, Offset, AM)
11367           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11368                                 BasePtr, Offset, AM);
11369         ++PostIndexedNodes;
11370         ++NodesCombined;
11371         DEBUG(dbgs() << "\nReplacing.5 ";
11372               N->dump(&DAG);
11373               dbgs() << "\nWith: ";
11374               Result.getNode()->dump(&DAG);
11375               dbgs() << '\n');
11376         WorklistRemover DeadNodes(*this);
11377         if (isLoad) {
11378           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11379           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11380         } else {
11381           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11382         }
11383 
11384         // Finally, since the node is now dead, remove it from the graph.
11385         deleteAndRecombine(N);
11386 
11387         // Replace the uses of Use with uses of the updated base value.
11388         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11389                                       Result.getValue(isLoad ? 1 : 0));
11390         deleteAndRecombine(Op);
11391         return true;
11392       }
11393     }
11394   }
11395 
11396   return false;
11397 }
11398 
11399 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11400 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11401   ISD::MemIndexedMode AM = LD->getAddressingMode();
11402   assert(AM != ISD::UNINDEXED);
11403   SDValue BP = LD->getOperand(1);
11404   SDValue Inc = LD->getOperand(2);
11405 
11406   // Some backends use TargetConstants for load offsets, but don't expect
11407   // TargetConstants in general ADD nodes. We can convert these constants into
11408   // regular Constants (if the constant is not opaque).
11409   assert((Inc.getOpcode() != ISD::TargetConstant ||
11410           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11411          "Cannot split out indexing using opaque target constants");
11412   if (Inc.getOpcode() == ISD::TargetConstant) {
11413     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11414     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11415                           ConstInc->getValueType(0));
11416   }
11417 
11418   unsigned Opc =
11419       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11420   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11421 }
11422 
11423 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11424   LoadSDNode *LD  = cast<LoadSDNode>(N);
11425   SDValue Chain = LD->getChain();
11426   SDValue Ptr   = LD->getBasePtr();
11427 
11428   // If load is not volatile and there are no uses of the loaded value (and
11429   // the updated indexed value in case of indexed loads), change uses of the
11430   // chain value into uses of the chain input (i.e. delete the dead load).
11431   if (!LD->isVolatile()) {
11432     if (N->getValueType(1) == MVT::Other) {
11433       // Unindexed loads.
11434       if (!N->hasAnyUseOfValue(0)) {
11435         // It's not safe to use the two value CombineTo variant here. e.g.
11436         // v1, chain2 = load chain1, loc
11437         // v2, chain3 = load chain2, loc
11438         // v3         = add v2, c
11439         // Now we replace use of chain2 with chain1.  This makes the second load
11440         // isomorphic to the one we are deleting, and thus makes this load live.
11441         DEBUG(dbgs() << "\nReplacing.6 ";
11442               N->dump(&DAG);
11443               dbgs() << "\nWith chain: ";
11444               Chain.getNode()->dump(&DAG);
11445               dbgs() << "\n");
11446         WorklistRemover DeadNodes(*this);
11447         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11448         AddUsersToWorklist(Chain.getNode());
11449         if (N->use_empty())
11450           deleteAndRecombine(N);
11451 
11452         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11453       }
11454     } else {
11455       // Indexed loads.
11456       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11457 
11458       // If this load has an opaque TargetConstant offset, then we cannot split
11459       // the indexing into an add/sub directly (that TargetConstant may not be
11460       // valid for a different type of node, and we cannot convert an opaque
11461       // target constant into a regular constant).
11462       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11463                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11464 
11465       if (!N->hasAnyUseOfValue(0) &&
11466           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11467         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11468         SDValue Index;
11469         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11470           Index = SplitIndexingFromLoad(LD);
11471           // Try to fold the base pointer arithmetic into subsequent loads and
11472           // stores.
11473           AddUsersToWorklist(N);
11474         } else
11475           Index = DAG.getUNDEF(N->getValueType(1));
11476         DEBUG(dbgs() << "\nReplacing.7 ";
11477               N->dump(&DAG);
11478               dbgs() << "\nWith: ";
11479               Undef.getNode()->dump(&DAG);
11480               dbgs() << " and 2 other values\n");
11481         WorklistRemover DeadNodes(*this);
11482         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11483         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11484         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11485         deleteAndRecombine(N);
11486         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11487       }
11488     }
11489   }
11490 
11491   // If this load is directly stored, replace the load value with the stored
11492   // value.
11493   // TODO: Handle store large -> read small portion.
11494   // TODO: Handle TRUNCSTORE/LOADEXT
11495   if (OptLevel != CodeGenOpt::None &&
11496       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11497     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11498       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11499       if (PrevST->getBasePtr() == Ptr &&
11500           PrevST->getValue().getValueType() == N->getValueType(0))
11501         return CombineTo(N, PrevST->getOperand(1), Chain);
11502     }
11503   }
11504 
11505   // Try to infer better alignment information than the load already has.
11506   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11507     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11508       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11509         SDValue NewLoad = DAG.getExtLoad(
11510             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11511             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11512             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11513         if (NewLoad.getNode() != N)
11514           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11515       }
11516     }
11517   }
11518 
11519   if (LD->isUnindexed()) {
11520     // Walk up chain skipping non-aliasing memory nodes.
11521     SDValue BetterChain = FindBetterChain(N, Chain);
11522 
11523     // If there is a better chain.
11524     if (Chain != BetterChain) {
11525       SDValue ReplLoad;
11526 
11527       // Replace the chain to void dependency.
11528       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11529         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11530                                BetterChain, Ptr, LD->getMemOperand());
11531       } else {
11532         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11533                                   LD->getValueType(0),
11534                                   BetterChain, Ptr, LD->getMemoryVT(),
11535                                   LD->getMemOperand());
11536       }
11537 
11538       // Create token factor to keep old chain connected.
11539       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11540                                   MVT::Other, Chain, ReplLoad.getValue(1));
11541 
11542       // Replace uses with load result and token factor
11543       return CombineTo(N, ReplLoad.getValue(0), Token);
11544     }
11545   }
11546 
11547   // Try transforming N to an indexed load.
11548   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11549     return SDValue(N, 0);
11550 
11551   // Try to slice up N to more direct loads if the slices are mapped to
11552   // different register banks or pairing can take place.
11553   if (SliceUpLoad(N))
11554     return SDValue(N, 0);
11555 
11556   return SDValue();
11557 }
11558 
11559 namespace {
11560 /// \brief Helper structure used to slice a load in smaller loads.
11561 /// Basically a slice is obtained from the following sequence:
11562 /// Origin = load Ty1, Base
11563 /// Shift = srl Ty1 Origin, CstTy Amount
11564 /// Inst = trunc Shift to Ty2
11565 ///
11566 /// Then, it will be rewritten into:
11567 /// Slice = load SliceTy, Base + SliceOffset
11568 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11569 ///
11570 /// SliceTy is deduced from the number of bits that are actually used to
11571 /// build Inst.
11572 struct LoadedSlice {
11573   /// \brief Helper structure used to compute the cost of a slice.
11574   struct Cost {
11575     /// Are we optimizing for code size.
11576     bool ForCodeSize;
11577     /// Various cost.
11578     unsigned Loads;
11579     unsigned Truncates;
11580     unsigned CrossRegisterBanksCopies;
11581     unsigned ZExts;
11582     unsigned Shift;
11583 
11584     Cost(bool ForCodeSize = false)
11585         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11586           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11587 
11588     /// \brief Get the cost of one isolated slice.
11589     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11590         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11591           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11592       EVT TruncType = LS.Inst->getValueType(0);
11593       EVT LoadedType = LS.getLoadedType();
11594       if (TruncType != LoadedType &&
11595           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11596         ZExts = 1;
11597     }
11598 
11599     /// \brief Account for slicing gain in the current cost.
11600     /// Slicing provide a few gains like removing a shift or a
11601     /// truncate. This method allows to grow the cost of the original
11602     /// load with the gain from this slice.
11603     void addSliceGain(const LoadedSlice &LS) {
11604       // Each slice saves a truncate.
11605       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11606       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11607                               LS.Inst->getValueType(0)))
11608         ++Truncates;
11609       // If there is a shift amount, this slice gets rid of it.
11610       if (LS.Shift)
11611         ++Shift;
11612       // If this slice can merge a cross register bank copy, account for it.
11613       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11614         ++CrossRegisterBanksCopies;
11615     }
11616 
11617     Cost &operator+=(const Cost &RHS) {
11618       Loads += RHS.Loads;
11619       Truncates += RHS.Truncates;
11620       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11621       ZExts += RHS.ZExts;
11622       Shift += RHS.Shift;
11623       return *this;
11624     }
11625 
11626     bool operator==(const Cost &RHS) const {
11627       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11628              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11629              ZExts == RHS.ZExts && Shift == RHS.Shift;
11630     }
11631 
11632     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11633 
11634     bool operator<(const Cost &RHS) const {
11635       // Assume cross register banks copies are as expensive as loads.
11636       // FIXME: Do we want some more target hooks?
11637       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11638       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11639       // Unless we are optimizing for code size, consider the
11640       // expensive operation first.
11641       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11642         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11643       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11644              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11645     }
11646 
11647     bool operator>(const Cost &RHS) const { return RHS < *this; }
11648 
11649     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11650 
11651     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11652   };
11653   // The last instruction that represent the slice. This should be a
11654   // truncate instruction.
11655   SDNode *Inst;
11656   // The original load instruction.
11657   LoadSDNode *Origin;
11658   // The right shift amount in bits from the original load.
11659   unsigned Shift;
11660   // The DAG from which Origin came from.
11661   // This is used to get some contextual information about legal types, etc.
11662   SelectionDAG *DAG;
11663 
11664   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11665               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11666       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11667 
11668   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11669   /// \return Result is \p BitWidth and has used bits set to 1 and
11670   ///         not used bits set to 0.
11671   APInt getUsedBits() const {
11672     // Reproduce the trunc(lshr) sequence:
11673     // - Start from the truncated value.
11674     // - Zero extend to the desired bit width.
11675     // - Shift left.
11676     assert(Origin && "No original load to compare against.");
11677     unsigned BitWidth = Origin->getValueSizeInBits(0);
11678     assert(Inst && "This slice is not bound to an instruction");
11679     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11680            "Extracted slice is bigger than the whole type!");
11681     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11682     UsedBits.setAllBits();
11683     UsedBits = UsedBits.zext(BitWidth);
11684     UsedBits <<= Shift;
11685     return UsedBits;
11686   }
11687 
11688   /// \brief Get the size of the slice to be loaded in bytes.
11689   unsigned getLoadedSize() const {
11690     unsigned SliceSize = getUsedBits().countPopulation();
11691     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11692     return SliceSize / 8;
11693   }
11694 
11695   /// \brief Get the type that will be loaded for this slice.
11696   /// Note: This may not be the final type for the slice.
11697   EVT getLoadedType() const {
11698     assert(DAG && "Missing context");
11699     LLVMContext &Ctxt = *DAG->getContext();
11700     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11701   }
11702 
11703   /// \brief Get the alignment of the load used for this slice.
11704   unsigned getAlignment() const {
11705     unsigned Alignment = Origin->getAlignment();
11706     unsigned Offset = getOffsetFromBase();
11707     if (Offset != 0)
11708       Alignment = MinAlign(Alignment, Alignment + Offset);
11709     return Alignment;
11710   }
11711 
11712   /// \brief Check if this slice can be rewritten with legal operations.
11713   bool isLegal() const {
11714     // An invalid slice is not legal.
11715     if (!Origin || !Inst || !DAG)
11716       return false;
11717 
11718     // Offsets are for indexed load only, we do not handle that.
11719     if (!Origin->getOffset().isUndef())
11720       return false;
11721 
11722     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11723 
11724     // Check that the type is legal.
11725     EVT SliceType = getLoadedType();
11726     if (!TLI.isTypeLegal(SliceType))
11727       return false;
11728 
11729     // Check that the load is legal for this type.
11730     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11731       return false;
11732 
11733     // Check that the offset can be computed.
11734     // 1. Check its type.
11735     EVT PtrType = Origin->getBasePtr().getValueType();
11736     if (PtrType == MVT::Untyped || PtrType.isExtended())
11737       return false;
11738 
11739     // 2. Check that it fits in the immediate.
11740     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11741       return false;
11742 
11743     // 3. Check that the computation is legal.
11744     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11745       return false;
11746 
11747     // Check that the zext is legal if it needs one.
11748     EVT TruncateType = Inst->getValueType(0);
11749     if (TruncateType != SliceType &&
11750         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11751       return false;
11752 
11753     return true;
11754   }
11755 
11756   /// \brief Get the offset in bytes of this slice in the original chunk of
11757   /// bits.
11758   /// \pre DAG != nullptr.
11759   uint64_t getOffsetFromBase() const {
11760     assert(DAG && "Missing context.");
11761     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11762     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11763     uint64_t Offset = Shift / 8;
11764     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11765     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11766            "The size of the original loaded type is not a multiple of a"
11767            " byte.");
11768     // If Offset is bigger than TySizeInBytes, it means we are loading all
11769     // zeros. This should have been optimized before in the process.
11770     assert(TySizeInBytes > Offset &&
11771            "Invalid shift amount for given loaded size");
11772     if (IsBigEndian)
11773       Offset = TySizeInBytes - Offset - getLoadedSize();
11774     return Offset;
11775   }
11776 
11777   /// \brief Generate the sequence of instructions to load the slice
11778   /// represented by this object and redirect the uses of this slice to
11779   /// this new sequence of instructions.
11780   /// \pre this->Inst && this->Origin are valid Instructions and this
11781   /// object passed the legal check: LoadedSlice::isLegal returned true.
11782   /// \return The last instruction of the sequence used to load the slice.
11783   SDValue loadSlice() const {
11784     assert(Inst && Origin && "Unable to replace a non-existing slice.");
11785     const SDValue &OldBaseAddr = Origin->getBasePtr();
11786     SDValue BaseAddr = OldBaseAddr;
11787     // Get the offset in that chunk of bytes w.r.t. the endianness.
11788     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11789     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11790     if (Offset) {
11791       // BaseAddr = BaseAddr + Offset.
11792       EVT ArithType = BaseAddr.getValueType();
11793       SDLoc DL(Origin);
11794       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11795                               DAG->getConstant(Offset, DL, ArithType));
11796     }
11797 
11798     // Create the type of the loaded slice according to its size.
11799     EVT SliceType = getLoadedType();
11800 
11801     // Create the load for the slice.
11802     SDValue LastInst =
11803         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11804                      Origin->getPointerInfo().getWithOffset(Offset),
11805                      getAlignment(), Origin->getMemOperand()->getFlags());
11806     // If the final type is not the same as the loaded type, this means that
11807     // we have to pad with zero. Create a zero extend for that.
11808     EVT FinalType = Inst->getValueType(0);
11809     if (SliceType != FinalType)
11810       LastInst =
11811           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11812     return LastInst;
11813   }
11814 
11815   /// \brief Check if this slice can be merged with an expensive cross register
11816   /// bank copy. E.g.,
11817   /// i = load i32
11818   /// f = bitcast i32 i to float
11819   bool canMergeExpensiveCrossRegisterBankCopy() const {
11820     if (!Inst || !Inst->hasOneUse())
11821       return false;
11822     SDNode *Use = *Inst->use_begin();
11823     if (Use->getOpcode() != ISD::BITCAST)
11824       return false;
11825     assert(DAG && "Missing context");
11826     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11827     EVT ResVT = Use->getValueType(0);
11828     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11829     const TargetRegisterClass *ArgRC =
11830         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11831     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11832       return false;
11833 
11834     // At this point, we know that we perform a cross-register-bank copy.
11835     // Check if it is expensive.
11836     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11837     // Assume bitcasts are cheap, unless both register classes do not
11838     // explicitly share a common sub class.
11839     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11840       return false;
11841 
11842     // Check if it will be merged with the load.
11843     // 1. Check the alignment constraint.
11844     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11845         ResVT.getTypeForEVT(*DAG->getContext()));
11846 
11847     if (RequiredAlignment > getAlignment())
11848       return false;
11849 
11850     // 2. Check that the load is a legal operation for that type.
11851     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11852       return false;
11853 
11854     // 3. Check that we do not have a zext in the way.
11855     if (Inst->getValueType(0) != getLoadedType())
11856       return false;
11857 
11858     return true;
11859   }
11860 };
11861 }
11862 
11863 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11864 /// \p UsedBits looks like 0..0 1..1 0..0.
11865 static bool areUsedBitsDense(const APInt &UsedBits) {
11866   // If all the bits are one, this is dense!
11867   if (UsedBits.isAllOnesValue())
11868     return true;
11869 
11870   // Get rid of the unused bits on the right.
11871   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11872   // Get rid of the unused bits on the left.
11873   if (NarrowedUsedBits.countLeadingZeros())
11874     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11875   // Check that the chunk of bits is completely used.
11876   return NarrowedUsedBits.isAllOnesValue();
11877 }
11878 
11879 /// \brief Check whether or not \p First and \p Second are next to each other
11880 /// in memory. This means that there is no hole between the bits loaded
11881 /// by \p First and the bits loaded by \p Second.
11882 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11883                                      const LoadedSlice &Second) {
11884   assert(First.Origin == Second.Origin && First.Origin &&
11885          "Unable to match different memory origins.");
11886   APInt UsedBits = First.getUsedBits();
11887   assert((UsedBits & Second.getUsedBits()) == 0 &&
11888          "Slices are not supposed to overlap.");
11889   UsedBits |= Second.getUsedBits();
11890   return areUsedBitsDense(UsedBits);
11891 }
11892 
11893 /// \brief Adjust the \p GlobalLSCost according to the target
11894 /// paring capabilities and the layout of the slices.
11895 /// \pre \p GlobalLSCost should account for at least as many loads as
11896 /// there is in the slices in \p LoadedSlices.
11897 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11898                                  LoadedSlice::Cost &GlobalLSCost) {
11899   unsigned NumberOfSlices = LoadedSlices.size();
11900   // If there is less than 2 elements, no pairing is possible.
11901   if (NumberOfSlices < 2)
11902     return;
11903 
11904   // Sort the slices so that elements that are likely to be next to each
11905   // other in memory are next to each other in the list.
11906   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11907             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11908     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11909     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11910   });
11911   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11912   // First (resp. Second) is the first (resp. Second) potentially candidate
11913   // to be placed in a paired load.
11914   const LoadedSlice *First = nullptr;
11915   const LoadedSlice *Second = nullptr;
11916   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11917                 // Set the beginning of the pair.
11918                                                            First = Second) {
11919 
11920     Second = &LoadedSlices[CurrSlice];
11921 
11922     // If First is NULL, it means we start a new pair.
11923     // Get to the next slice.
11924     if (!First)
11925       continue;
11926 
11927     EVT LoadedType = First->getLoadedType();
11928 
11929     // If the types of the slices are different, we cannot pair them.
11930     if (LoadedType != Second->getLoadedType())
11931       continue;
11932 
11933     // Check if the target supplies paired loads for this type.
11934     unsigned RequiredAlignment = 0;
11935     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11936       // move to the next pair, this type is hopeless.
11937       Second = nullptr;
11938       continue;
11939     }
11940     // Check if we meet the alignment requirement.
11941     if (RequiredAlignment > First->getAlignment())
11942       continue;
11943 
11944     // Check that both loads are next to each other in memory.
11945     if (!areSlicesNextToEachOther(*First, *Second))
11946       continue;
11947 
11948     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11949     --GlobalLSCost.Loads;
11950     // Move to the next pair.
11951     Second = nullptr;
11952   }
11953 }
11954 
11955 /// \brief Check the profitability of all involved LoadedSlice.
11956 /// Currently, it is considered profitable if there is exactly two
11957 /// involved slices (1) which are (2) next to each other in memory, and
11958 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11959 ///
11960 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11961 /// the elements themselves.
11962 ///
11963 /// FIXME: When the cost model will be mature enough, we can relax
11964 /// constraints (1) and (2).
11965 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11966                                 const APInt &UsedBits, bool ForCodeSize) {
11967   unsigned NumberOfSlices = LoadedSlices.size();
11968   if (StressLoadSlicing)
11969     return NumberOfSlices > 1;
11970 
11971   // Check (1).
11972   if (NumberOfSlices != 2)
11973     return false;
11974 
11975   // Check (2).
11976   if (!areUsedBitsDense(UsedBits))
11977     return false;
11978 
11979   // Check (3).
11980   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11981   // The original code has one big load.
11982   OrigCost.Loads = 1;
11983   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11984     const LoadedSlice &LS = LoadedSlices[CurrSlice];
11985     // Accumulate the cost of all the slices.
11986     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11987     GlobalSlicingCost += SliceCost;
11988 
11989     // Account as cost in the original configuration the gain obtained
11990     // with the current slices.
11991     OrigCost.addSliceGain(LS);
11992   }
11993 
11994   // If the target supports paired load, adjust the cost accordingly.
11995   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11996   return OrigCost > GlobalSlicingCost;
11997 }
11998 
11999 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
12000 /// operations, split it in the various pieces being extracted.
12001 ///
12002 /// This sort of thing is introduced by SROA.
12003 /// This slicing takes care not to insert overlapping loads.
12004 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
12005 bool DAGCombiner::SliceUpLoad(SDNode *N) {
12006   if (Level < AfterLegalizeDAG)
12007     return false;
12008 
12009   LoadSDNode *LD = cast<LoadSDNode>(N);
12010   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
12011       !LD->getValueType(0).isInteger())
12012     return false;
12013 
12014   // Keep track of already used bits to detect overlapping values.
12015   // In that case, we will just abort the transformation.
12016   APInt UsedBits(LD->getValueSizeInBits(0), 0);
12017 
12018   SmallVector<LoadedSlice, 4> LoadedSlices;
12019 
12020   // Check if this load is used as several smaller chunks of bits.
12021   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
12022   // of computation for each trunc.
12023   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
12024        UI != UIEnd; ++UI) {
12025     // Skip the uses of the chain.
12026     if (UI.getUse().getResNo() != 0)
12027       continue;
12028 
12029     SDNode *User = *UI;
12030     unsigned Shift = 0;
12031 
12032     // Check if this is a trunc(lshr).
12033     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
12034         isa<ConstantSDNode>(User->getOperand(1))) {
12035       Shift = User->getConstantOperandVal(1);
12036       User = *User->use_begin();
12037     }
12038 
12039     // At this point, User is a Truncate, iff we encountered, trunc or
12040     // trunc(lshr).
12041     if (User->getOpcode() != ISD::TRUNCATE)
12042       return false;
12043 
12044     // The width of the type must be a power of 2 and greater than 8-bits.
12045     // Otherwise the load cannot be represented in LLVM IR.
12046     // Moreover, if we shifted with a non-8-bits multiple, the slice
12047     // will be across several bytes. We do not support that.
12048     unsigned Width = User->getValueSizeInBits(0);
12049     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
12050       return 0;
12051 
12052     // Build the slice for this chain of computations.
12053     LoadedSlice LS(User, LD, Shift, &DAG);
12054     APInt CurrentUsedBits = LS.getUsedBits();
12055 
12056     // Check if this slice overlaps with another.
12057     if ((CurrentUsedBits & UsedBits) != 0)
12058       return false;
12059     // Update the bits used globally.
12060     UsedBits |= CurrentUsedBits;
12061 
12062     // Check if the new slice would be legal.
12063     if (!LS.isLegal())
12064       return false;
12065 
12066     // Record the slice.
12067     LoadedSlices.push_back(LS);
12068   }
12069 
12070   // Abort slicing if it does not seem to be profitable.
12071   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
12072     return false;
12073 
12074   ++SlicedLoads;
12075 
12076   // Rewrite each chain to use an independent load.
12077   // By construction, each chain can be represented by a unique load.
12078 
12079   // Prepare the argument for the new token factor for all the slices.
12080   SmallVector<SDValue, 8> ArgChains;
12081   for (SmallVectorImpl<LoadedSlice>::const_iterator
12082            LSIt = LoadedSlices.begin(),
12083            LSItEnd = LoadedSlices.end();
12084        LSIt != LSItEnd; ++LSIt) {
12085     SDValue SliceInst = LSIt->loadSlice();
12086     CombineTo(LSIt->Inst, SliceInst, true);
12087     if (SliceInst.getOpcode() != ISD::LOAD)
12088       SliceInst = SliceInst.getOperand(0);
12089     assert(SliceInst->getOpcode() == ISD::LOAD &&
12090            "It takes more than a zext to get to the loaded slice!!");
12091     ArgChains.push_back(SliceInst.getValue(1));
12092   }
12093 
12094   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
12095                               ArgChains);
12096   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
12097   AddToWorklist(Chain.getNode());
12098   return true;
12099 }
12100 
12101 /// Check to see if V is (and load (ptr), imm), where the load is having
12102 /// specific bytes cleared out.  If so, return the byte size being masked out
12103 /// and the shift amount.
12104 static std::pair<unsigned, unsigned>
12105 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
12106   std::pair<unsigned, unsigned> Result(0, 0);
12107 
12108   // Check for the structure we're looking for.
12109   if (V->getOpcode() != ISD::AND ||
12110       !isa<ConstantSDNode>(V->getOperand(1)) ||
12111       !ISD::isNormalLoad(V->getOperand(0).getNode()))
12112     return Result;
12113 
12114   // Check the chain and pointer.
12115   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
12116   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
12117 
12118   // The store should be chained directly to the load or be an operand of a
12119   // tokenfactor.
12120   if (LD == Chain.getNode())
12121     ; // ok.
12122   else if (Chain->getOpcode() != ISD::TokenFactor)
12123     return Result; // Fail.
12124   else {
12125     bool isOk = false;
12126     for (const SDValue &ChainOp : Chain->op_values())
12127       if (ChainOp.getNode() == LD) {
12128         isOk = true;
12129         break;
12130       }
12131     if (!isOk) return Result;
12132   }
12133 
12134   // This only handles simple types.
12135   if (V.getValueType() != MVT::i16 &&
12136       V.getValueType() != MVT::i32 &&
12137       V.getValueType() != MVT::i64)
12138     return Result;
12139 
12140   // Check the constant mask.  Invert it so that the bits being masked out are
12141   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
12142   // follow the sign bit for uniformity.
12143   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12144   unsigned NotMaskLZ = countLeadingZeros(NotMask);
12145   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
12146   unsigned NotMaskTZ = countTrailingZeros(NotMask);
12147   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
12148   if (NotMaskLZ == 64) return Result;  // All zero mask.
12149 
12150   // See if we have a continuous run of bits.  If so, we have 0*1+0*
12151   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12152     return Result;
12153 
12154   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12155   if (V.getValueType() != MVT::i64 && NotMaskLZ)
12156     NotMaskLZ -= 64-V.getValueSizeInBits();
12157 
12158   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12159   switch (MaskedBytes) {
12160   case 1:
12161   case 2:
12162   case 4: break;
12163   default: return Result; // All one mask, or 5-byte mask.
12164   }
12165 
12166   // Verify that the first bit starts at a multiple of mask so that the access
12167   // is aligned the same as the access width.
12168   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12169 
12170   Result.first = MaskedBytes;
12171   Result.second = NotMaskTZ/8;
12172   return Result;
12173 }
12174 
12175 
12176 /// Check to see if IVal is something that provides a value as specified by
12177 /// MaskInfo. If so, replace the specified store with a narrower store of
12178 /// truncated IVal.
12179 static SDNode *
12180 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12181                                 SDValue IVal, StoreSDNode *St,
12182                                 DAGCombiner *DC) {
12183   unsigned NumBytes = MaskInfo.first;
12184   unsigned ByteShift = MaskInfo.second;
12185   SelectionDAG &DAG = DC->getDAG();
12186 
12187   // Check to see if IVal is all zeros in the part being masked in by the 'or'
12188   // that uses this.  If not, this is not a replacement.
12189   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12190                                   ByteShift*8, (ByteShift+NumBytes)*8);
12191   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12192 
12193   // Check that it is legal on the target to do this.  It is legal if the new
12194   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12195   // legalization.
12196   MVT VT = MVT::getIntegerVT(NumBytes*8);
12197   if (!DC->isTypeLegal(VT))
12198     return nullptr;
12199 
12200   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
12201   // shifted by ByteShift and truncated down to NumBytes.
12202   if (ByteShift) {
12203     SDLoc DL(IVal);
12204     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12205                        DAG.getConstant(ByteShift*8, DL,
12206                                     DC->getShiftAmountTy(IVal.getValueType())));
12207   }
12208 
12209   // Figure out the offset for the store and the alignment of the access.
12210   unsigned StOffset;
12211   unsigned NewAlign = St->getAlignment();
12212 
12213   if (DAG.getDataLayout().isLittleEndian())
12214     StOffset = ByteShift;
12215   else
12216     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12217 
12218   SDValue Ptr = St->getBasePtr();
12219   if (StOffset) {
12220     SDLoc DL(IVal);
12221     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12222                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12223     NewAlign = MinAlign(NewAlign, StOffset);
12224   }
12225 
12226   // Truncate down to the new size.
12227   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12228 
12229   ++OpsNarrowed;
12230   return DAG
12231       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12232                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12233       .getNode();
12234 }
12235 
12236 
12237 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12238 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12239 /// narrowing the load and store if it would end up being a win for performance
12240 /// or code size.
12241 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12242   StoreSDNode *ST  = cast<StoreSDNode>(N);
12243   if (ST->isVolatile())
12244     return SDValue();
12245 
12246   SDValue Chain = ST->getChain();
12247   SDValue Value = ST->getValue();
12248   SDValue Ptr   = ST->getBasePtr();
12249   EVT VT = Value.getValueType();
12250 
12251   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12252     return SDValue();
12253 
12254   unsigned Opc = Value.getOpcode();
12255 
12256   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12257   // is a byte mask indicating a consecutive number of bytes, check to see if
12258   // Y is known to provide just those bytes.  If so, we try to replace the
12259   // load + replace + store sequence with a single (narrower) store, which makes
12260   // the load dead.
12261   if (Opc == ISD::OR) {
12262     std::pair<unsigned, unsigned> MaskedLoad;
12263     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12264     if (MaskedLoad.first)
12265       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12266                                                   Value.getOperand(1), ST,this))
12267         return SDValue(NewST, 0);
12268 
12269     // Or is commutative, so try swapping X and Y.
12270     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12271     if (MaskedLoad.first)
12272       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12273                                                   Value.getOperand(0), ST,this))
12274         return SDValue(NewST, 0);
12275   }
12276 
12277   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12278       Value.getOperand(1).getOpcode() != ISD::Constant)
12279     return SDValue();
12280 
12281   SDValue N0 = Value.getOperand(0);
12282   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12283       Chain == SDValue(N0.getNode(), 1)) {
12284     LoadSDNode *LD = cast<LoadSDNode>(N0);
12285     if (LD->getBasePtr() != Ptr ||
12286         LD->getPointerInfo().getAddrSpace() !=
12287         ST->getPointerInfo().getAddrSpace())
12288       return SDValue();
12289 
12290     // Find the type to narrow it the load / op / store to.
12291     SDValue N1 = Value.getOperand(1);
12292     unsigned BitWidth = N1.getValueSizeInBits();
12293     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12294     if (Opc == ISD::AND)
12295       Imm ^= APInt::getAllOnesValue(BitWidth);
12296     if (Imm == 0 || Imm.isAllOnesValue())
12297       return SDValue();
12298     unsigned ShAmt = Imm.countTrailingZeros();
12299     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12300     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12301     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12302     // The narrowing should be profitable, the load/store operation should be
12303     // legal (or custom) and the store size should be equal to the NewVT width.
12304     while (NewBW < BitWidth &&
12305            (NewVT.getStoreSizeInBits() != NewBW ||
12306             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12307             !TLI.isNarrowingProfitable(VT, NewVT))) {
12308       NewBW = NextPowerOf2(NewBW);
12309       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12310     }
12311     if (NewBW >= BitWidth)
12312       return SDValue();
12313 
12314     // If the lsb changed does not start at the type bitwidth boundary,
12315     // start at the previous one.
12316     if (ShAmt % NewBW)
12317       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12318     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12319                                    std::min(BitWidth, ShAmt + NewBW));
12320     if ((Imm & Mask) == Imm) {
12321       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12322       if (Opc == ISD::AND)
12323         NewImm ^= APInt::getAllOnesValue(NewBW);
12324       uint64_t PtrOff = ShAmt / 8;
12325       // For big endian targets, we need to adjust the offset to the pointer to
12326       // load the correct bytes.
12327       if (DAG.getDataLayout().isBigEndian())
12328         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12329 
12330       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12331       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12332       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12333         return SDValue();
12334 
12335       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12336                                    Ptr.getValueType(), Ptr,
12337                                    DAG.getConstant(PtrOff, SDLoc(LD),
12338                                                    Ptr.getValueType()));
12339       SDValue NewLD =
12340           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12341                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12342                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12343       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12344                                    DAG.getConstant(NewImm, SDLoc(Value),
12345                                                    NewVT));
12346       SDValue NewST =
12347           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12348                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12349 
12350       AddToWorklist(NewPtr.getNode());
12351       AddToWorklist(NewLD.getNode());
12352       AddToWorklist(NewVal.getNode());
12353       WorklistRemover DeadNodes(*this);
12354       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12355       ++OpsNarrowed;
12356       return NewST;
12357     }
12358   }
12359 
12360   return SDValue();
12361 }
12362 
12363 /// For a given floating point load / store pair, if the load value isn't used
12364 /// by any other operations, then consider transforming the pair to integer
12365 /// load / store operations if the target deems the transformation profitable.
12366 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12367   StoreSDNode *ST  = cast<StoreSDNode>(N);
12368   SDValue Chain = ST->getChain();
12369   SDValue Value = ST->getValue();
12370   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12371       Value.hasOneUse() &&
12372       Chain == SDValue(Value.getNode(), 1)) {
12373     LoadSDNode *LD = cast<LoadSDNode>(Value);
12374     EVT VT = LD->getMemoryVT();
12375     if (!VT.isFloatingPoint() ||
12376         VT != ST->getMemoryVT() ||
12377         LD->isNonTemporal() ||
12378         ST->isNonTemporal() ||
12379         LD->getPointerInfo().getAddrSpace() != 0 ||
12380         ST->getPointerInfo().getAddrSpace() != 0)
12381       return SDValue();
12382 
12383     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12384     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12385         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12386         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12387         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12388       return SDValue();
12389 
12390     unsigned LDAlign = LD->getAlignment();
12391     unsigned STAlign = ST->getAlignment();
12392     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12393     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12394     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12395       return SDValue();
12396 
12397     SDValue NewLD =
12398         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12399                     LD->getPointerInfo(), LDAlign);
12400 
12401     SDValue NewST =
12402         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12403                      ST->getPointerInfo(), STAlign);
12404 
12405     AddToWorklist(NewLD.getNode());
12406     AddToWorklist(NewST.getNode());
12407     WorklistRemover DeadNodes(*this);
12408     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12409     ++LdStFP2Int;
12410     return NewST;
12411   }
12412 
12413   return SDValue();
12414 }
12415 
12416 // This is a helper function for visitMUL to check the profitability
12417 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12418 // MulNode is the original multiply, AddNode is (add x, c1),
12419 // and ConstNode is c2.
12420 //
12421 // If the (add x, c1) has multiple uses, we could increase
12422 // the number of adds if we make this transformation.
12423 // It would only be worth doing this if we can remove a
12424 // multiply in the process. Check for that here.
12425 // To illustrate:
12426 //     (A + c1) * c3
12427 //     (A + c2) * c3
12428 // We're checking for cases where we have common "c3 * A" expressions.
12429 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12430                                               SDValue &AddNode,
12431                                               SDValue &ConstNode) {
12432   APInt Val;
12433 
12434   // If the add only has one use, this would be OK to do.
12435   if (AddNode.getNode()->hasOneUse())
12436     return true;
12437 
12438   // Walk all the users of the constant with which we're multiplying.
12439   for (SDNode *Use : ConstNode->uses()) {
12440 
12441     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12442       continue;
12443 
12444     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12445       SDNode *OtherOp;
12446       SDNode *MulVar = AddNode.getOperand(0).getNode();
12447 
12448       // OtherOp is what we're multiplying against the constant.
12449       if (Use->getOperand(0) == ConstNode)
12450         OtherOp = Use->getOperand(1).getNode();
12451       else
12452         OtherOp = Use->getOperand(0).getNode();
12453 
12454       // Check to see if multiply is with the same operand of our "add".
12455       //
12456       //     ConstNode  = CONST
12457       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12458       //     ...
12459       //     AddNode  = (A + c1)  <-- MulVar is A.
12460       //         = AddNode * ConstNode   <-- current visiting instruction.
12461       //
12462       // If we make this transformation, we will have a common
12463       // multiply (ConstNode * A) that we can save.
12464       if (OtherOp == MulVar)
12465         return true;
12466 
12467       // Now check to see if a future expansion will give us a common
12468       // multiply.
12469       //
12470       //     ConstNode  = CONST
12471       //     AddNode    = (A + c1)
12472       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12473       //     ...
12474       //     OtherOp = (A + c2)
12475       //     Use     = OtherOp * ConstNode <-- visiting Use.
12476       //
12477       // If we make this transformation, we will have a common
12478       // multiply (CONST * A) after we also do the same transformation
12479       // to the "t2" instruction.
12480       if (OtherOp->getOpcode() == ISD::ADD &&
12481           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12482           OtherOp->getOperand(0).getNode() == MulVar)
12483         return true;
12484     }
12485   }
12486 
12487   // Didn't find a case where this would be profitable.
12488   return false;
12489 }
12490 
12491 static SDValue peekThroughBitcast(SDValue V) {
12492   while (V.getOpcode() == ISD::BITCAST)
12493     V = V.getOperand(0);
12494   return V;
12495 }
12496 
12497 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12498                                          unsigned NumStores) {
12499   SmallVector<SDValue, 8> Chains;
12500   SmallPtrSet<const SDNode *, 8> Visited;
12501   SDLoc StoreDL(StoreNodes[0].MemNode);
12502 
12503   for (unsigned i = 0; i < NumStores; ++i) {
12504     Visited.insert(StoreNodes[i].MemNode);
12505   }
12506 
12507   // don't include nodes that are children
12508   for (unsigned i = 0; i < NumStores; ++i) {
12509     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12510       Chains.push_back(StoreNodes[i].MemNode->getChain());
12511   }
12512 
12513   assert(Chains.size() > 0 && "Chain should have generated a chain");
12514   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12515 }
12516 
12517 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12518     SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
12519     bool IsConstantSrc, bool UseVector, bool UseTrunc) {
12520   // Make sure we have something to merge.
12521   if (NumStores < 2)
12522     return false;
12523 
12524   // The latest Node in the DAG.
12525   SDLoc DL(StoreNodes[0].MemNode);
12526 
12527   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12528   unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12529   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
12530 
12531   EVT StoreTy;
12532   if (UseVector) {
12533     unsigned Elts = NumStores * NumMemElts;
12534     // Get the type for the merged vector store.
12535     StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12536   } else
12537     StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12538 
12539   SDValue StoredVal;
12540   if (UseVector) {
12541     if (IsConstantSrc) {
12542       SmallVector<SDValue, 8> BuildVector;
12543       for (unsigned I = 0; I != NumStores; ++I) {
12544         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12545         SDValue Val = St->getValue();
12546         // If constant is of the wrong type, convert it now.
12547         if (MemVT != Val.getValueType()) {
12548           Val = peekThroughBitcast(Val);
12549           // Deal with constants of wrong size.
12550           if (ElementSizeBytes * 8 != Val.getValueSizeInBits()) {
12551             EVT IntMemVT =
12552                 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
12553             if (auto *CFP = dyn_cast<ConstantFPSDNode>(Val))
12554               Val = DAG.getConstant(
12555                   CFP->getValueAPF().bitcastToAPInt().zextOrTrunc(
12556                       8 * ElementSizeBytes),
12557                   SDLoc(CFP), IntMemVT);
12558             else if (auto *C = dyn_cast<ConstantSDNode>(Val))
12559               Val = DAG.getConstant(
12560                   C->getAPIntValue().zextOrTrunc(8 * ElementSizeBytes),
12561                   SDLoc(C), IntMemVT);
12562           }
12563           // Make sure correctly size type is the correct type.
12564           Val = DAG.getBitcast(MemVT, Val);
12565         }
12566         BuildVector.push_back(Val);
12567       }
12568       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12569                                                : ISD::BUILD_VECTOR,
12570                               DL, StoreTy, BuildVector);
12571     } else {
12572       SmallVector<SDValue, 8> Ops;
12573       for (unsigned i = 0; i < NumStores; ++i) {
12574         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12575         SDValue Val = peekThroughBitcast(St->getValue());
12576         // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
12577         // type MemVT. If the underlying value is not the correct
12578         // type, but it is an extraction of an appropriate vector we
12579         // can recast Val to be of the correct type. This may require
12580         // converting between EXTRACT_VECTOR_ELT and
12581         // EXTRACT_SUBVECTOR.
12582         if ((MemVT != Val.getValueType()) &&
12583             (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12584              Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
12585           SDValue Vec = Val.getOperand(0);
12586           EVT MemVTScalarTy = MemVT.getScalarType();
12587           // We may need to add a bitcast here to get types to line up.
12588           if (MemVTScalarTy != Vec.getValueType()) {
12589             unsigned Elts = Vec.getValueType().getSizeInBits() /
12590                             MemVTScalarTy.getSizeInBits();
12591             EVT NewVecTy =
12592                 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts);
12593             Vec = DAG.getBitcast(NewVecTy, Vec);
12594           }
12595           auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR
12596                                         : ISD::EXTRACT_VECTOR_ELT;
12597           Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1));
12598         }
12599         Ops.push_back(Val);
12600       }
12601 
12602       // Build the extracted vector elements back into a vector.
12603       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12604                                                : ISD::BUILD_VECTOR,
12605                               DL, StoreTy, Ops);
12606     }
12607   } else {
12608     // We should always use a vector store when merging extracted vector
12609     // elements, so this path implies a store of constants.
12610     assert(IsConstantSrc && "Merged vector elements should use vector store");
12611 
12612     APInt StoreInt(SizeInBits, 0);
12613 
12614     // Construct a single integer constant which is made of the smaller
12615     // constant inputs.
12616     bool IsLE = DAG.getDataLayout().isLittleEndian();
12617     for (unsigned i = 0; i < NumStores; ++i) {
12618       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12619       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12620 
12621       SDValue Val = St->getValue();
12622       StoreInt <<= ElementSizeBytes * 8;
12623       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12624         StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits);
12625       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12626         StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits);
12627       } else {
12628         llvm_unreachable("Invalid constant element type");
12629       }
12630     }
12631 
12632     // Create the new Load and Store operations.
12633     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12634   }
12635 
12636   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12637   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12638 
12639   // make sure we use trunc store if it's necessary to be legal.
12640   SDValue NewStore;
12641   if (!UseTrunc) {
12642     NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
12643                             FirstInChain->getPointerInfo(),
12644                             FirstInChain->getAlignment());
12645   } else { // Must be realized as a trunc store
12646     EVT LegalizedStoredValueTy =
12647         TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
12648     unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
12649     ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
12650     SDValue ExtendedStoreVal =
12651         DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
12652                         LegalizedStoredValueTy);
12653     NewStore = DAG.getTruncStore(
12654         NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
12655         FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
12656         FirstInChain->getAlignment(),
12657         FirstInChain->getMemOperand()->getFlags());
12658   }
12659 
12660   // Replace all merged stores with the new store.
12661   for (unsigned i = 0; i < NumStores; ++i)
12662     CombineTo(StoreNodes[i].MemNode, NewStore);
12663 
12664   AddToWorklist(NewChain.getNode());
12665   return true;
12666 }
12667 
12668 void DAGCombiner::getStoreMergeCandidates(
12669     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12670   // This holds the base pointer, index, and the offset in bytes from the base
12671   // pointer.
12672   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12673   EVT MemVT = St->getMemoryVT();
12674 
12675   SDValue Val = peekThroughBitcast(St->getValue());
12676   // We must have a base and an offset.
12677   if (!BasePtr.getBase().getNode())
12678     return;
12679 
12680   // Do not handle stores to undef base pointers.
12681   if (BasePtr.getBase().isUndef())
12682     return;
12683 
12684   bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
12685   bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12686                           Val.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12687   bool IsLoadSrc = isa<LoadSDNode>(Val);
12688   BaseIndexOffset LBasePtr;
12689   // Match on loadbaseptr if relevant.
12690   EVT LoadVT;
12691   if (IsLoadSrc) {
12692     auto *Ld = cast<LoadSDNode>(Val);
12693     LBasePtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12694     LoadVT = Ld->getMemoryVT();
12695     // Load and store should be the same type.
12696     if (MemVT != LoadVT)
12697       return;
12698   }
12699   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
12700                             int64_t &Offset) -> bool {
12701     if (Other->isVolatile() || Other->isIndexed())
12702       return false;
12703     SDValue Val = peekThroughBitcast(Other->getValue());
12704     // Allow merging constants of different types as integers.
12705     bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
12706                                            : Other->getMemoryVT() != MemVT;
12707     if (IsLoadSrc) {
12708       if (NoTypeMatch)
12709         return false;
12710       // The Load's Base Ptr must also match
12711       if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) {
12712         auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG);
12713         if (LoadVT != OtherLd->getMemoryVT())
12714           return false;
12715         if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
12716           return false;
12717       } else
12718         return false;
12719     }
12720     if (IsConstantSrc) {
12721       if (NoTypeMatch)
12722         return false;
12723       if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val)))
12724         return false;
12725     }
12726     if (IsExtractVecSrc) {
12727       // Do not merge truncated stores here.
12728       if (Other->isTruncatingStore())
12729         return false;
12730       if (!MemVT.bitsEq(Val.getValueType()))
12731         return false;
12732       if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
12733           Val.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12734         return false;
12735     }
12736     Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12737     return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
12738   };
12739   // We looking for a root node which is an ancestor to all mergable
12740   // stores. We search up through a load, to our root and then down
12741   // through all children. For instance we will find Store{1,2,3} if
12742   // St is Store1, Store2. or Store3 where the root is not a load
12743   // which always true for nonvolatile ops. TODO: Expand
12744   // the search to find all valid candidates through multiple layers of loads.
12745   //
12746   // Root
12747   // |-------|-------|
12748   // Load    Load    Store3
12749   // |       |
12750   // Store1   Store2
12751   //
12752   // FIXME: We should be able to climb and
12753   // descend TokenFactors to find candidates as well.
12754 
12755   SDNode *RootNode = (St->getChain()).getNode();
12756 
12757   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12758     RootNode = Ldn->getChain().getNode();
12759     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12760       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12761         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12762           if (I2.getOperandNo() == 0)
12763             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12764               BaseIndexOffset Ptr;
12765               int64_t PtrDiff;
12766               if (CandidateMatch(OtherST, Ptr, PtrDiff))
12767                 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12768             }
12769   } else
12770     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12771       if (I.getOperandNo() == 0)
12772         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12773           BaseIndexOffset Ptr;
12774           int64_t PtrDiff;
12775           if (CandidateMatch(OtherST, Ptr, PtrDiff))
12776             StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12777         }
12778 }
12779 
12780 // We need to check that merging these stores does not cause a loop
12781 // in the DAG. Any store candidate may depend on another candidate
12782 // indirectly through its operand (we already consider dependencies
12783 // through the chain). Check in parallel by searching up from
12784 // non-chain operands of candidates.
12785 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12786     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12787   SmallPtrSet<const SDNode *, 16> Visited;
12788   SmallVector<const SDNode *, 8> Worklist;
12789   // search ops of store candidates
12790   for (unsigned i = 0; i < NumStores; ++i) {
12791     SDNode *n = StoreNodes[i].MemNode;
12792     // Potential loops may happen only through non-chain operands
12793     for (unsigned j = 1; j < n->getNumOperands(); ++j)
12794       Worklist.push_back(n->getOperand(j).getNode());
12795   }
12796   // search through DAG. We can stop early if we find a storenode
12797   for (unsigned i = 0; i < NumStores; ++i) {
12798     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12799       return false;
12800   }
12801   return true;
12802 }
12803 
12804 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12805   if (OptLevel == CodeGenOpt::None)
12806     return false;
12807 
12808   EVT MemVT = St->getMemoryVT();
12809   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12810   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
12811 
12812   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12813     return false;
12814 
12815   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12816       Attribute::NoImplicitFloat);
12817 
12818   // This function cannot currently deal with non-byte-sized memory sizes.
12819   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12820     return false;
12821 
12822   if (!MemVT.isSimple())
12823     return false;
12824 
12825   // Perform an early exit check. Do not bother looking at stored values that
12826   // are not constants, loads, or extracted vector elements.
12827   SDValue StoredVal = peekThroughBitcast(St->getValue());
12828   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12829   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12830                        isa<ConstantFPSDNode>(StoredVal);
12831   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12832                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12833 
12834   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12835     return false;
12836 
12837   SmallVector<MemOpLink, 8> StoreNodes;
12838   // Find potential store merge candidates by searching through chain sub-DAG
12839   getStoreMergeCandidates(St, StoreNodes);
12840 
12841   // Check if there is anything to merge.
12842   if (StoreNodes.size() < 2)
12843     return false;
12844 
12845   // Sort the memory operands according to their distance from the
12846   // base pointer.
12847   std::sort(StoreNodes.begin(), StoreNodes.end(),
12848             [](MemOpLink LHS, MemOpLink RHS) {
12849               return LHS.OffsetFromBase < RHS.OffsetFromBase;
12850             });
12851 
12852   // Store Merge attempts to merge the lowest stores. This generally
12853   // works out as if successful, as the remaining stores are checked
12854   // after the first collection of stores is merged. However, in the
12855   // case that a non-mergeable store is found first, e.g., {p[-2],
12856   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12857   // mergeable cases. To prevent this, we prune such stores from the
12858   // front of StoreNodes here.
12859 
12860   bool RV = false;
12861   while (StoreNodes.size() > 1) {
12862     unsigned StartIdx = 0;
12863     while ((StartIdx + 1 < StoreNodes.size()) &&
12864            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12865                StoreNodes[StartIdx + 1].OffsetFromBase)
12866       ++StartIdx;
12867 
12868     // Bail if we don't have enough candidates to merge.
12869     if (StartIdx + 1 >= StoreNodes.size())
12870       return RV;
12871 
12872     if (StartIdx)
12873       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12874 
12875     // Scan the memory operations on the chain and find the first
12876     // non-consecutive store memory address.
12877     unsigned NumConsecutiveStores = 1;
12878     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12879     // Check that the addresses are consecutive starting from the second
12880     // element in the list of stores.
12881     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12882       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12883       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12884         break;
12885       NumConsecutiveStores = i + 1;
12886     }
12887 
12888     if (NumConsecutiveStores < 2) {
12889       StoreNodes.erase(StoreNodes.begin(),
12890                        StoreNodes.begin() + NumConsecutiveStores);
12891       continue;
12892     }
12893 
12894     // Check that we can merge these candidates without causing a cycle
12895     if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
12896                                                   NumConsecutiveStores)) {
12897       StoreNodes.erase(StoreNodes.begin(),
12898                        StoreNodes.begin() + NumConsecutiveStores);
12899       continue;
12900     }
12901 
12902     // The node with the lowest store address.
12903     LLVMContext &Context = *DAG.getContext();
12904     const DataLayout &DL = DAG.getDataLayout();
12905 
12906     // Store the constants into memory as one consecutive store.
12907     if (IsConstantSrc) {
12908       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12909       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12910       unsigned FirstStoreAlign = FirstInChain->getAlignment();
12911       unsigned LastLegalType = 1;
12912       unsigned LastLegalVectorType = 1;
12913       bool LastIntegerTrunc = false;
12914       bool NonZero = false;
12915       unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
12916       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12917         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12918         SDValue StoredVal = ST->getValue();
12919         bool IsElementZero = false;
12920         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
12921           IsElementZero = C->isNullValue();
12922         else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
12923           IsElementZero = C->getConstantFPValue()->isNullValue();
12924         if (IsElementZero) {
12925           if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
12926             FirstZeroAfterNonZero = i;
12927         }
12928         NonZero |= !IsElementZero;
12929 
12930         // Find a legal type for the constant store.
12931         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12932         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12933         bool IsFast = false;
12934         if (TLI.isTypeLegal(StoreTy) &&
12935             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
12936             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12937                                    FirstStoreAlign, &IsFast) &&
12938             IsFast) {
12939           LastIntegerTrunc = false;
12940           LastLegalType = i + 1;
12941           // Or check whether a truncstore is legal.
12942         } else if (TLI.getTypeAction(Context, StoreTy) ==
12943                    TargetLowering::TypePromoteInteger) {
12944           EVT LegalizedStoredValueTy =
12945               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12946           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12947               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
12948               TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12949                                      FirstStoreAlign, &IsFast) &&
12950               IsFast) {
12951             LastIntegerTrunc = true;
12952             LastLegalType = i + 1;
12953           }
12954         }
12955 
12956         // We only use vectors if the constant is known to be zero or the target
12957         // allows it and the function is not marked with the noimplicitfloat
12958         // attribute.
12959         if ((!NonZero ||
12960              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12961             !NoVectors) {
12962           // Find a legal type for the vector store.
12963           unsigned Elts = (i + 1) * NumMemElts;
12964           EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
12965           if (TLI.isTypeLegal(Ty) &&
12966               TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
12967               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12968                                      FirstStoreAlign, &IsFast) &&
12969               IsFast)
12970             LastLegalVectorType = i + 1;
12971         }
12972       }
12973 
12974       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12975       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12976 
12977       // Check if we found a legal integer type that creates a meaningful merge.
12978       if (NumElem < 2) {
12979         // We know that candidate stores are in order and of correct
12980         // shape. While there is no mergeable sequence from the
12981         // beginning one may start later in the sequence. The only
12982         // reason a merge of size N could have failed where another of
12983         // the same size would not have, is if the alignment has
12984         // improved or we've dropped a non-zero value. Drop as many
12985         // candidates as we can here.
12986         unsigned NumSkip = 1;
12987         while (
12988             (NumSkip < NumConsecutiveStores) &&
12989             (NumSkip < FirstZeroAfterNonZero) &&
12990             (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) {
12991           NumSkip++;
12992         }
12993         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
12994         continue;
12995       }
12996 
12997       bool Merged = MergeStoresOfConstantsOrVecElts(
12998           StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
12999       RV |= Merged;
13000 
13001       // Remove merged stores for next iteration.
13002       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13003       continue;
13004     }
13005 
13006     // When extracting multiple vector elements, try to store them
13007     // in one vector store rather than a sequence of scalar stores.
13008     if (IsExtractVecSrc) {
13009       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13010       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13011       unsigned FirstStoreAlign = FirstInChain->getAlignment();
13012       unsigned NumStoresToMerge = 1;
13013       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13014         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13015         SDValue StVal = peekThroughBitcast(St->getValue());
13016         // This restriction could be loosened.
13017         // Bail out if any stored values are not elements extracted from a
13018         // vector. It should be possible to handle mixed sources, but load
13019         // sources need more careful handling (see the block of code below that
13020         // handles consecutive loads).
13021         if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13022             StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13023           return RV;
13024 
13025         // Find a legal type for the vector store.
13026         unsigned Elts = (i + 1) * NumMemElts;
13027         EVT Ty =
13028             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
13029         bool IsFast;
13030         if (TLI.isTypeLegal(Ty) &&
13031             TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13032             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13033                                    FirstStoreAlign, &IsFast) &&
13034             IsFast)
13035           NumStoresToMerge = i + 1;
13036       }
13037 
13038       // Check if we found a legal integer type that creates a meaningful merge.
13039       if (NumStoresToMerge < 2) {
13040         // We know that candidate stores are in order and of correct
13041         // shape. While there is no mergeable sequence from the
13042         // beginning one may start later in the sequence. The only
13043         // reason a merge of size N could have failed where another of
13044         // the same size would not have, is if the alignment has
13045         // improved. Drop as many candidates as we can here.
13046         unsigned NumSkip = 1;
13047         while ((NumSkip < NumConsecutiveStores) &&
13048                (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13049           NumSkip++;
13050 
13051         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13052         continue;
13053       }
13054 
13055       bool Merged = MergeStoresOfConstantsOrVecElts(
13056           StoreNodes, MemVT, NumStoresToMerge, false, true, false);
13057       if (!Merged) {
13058         StoreNodes.erase(StoreNodes.begin(),
13059                          StoreNodes.begin() + NumStoresToMerge);
13060         continue;
13061       }
13062       // Remove merged stores for next iteration.
13063       StoreNodes.erase(StoreNodes.begin(),
13064                        StoreNodes.begin() + NumStoresToMerge);
13065       RV = true;
13066       continue;
13067     }
13068 
13069     // Below we handle the case of multiple consecutive stores that
13070     // come from multiple consecutive loads. We merge them into a single
13071     // wide load and a single wide store.
13072 
13073     // Look for load nodes which are used by the stored values.
13074     SmallVector<MemOpLink, 8> LoadNodes;
13075 
13076     // Find acceptable loads. Loads need to have the same chain (token factor),
13077     // must not be zext, volatile, indexed, and they must be consecutive.
13078     BaseIndexOffset LdBasePtr;
13079     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13080       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13081       SDValue Val = peekThroughBitcast(St->getValue());
13082       LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val);
13083       if (!Ld)
13084         break;
13085 
13086       // Loads must only have one use.
13087       if (!Ld->hasNUsesOfValue(1, 0))
13088         break;
13089 
13090       // The memory operands must not be volatile.
13091       if (Ld->isVolatile() || Ld->isIndexed())
13092         break;
13093 
13094       // The stored memory type must be the same.
13095       if (Ld->getMemoryVT() != MemVT)
13096         break;
13097 
13098       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
13099       // If this is not the first ptr that we check.
13100       int64_t LdOffset = 0;
13101       if (LdBasePtr.getBase().getNode()) {
13102         // The base ptr must be the same.
13103         if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
13104           break;
13105       } else {
13106         // Check that all other base pointers are the same as this one.
13107         LdBasePtr = LdPtr;
13108       }
13109 
13110       // We found a potential memory operand to merge.
13111       LoadNodes.push_back(MemOpLink(Ld, LdOffset));
13112     }
13113 
13114     if (LoadNodes.size() < 2) {
13115       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
13116       continue;
13117     }
13118 
13119     // If we have load/store pair instructions and we only have two values,
13120     // don't bother merging.
13121     unsigned RequiredAlignment;
13122     if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
13123         StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
13124       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
13125       continue;
13126     }
13127     LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13128     unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13129     unsigned FirstStoreAlign = FirstInChain->getAlignment();
13130     LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
13131     unsigned FirstLoadAS = FirstLoad->getAddressSpace();
13132     unsigned FirstLoadAlign = FirstLoad->getAlignment();
13133 
13134     // Scan the memory operations on the chain and find the first
13135     // non-consecutive load memory address. These variables hold the index in
13136     // the store node array.
13137     unsigned LastConsecutiveLoad = 1;
13138     // This variable refers to the size and not index in the array.
13139     unsigned LastLegalVectorType = 1;
13140     unsigned LastLegalIntegerType = 1;
13141     bool isDereferenceable = true;
13142     bool DoIntegerTruncate = false;
13143     StartAddress = LoadNodes[0].OffsetFromBase;
13144     SDValue FirstChain = FirstLoad->getChain();
13145     for (unsigned i = 1; i < LoadNodes.size(); ++i) {
13146       // All loads must share the same chain.
13147       if (LoadNodes[i].MemNode->getChain() != FirstChain)
13148         break;
13149 
13150       int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
13151       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13152         break;
13153       LastConsecutiveLoad = i;
13154 
13155       if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
13156         isDereferenceable = false;
13157 
13158       // Find a legal type for the vector store.
13159       unsigned Elts = (i + 1) * NumMemElts;
13160       EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13161 
13162       bool IsFastSt, IsFastLd;
13163       if (TLI.isTypeLegal(StoreTy) &&
13164           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13165           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13166                                  FirstStoreAlign, &IsFastSt) &&
13167           IsFastSt &&
13168           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13169                                  FirstLoadAlign, &IsFastLd) &&
13170           IsFastLd) {
13171         LastLegalVectorType = i + 1;
13172       }
13173 
13174       // Find a legal type for the integer store.
13175       unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13176       StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13177       if (TLI.isTypeLegal(StoreTy) &&
13178           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13179           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13180                                  FirstStoreAlign, &IsFastSt) &&
13181           IsFastSt &&
13182           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13183                                  FirstLoadAlign, &IsFastLd) &&
13184           IsFastLd) {
13185         LastLegalIntegerType = i + 1;
13186         DoIntegerTruncate = false;
13187         // Or check whether a truncstore and extload is legal.
13188       } else if (TLI.getTypeAction(Context, StoreTy) ==
13189                  TargetLowering::TypePromoteInteger) {
13190         EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
13191         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13192             TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13193             TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
13194                                StoreTy) &&
13195             TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
13196                                StoreTy) &&
13197             TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
13198             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13199                                    FirstStoreAlign, &IsFastSt) &&
13200             IsFastSt &&
13201             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13202                                    FirstLoadAlign, &IsFastLd) &&
13203             IsFastLd) {
13204           LastLegalIntegerType = i + 1;
13205           DoIntegerTruncate = true;
13206         }
13207       }
13208     }
13209 
13210     // Only use vector types if the vector type is larger than the integer type.
13211     // If they are the same, use integers.
13212     bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
13213     unsigned LastLegalType =
13214         std::max(LastLegalVectorType, LastLegalIntegerType);
13215 
13216     // We add +1 here because the LastXXX variables refer to location while
13217     // the NumElem refers to array/index size.
13218     unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
13219     NumElem = std::min(LastLegalType, NumElem);
13220 
13221     if (NumElem < 2) {
13222       // We know that candidate stores are in order and of correct
13223       // shape. While there is no mergeable sequence from the
13224       // beginning one may start later in the sequence. The only
13225       // reason a merge of size N could have failed where another of
13226       // the same size would not have is if the alignment or either
13227       // the load or store has improved. Drop as many candidates as we
13228       // can here.
13229       unsigned NumSkip = 1;
13230       while ((NumSkip < LoadNodes.size()) &&
13231              (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
13232              (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13233         NumSkip++;
13234       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13235       continue;
13236     }
13237 
13238     // Find if it is better to use vectors or integers to load and store
13239     // to memory.
13240     EVT JointMemOpVT;
13241     if (UseVectorTy) {
13242       // Find a legal type for the vector store.
13243       unsigned Elts = NumElem * NumMemElts;
13244       JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13245     } else {
13246       unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
13247       JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
13248     }
13249 
13250     SDLoc LoadDL(LoadNodes[0].MemNode);
13251     SDLoc StoreDL(StoreNodes[0].MemNode);
13252 
13253     // The merged loads are required to have the same incoming chain, so
13254     // using the first's chain is acceptable.
13255 
13256     SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
13257     AddToWorklist(NewStoreChain.getNode());
13258 
13259     MachineMemOperand::Flags MMOFlags = isDereferenceable ?
13260                                           MachineMemOperand::MODereferenceable:
13261                                           MachineMemOperand::MONone;
13262 
13263     SDValue NewLoad, NewStore;
13264     if (UseVectorTy || !DoIntegerTruncate) {
13265       NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
13266                             FirstLoad->getBasePtr(),
13267                             FirstLoad->getPointerInfo(), FirstLoadAlign,
13268                             MMOFlags);
13269       NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
13270                               FirstInChain->getBasePtr(),
13271                               FirstInChain->getPointerInfo(), FirstStoreAlign);
13272     } else { // This must be the truncstore/extload case
13273       EVT ExtendedTy =
13274           TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
13275       NewLoad =
13276           DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13277                          FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13278                          JointMemOpVT, FirstLoadAlign, MMOFlags);
13279       NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13280                                    FirstInChain->getBasePtr(),
13281                                    FirstInChain->getPointerInfo(), JointMemOpVT,
13282                                    FirstInChain->getAlignment(),
13283                                    FirstInChain->getMemOperand()->getFlags());
13284     }
13285 
13286     // Transfer chain users from old loads to the new load.
13287     for (unsigned i = 0; i < NumElem; ++i) {
13288       LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13289       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13290                                     SDValue(NewLoad.getNode(), 1));
13291     }
13292 
13293     // Replace the all stores with the new store. Recursively remove
13294     // corresponding value if its no longer used.
13295     for (unsigned i = 0; i < NumElem; ++i) {
13296       SDValue Val = StoreNodes[i].MemNode->getOperand(1);
13297       CombineTo(StoreNodes[i].MemNode, NewStore);
13298       if (Val.getNode()->use_empty())
13299         recursivelyDeleteUnusedNodes(Val.getNode());
13300     }
13301 
13302     RV = true;
13303     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13304     continue;
13305   }
13306   return RV;
13307 }
13308 
13309 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13310   SDLoc SL(ST);
13311   SDValue ReplStore;
13312 
13313   // Replace the chain to avoid dependency.
13314   if (ST->isTruncatingStore()) {
13315     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13316                                   ST->getBasePtr(), ST->getMemoryVT(),
13317                                   ST->getMemOperand());
13318   } else {
13319     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13320                              ST->getMemOperand());
13321   }
13322 
13323   // Create token to keep both nodes around.
13324   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13325                               MVT::Other, ST->getChain(), ReplStore);
13326 
13327   // Make sure the new and old chains are cleaned up.
13328   AddToWorklist(Token.getNode());
13329 
13330   // Don't add users to work list.
13331   return CombineTo(ST, Token, false);
13332 }
13333 
13334 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13335   SDValue Value = ST->getValue();
13336   if (Value.getOpcode() == ISD::TargetConstantFP)
13337     return SDValue();
13338 
13339   SDLoc DL(ST);
13340 
13341   SDValue Chain = ST->getChain();
13342   SDValue Ptr = ST->getBasePtr();
13343 
13344   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13345 
13346   // NOTE: If the original store is volatile, this transform must not increase
13347   // the number of stores.  For example, on x86-32 an f64 can be stored in one
13348   // processor operation but an i64 (which is not legal) requires two.  So the
13349   // transform should not be done in this case.
13350 
13351   SDValue Tmp;
13352   switch (CFP->getSimpleValueType(0).SimpleTy) {
13353   default:
13354     llvm_unreachable("Unknown FP type");
13355   case MVT::f16:    // We don't do this for these yet.
13356   case MVT::f80:
13357   case MVT::f128:
13358   case MVT::ppcf128:
13359     return SDValue();
13360   case MVT::f32:
13361     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13362         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13363       ;
13364       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13365                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13366                             MVT::i32);
13367       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13368     }
13369 
13370     return SDValue();
13371   case MVT::f64:
13372     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13373          !ST->isVolatile()) ||
13374         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13375       ;
13376       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13377                             getZExtValue(), SDLoc(CFP), MVT::i64);
13378       return DAG.getStore(Chain, DL, Tmp,
13379                           Ptr, ST->getMemOperand());
13380     }
13381 
13382     if (!ST->isVolatile() &&
13383         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13384       // Many FP stores are not made apparent until after legalize, e.g. for
13385       // argument passing.  Since this is so common, custom legalize the
13386       // 64-bit integer store into two 32-bit stores.
13387       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13388       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13389       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13390       if (DAG.getDataLayout().isBigEndian())
13391         std::swap(Lo, Hi);
13392 
13393       unsigned Alignment = ST->getAlignment();
13394       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13395       AAMDNodes AAInfo = ST->getAAInfo();
13396 
13397       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13398                                  ST->getAlignment(), MMOFlags, AAInfo);
13399       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13400                         DAG.getConstant(4, DL, Ptr.getValueType()));
13401       Alignment = MinAlign(Alignment, 4U);
13402       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13403                                  ST->getPointerInfo().getWithOffset(4),
13404                                  Alignment, MMOFlags, AAInfo);
13405       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13406                          St0, St1);
13407     }
13408 
13409     return SDValue();
13410   }
13411 }
13412 
13413 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13414   StoreSDNode *ST  = cast<StoreSDNode>(N);
13415   SDValue Chain = ST->getChain();
13416   SDValue Value = ST->getValue();
13417   SDValue Ptr   = ST->getBasePtr();
13418 
13419   // If this is a store of a bit convert, store the input value if the
13420   // resultant store does not need a higher alignment than the original.
13421   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13422       ST->isUnindexed()) {
13423     EVT SVT = Value.getOperand(0).getValueType();
13424     if (((!LegalOperations && !ST->isVolatile()) ||
13425          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13426         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13427       unsigned OrigAlign = ST->getAlignment();
13428       bool Fast = false;
13429       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13430                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13431           Fast) {
13432         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13433                             ST->getPointerInfo(), OrigAlign,
13434                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13435       }
13436     }
13437   }
13438 
13439   // Turn 'store undef, Ptr' -> nothing.
13440   if (Value.isUndef() && ST->isUnindexed())
13441     return Chain;
13442 
13443   // Try to infer better alignment information than the store already has.
13444   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13445     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13446       if (Align > ST->getAlignment()) {
13447         SDValue NewStore =
13448             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13449                               ST->getMemoryVT(), Align,
13450                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13451         if (NewStore.getNode() != N)
13452           return CombineTo(ST, NewStore, true);
13453       }
13454     }
13455   }
13456 
13457   // Try transforming a pair floating point load / store ops to integer
13458   // load / store ops.
13459   if (SDValue NewST = TransformFPLoadStorePair(N))
13460     return NewST;
13461 
13462   if (ST->isUnindexed()) {
13463     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13464     // adjacent stores.
13465     if (findBetterNeighborChains(ST)) {
13466       // replaceStoreChain uses CombineTo, which handled all of the worklist
13467       // manipulation. Return the original node to not do anything else.
13468       return SDValue(ST, 0);
13469     }
13470     Chain = ST->getChain();
13471   }
13472 
13473   // FIXME: is there such a thing as a truncating indexed store?
13474   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13475       Value.getValueType().isInteger()) {
13476     // See if we can simplify the input to this truncstore with knowledge that
13477     // only the low bits are being used.  For example:
13478     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13479     SDValue Shorter = DAG.GetDemandedBits(
13480         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13481                                     ST->getMemoryVT().getScalarSizeInBits()));
13482     AddToWorklist(Value.getNode());
13483     if (Shorter.getNode())
13484       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13485                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13486 
13487     // Otherwise, see if we can simplify the operation with
13488     // SimplifyDemandedBits, which only works if the value has a single use.
13489     if (SimplifyDemandedBits(
13490             Value,
13491             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13492                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13493       // Re-visit the store if anything changed and the store hasn't been merged
13494       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13495       // node back to the worklist if necessary, but we also need to re-visit
13496       // the Store node itself.
13497       if (N->getOpcode() != ISD::DELETED_NODE)
13498         AddToWorklist(N);
13499       return SDValue(N, 0);
13500     }
13501   }
13502 
13503   // If this is a load followed by a store to the same location, then the store
13504   // is dead/noop.
13505   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13506     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13507         ST->isUnindexed() && !ST->isVolatile() &&
13508         // There can't be any side effects between the load and store, such as
13509         // a call or store.
13510         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13511       // The store is dead, remove it.
13512       return Chain;
13513     }
13514   }
13515 
13516   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13517     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13518         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13519         ST->getMemoryVT() == ST1->getMemoryVT()) {
13520       // If this is a store followed by a store with the same value to the same
13521       // location, then the store is dead/noop.
13522       if (ST1->getValue() == Value) {
13523         // The store is dead, remove it.
13524         return Chain;
13525       }
13526 
13527       // If this is a store who's preceeding store to the same location
13528       // and no one other node is chained to that store we can effectively
13529       // drop the store. Do not remove stores to undef as they may be used as
13530       // data sinks.
13531       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13532           !ST1->getBasePtr().isUndef()) {
13533         // ST1 is fully overwritten and can be elided. Combine with it's chain
13534         // value.
13535         CombineTo(ST1, ST1->getChain());
13536         return SDValue();
13537       }
13538     }
13539   }
13540 
13541   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13542   // truncating store.  We can do this even if this is already a truncstore.
13543   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13544       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13545       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13546                             ST->getMemoryVT())) {
13547     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13548                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
13549   }
13550 
13551   // Only perform this optimization before the types are legal, because we
13552   // don't want to perform this optimization on every DAGCombine invocation.
13553   if ((TLI.mergeStoresAfterLegalization()) ? Level == AfterLegalizeDAG
13554                                            : !LegalTypes) {
13555     for (;;) {
13556       // There can be multiple store sequences on the same chain.
13557       // Keep trying to merge store sequences until we are unable to do so
13558       // or until we merge the last store on the chain.
13559       bool Changed = MergeConsecutiveStores(ST);
13560       if (!Changed) break;
13561       // Return N as merge only uses CombineTo and no worklist clean
13562       // up is necessary.
13563       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13564         return SDValue(N, 0);
13565     }
13566   }
13567 
13568   // Try transforming N to an indexed store.
13569   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13570     return SDValue(N, 0);
13571 
13572   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13573   //
13574   // Make sure to do this only after attempting to merge stores in order to
13575   //  avoid changing the types of some subset of stores due to visit order,
13576   //  preventing their merging.
13577   if (isa<ConstantFPSDNode>(ST->getValue())) {
13578     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13579       return NewSt;
13580   }
13581 
13582   if (SDValue NewSt = splitMergedValStore(ST))
13583     return NewSt;
13584 
13585   return ReduceLoadOpStoreWidth(N);
13586 }
13587 
13588 /// For the instruction sequence of store below, F and I values
13589 /// are bundled together as an i64 value before being stored into memory.
13590 /// Sometimes it is more efficent to generate separate stores for F and I,
13591 /// which can remove the bitwise instructions or sink them to colder places.
13592 ///
13593 ///   (store (or (zext (bitcast F to i32) to i64),
13594 ///              (shl (zext I to i64), 32)), addr)  -->
13595 ///   (store F, addr) and (store I, addr+4)
13596 ///
13597 /// Similarly, splitting for other merged store can also be beneficial, like:
13598 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13599 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13600 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13601 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13602 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13603 ///
13604 /// We allow each target to determine specifically which kind of splitting is
13605 /// supported.
13606 ///
13607 /// The store patterns are commonly seen from the simple code snippet below
13608 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13609 ///   void goo(const std::pair<int, float> &);
13610 ///   hoo() {
13611 ///     ...
13612 ///     goo(std::make_pair(tmp, ftmp));
13613 ///     ...
13614 ///   }
13615 ///
13616 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13617   if (OptLevel == CodeGenOpt::None)
13618     return SDValue();
13619 
13620   SDValue Val = ST->getValue();
13621   SDLoc DL(ST);
13622 
13623   // Match OR operand.
13624   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13625     return SDValue();
13626 
13627   // Match SHL operand and get Lower and Higher parts of Val.
13628   SDValue Op1 = Val.getOperand(0);
13629   SDValue Op2 = Val.getOperand(1);
13630   SDValue Lo, Hi;
13631   if (Op1.getOpcode() != ISD::SHL) {
13632     std::swap(Op1, Op2);
13633     if (Op1.getOpcode() != ISD::SHL)
13634       return SDValue();
13635   }
13636   Lo = Op2;
13637   Hi = Op1.getOperand(0);
13638   if (!Op1.hasOneUse())
13639     return SDValue();
13640 
13641   // Match shift amount to HalfValBitSize.
13642   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13643   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13644   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13645     return SDValue();
13646 
13647   // Lo and Hi are zero-extended from int with size less equal than 32
13648   // to i64.
13649   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13650       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13651       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13652       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13653       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13654       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13655     return SDValue();
13656 
13657   // Use the EVT of low and high parts before bitcast as the input
13658   // of target query.
13659   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13660                   ? Lo.getOperand(0).getValueType()
13661                   : Lo.getValueType();
13662   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13663                    ? Hi.getOperand(0).getValueType()
13664                    : Hi.getValueType();
13665   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13666     return SDValue();
13667 
13668   // Start to split store.
13669   unsigned Alignment = ST->getAlignment();
13670   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13671   AAMDNodes AAInfo = ST->getAAInfo();
13672 
13673   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13674   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13675   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13676   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13677 
13678   SDValue Chain = ST->getChain();
13679   SDValue Ptr = ST->getBasePtr();
13680   // Lower value store.
13681   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13682                              ST->getAlignment(), MMOFlags, AAInfo);
13683   Ptr =
13684       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13685                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13686   // Higher value store.
13687   SDValue St1 =
13688       DAG.getStore(St0, DL, Hi, Ptr,
13689                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13690                    Alignment / 2, MMOFlags, AAInfo);
13691   return St1;
13692 }
13693 
13694 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13695   SDValue InVec = N->getOperand(0);
13696   SDValue InVal = N->getOperand(1);
13697   SDValue EltNo = N->getOperand(2);
13698   SDLoc DL(N);
13699 
13700   // If the inserted element is an UNDEF, just use the input vector.
13701   if (InVal.isUndef())
13702     return InVec;
13703 
13704   EVT VT = InVec.getValueType();
13705 
13706   // Remove redundant insertions:
13707   // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
13708   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
13709       InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
13710     return InVec;
13711 
13712   // Check that we know which element is being inserted
13713   if (!isa<ConstantSDNode>(EltNo))
13714     return SDValue();
13715   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13716 
13717   // Canonicalize insert_vector_elt dag nodes.
13718   // Example:
13719   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13720   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13721   //
13722   // Do this only if the child insert_vector node has one use; also
13723   // do this only if indices are both constants and Idx1 < Idx0.
13724   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13725       && isa<ConstantSDNode>(InVec.getOperand(2))) {
13726     unsigned OtherElt = InVec.getConstantOperandVal(2);
13727     if (Elt < OtherElt) {
13728       // Swap nodes.
13729       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13730                                   InVec.getOperand(0), InVal, EltNo);
13731       AddToWorklist(NewOp.getNode());
13732       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13733                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13734     }
13735   }
13736 
13737   // If we can't generate a legal BUILD_VECTOR, exit
13738   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13739     return SDValue();
13740 
13741   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13742   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
13743   // vector elements.
13744   SmallVector<SDValue, 8> Ops;
13745   // Do not combine these two vectors if the output vector will not replace
13746   // the input vector.
13747   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13748     Ops.append(InVec.getNode()->op_begin(),
13749                InVec.getNode()->op_end());
13750   } else if (InVec.isUndef()) {
13751     unsigned NElts = VT.getVectorNumElements();
13752     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13753   } else {
13754     return SDValue();
13755   }
13756 
13757   // Insert the element
13758   if (Elt < Ops.size()) {
13759     // All the operands of BUILD_VECTOR must have the same type;
13760     // we enforce that here.
13761     EVT OpVT = Ops[0].getValueType();
13762     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13763   }
13764 
13765   // Return the new vector
13766   return DAG.getBuildVector(VT, DL, Ops);
13767 }
13768 
13769 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13770     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13771   assert(!OriginalLoad->isVolatile());
13772 
13773   EVT ResultVT = EVE->getValueType(0);
13774   EVT VecEltVT = InVecVT.getVectorElementType();
13775   unsigned Align = OriginalLoad->getAlignment();
13776   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13777       VecEltVT.getTypeForEVT(*DAG.getContext()));
13778 
13779   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13780     return SDValue();
13781 
13782   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13783     ISD::NON_EXTLOAD : ISD::EXTLOAD;
13784   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13785     return SDValue();
13786 
13787   Align = NewAlign;
13788 
13789   SDValue NewPtr = OriginalLoad->getBasePtr();
13790   SDValue Offset;
13791   EVT PtrType = NewPtr.getValueType();
13792   MachinePointerInfo MPI;
13793   SDLoc DL(EVE);
13794   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13795     int Elt = ConstEltNo->getZExtValue();
13796     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13797     Offset = DAG.getConstant(PtrOff, DL, PtrType);
13798     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13799   } else {
13800     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13801     Offset = DAG.getNode(
13802         ISD::MUL, DL, PtrType, Offset,
13803         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13804     MPI = OriginalLoad->getPointerInfo();
13805   }
13806   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13807 
13808   // The replacement we need to do here is a little tricky: we need to
13809   // replace an extractelement of a load with a load.
13810   // Use ReplaceAllUsesOfValuesWith to do the replacement.
13811   // Note that this replacement assumes that the extractvalue is the only
13812   // use of the load; that's okay because we don't want to perform this
13813   // transformation in other cases anyway.
13814   SDValue Load;
13815   SDValue Chain;
13816   if (ResultVT.bitsGT(VecEltVT)) {
13817     // If the result type of vextract is wider than the load, then issue an
13818     // extending load instead.
13819     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13820                                                   VecEltVT)
13821                                    ? ISD::ZEXTLOAD
13822                                    : ISD::EXTLOAD;
13823     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13824                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13825                           Align, OriginalLoad->getMemOperand()->getFlags(),
13826                           OriginalLoad->getAAInfo());
13827     Chain = Load.getValue(1);
13828   } else {
13829     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13830                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13831                        OriginalLoad->getAAInfo());
13832     Chain = Load.getValue(1);
13833     if (ResultVT.bitsLT(VecEltVT))
13834       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13835     else
13836       Load = DAG.getBitcast(ResultVT, Load);
13837   }
13838   WorklistRemover DeadNodes(*this);
13839   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13840   SDValue To[] = { Load, Chain };
13841   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13842   // Since we're explicitly calling ReplaceAllUses, add the new node to the
13843   // worklist explicitly as well.
13844   AddToWorklist(Load.getNode());
13845   AddUsersToWorklist(Load.getNode()); // Add users too
13846   // Make sure to revisit this node to clean it up; it will usually be dead.
13847   AddToWorklist(EVE);
13848   ++OpsNarrowed;
13849   return SDValue(EVE, 0);
13850 }
13851 
13852 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13853   // (vextract (scalar_to_vector val, 0) -> val
13854   SDValue InVec = N->getOperand(0);
13855   EVT VT = InVec.getValueType();
13856   EVT NVT = N->getValueType(0);
13857 
13858   if (InVec.isUndef())
13859     return DAG.getUNDEF(NVT);
13860 
13861   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13862     // Check if the result type doesn't match the inserted element type. A
13863     // SCALAR_TO_VECTOR may truncate the inserted element and the
13864     // EXTRACT_VECTOR_ELT may widen the extracted vector.
13865     SDValue InOp = InVec.getOperand(0);
13866     if (InOp.getValueType() != NVT) {
13867       assert(InOp.getValueType().isInteger() && NVT.isInteger());
13868       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13869     }
13870     return InOp;
13871   }
13872 
13873   SDValue EltNo = N->getOperand(1);
13874   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13875 
13876   // extract_vector_elt (build_vector x, y), 1 -> y
13877   if (ConstEltNo &&
13878       InVec.getOpcode() == ISD::BUILD_VECTOR &&
13879       TLI.isTypeLegal(VT) &&
13880       (InVec.hasOneUse() ||
13881        TLI.aggressivelyPreferBuildVectorSources(VT))) {
13882     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13883     EVT InEltVT = Elt.getValueType();
13884 
13885     // Sometimes build_vector's scalar input types do not match result type.
13886     if (NVT == InEltVT)
13887       return Elt;
13888 
13889     // TODO: It may be useful to truncate if free if the build_vector implicitly
13890     // converts.
13891   }
13892 
13893   // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x)
13894   bool isLE = DAG.getDataLayout().isLittleEndian();
13895   unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1;
13896   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13897       ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) {
13898     SDValue BCSrc = InVec.getOperand(0);
13899     if (BCSrc.getValueType().isScalarInteger())
13900       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13901   }
13902 
13903   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13904   //
13905   // This only really matters if the index is non-constant since other combines
13906   // on the constant elements already work.
13907   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13908       EltNo == InVec.getOperand(2)) {
13909     SDValue Elt = InVec.getOperand(1);
13910     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13911   }
13912 
13913   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13914   // We only perform this optimization before the op legalization phase because
13915   // we may introduce new vector instructions which are not backed by TD
13916   // patterns. For example on AVX, extracting elements from a wide vector
13917   // without using extract_subvector. However, if we can find an underlying
13918   // scalar value, then we can always use that.
13919   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13920     int NumElem = VT.getVectorNumElements();
13921     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13922     // Find the new index to extract from.
13923     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13924 
13925     // Extracting an undef index is undef.
13926     if (OrigElt == -1)
13927       return DAG.getUNDEF(NVT);
13928 
13929     // Select the right vector half to extract from.
13930     SDValue SVInVec;
13931     if (OrigElt < NumElem) {
13932       SVInVec = InVec->getOperand(0);
13933     } else {
13934       SVInVec = InVec->getOperand(1);
13935       OrigElt -= NumElem;
13936     }
13937 
13938     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13939       SDValue InOp = SVInVec.getOperand(OrigElt);
13940       if (InOp.getValueType() != NVT) {
13941         assert(InOp.getValueType().isInteger() && NVT.isInteger());
13942         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13943       }
13944 
13945       return InOp;
13946     }
13947 
13948     // FIXME: We should handle recursing on other vector shuffles and
13949     // scalar_to_vector here as well.
13950 
13951     if (!LegalOperations) {
13952       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13953       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13954                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13955     }
13956   }
13957 
13958   bool BCNumEltsChanged = false;
13959   EVT ExtVT = VT.getVectorElementType();
13960   EVT LVT = ExtVT;
13961 
13962   // If the result of load has to be truncated, then it's not necessarily
13963   // profitable.
13964   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13965     return SDValue();
13966 
13967   if (InVec.getOpcode() == ISD::BITCAST) {
13968     // Don't duplicate a load with other uses.
13969     if (!InVec.hasOneUse())
13970       return SDValue();
13971 
13972     EVT BCVT = InVec.getOperand(0).getValueType();
13973     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13974       return SDValue();
13975     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13976       BCNumEltsChanged = true;
13977     InVec = InVec.getOperand(0);
13978     ExtVT = BCVT.getVectorElementType();
13979   }
13980 
13981   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13982   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13983       ISD::isNormalLoad(InVec.getNode()) &&
13984       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13985     SDValue Index = N->getOperand(1);
13986     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13987       if (!OrigLoad->isVolatile()) {
13988         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13989                                                              OrigLoad);
13990       }
13991     }
13992   }
13993 
13994   // Perform only after legalization to ensure build_vector / vector_shuffle
13995   // optimizations have already been done.
13996   if (!LegalOperations) return SDValue();
13997 
13998   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13999   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
14000   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
14001 
14002   if (ConstEltNo) {
14003     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14004 
14005     LoadSDNode *LN0 = nullptr;
14006     const ShuffleVectorSDNode *SVN = nullptr;
14007     if (ISD::isNormalLoad(InVec.getNode())) {
14008       LN0 = cast<LoadSDNode>(InVec);
14009     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14010                InVec.getOperand(0).getValueType() == ExtVT &&
14011                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
14012       // Don't duplicate a load with other uses.
14013       if (!InVec.hasOneUse())
14014         return SDValue();
14015 
14016       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
14017     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
14018       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
14019       // =>
14020       // (load $addr+1*size)
14021 
14022       // Don't duplicate a load with other uses.
14023       if (!InVec.hasOneUse())
14024         return SDValue();
14025 
14026       // If the bit convert changed the number of elements, it is unsafe
14027       // to examine the mask.
14028       if (BCNumEltsChanged)
14029         return SDValue();
14030 
14031       // Select the input vector, guarding against out of range extract vector.
14032       unsigned NumElems = VT.getVectorNumElements();
14033       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
14034       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
14035 
14036       if (InVec.getOpcode() == ISD::BITCAST) {
14037         // Don't duplicate a load with other uses.
14038         if (!InVec.hasOneUse())
14039           return SDValue();
14040 
14041         InVec = InVec.getOperand(0);
14042       }
14043       if (ISD::isNormalLoad(InVec.getNode())) {
14044         LN0 = cast<LoadSDNode>(InVec);
14045         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
14046         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
14047       }
14048     }
14049 
14050     // Make sure we found a non-volatile load and the extractelement is
14051     // the only use.
14052     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
14053       return SDValue();
14054 
14055     // If Idx was -1 above, Elt is going to be -1, so just return undef.
14056     if (Elt == -1)
14057       return DAG.getUNDEF(LVT);
14058 
14059     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
14060   }
14061 
14062   return SDValue();
14063 }
14064 
14065 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
14066 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
14067   // We perform this optimization post type-legalization because
14068   // the type-legalizer often scalarizes integer-promoted vectors.
14069   // Performing this optimization before may create bit-casts which
14070   // will be type-legalized to complex code sequences.
14071   // We perform this optimization only before the operation legalizer because we
14072   // may introduce illegal operations.
14073   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
14074     return SDValue();
14075 
14076   unsigned NumInScalars = N->getNumOperands();
14077   SDLoc DL(N);
14078   EVT VT = N->getValueType(0);
14079 
14080   // Check to see if this is a BUILD_VECTOR of a bunch of values
14081   // which come from any_extend or zero_extend nodes. If so, we can create
14082   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
14083   // optimizations. We do not handle sign-extend because we can't fill the sign
14084   // using shuffles.
14085   EVT SourceType = MVT::Other;
14086   bool AllAnyExt = true;
14087 
14088   for (unsigned i = 0; i != NumInScalars; ++i) {
14089     SDValue In = N->getOperand(i);
14090     // Ignore undef inputs.
14091     if (In.isUndef()) continue;
14092 
14093     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
14094     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
14095 
14096     // Abort if the element is not an extension.
14097     if (!ZeroExt && !AnyExt) {
14098       SourceType = MVT::Other;
14099       break;
14100     }
14101 
14102     // The input is a ZeroExt or AnyExt. Check the original type.
14103     EVT InTy = In.getOperand(0).getValueType();
14104 
14105     // Check that all of the widened source types are the same.
14106     if (SourceType == MVT::Other)
14107       // First time.
14108       SourceType = InTy;
14109     else if (InTy != SourceType) {
14110       // Multiple income types. Abort.
14111       SourceType = MVT::Other;
14112       break;
14113     }
14114 
14115     // Check if all of the extends are ANY_EXTENDs.
14116     AllAnyExt &= AnyExt;
14117   }
14118 
14119   // In order to have valid types, all of the inputs must be extended from the
14120   // same source type and all of the inputs must be any or zero extend.
14121   // Scalar sizes must be a power of two.
14122   EVT OutScalarTy = VT.getScalarType();
14123   bool ValidTypes = SourceType != MVT::Other &&
14124                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
14125                  isPowerOf2_32(SourceType.getSizeInBits());
14126 
14127   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
14128   // turn into a single shuffle instruction.
14129   if (!ValidTypes)
14130     return SDValue();
14131 
14132   bool isLE = DAG.getDataLayout().isLittleEndian();
14133   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
14134   assert(ElemRatio > 1 && "Invalid element size ratio");
14135   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
14136                                DAG.getConstant(0, DL, SourceType);
14137 
14138   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
14139   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
14140 
14141   // Populate the new build_vector
14142   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14143     SDValue Cast = N->getOperand(i);
14144     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
14145             Cast.getOpcode() == ISD::ZERO_EXTEND ||
14146             Cast.isUndef()) && "Invalid cast opcode");
14147     SDValue In;
14148     if (Cast.isUndef())
14149       In = DAG.getUNDEF(SourceType);
14150     else
14151       In = Cast->getOperand(0);
14152     unsigned Index = isLE ? (i * ElemRatio) :
14153                             (i * ElemRatio + (ElemRatio - 1));
14154 
14155     assert(Index < Ops.size() && "Invalid index");
14156     Ops[Index] = In;
14157   }
14158 
14159   // The type of the new BUILD_VECTOR node.
14160   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
14161   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
14162          "Invalid vector size");
14163   // Check if the new vector type is legal.
14164   if (!isTypeLegal(VecVT)) return SDValue();
14165 
14166   // Make the new BUILD_VECTOR.
14167   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
14168 
14169   // The new BUILD_VECTOR node has the potential to be further optimized.
14170   AddToWorklist(BV.getNode());
14171   // Bitcast to the desired type.
14172   return DAG.getBitcast(VT, BV);
14173 }
14174 
14175 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
14176   EVT VT = N->getValueType(0);
14177 
14178   unsigned NumInScalars = N->getNumOperands();
14179   SDLoc DL(N);
14180 
14181   EVT SrcVT = MVT::Other;
14182   unsigned Opcode = ISD::DELETED_NODE;
14183   unsigned NumDefs = 0;
14184 
14185   for (unsigned i = 0; i != NumInScalars; ++i) {
14186     SDValue In = N->getOperand(i);
14187     unsigned Opc = In.getOpcode();
14188 
14189     if (Opc == ISD::UNDEF)
14190       continue;
14191 
14192     // If all scalar values are floats and converted from integers.
14193     if (Opcode == ISD::DELETED_NODE &&
14194         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
14195       Opcode = Opc;
14196     }
14197 
14198     if (Opc != Opcode)
14199       return SDValue();
14200 
14201     EVT InVT = In.getOperand(0).getValueType();
14202 
14203     // If all scalar values are typed differently, bail out. It's chosen to
14204     // simplify BUILD_VECTOR of integer types.
14205     if (SrcVT == MVT::Other)
14206       SrcVT = InVT;
14207     if (SrcVT != InVT)
14208       return SDValue();
14209     NumDefs++;
14210   }
14211 
14212   // If the vector has just one element defined, it's not worth to fold it into
14213   // a vectorized one.
14214   if (NumDefs < 2)
14215     return SDValue();
14216 
14217   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
14218          && "Should only handle conversion from integer to float.");
14219   assert(SrcVT != MVT::Other && "Cannot determine source type!");
14220 
14221   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
14222 
14223   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
14224     return SDValue();
14225 
14226   // Just because the floating-point vector type is legal does not necessarily
14227   // mean that the corresponding integer vector type is.
14228   if (!isTypeLegal(NVT))
14229     return SDValue();
14230 
14231   SmallVector<SDValue, 8> Opnds;
14232   for (unsigned i = 0; i != NumInScalars; ++i) {
14233     SDValue In = N->getOperand(i);
14234 
14235     if (In.isUndef())
14236       Opnds.push_back(DAG.getUNDEF(SrcVT));
14237     else
14238       Opnds.push_back(In.getOperand(0));
14239   }
14240   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
14241   AddToWorklist(BV.getNode());
14242 
14243   return DAG.getNode(Opcode, DL, VT, BV);
14244 }
14245 
14246 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
14247                                            ArrayRef<int> VectorMask,
14248                                            SDValue VecIn1, SDValue VecIn2,
14249                                            unsigned LeftIdx) {
14250   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14251   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
14252 
14253   EVT VT = N->getValueType(0);
14254   EVT InVT1 = VecIn1.getValueType();
14255   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
14256 
14257   unsigned Vec2Offset = 0;
14258   unsigned NumElems = VT.getVectorNumElements();
14259   unsigned ShuffleNumElems = NumElems;
14260 
14261   // In case both the input vectors are extracted from same base
14262   // vector we do not need extra addend (Vec2Offset) while
14263   // computing shuffle mask.
14264   if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14265       !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14266       !(VecIn1.getOperand(0) == VecIn2.getOperand(0)))
14267     Vec2Offset = InVT1.getVectorNumElements();
14268 
14269   // We can't generate a shuffle node with mismatched input and output types.
14270   // Try to make the types match the type of the output.
14271   if (InVT1 != VT || InVT2 != VT) {
14272     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
14273       // If the output vector length is a multiple of both input lengths,
14274       // we can concatenate them and pad the rest with undefs.
14275       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
14276       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
14277       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
14278       ConcatOps[0] = VecIn1;
14279       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
14280       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14281       VecIn2 = SDValue();
14282     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
14283       if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
14284         return SDValue();
14285 
14286       if (!VecIn2.getNode()) {
14287         // If we only have one input vector, and it's twice the size of the
14288         // output, split it in two.
14289         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
14290                              DAG.getConstant(NumElems, DL, IdxTy));
14291         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
14292         // Since we now have shorter input vectors, adjust the offset of the
14293         // second vector's start.
14294         Vec2Offset = NumElems;
14295       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
14296         // VecIn1 is wider than the output, and we have another, possibly
14297         // smaller input. Pad the smaller input with undefs, shuffle at the
14298         // input vector width, and extract the output.
14299         // The shuffle type is different than VT, so check legality again.
14300         if (LegalOperations &&
14301             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14302           return SDValue();
14303 
14304         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14305         // lower it back into a BUILD_VECTOR. So if the inserted type is
14306         // illegal, don't even try.
14307         if (InVT1 != InVT2) {
14308           if (!TLI.isTypeLegal(InVT2))
14309             return SDValue();
14310           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14311                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14312         }
14313         ShuffleNumElems = NumElems * 2;
14314       } else {
14315         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14316         // than VecIn1. We can't handle this for now - this case will disappear
14317         // when we start sorting the vectors by type.
14318         return SDValue();
14319       }
14320     } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
14321                InVT1.getSizeInBits() == VT.getSizeInBits()) {
14322       SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
14323       ConcatOps[0] = VecIn2;
14324       VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14325     } else {
14326       // TODO: Support cases where the length mismatch isn't exactly by a
14327       // factor of 2.
14328       // TODO: Move this check upwards, so that if we have bad type
14329       // mismatches, we don't create any DAG nodes.
14330       return SDValue();
14331     }
14332   }
14333 
14334   // Initialize mask to undef.
14335   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14336 
14337   // Only need to run up to the number of elements actually used, not the
14338   // total number of elements in the shuffle - if we are shuffling a wider
14339   // vector, the high lanes should be set to undef.
14340   for (unsigned i = 0; i != NumElems; ++i) {
14341     if (VectorMask[i] <= 0)
14342       continue;
14343 
14344     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14345     if (VectorMask[i] == (int)LeftIdx) {
14346       Mask[i] = ExtIndex;
14347     } else if (VectorMask[i] == (int)LeftIdx + 1) {
14348       Mask[i] = Vec2Offset + ExtIndex;
14349     }
14350   }
14351 
14352   // The type the input vectors may have changed above.
14353   InVT1 = VecIn1.getValueType();
14354 
14355   // If we already have a VecIn2, it should have the same type as VecIn1.
14356   // If we don't, get an undef/zero vector of the appropriate type.
14357   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14358   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
14359 
14360   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14361   if (ShuffleNumElems > NumElems)
14362     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14363 
14364   return Shuffle;
14365 }
14366 
14367 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14368 // operations. If the types of the vectors we're extracting from allow it,
14369 // turn this into a vector_shuffle node.
14370 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14371   SDLoc DL(N);
14372   EVT VT = N->getValueType(0);
14373 
14374   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14375   if (!isTypeLegal(VT))
14376     return SDValue();
14377 
14378   // May only combine to shuffle after legalize if shuffle is legal.
14379   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14380     return SDValue();
14381 
14382   bool UsesZeroVector = false;
14383   unsigned NumElems = N->getNumOperands();
14384 
14385   // Record, for each element of the newly built vector, which input vector
14386   // that element comes from. -1 stands for undef, 0 for the zero vector,
14387   // and positive values for the input vectors.
14388   // VectorMask maps each element to its vector number, and VecIn maps vector
14389   // numbers to their initial SDValues.
14390 
14391   SmallVector<int, 8> VectorMask(NumElems, -1);
14392   SmallVector<SDValue, 8> VecIn;
14393   VecIn.push_back(SDValue());
14394 
14395   for (unsigned i = 0; i != NumElems; ++i) {
14396     SDValue Op = N->getOperand(i);
14397 
14398     if (Op.isUndef())
14399       continue;
14400 
14401     // See if we can use a blend with a zero vector.
14402     // TODO: Should we generalize this to a blend with an arbitrary constant
14403     // vector?
14404     if (isNullConstant(Op) || isNullFPConstant(Op)) {
14405       UsesZeroVector = true;
14406       VectorMask[i] = 0;
14407       continue;
14408     }
14409 
14410     // Not an undef or zero. If the input is something other than an
14411     // EXTRACT_VECTOR_ELT with a constant index, bail out.
14412     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14413         !isa<ConstantSDNode>(Op.getOperand(1)))
14414       return SDValue();
14415     SDValue ExtractedFromVec = Op.getOperand(0);
14416 
14417     // All inputs must have the same element type as the output.
14418     if (VT.getVectorElementType() !=
14419         ExtractedFromVec.getValueType().getVectorElementType())
14420       return SDValue();
14421 
14422     // Have we seen this input vector before?
14423     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14424     // a map back from SDValues to numbers isn't worth it.
14425     unsigned Idx = std::distance(
14426         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14427     if (Idx == VecIn.size())
14428       VecIn.push_back(ExtractedFromVec);
14429 
14430     VectorMask[i] = Idx;
14431   }
14432 
14433   // If we didn't find at least one input vector, bail out.
14434   if (VecIn.size() < 2)
14435     return SDValue();
14436 
14437   // If all the Operands of BUILD_VECTOR extract from same
14438   // vector, then split the vector efficiently based on the maximum
14439   // vector access index and adjust the VectorMask and
14440   // VecIn accordingly.
14441   if (VecIn.size() == 2) {
14442     unsigned MaxIndex = 0;
14443     unsigned NearestPow2 = 0;
14444     SDValue Vec = VecIn.back();
14445     EVT InVT = Vec.getValueType();
14446     MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14447     SmallVector<unsigned, 8> IndexVec(NumElems, 0);
14448 
14449     for (unsigned i = 0; i < NumElems; i++) {
14450       if (VectorMask[i] <= 0)
14451         continue;
14452       unsigned Index = N->getOperand(i).getConstantOperandVal(1);
14453       IndexVec[i] = Index;
14454       MaxIndex = std::max(MaxIndex, Index);
14455     }
14456 
14457     NearestPow2 = PowerOf2Ceil(MaxIndex);
14458     if (InVT.isSimple() && (NearestPow2 > 2) &&
14459         ((NumElems * 2) < NearestPow2)) {
14460       unsigned SplitSize = NearestPow2 / 2;
14461       EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
14462                                      InVT.getVectorElementType(), SplitSize);
14463       if (TLI.isTypeLegal(SplitVT)) {
14464         SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
14465                                      DAG.getConstant(SplitSize, DL, IdxTy));
14466         SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
14467                                      DAG.getConstant(0, DL, IdxTy));
14468         VecIn.pop_back();
14469         VecIn.push_back(VecIn1);
14470         VecIn.push_back(VecIn2);
14471 
14472         for (unsigned i = 0; i < NumElems; i++) {
14473           if (VectorMask[i] <= 0)
14474             continue;
14475           VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
14476         }
14477       }
14478     }
14479   }
14480 
14481   // TODO: We want to sort the vectors by descending length, so that adjacent
14482   // pairs have similar length, and the longer vector is always first in the
14483   // pair.
14484 
14485   // TODO: Should this fire if some of the input vectors has illegal type (like
14486   // it does now), or should we let legalization run its course first?
14487 
14488   // Shuffle phase:
14489   // Take pairs of vectors, and shuffle them so that the result has elements
14490   // from these vectors in the correct places.
14491   // For example, given:
14492   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14493   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14494   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14495   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14496   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14497   // We will generate:
14498   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14499   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14500   SmallVector<SDValue, 4> Shuffles;
14501   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14502     unsigned LeftIdx = 2 * In + 1;
14503     SDValue VecLeft = VecIn[LeftIdx];
14504     SDValue VecRight =
14505         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14506 
14507     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14508                                                 VecRight, LeftIdx))
14509       Shuffles.push_back(Shuffle);
14510     else
14511       return SDValue();
14512   }
14513 
14514   // If we need the zero vector as an "ingredient" in the blend tree, add it
14515   // to the list of shuffles.
14516   if (UsesZeroVector)
14517     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14518                                       : DAG.getConstantFP(0.0, DL, VT));
14519 
14520   // If we only have one shuffle, we're done.
14521   if (Shuffles.size() == 1)
14522     return Shuffles[0];
14523 
14524   // Update the vector mask to point to the post-shuffle vectors.
14525   for (int &Vec : VectorMask)
14526     if (Vec == 0)
14527       Vec = Shuffles.size() - 1;
14528     else
14529       Vec = (Vec - 1) / 2;
14530 
14531   // More than one shuffle. Generate a binary tree of blends, e.g. if from
14532   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14533   // generate:
14534   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14535   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14536   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14537   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14538   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14539   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14540   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14541 
14542   // Make sure the initial size of the shuffle list is even.
14543   if (Shuffles.size() % 2)
14544     Shuffles.push_back(DAG.getUNDEF(VT));
14545 
14546   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14547     if (CurSize % 2) {
14548       Shuffles[CurSize] = DAG.getUNDEF(VT);
14549       CurSize++;
14550     }
14551     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14552       int Left = 2 * In;
14553       int Right = 2 * In + 1;
14554       SmallVector<int, 8> Mask(NumElems, -1);
14555       for (unsigned i = 0; i != NumElems; ++i) {
14556         if (VectorMask[i] == Left) {
14557           Mask[i] = i;
14558           VectorMask[i] = In;
14559         } else if (VectorMask[i] == Right) {
14560           Mask[i] = i + NumElems;
14561           VectorMask[i] = In;
14562         }
14563       }
14564 
14565       Shuffles[In] =
14566           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14567     }
14568   }
14569   return Shuffles[0];
14570 }
14571 
14572 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14573 // operations which can be matched to a truncate or to a shuffle-truncate.
14574 SDValue DAGCombiner::reduceBuildVecToTrunc(SDNode *N) {
14575   // TODO: Add support for big-endian.
14576   if (DAG.getDataLayout().isBigEndian())
14577     return SDValue();
14578   if (N->getNumOperands() < 2)
14579     return SDValue();
14580   SDLoc DL(N);
14581   EVT VT = N->getValueType(0);
14582   unsigned NumElems = N->getNumOperands();
14583 
14584   if (!isTypeLegal(VT))
14585     return SDValue();
14586 
14587   // If the input is something other than an EXTRACT_VECTOR_ELT with a constant
14588   // index, bail out.
14589   // TODO: Allow undef elements in some cases?
14590   if (any_of(N->ops(), [VT](SDValue Op) {
14591         return Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14592                !isa<ConstantSDNode>(Op.getOperand(1)) ||
14593                Op.getValueType() != VT.getVectorElementType();
14594       }))
14595     return SDValue();
14596 
14597   // Helper for obtaining an EXTRACT_VECTOR_ELT's constant index
14598   auto GetExtractIdx = [](SDValue Extract) {
14599     return cast<ConstantSDNode>(Extract.getOperand(1))->getSExtValue();
14600   };
14601 
14602   // The offset is defined to be the BUILD_VECTOR's first operand (assuming no
14603   // undef and little-endian).
14604   int Offset = GetExtractIdx(N->getOperand(0));
14605 
14606   // Compute the stride from the next operand.
14607   int Stride = GetExtractIdx(N->getOperand(1)) - Offset;
14608   SDValue ExtractedFromVec = N->getOperand(0).getOperand(0);
14609 
14610   // Proceed only if the stride and the types can be matched to a truncate.
14611   if ((Stride == 1 || !isPowerOf2_32(Stride)) ||
14612       (ExtractedFromVec.getValueType().getVectorNumElements() !=
14613        Stride * NumElems) ||
14614       (VT.getScalarSizeInBits() * Stride > 64))
14615     return SDValue();
14616 
14617   // Check remaining operands are consistent with the computed stride.
14618   for (unsigned i = 1; i != NumElems; ++i) {
14619     SDValue Op = N->getOperand(i);
14620 
14621     if ((Op.getOperand(0) != ExtractedFromVec) ||
14622         (GetExtractIdx(Op) != Stride * i + Offset))
14623       return SDValue();
14624   }
14625 
14626   SDValue Res = ExtractedFromVec;
14627   EVT TruncVT =
14628       VT.isFloatingPoint() ? VT.changeVectorElementTypeToInteger() : VT;
14629   if (Offset) {
14630     // If the first index is non-zero, need to shuffle elements of interest to
14631     // lower parts of the vector's elements the truncate will act upon.
14632     // TODO: Generalize to compute the permute-shuffle that will prepare any
14633     // element permutation for the truncate, and let the target decide if
14634     // profitable.
14635     EVT ExtractedVT = ExtractedFromVec.getValueType();
14636     SmallVector<int, 64> Mask;
14637     for (unsigned i = 0; i != NumElems; ++i) {
14638       Mask.push_back(Offset + i * Stride);
14639       // Pad the elements that will be lost after the truncate with undefs.
14640       Mask.append(Stride - 1, -1);
14641     }
14642     if (!TLI.isShuffleMaskLegal(Mask, ExtractedVT) ||
14643         !TLI.isDesirableToCombineBuildVectorToShuffleTruncate(Mask, ExtractedVT,
14644                                                               TruncVT))
14645       return SDValue();
14646     Res = DAG.getVectorShuffle(ExtractedVT, SDLoc(N), Res,
14647                                DAG.getUNDEF(ExtractedVT), Mask);
14648   }
14649   // Construct the truncate.
14650   LLVMContext &Ctx = *DAG.getContext();
14651   EVT NewVT = VT.getVectorVT(
14652       Ctx, EVT::getIntegerVT(Ctx, VT.getScalarSizeInBits() * Stride), NumElems);
14653 
14654   Res = DAG.getBitcast(NewVT, Res);
14655   Res = DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, Res);
14656   return DAG.getBitcast(VT, Res);
14657 }
14658 
14659 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14660   EVT VT = N->getValueType(0);
14661 
14662   // A vector built entirely of undefs is undef.
14663   if (ISD::allOperandsUndef(N))
14664     return DAG.getUNDEF(VT);
14665 
14666   // Check if we can express BUILD VECTOR via subvector extract.
14667   if (!LegalTypes && (N->getNumOperands() > 1)) {
14668     SDValue Op0 = N->getOperand(0);
14669     auto checkElem = [&](SDValue Op) -> uint64_t {
14670       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14671           (Op0.getOperand(0) == Op.getOperand(0)))
14672         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14673           return CNode->getZExtValue();
14674       return -1;
14675     };
14676 
14677     int Offset = checkElem(Op0);
14678     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14679       if (Offset + i != checkElem(N->getOperand(i))) {
14680         Offset = -1;
14681         break;
14682       }
14683     }
14684 
14685     if ((Offset == 0) &&
14686         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14687       return Op0.getOperand(0);
14688     if ((Offset != -1) &&
14689         ((Offset % N->getValueType(0).getVectorNumElements()) ==
14690          0)) // IDX must be multiple of output size.
14691       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14692                          Op0.getOperand(0), Op0.getOperand(1));
14693   }
14694 
14695   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14696     return V;
14697 
14698   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14699     return V;
14700 
14701   if (TLI.isDesirableToCombineBuildVectorToTruncate())
14702     if (SDValue V = reduceBuildVecToTrunc(N))
14703       return V;
14704 
14705   if (SDValue V = reduceBuildVecToShuffle(N))
14706     return V;
14707 
14708   return SDValue();
14709 }
14710 
14711 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14712   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14713   EVT OpVT = N->getOperand(0).getValueType();
14714 
14715   // If the operands are legal vectors, leave them alone.
14716   if (TLI.isTypeLegal(OpVT))
14717     return SDValue();
14718 
14719   SDLoc DL(N);
14720   EVT VT = N->getValueType(0);
14721   SmallVector<SDValue, 8> Ops;
14722 
14723   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14724   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14725 
14726   // Keep track of what we encounter.
14727   bool AnyInteger = false;
14728   bool AnyFP = false;
14729   for (const SDValue &Op : N->ops()) {
14730     if (ISD::BITCAST == Op.getOpcode() &&
14731         !Op.getOperand(0).getValueType().isVector())
14732       Ops.push_back(Op.getOperand(0));
14733     else if (ISD::UNDEF == Op.getOpcode())
14734       Ops.push_back(ScalarUndef);
14735     else
14736       return SDValue();
14737 
14738     // Note whether we encounter an integer or floating point scalar.
14739     // If it's neither, bail out, it could be something weird like x86mmx.
14740     EVT LastOpVT = Ops.back().getValueType();
14741     if (LastOpVT.isFloatingPoint())
14742       AnyFP = true;
14743     else if (LastOpVT.isInteger())
14744       AnyInteger = true;
14745     else
14746       return SDValue();
14747   }
14748 
14749   // If any of the operands is a floating point scalar bitcast to a vector,
14750   // use floating point types throughout, and bitcast everything.
14751   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14752   if (AnyFP) {
14753     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14754     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14755     if (AnyInteger) {
14756       for (SDValue &Op : Ops) {
14757         if (Op.getValueType() == SVT)
14758           continue;
14759         if (Op.isUndef())
14760           Op = ScalarUndef;
14761         else
14762           Op = DAG.getBitcast(SVT, Op);
14763       }
14764     }
14765   }
14766 
14767   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14768                                VT.getSizeInBits() / SVT.getSizeInBits());
14769   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14770 }
14771 
14772 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14773 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14774 // most two distinct vectors the same size as the result, attempt to turn this
14775 // into a legal shuffle.
14776 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14777   EVT VT = N->getValueType(0);
14778   EVT OpVT = N->getOperand(0).getValueType();
14779   int NumElts = VT.getVectorNumElements();
14780   int NumOpElts = OpVT.getVectorNumElements();
14781 
14782   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14783   SmallVector<int, 8> Mask;
14784 
14785   for (SDValue Op : N->ops()) {
14786     // Peek through any bitcast.
14787     Op = peekThroughBitcast(Op);
14788 
14789     // UNDEF nodes convert to UNDEF shuffle mask values.
14790     if (Op.isUndef()) {
14791       Mask.append((unsigned)NumOpElts, -1);
14792       continue;
14793     }
14794 
14795     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14796       return SDValue();
14797 
14798     // What vector are we extracting the subvector from and at what index?
14799     SDValue ExtVec = Op.getOperand(0);
14800 
14801     // We want the EVT of the original extraction to correctly scale the
14802     // extraction index.
14803     EVT ExtVT = ExtVec.getValueType();
14804 
14805     // Peek through any bitcast.
14806     ExtVec = peekThroughBitcast(ExtVec);
14807 
14808     // UNDEF nodes convert to UNDEF shuffle mask values.
14809     if (ExtVec.isUndef()) {
14810       Mask.append((unsigned)NumOpElts, -1);
14811       continue;
14812     }
14813 
14814     if (!isa<ConstantSDNode>(Op.getOperand(1)))
14815       return SDValue();
14816     int ExtIdx = Op.getConstantOperandVal(1);
14817 
14818     // Ensure that we are extracting a subvector from a vector the same
14819     // size as the result.
14820     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14821       return SDValue();
14822 
14823     // Scale the subvector index to account for any bitcast.
14824     int NumExtElts = ExtVT.getVectorNumElements();
14825     if (0 == (NumExtElts % NumElts))
14826       ExtIdx /= (NumExtElts / NumElts);
14827     else if (0 == (NumElts % NumExtElts))
14828       ExtIdx *= (NumElts / NumExtElts);
14829     else
14830       return SDValue();
14831 
14832     // At most we can reference 2 inputs in the final shuffle.
14833     if (SV0.isUndef() || SV0 == ExtVec) {
14834       SV0 = ExtVec;
14835       for (int i = 0; i != NumOpElts; ++i)
14836         Mask.push_back(i + ExtIdx);
14837     } else if (SV1.isUndef() || SV1 == ExtVec) {
14838       SV1 = ExtVec;
14839       for (int i = 0; i != NumOpElts; ++i)
14840         Mask.push_back(i + ExtIdx + NumElts);
14841     } else {
14842       return SDValue();
14843     }
14844   }
14845 
14846   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14847     return SDValue();
14848 
14849   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14850                               DAG.getBitcast(VT, SV1), Mask);
14851 }
14852 
14853 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14854   // If we only have one input vector, we don't need to do any concatenation.
14855   if (N->getNumOperands() == 1)
14856     return N->getOperand(0);
14857 
14858   // Check if all of the operands are undefs.
14859   EVT VT = N->getValueType(0);
14860   if (ISD::allOperandsUndef(N))
14861     return DAG.getUNDEF(VT);
14862 
14863   // Optimize concat_vectors where all but the first of the vectors are undef.
14864   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14865         return Op.isUndef();
14866       })) {
14867     SDValue In = N->getOperand(0);
14868     assert(In.getValueType().isVector() && "Must concat vectors");
14869 
14870     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14871     if (In->getOpcode() == ISD::BITCAST &&
14872         !In->getOperand(0)->getValueType(0).isVector()) {
14873       SDValue Scalar = In->getOperand(0);
14874 
14875       // If the bitcast type isn't legal, it might be a trunc of a legal type;
14876       // look through the trunc so we can still do the transform:
14877       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14878       if (Scalar->getOpcode() == ISD::TRUNCATE &&
14879           !TLI.isTypeLegal(Scalar.getValueType()) &&
14880           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14881         Scalar = Scalar->getOperand(0);
14882 
14883       EVT SclTy = Scalar->getValueType(0);
14884 
14885       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14886         return SDValue();
14887 
14888       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14889       if (VNTNumElms < 2)
14890         return SDValue();
14891 
14892       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14893       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14894         return SDValue();
14895 
14896       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14897       return DAG.getBitcast(VT, Res);
14898     }
14899   }
14900 
14901   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14902   // We have already tested above for an UNDEF only concatenation.
14903   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14904   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14905   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14906     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14907   };
14908   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14909     SmallVector<SDValue, 8> Opnds;
14910     EVT SVT = VT.getScalarType();
14911 
14912     EVT MinVT = SVT;
14913     if (!SVT.isFloatingPoint()) {
14914       // If BUILD_VECTOR are from built from integer, they may have different
14915       // operand types. Get the smallest type and truncate all operands to it.
14916       bool FoundMinVT = false;
14917       for (const SDValue &Op : N->ops())
14918         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14919           EVT OpSVT = Op.getOperand(0)->getValueType(0);
14920           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14921           FoundMinVT = true;
14922         }
14923       assert(FoundMinVT && "Concat vector type mismatch");
14924     }
14925 
14926     for (const SDValue &Op : N->ops()) {
14927       EVT OpVT = Op.getValueType();
14928       unsigned NumElts = OpVT.getVectorNumElements();
14929 
14930       if (ISD::UNDEF == Op.getOpcode())
14931         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14932 
14933       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14934         if (SVT.isFloatingPoint()) {
14935           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14936           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14937         } else {
14938           for (unsigned i = 0; i != NumElts; ++i)
14939             Opnds.push_back(
14940                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14941         }
14942       }
14943     }
14944 
14945     assert(VT.getVectorNumElements() == Opnds.size() &&
14946            "Concat vector type mismatch");
14947     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14948   }
14949 
14950   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14951   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14952     return V;
14953 
14954   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14955   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14956     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14957       return V;
14958 
14959   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14960   // nodes often generate nop CONCAT_VECTOR nodes.
14961   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14962   // place the incoming vectors at the exact same location.
14963   SDValue SingleSource = SDValue();
14964   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14965 
14966   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14967     SDValue Op = N->getOperand(i);
14968 
14969     if (Op.isUndef())
14970       continue;
14971 
14972     // Check if this is the identity extract:
14973     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14974       return SDValue();
14975 
14976     // Find the single incoming vector for the extract_subvector.
14977     if (SingleSource.getNode()) {
14978       if (Op.getOperand(0) != SingleSource)
14979         return SDValue();
14980     } else {
14981       SingleSource = Op.getOperand(0);
14982 
14983       // Check the source type is the same as the type of the result.
14984       // If not, this concat may extend the vector, so we can not
14985       // optimize it away.
14986       if (SingleSource.getValueType() != N->getValueType(0))
14987         return SDValue();
14988     }
14989 
14990     unsigned IdentityIndex = i * PartNumElem;
14991     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14992     // The extract index must be constant.
14993     if (!CS)
14994       return SDValue();
14995 
14996     // Check that we are reading from the identity index.
14997     if (CS->getZExtValue() != IdentityIndex)
14998       return SDValue();
14999   }
15000 
15001   if (SingleSource.getNode())
15002     return SingleSource;
15003 
15004   return SDValue();
15005 }
15006 
15007 /// If we are extracting a subvector produced by a wide binary operator with at
15008 /// at least one operand that was the result of a vector concatenation, then try
15009 /// to use the narrow vector operands directly to avoid the concatenation and
15010 /// extraction.
15011 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
15012   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
15013   // some of these bailouts with other transforms.
15014 
15015   // The extract index must be a constant, so we can map it to a concat operand.
15016   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15017   if (!ExtractIndex)
15018     return SDValue();
15019 
15020   // Only handle the case where we are doubling and then halving. A larger ratio
15021   // may require more than two narrow binops to replace the wide binop.
15022   EVT VT = Extract->getValueType(0);
15023   unsigned NumElems = VT.getVectorNumElements();
15024   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
15025          "Extract index is not a multiple of the vector length.");
15026   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
15027     return SDValue();
15028 
15029   // We are looking for an optionally bitcasted wide vector binary operator
15030   // feeding an extract subvector.
15031   SDValue BinOp = peekThroughBitcast(Extract->getOperand(0));
15032 
15033   // TODO: The motivating case for this transform is an x86 AVX1 target. That
15034   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
15035   // flavors, but no other 256-bit integer support. This could be extended to
15036   // handle any binop, but that may require fixing/adding other folds to avoid
15037   // codegen regressions.
15038   unsigned BOpcode = BinOp.getOpcode();
15039   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
15040     return SDValue();
15041 
15042   // The binop must be a vector type, so we can chop it in half.
15043   EVT WideBVT = BinOp.getValueType();
15044   if (!WideBVT.isVector())
15045     return SDValue();
15046 
15047   // Bail out if the target does not support a narrower version of the binop.
15048   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
15049                                    WideBVT.getVectorNumElements() / 2);
15050   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15051   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
15052     return SDValue();
15053 
15054   // Peek through bitcasts of the binary operator operands if needed.
15055   SDValue LHS = peekThroughBitcast(BinOp.getOperand(0));
15056   SDValue RHS = peekThroughBitcast(BinOp.getOperand(1));
15057 
15058   // We need at least one concatenation operation of a binop operand to make
15059   // this transform worthwhile. The concat must double the input vector sizes.
15060   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
15061   bool ConcatL =
15062       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
15063   bool ConcatR =
15064       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
15065   if (!ConcatL && !ConcatR)
15066     return SDValue();
15067 
15068   // If one of the binop operands was not the result of a concat, we must
15069   // extract a half-sized operand for our new narrow binop. We can't just reuse
15070   // the original extract index operand because we may have bitcasted.
15071   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
15072   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
15073   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
15074   SDLoc DL(Extract);
15075 
15076   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
15077   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
15078   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
15079   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
15080                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15081                                     BinOp.getOperand(0),
15082                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15083 
15084   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
15085                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15086                                     BinOp.getOperand(1),
15087                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15088 
15089   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
15090   return DAG.getBitcast(VT, NarrowBinOp);
15091 }
15092 
15093 /// If we are extracting a subvector from a wide vector load, convert to a
15094 /// narrow load to eliminate the extraction:
15095 /// (extract_subvector (load wide vector)) --> (load narrow vector)
15096 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
15097   // TODO: Add support for big-endian. The offset calculation must be adjusted.
15098   if (DAG.getDataLayout().isBigEndian())
15099     return SDValue();
15100 
15101   // TODO: The one-use check is overly conservative. Check the cost of the
15102   // extract instead or remove that condition entirely.
15103   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
15104   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15105   if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
15106       !ExtIdx)
15107     return SDValue();
15108 
15109   // The narrow load will be offset from the base address of the old load if
15110   // we are extracting from something besides index 0 (little-endian).
15111   EVT VT = Extract->getValueType(0);
15112   SDLoc DL(Extract);
15113   SDValue BaseAddr = Ld->getOperand(1);
15114   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
15115 
15116   // TODO: Use "BaseIndexOffset" to make this more effective.
15117   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
15118   MachineFunction &MF = DAG.getMachineFunction();
15119   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
15120                                                    VT.getStoreSize());
15121   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
15122   DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
15123   return NewLd;
15124 }
15125 
15126 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
15127   EVT NVT = N->getValueType(0);
15128   SDValue V = N->getOperand(0);
15129 
15130   // Extract from UNDEF is UNDEF.
15131   if (V.isUndef())
15132     return DAG.getUNDEF(NVT);
15133 
15134   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
15135     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
15136       return NarrowLoad;
15137 
15138   // Combine:
15139   //    (extract_subvec (concat V1, V2, ...), i)
15140   // Into:
15141   //    Vi if possible
15142   // Only operand 0 is checked as 'concat' assumes all inputs of the same
15143   // type.
15144   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
15145       isa<ConstantSDNode>(N->getOperand(1)) &&
15146       V->getOperand(0).getValueType() == NVT) {
15147     unsigned Idx = N->getConstantOperandVal(1);
15148     unsigned NumElems = NVT.getVectorNumElements();
15149     assert((Idx % NumElems) == 0 &&
15150            "IDX in concat is not a multiple of the result vector length.");
15151     return V->getOperand(Idx / NumElems);
15152   }
15153 
15154   // Skip bitcasting
15155   V = peekThroughBitcast(V);
15156 
15157   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
15158     // Handle only simple case where vector being inserted and vector
15159     // being extracted are of same size.
15160     EVT SmallVT = V->getOperand(1).getValueType();
15161     if (!NVT.bitsEq(SmallVT))
15162       return SDValue();
15163 
15164     // Only handle cases where both indexes are constants.
15165     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
15166     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
15167 
15168     if (InsIdx && ExtIdx) {
15169       // Combine:
15170       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
15171       // Into:
15172       //    indices are equal or bit offsets are equal => V1
15173       //    otherwise => (extract_subvec V1, ExtIdx)
15174       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
15175           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
15176         return DAG.getBitcast(NVT, V->getOperand(1));
15177       return DAG.getNode(
15178           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
15179           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
15180           N->getOperand(1));
15181     }
15182   }
15183 
15184   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
15185     return NarrowBOp;
15186 
15187   return SDValue();
15188 }
15189 
15190 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
15191                                                  SDValue V, SelectionDAG &DAG) {
15192   SDLoc DL(V);
15193   EVT VT = V.getValueType();
15194 
15195   switch (V.getOpcode()) {
15196   default:
15197     return V;
15198 
15199   case ISD::CONCAT_VECTORS: {
15200     EVT OpVT = V->getOperand(0).getValueType();
15201     int OpSize = OpVT.getVectorNumElements();
15202     SmallBitVector OpUsedElements(OpSize, false);
15203     bool FoundSimplification = false;
15204     SmallVector<SDValue, 4> NewOps;
15205     NewOps.reserve(V->getNumOperands());
15206     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
15207       SDValue Op = V->getOperand(i);
15208       bool OpUsed = false;
15209       for (int j = 0; j < OpSize; ++j)
15210         if (UsedElements[i * OpSize + j]) {
15211           OpUsedElements[j] = true;
15212           OpUsed = true;
15213         }
15214       NewOps.push_back(
15215           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
15216                  : DAG.getUNDEF(OpVT));
15217       FoundSimplification |= Op == NewOps.back();
15218       OpUsedElements.reset();
15219     }
15220     if (FoundSimplification)
15221       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
15222     return V;
15223   }
15224 
15225   case ISD::INSERT_SUBVECTOR: {
15226     SDValue BaseV = V->getOperand(0);
15227     SDValue SubV = V->getOperand(1);
15228     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
15229     if (!IdxN)
15230       return V;
15231 
15232     int SubSize = SubV.getValueType().getVectorNumElements();
15233     int Idx = IdxN->getZExtValue();
15234     bool SubVectorUsed = false;
15235     SmallBitVector SubUsedElements(SubSize, false);
15236     for (int i = 0; i < SubSize; ++i)
15237       if (UsedElements[i + Idx]) {
15238         SubVectorUsed = true;
15239         SubUsedElements[i] = true;
15240         UsedElements[i + Idx] = false;
15241       }
15242 
15243     // Now recurse on both the base and sub vectors.
15244     SDValue SimplifiedSubV =
15245         SubVectorUsed
15246             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
15247             : DAG.getUNDEF(SubV.getValueType());
15248     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
15249     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
15250       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15251                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
15252     return V;
15253   }
15254   }
15255 }
15256 
15257 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
15258                                        SDValue N1, SelectionDAG &DAG) {
15259   EVT VT = SVN->getValueType(0);
15260   int NumElts = VT.getVectorNumElements();
15261   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
15262   for (int M : SVN->getMask())
15263     if (M >= 0 && M < NumElts)
15264       N0UsedElements[M] = true;
15265     else if (M >= NumElts)
15266       N1UsedElements[M - NumElts] = true;
15267 
15268   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
15269   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
15270   if (S0 == N0 && S1 == N1)
15271     return SDValue();
15272 
15273   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
15274 }
15275 
15276 static SDValue simplifyShuffleMask(ShuffleVectorSDNode *SVN, SDValue N0,
15277                                    SDValue N1, SelectionDAG &DAG) {
15278   auto isUndefElt = [](SDValue V, int Idx) {
15279     // TODO - handle more cases as required.
15280     if (V.getOpcode() == ISD::BUILD_VECTOR)
15281       return V.getOperand(Idx).isUndef();
15282     return false;
15283   };
15284 
15285   EVT VT = SVN->getValueType(0);
15286   unsigned NumElts = VT.getVectorNumElements();
15287 
15288   bool Changed = false;
15289   SmallVector<int, 8> NewMask;
15290   for (unsigned i = 0; i != NumElts; ++i) {
15291     int Idx = SVN->getMaskElt(i);
15292     if ((0 <= Idx && Idx < (int)NumElts && isUndefElt(N0, Idx)) ||
15293         ((int)NumElts < Idx && isUndefElt(N1, Idx - NumElts))) {
15294       Changed = true;
15295       Idx = -1;
15296     }
15297     NewMask.push_back(Idx);
15298   }
15299   if (Changed)
15300     return DAG.getVectorShuffle(VT, SDLoc(SVN), N0, N1, NewMask);
15301 
15302   return SDValue();
15303 }
15304 
15305 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
15306 // or turn a shuffle of a single concat into simpler shuffle then concat.
15307 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
15308   EVT VT = N->getValueType(0);
15309   unsigned NumElts = VT.getVectorNumElements();
15310 
15311   SDValue N0 = N->getOperand(0);
15312   SDValue N1 = N->getOperand(1);
15313   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15314 
15315   SmallVector<SDValue, 4> Ops;
15316   EVT ConcatVT = N0.getOperand(0).getValueType();
15317   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
15318   unsigned NumConcats = NumElts / NumElemsPerConcat;
15319 
15320   // Special case: shuffle(concat(A,B)) can be more efficiently represented
15321   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
15322   // half vector elements.
15323   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
15324       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
15325                   SVN->getMask().end(), [](int i) { return i == -1; })) {
15326     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
15327                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
15328     N1 = DAG.getUNDEF(ConcatVT);
15329     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
15330   }
15331 
15332   // Look at every vector that's inserted. We're looking for exact
15333   // subvector-sized copies from a concatenated vector
15334   for (unsigned I = 0; I != NumConcats; ++I) {
15335     // Make sure we're dealing with a copy.
15336     unsigned Begin = I * NumElemsPerConcat;
15337     bool AllUndef = true, NoUndef = true;
15338     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
15339       if (SVN->getMaskElt(J) >= 0)
15340         AllUndef = false;
15341       else
15342         NoUndef = false;
15343     }
15344 
15345     if (NoUndef) {
15346       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
15347         return SDValue();
15348 
15349       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
15350         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
15351           return SDValue();
15352 
15353       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
15354       if (FirstElt < N0.getNumOperands())
15355         Ops.push_back(N0.getOperand(FirstElt));
15356       else
15357         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
15358 
15359     } else if (AllUndef) {
15360       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
15361     } else { // Mixed with general masks and undefs, can't do optimization.
15362       return SDValue();
15363     }
15364   }
15365 
15366   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15367 }
15368 
15369 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15370 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15371 //
15372 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
15373 // a simplification in some sense, but it isn't appropriate in general: some
15374 // BUILD_VECTORs are substantially cheaper than others. The general case
15375 // of a BUILD_VECTOR requires inserting each element individually (or
15376 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
15377 // all constants is a single constant pool load.  A BUILD_VECTOR where each
15378 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
15379 // are undef lowers to a small number of element insertions.
15380 //
15381 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
15382 // We don't fold shuffles where one side is a non-zero constant, and we don't
15383 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
15384 // non-constant operands. This seems to work out reasonably well in practice.
15385 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
15386                                        SelectionDAG &DAG,
15387                                        const TargetLowering &TLI) {
15388   EVT VT = SVN->getValueType(0);
15389   unsigned NumElts = VT.getVectorNumElements();
15390   SDValue N0 = SVN->getOperand(0);
15391   SDValue N1 = SVN->getOperand(1);
15392 
15393   if (!N0->hasOneUse() || !N1->hasOneUse())
15394     return SDValue();
15395   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
15396   // discussed above.
15397   if (!N1.isUndef()) {
15398     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
15399     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
15400     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
15401       return SDValue();
15402     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
15403       return SDValue();
15404   }
15405 
15406   SmallVector<SDValue, 8> Ops;
15407   SmallSet<SDValue, 16> DuplicateOps;
15408   for (int M : SVN->getMask()) {
15409     SDValue Op = DAG.getUNDEF(VT.getScalarType());
15410     if (M >= 0) {
15411       int Idx = M < (int)NumElts ? M : M - NumElts;
15412       SDValue &S = (M < (int)NumElts ? N0 : N1);
15413       if (S.getOpcode() == ISD::BUILD_VECTOR) {
15414         Op = S.getOperand(Idx);
15415       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
15416         if (Idx == 0)
15417           Op = S.getOperand(0);
15418       } else {
15419         // Operand can't be combined - bail out.
15420         return SDValue();
15421       }
15422     }
15423 
15424     // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
15425     // fine, but it's likely to generate low-quality code if the target can't
15426     // reconstruct an appropriate shuffle.
15427     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
15428       if (!DuplicateOps.insert(Op).second)
15429         return SDValue();
15430 
15431     Ops.push_back(Op);
15432   }
15433   // BUILD_VECTOR requires all inputs to be of the same type, find the
15434   // maximum type and extend them all.
15435   EVT SVT = VT.getScalarType();
15436   if (SVT.isInteger())
15437     for (SDValue &Op : Ops)
15438       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
15439   if (SVT != VT.getScalarType())
15440     for (SDValue &Op : Ops)
15441       Op = TLI.isZExtFree(Op.getValueType(), SVT)
15442                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
15443                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
15444   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
15445 }
15446 
15447 // Match shuffles that can be converted to any_vector_extend_in_reg.
15448 // This is often generated during legalization.
15449 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
15450 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
15451 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
15452                                             SelectionDAG &DAG,
15453                                             const TargetLowering &TLI,
15454                                             bool LegalOperations) {
15455   EVT VT = SVN->getValueType(0);
15456   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15457 
15458   // TODO Add support for big-endian when we have a test case.
15459   if (!VT.isInteger() || IsBigEndian)
15460     return SDValue();
15461 
15462   unsigned NumElts = VT.getVectorNumElements();
15463   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15464   ArrayRef<int> Mask = SVN->getMask();
15465   SDValue N0 = SVN->getOperand(0);
15466 
15467   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15468   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15469     for (unsigned i = 0; i != NumElts; ++i) {
15470       if (Mask[i] < 0)
15471         continue;
15472       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15473         continue;
15474       return false;
15475     }
15476     return true;
15477   };
15478 
15479   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15480   // power-of-2 extensions as they are the most likely.
15481   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15482     if (!isAnyExtend(Scale))
15483       continue;
15484 
15485     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15486     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15487     if (!LegalOperations ||
15488         TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15489       return DAG.getBitcast(VT,
15490                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15491   }
15492 
15493   return SDValue();
15494 }
15495 
15496 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15497 // each source element of a large type into the lowest elements of a smaller
15498 // destination type. This is often generated during legalization.
15499 // If the source node itself was a '*_extend_vector_inreg' node then we should
15500 // then be able to remove it.
15501 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15502                                         SelectionDAG &DAG) {
15503   EVT VT = SVN->getValueType(0);
15504   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15505 
15506   // TODO Add support for big-endian when we have a test case.
15507   if (!VT.isInteger() || IsBigEndian)
15508     return SDValue();
15509 
15510   SDValue N0 = peekThroughBitcast(SVN->getOperand(0));
15511 
15512   unsigned Opcode = N0.getOpcode();
15513   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15514       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15515       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15516     return SDValue();
15517 
15518   SDValue N00 = N0.getOperand(0);
15519   ArrayRef<int> Mask = SVN->getMask();
15520   unsigned NumElts = VT.getVectorNumElements();
15521   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15522   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15523   unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
15524 
15525   if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
15526     return SDValue();
15527   unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
15528 
15529   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15530   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15531   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15532   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15533     for (unsigned i = 0; i != NumElts; ++i) {
15534       if (Mask[i] < 0)
15535         continue;
15536       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15537         continue;
15538       return false;
15539     }
15540     return true;
15541   };
15542 
15543   // At the moment we just handle the case where we've truncated back to the
15544   // same size as before the extension.
15545   // TODO: handle more extension/truncation cases as cases arise.
15546   if (EltSizeInBits != ExtSrcSizeInBits)
15547     return SDValue();
15548 
15549   // We can remove *extend_vector_inreg only if the truncation happens at
15550   // the same scale as the extension.
15551   if (isTruncate(ExtScale))
15552     return DAG.getBitcast(VT, N00);
15553 
15554   return SDValue();
15555 }
15556 
15557 // Combine shuffles of splat-shuffles of the form:
15558 // shuffle (shuffle V, undef, splat-mask), undef, M
15559 // If splat-mask contains undef elements, we need to be careful about
15560 // introducing undef's in the folded mask which are not the result of composing
15561 // the masks of the shuffles.
15562 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15563                                      ShuffleVectorSDNode *Splat,
15564                                      SelectionDAG &DAG) {
15565   ArrayRef<int> SplatMask = Splat->getMask();
15566   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
15567 
15568   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15569   // every undef mask element in the splat-shuffle has a corresponding undef
15570   // element in the user-shuffle's mask or if the composition of mask elements
15571   // would result in undef.
15572   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15573   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15574   //   In this case it is not legal to simplify to the splat-shuffle because we
15575   //   may be exposing the users of the shuffle an undef element at index 1
15576   //   which was not there before the combine.
15577   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15578   //   In this case the composition of masks yields SplatMask, so it's ok to
15579   //   simplify to the splat-shuffle.
15580   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15581   //   In this case the composed mask includes all undef elements of SplatMask
15582   //   and in addition sets element zero to undef. It is safe to simplify to
15583   //   the splat-shuffle.
15584   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15585                                        ArrayRef<int> SplatMask) {
15586     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15587       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15588           SplatMask[UserMask[i]] != -1)
15589         return false;
15590     return true;
15591   };
15592   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15593     return SDValue(Splat, 0);
15594 
15595   // Create a new shuffle with a mask that is composed of the two shuffles'
15596   // masks.
15597   SmallVector<int, 32> NewMask;
15598   for (int Idx : UserMask)
15599     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15600 
15601   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15602                               Splat->getOperand(0), Splat->getOperand(1),
15603                               NewMask);
15604 }
15605 
15606 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
15607   EVT VT = N->getValueType(0);
15608   unsigned NumElts = VT.getVectorNumElements();
15609 
15610   SDValue N0 = N->getOperand(0);
15611   SDValue N1 = N->getOperand(1);
15612 
15613   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
15614 
15615   // Canonicalize shuffle undef, undef -> undef
15616   if (N0.isUndef() && N1.isUndef())
15617     return DAG.getUNDEF(VT);
15618 
15619   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15620 
15621   // Canonicalize shuffle v, v -> v, undef
15622   if (N0 == N1) {
15623     SmallVector<int, 8> NewMask;
15624     for (unsigned i = 0; i != NumElts; ++i) {
15625       int Idx = SVN->getMaskElt(i);
15626       if (Idx >= (int)NumElts) Idx -= NumElts;
15627       NewMask.push_back(Idx);
15628     }
15629     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
15630   }
15631 
15632   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
15633   if (N0.isUndef())
15634     return DAG.getCommutedVectorShuffle(*SVN);
15635 
15636   // Remove references to rhs if it is undef
15637   if (N1.isUndef()) {
15638     bool Changed = false;
15639     SmallVector<int, 8> NewMask;
15640     for (unsigned i = 0; i != NumElts; ++i) {
15641       int Idx = SVN->getMaskElt(i);
15642       if (Idx >= (int)NumElts) {
15643         Idx = -1;
15644         Changed = true;
15645       }
15646       NewMask.push_back(Idx);
15647     }
15648     if (Changed)
15649       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
15650   }
15651 
15652   // Simplify shuffle mask if a referenced element is UNDEF.
15653   if (SDValue V = simplifyShuffleMask(SVN, N0, N1, DAG))
15654     return V;
15655 
15656   // A shuffle of a single vector that is a splat can always be folded.
15657   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
15658     if (N1->isUndef() && N0Shuf->isSplat())
15659       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
15660 
15661   // If it is a splat, check if the argument vector is another splat or a
15662   // build_vector.
15663   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
15664     SDNode *V = N0.getNode();
15665 
15666     // If this is a bit convert that changes the element type of the vector but
15667     // not the number of vector elements, look through it.  Be careful not to
15668     // look though conversions that change things like v4f32 to v2f64.
15669     if (V->getOpcode() == ISD::BITCAST) {
15670       SDValue ConvInput = V->getOperand(0);
15671       if (ConvInput.getValueType().isVector() &&
15672           ConvInput.getValueType().getVectorNumElements() == NumElts)
15673         V = ConvInput.getNode();
15674     }
15675 
15676     if (V->getOpcode() == ISD::BUILD_VECTOR) {
15677       assert(V->getNumOperands() == NumElts &&
15678              "BUILD_VECTOR has wrong number of operands");
15679       SDValue Base;
15680       bool AllSame = true;
15681       for (unsigned i = 0; i != NumElts; ++i) {
15682         if (!V->getOperand(i).isUndef()) {
15683           Base = V->getOperand(i);
15684           break;
15685         }
15686       }
15687       // Splat of <u, u, u, u>, return <u, u, u, u>
15688       if (!Base.getNode())
15689         return N0;
15690       for (unsigned i = 0; i != NumElts; ++i) {
15691         if (V->getOperand(i) != Base) {
15692           AllSame = false;
15693           break;
15694         }
15695       }
15696       // Splat of <x, x, x, x>, return <x, x, x, x>
15697       if (AllSame)
15698         return N0;
15699 
15700       // Canonicalize any other splat as a build_vector.
15701       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
15702       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
15703       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
15704 
15705       // We may have jumped through bitcasts, so the type of the
15706       // BUILD_VECTOR may not match the type of the shuffle.
15707       if (V->getValueType(0) != VT)
15708         NewBV = DAG.getBitcast(VT, NewBV);
15709       return NewBV;
15710     }
15711   }
15712 
15713   // There are various patterns used to build up a vector from smaller vectors,
15714   // subvectors, or elements. Scan chains of these and replace unused insertions
15715   // or components with undef.
15716   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
15717     return S;
15718 
15719   // Match shuffles that can be converted to any_vector_extend_in_reg.
15720   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
15721     return V;
15722 
15723   // Combine "truncate_vector_in_reg" style shuffles.
15724   if (SDValue V = combineTruncationShuffle(SVN, DAG))
15725     return V;
15726 
15727   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
15728       Level < AfterLegalizeVectorOps &&
15729       (N1.isUndef() ||
15730       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
15731        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
15732     if (SDValue V = partitionShuffleOfConcats(N, DAG))
15733       return V;
15734   }
15735 
15736   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15737   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15738   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15739     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
15740       return Res;
15741 
15742   // If this shuffle only has a single input that is a bitcasted shuffle,
15743   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
15744   // back to their original types.
15745   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
15746       N1.isUndef() && Level < AfterLegalizeVectorOps &&
15747       TLI.isTypeLegal(VT)) {
15748 
15749     // Peek through the bitcast only if there is one user.
15750     SDValue BC0 = N0;
15751     while (BC0.getOpcode() == ISD::BITCAST) {
15752       if (!BC0.hasOneUse())
15753         break;
15754       BC0 = BC0.getOperand(0);
15755     }
15756 
15757     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
15758       if (Scale == 1)
15759         return SmallVector<int, 8>(Mask.begin(), Mask.end());
15760 
15761       SmallVector<int, 8> NewMask;
15762       for (int M : Mask)
15763         for (int s = 0; s != Scale; ++s)
15764           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
15765       return NewMask;
15766     };
15767 
15768     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
15769       EVT SVT = VT.getScalarType();
15770       EVT InnerVT = BC0->getValueType(0);
15771       EVT InnerSVT = InnerVT.getScalarType();
15772 
15773       // Determine which shuffle works with the smaller scalar type.
15774       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
15775       EVT ScaleSVT = ScaleVT.getScalarType();
15776 
15777       if (TLI.isTypeLegal(ScaleVT) &&
15778           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
15779           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
15780 
15781         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15782         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15783 
15784         // Scale the shuffle masks to the smaller scalar type.
15785         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
15786         SmallVector<int, 8> InnerMask =
15787             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
15788         SmallVector<int, 8> OuterMask =
15789             ScaleShuffleMask(SVN->getMask(), OuterScale);
15790 
15791         // Merge the shuffle masks.
15792         SmallVector<int, 8> NewMask;
15793         for (int M : OuterMask)
15794           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
15795 
15796         // Test for shuffle mask legality over both commutations.
15797         SDValue SV0 = BC0->getOperand(0);
15798         SDValue SV1 = BC0->getOperand(1);
15799         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15800         if (!LegalMask) {
15801           std::swap(SV0, SV1);
15802           ShuffleVectorSDNode::commuteMask(NewMask);
15803           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15804         }
15805 
15806         if (LegalMask) {
15807           SV0 = DAG.getBitcast(ScaleVT, SV0);
15808           SV1 = DAG.getBitcast(ScaleVT, SV1);
15809           return DAG.getBitcast(
15810               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
15811         }
15812       }
15813     }
15814   }
15815 
15816   // Canonicalize shuffles according to rules:
15817   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
15818   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
15819   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
15820   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
15821       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
15822       TLI.isTypeLegal(VT)) {
15823     // The incoming shuffle must be of the same type as the result of the
15824     // current shuffle.
15825     assert(N1->getOperand(0).getValueType() == VT &&
15826            "Shuffle types don't match");
15827 
15828     SDValue SV0 = N1->getOperand(0);
15829     SDValue SV1 = N1->getOperand(1);
15830     bool HasSameOp0 = N0 == SV0;
15831     bool IsSV1Undef = SV1.isUndef();
15832     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
15833       // Commute the operands of this shuffle so that next rule
15834       // will trigger.
15835       return DAG.getCommutedVectorShuffle(*SVN);
15836   }
15837 
15838   // Try to fold according to rules:
15839   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15840   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15841   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15842   // Don't try to fold shuffles with illegal type.
15843   // Only fold if this shuffle is the only user of the other shuffle.
15844   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
15845       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
15846     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
15847 
15848     // Don't try to fold splats; they're likely to simplify somehow, or they
15849     // might be free.
15850     if (OtherSV->isSplat())
15851       return SDValue();
15852 
15853     // The incoming shuffle must be of the same type as the result of the
15854     // current shuffle.
15855     assert(OtherSV->getOperand(0).getValueType() == VT &&
15856            "Shuffle types don't match");
15857 
15858     SDValue SV0, SV1;
15859     SmallVector<int, 4> Mask;
15860     // Compute the combined shuffle mask for a shuffle with SV0 as the first
15861     // operand, and SV1 as the second operand.
15862     for (unsigned i = 0; i != NumElts; ++i) {
15863       int Idx = SVN->getMaskElt(i);
15864       if (Idx < 0) {
15865         // Propagate Undef.
15866         Mask.push_back(Idx);
15867         continue;
15868       }
15869 
15870       SDValue CurrentVec;
15871       if (Idx < (int)NumElts) {
15872         // This shuffle index refers to the inner shuffle N0. Lookup the inner
15873         // shuffle mask to identify which vector is actually referenced.
15874         Idx = OtherSV->getMaskElt(Idx);
15875         if (Idx < 0) {
15876           // Propagate Undef.
15877           Mask.push_back(Idx);
15878           continue;
15879         }
15880 
15881         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
15882                                            : OtherSV->getOperand(1);
15883       } else {
15884         // This shuffle index references an element within N1.
15885         CurrentVec = N1;
15886       }
15887 
15888       // Simple case where 'CurrentVec' is UNDEF.
15889       if (CurrentVec.isUndef()) {
15890         Mask.push_back(-1);
15891         continue;
15892       }
15893 
15894       // Canonicalize the shuffle index. We don't know yet if CurrentVec
15895       // will be the first or second operand of the combined shuffle.
15896       Idx = Idx % NumElts;
15897       if (!SV0.getNode() || SV0 == CurrentVec) {
15898         // Ok. CurrentVec is the left hand side.
15899         // Update the mask accordingly.
15900         SV0 = CurrentVec;
15901         Mask.push_back(Idx);
15902         continue;
15903       }
15904 
15905       // Bail out if we cannot convert the shuffle pair into a single shuffle.
15906       if (SV1.getNode() && SV1 != CurrentVec)
15907         return SDValue();
15908 
15909       // Ok. CurrentVec is the right hand side.
15910       // Update the mask accordingly.
15911       SV1 = CurrentVec;
15912       Mask.push_back(Idx + NumElts);
15913     }
15914 
15915     // Check if all indices in Mask are Undef. In case, propagate Undef.
15916     bool isUndefMask = true;
15917     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
15918       isUndefMask &= Mask[i] < 0;
15919 
15920     if (isUndefMask)
15921       return DAG.getUNDEF(VT);
15922 
15923     if (!SV0.getNode())
15924       SV0 = DAG.getUNDEF(VT);
15925     if (!SV1.getNode())
15926       SV1 = DAG.getUNDEF(VT);
15927 
15928     // Avoid introducing shuffles with illegal mask.
15929     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
15930       ShuffleVectorSDNode::commuteMask(Mask);
15931 
15932       if (!TLI.isShuffleMaskLegal(Mask, VT))
15933         return SDValue();
15934 
15935       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
15936       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
15937       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
15938       std::swap(SV0, SV1);
15939     }
15940 
15941     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15942     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15943     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15944     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
15945   }
15946 
15947   return SDValue();
15948 }
15949 
15950 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
15951   SDValue InVal = N->getOperand(0);
15952   EVT VT = N->getValueType(0);
15953 
15954   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
15955   // with a VECTOR_SHUFFLE and possible truncate.
15956   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15957     SDValue InVec = InVal->getOperand(0);
15958     SDValue EltNo = InVal->getOperand(1);
15959     auto InVecT = InVec.getValueType();
15960     if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
15961       SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
15962       int Elt = C0->getZExtValue();
15963       NewMask[0] = Elt;
15964       SDValue Val;
15965       // If we have an implict truncate do truncate here as long as it's legal.
15966       // if it's not legal, this should
15967       if (VT.getScalarType() != InVal.getValueType() &&
15968           InVal.getValueType().isScalarInteger() &&
15969           isTypeLegal(VT.getScalarType())) {
15970         Val =
15971             DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
15972         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
15973       }
15974       if (VT.getScalarType() == InVecT.getScalarType() &&
15975           VT.getVectorNumElements() <= InVecT.getVectorNumElements() &&
15976           TLI.isShuffleMaskLegal(NewMask, VT)) {
15977         Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec,
15978                                    DAG.getUNDEF(InVecT), NewMask);
15979         // If the initial vector is the correct size this shuffle is a
15980         // valid result.
15981         if (VT == InVecT)
15982           return Val;
15983         // If not we must truncate the vector.
15984         if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
15985           MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
15986           SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy);
15987           EVT SubVT =
15988               EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(),
15989                                VT.getVectorNumElements());
15990           Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val,
15991                             ZeroIdx);
15992           return Val;
15993         }
15994       }
15995     }
15996   }
15997 
15998   return SDValue();
15999 }
16000 
16001 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
16002   EVT VT = N->getValueType(0);
16003   SDValue N0 = N->getOperand(0);
16004   SDValue N1 = N->getOperand(1);
16005   SDValue N2 = N->getOperand(2);
16006 
16007   // If inserting an UNDEF, just return the original vector.
16008   if (N1.isUndef())
16009     return N0;
16010 
16011   // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow
16012   // us to pull BITCASTs from input to output.
16013   if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR)
16014     if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode()))
16015       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2);
16016 
16017   // If this is an insert of an extracted vector into an undef vector, we can
16018   // just use the input to the extract.
16019   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16020       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
16021     return N1.getOperand(0);
16022 
16023   // If we are inserting a bitcast value into an undef, with the same
16024   // number of elements, just use the bitcast input of the extract.
16025   // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
16026   //        BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
16027   if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
16028       N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16029       N1.getOperand(0).getOperand(1) == N2 &&
16030       N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
16031           VT.getVectorNumElements()) {
16032     return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
16033   }
16034 
16035   // If both N1 and N2 are bitcast values on which insert_subvector
16036   // would makes sense, pull the bitcast through.
16037   // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
16038   //        BITCAST (INSERT_SUBVECTOR N0 N1 N2)
16039   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
16040     SDValue CN0 = N0.getOperand(0);
16041     SDValue CN1 = N1.getOperand(0);
16042     if (CN0.getValueType().getVectorElementType() ==
16043             CN1.getValueType().getVectorElementType() &&
16044         CN0.getValueType().getVectorNumElements() ==
16045             VT.getVectorNumElements()) {
16046       SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
16047                                       CN0.getValueType(), CN0, CN1, N2);
16048       return DAG.getBitcast(VT, NewINSERT);
16049     }
16050   }
16051 
16052   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
16053   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
16054   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
16055   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
16056       N0.getOperand(1).getValueType() == N1.getValueType() &&
16057       N0.getOperand(2) == N2)
16058     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
16059                        N1, N2);
16060 
16061   if (!isa<ConstantSDNode>(N2))
16062     return SDValue();
16063 
16064   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
16065 
16066   // Canonicalize insert_subvector dag nodes.
16067   // Example:
16068   // (insert_subvector (insert_subvector A, Idx0), Idx1)
16069   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
16070   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
16071       N1.getValueType() == N0.getOperand(1).getValueType() &&
16072       isa<ConstantSDNode>(N0.getOperand(2))) {
16073     unsigned OtherIdx = N0.getConstantOperandVal(2);
16074     if (InsIdx < OtherIdx) {
16075       // Swap nodes.
16076       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
16077                                   N0.getOperand(0), N1, N2);
16078       AddToWorklist(NewOp.getNode());
16079       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
16080                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
16081     }
16082   }
16083 
16084   // If the input vector is a concatenation, and the insert replaces
16085   // one of the pieces, we can optimize into a single concat_vectors.
16086   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
16087       N0.getOperand(0).getValueType() == N1.getValueType()) {
16088     unsigned Factor = N1.getValueType().getVectorNumElements();
16089 
16090     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
16091     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
16092 
16093     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
16094   }
16095 
16096   return SDValue();
16097 }
16098 
16099 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
16100   SDValue N0 = N->getOperand(0);
16101 
16102   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
16103   if (N0->getOpcode() == ISD::FP16_TO_FP)
16104     return N0->getOperand(0);
16105 
16106   return SDValue();
16107 }
16108 
16109 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
16110   SDValue N0 = N->getOperand(0);
16111 
16112   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
16113   if (N0->getOpcode() == ISD::AND) {
16114     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
16115     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
16116       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
16117                          N0.getOperand(0));
16118     }
16119   }
16120 
16121   return SDValue();
16122 }
16123 
16124 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
16125 /// with the destination vector and a zero vector.
16126 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
16127 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
16128 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
16129   EVT VT = N->getValueType(0);
16130   SDValue LHS = N->getOperand(0);
16131   SDValue RHS = peekThroughBitcast(N->getOperand(1));
16132   SDLoc DL(N);
16133 
16134   // Make sure we're not running after operation legalization where it
16135   // may have custom lowered the vector shuffles.
16136   if (LegalOperations)
16137     return SDValue();
16138 
16139   if (N->getOpcode() != ISD::AND)
16140     return SDValue();
16141 
16142   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
16143     return SDValue();
16144 
16145   EVT RVT = RHS.getValueType();
16146   unsigned NumElts = RHS.getNumOperands();
16147 
16148   // Attempt to create a valid clear mask, splitting the mask into
16149   // sub elements and checking to see if each is
16150   // all zeros or all ones - suitable for shuffle masking.
16151   auto BuildClearMask = [&](int Split) {
16152     int NumSubElts = NumElts * Split;
16153     int NumSubBits = RVT.getScalarSizeInBits() / Split;
16154 
16155     SmallVector<int, 8> Indices;
16156     for (int i = 0; i != NumSubElts; ++i) {
16157       int EltIdx = i / Split;
16158       int SubIdx = i % Split;
16159       SDValue Elt = RHS.getOperand(EltIdx);
16160       if (Elt.isUndef()) {
16161         Indices.push_back(-1);
16162         continue;
16163       }
16164 
16165       APInt Bits;
16166       if (isa<ConstantSDNode>(Elt))
16167         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
16168       else if (isa<ConstantFPSDNode>(Elt))
16169         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
16170       else
16171         return SDValue();
16172 
16173       // Extract the sub element from the constant bit mask.
16174       if (DAG.getDataLayout().isBigEndian()) {
16175         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
16176       } else {
16177         Bits.lshrInPlace(SubIdx * NumSubBits);
16178       }
16179 
16180       if (Split > 1)
16181         Bits = Bits.trunc(NumSubBits);
16182 
16183       if (Bits.isAllOnesValue())
16184         Indices.push_back(i);
16185       else if (Bits == 0)
16186         Indices.push_back(i + NumSubElts);
16187       else
16188         return SDValue();
16189     }
16190 
16191     // Let's see if the target supports this vector_shuffle.
16192     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
16193     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
16194     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
16195       return SDValue();
16196 
16197     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
16198     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
16199                                                    DAG.getBitcast(ClearVT, LHS),
16200                                                    Zero, Indices));
16201   };
16202 
16203   // Determine maximum split level (byte level masking).
16204   int MaxSplit = 1;
16205   if (RVT.getScalarSizeInBits() % 8 == 0)
16206     MaxSplit = RVT.getScalarSizeInBits() / 8;
16207 
16208   for (int Split = 1; Split <= MaxSplit; ++Split)
16209     if (RVT.getScalarSizeInBits() % Split == 0)
16210       if (SDValue S = BuildClearMask(Split))
16211         return S;
16212 
16213   return SDValue();
16214 }
16215 
16216 /// Visit a binary vector operation, like ADD.
16217 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
16218   assert(N->getValueType(0).isVector() &&
16219          "SimplifyVBinOp only works on vectors!");
16220 
16221   SDValue LHS = N->getOperand(0);
16222   SDValue RHS = N->getOperand(1);
16223   SDValue Ops[] = {LHS, RHS};
16224 
16225   // See if we can constant fold the vector operation.
16226   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
16227           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
16228     return Fold;
16229 
16230   // Try to convert a constant mask AND into a shuffle clear mask.
16231   if (SDValue Shuffle = XformToShuffleWithZero(N))
16232     return Shuffle;
16233 
16234   // Type legalization might introduce new shuffles in the DAG.
16235   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
16236   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
16237   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
16238       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
16239       LHS.getOperand(1).isUndef() &&
16240       RHS.getOperand(1).isUndef()) {
16241     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
16242     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
16243 
16244     if (SVN0->getMask().equals(SVN1->getMask())) {
16245       EVT VT = N->getValueType(0);
16246       SDValue UndefVector = LHS.getOperand(1);
16247       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
16248                                      LHS.getOperand(0), RHS.getOperand(0),
16249                                      N->getFlags());
16250       AddUsersToWorklist(N);
16251       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
16252                                   SVN0->getMask());
16253     }
16254   }
16255 
16256   return SDValue();
16257 }
16258 
16259 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
16260                                     SDValue N2) {
16261   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
16262 
16263   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
16264                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
16265 
16266   // If we got a simplified select_cc node back from SimplifySelectCC, then
16267   // break it down into a new SETCC node, and a new SELECT node, and then return
16268   // the SELECT node, since we were called with a SELECT node.
16269   if (SCC.getNode()) {
16270     // Check to see if we got a select_cc back (to turn into setcc/select).
16271     // Otherwise, just return whatever node we got back, like fabs.
16272     if (SCC.getOpcode() == ISD::SELECT_CC) {
16273       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
16274                                   N0.getValueType(),
16275                                   SCC.getOperand(0), SCC.getOperand(1),
16276                                   SCC.getOperand(4));
16277       AddToWorklist(SETCC.getNode());
16278       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
16279                            SCC.getOperand(2), SCC.getOperand(3));
16280     }
16281 
16282     return SCC;
16283   }
16284   return SDValue();
16285 }
16286 
16287 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
16288 /// being selected between, see if we can simplify the select.  Callers of this
16289 /// should assume that TheSelect is deleted if this returns true.  As such, they
16290 /// should return the appropriate thing (e.g. the node) back to the top-level of
16291 /// the DAG combiner loop to avoid it being looked at.
16292 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
16293                                     SDValue RHS) {
16294 
16295   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16296   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
16297   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
16298     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
16299       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
16300       SDValue Sqrt = RHS;
16301       ISD::CondCode CC;
16302       SDValue CmpLHS;
16303       const ConstantFPSDNode *Zero = nullptr;
16304 
16305       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
16306         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
16307         CmpLHS = TheSelect->getOperand(0);
16308         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
16309       } else {
16310         // SELECT or VSELECT
16311         SDValue Cmp = TheSelect->getOperand(0);
16312         if (Cmp.getOpcode() == ISD::SETCC) {
16313           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
16314           CmpLHS = Cmp.getOperand(0);
16315           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
16316         }
16317       }
16318       if (Zero && Zero->isZero() &&
16319           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
16320           CC == ISD::SETULT || CC == ISD::SETLT)) {
16321         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16322         CombineTo(TheSelect, Sqrt);
16323         return true;
16324       }
16325     }
16326   }
16327   // Cannot simplify select with vector condition
16328   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
16329 
16330   // If this is a select from two identical things, try to pull the operation
16331   // through the select.
16332   if (LHS.getOpcode() != RHS.getOpcode() ||
16333       !LHS.hasOneUse() || !RHS.hasOneUse())
16334     return false;
16335 
16336   // If this is a load and the token chain is identical, replace the select
16337   // of two loads with a load through a select of the address to load from.
16338   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
16339   // constants have been dropped into the constant pool.
16340   if (LHS.getOpcode() == ISD::LOAD) {
16341     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
16342     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
16343 
16344     // Token chains must be identical.
16345     if (LHS.getOperand(0) != RHS.getOperand(0) ||
16346         // Do not let this transformation reduce the number of volatile loads.
16347         LLD->isVolatile() || RLD->isVolatile() ||
16348         // FIXME: If either is a pre/post inc/dec load,
16349         // we'd need to split out the address adjustment.
16350         LLD->isIndexed() || RLD->isIndexed() ||
16351         // If this is an EXTLOAD, the VT's must match.
16352         LLD->getMemoryVT() != RLD->getMemoryVT() ||
16353         // If this is an EXTLOAD, the kind of extension must match.
16354         (LLD->getExtensionType() != RLD->getExtensionType() &&
16355          // The only exception is if one of the extensions is anyext.
16356          LLD->getExtensionType() != ISD::EXTLOAD &&
16357          RLD->getExtensionType() != ISD::EXTLOAD) ||
16358         // FIXME: this discards src value information.  This is
16359         // over-conservative. It would be beneficial to be able to remember
16360         // both potential memory locations.  Since we are discarding
16361         // src value info, don't do the transformation if the memory
16362         // locations are not in the default address space.
16363         LLD->getPointerInfo().getAddrSpace() != 0 ||
16364         RLD->getPointerInfo().getAddrSpace() != 0 ||
16365         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
16366                                       LLD->getBasePtr().getValueType()))
16367       return false;
16368 
16369     // Check that the select condition doesn't reach either load.  If so,
16370     // folding this will induce a cycle into the DAG.  If not, this is safe to
16371     // xform, so create a select of the addresses.
16372     SDValue Addr;
16373     if (TheSelect->getOpcode() == ISD::SELECT) {
16374       SDNode *CondNode = TheSelect->getOperand(0).getNode();
16375       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
16376           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
16377         return false;
16378       // The loads must not depend on one another.
16379       if (LLD->isPredecessorOf(RLD) ||
16380           RLD->isPredecessorOf(LLD))
16381         return false;
16382       Addr = DAG.getSelect(SDLoc(TheSelect),
16383                            LLD->getBasePtr().getValueType(),
16384                            TheSelect->getOperand(0), LLD->getBasePtr(),
16385                            RLD->getBasePtr());
16386     } else {  // Otherwise SELECT_CC
16387       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
16388       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
16389 
16390       if ((LLD->hasAnyUseOfValue(1) &&
16391            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
16392           (RLD->hasAnyUseOfValue(1) &&
16393            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
16394         return false;
16395 
16396       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
16397                          LLD->getBasePtr().getValueType(),
16398                          TheSelect->getOperand(0),
16399                          TheSelect->getOperand(1),
16400                          LLD->getBasePtr(), RLD->getBasePtr(),
16401                          TheSelect->getOperand(4));
16402     }
16403 
16404     SDValue Load;
16405     // It is safe to replace the two loads if they have different alignments,
16406     // but the new load must be the minimum (most restrictive) alignment of the
16407     // inputs.
16408     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
16409     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
16410     if (!RLD->isInvariant())
16411       MMOFlags &= ~MachineMemOperand::MOInvariant;
16412     if (!RLD->isDereferenceable())
16413       MMOFlags &= ~MachineMemOperand::MODereferenceable;
16414     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
16415       // FIXME: Discards pointer and AA info.
16416       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
16417                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
16418                          MMOFlags);
16419     } else {
16420       // FIXME: Discards pointer and AA info.
16421       Load = DAG.getExtLoad(
16422           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
16423                                                   : LLD->getExtensionType(),
16424           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
16425           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
16426     }
16427 
16428     // Users of the select now use the result of the load.
16429     CombineTo(TheSelect, Load);
16430 
16431     // Users of the old loads now use the new load's chain.  We know the
16432     // old-load value is dead now.
16433     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
16434     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
16435     return true;
16436   }
16437 
16438   return false;
16439 }
16440 
16441 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
16442 /// bitwise 'and'.
16443 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
16444                                             SDValue N1, SDValue N2, SDValue N3,
16445                                             ISD::CondCode CC) {
16446   // If this is a select where the false operand is zero and the compare is a
16447   // check of the sign bit, see if we can perform the "gzip trick":
16448   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
16449   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
16450   EVT XType = N0.getValueType();
16451   EVT AType = N2.getValueType();
16452   if (!isNullConstant(N3) || !XType.bitsGE(AType))
16453     return SDValue();
16454 
16455   // If the comparison is testing for a positive value, we have to invert
16456   // the sign bit mask, so only do that transform if the target has a bitwise
16457   // 'and not' instruction (the invert is free).
16458   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
16459     // (X > -1) ? A : 0
16460     // (X >  0) ? X : 0 <-- This is canonical signed max.
16461     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
16462       return SDValue();
16463   } else if (CC == ISD::SETLT) {
16464     // (X <  0) ? A : 0
16465     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
16466     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
16467       return SDValue();
16468   } else {
16469     return SDValue();
16470   }
16471 
16472   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
16473   // constant.
16474   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
16475   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16476   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
16477     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
16478     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
16479     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
16480     AddToWorklist(Shift.getNode());
16481 
16482     if (XType.bitsGT(AType)) {
16483       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16484       AddToWorklist(Shift.getNode());
16485     }
16486 
16487     if (CC == ISD::SETGT)
16488       Shift = DAG.getNOT(DL, Shift, AType);
16489 
16490     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16491   }
16492 
16493   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
16494   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
16495   AddToWorklist(Shift.getNode());
16496 
16497   if (XType.bitsGT(AType)) {
16498     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16499     AddToWorklist(Shift.getNode());
16500   }
16501 
16502   if (CC == ISD::SETGT)
16503     Shift = DAG.getNOT(DL, Shift, AType);
16504 
16505   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16506 }
16507 
16508 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
16509 /// where 'cond' is the comparison specified by CC.
16510 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
16511                                       SDValue N2, SDValue N3, ISD::CondCode CC,
16512                                       bool NotExtCompare) {
16513   // (x ? y : y) -> y.
16514   if (N2 == N3) return N2;
16515 
16516   EVT VT = N2.getValueType();
16517   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
16518   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16519 
16520   // Determine if the condition we're dealing with is constant
16521   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
16522                               N0, N1, CC, DL, false);
16523   if (SCC.getNode()) AddToWorklist(SCC.getNode());
16524 
16525   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
16526     // fold select_cc true, x, y -> x
16527     // fold select_cc false, x, y -> y
16528     return !SCCC->isNullValue() ? N2 : N3;
16529   }
16530 
16531   // Check to see if we can simplify the select into an fabs node
16532   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
16533     // Allow either -0.0 or 0.0
16534     if (CFP->isZero()) {
16535       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
16536       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
16537           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
16538           N2 == N3.getOperand(0))
16539         return DAG.getNode(ISD::FABS, DL, VT, N0);
16540 
16541       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
16542       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
16543           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
16544           N2.getOperand(0) == N3)
16545         return DAG.getNode(ISD::FABS, DL, VT, N3);
16546     }
16547   }
16548 
16549   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
16550   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
16551   // in it.  This is a win when the constant is not otherwise available because
16552   // it replaces two constant pool loads with one.  We only do this if the FP
16553   // type is known to be legal, because if it isn't, then we are before legalize
16554   // types an we want the other legalization to happen first (e.g. to avoid
16555   // messing with soft float) and if the ConstantFP is not legal, because if
16556   // it is legal, we may not need to store the FP constant in a constant pool.
16557   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
16558     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
16559       if (TLI.isTypeLegal(N2.getValueType()) &&
16560           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
16561                TargetLowering::Legal &&
16562            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
16563            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
16564           // If both constants have multiple uses, then we won't need to do an
16565           // extra load, they are likely around in registers for other users.
16566           (TV->hasOneUse() || FV->hasOneUse())) {
16567         Constant *Elts[] = {
16568           const_cast<ConstantFP*>(FV->getConstantFPValue()),
16569           const_cast<ConstantFP*>(TV->getConstantFPValue())
16570         };
16571         Type *FPTy = Elts[0]->getType();
16572         const DataLayout &TD = DAG.getDataLayout();
16573 
16574         // Create a ConstantArray of the two constants.
16575         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
16576         SDValue CPIdx =
16577             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
16578                                 TD.getPrefTypeAlignment(FPTy));
16579         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
16580 
16581         // Get the offsets to the 0 and 1 element of the array so that we can
16582         // select between them.
16583         SDValue Zero = DAG.getIntPtrConstant(0, DL);
16584         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
16585         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
16586 
16587         SDValue Cond = DAG.getSetCC(DL,
16588                                     getSetCCResultType(N0.getValueType()),
16589                                     N0, N1, CC);
16590         AddToWorklist(Cond.getNode());
16591         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
16592                                           Cond, One, Zero);
16593         AddToWorklist(CstOffset.getNode());
16594         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
16595                             CstOffset);
16596         AddToWorklist(CPIdx.getNode());
16597         return DAG.getLoad(
16598             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
16599             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
16600             Alignment);
16601       }
16602     }
16603 
16604   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
16605     return V;
16606 
16607   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
16608   // where y is has a single bit set.
16609   // A plaintext description would be, we can turn the SELECT_CC into an AND
16610   // when the condition can be materialized as an all-ones register.  Any
16611   // single bit-test can be materialized as an all-ones register with
16612   // shift-left and shift-right-arith.
16613   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
16614       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
16615     SDValue AndLHS = N0->getOperand(0);
16616     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
16617     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
16618       // Shift the tested bit over the sign bit.
16619       const APInt &AndMask = ConstAndRHS->getAPIntValue();
16620       SDValue ShlAmt =
16621         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
16622                         getShiftAmountTy(AndLHS.getValueType()));
16623       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
16624 
16625       // Now arithmetic right shift it all the way over, so the result is either
16626       // all-ones, or zero.
16627       SDValue ShrAmt =
16628         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
16629                         getShiftAmountTy(Shl.getValueType()));
16630       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
16631 
16632       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
16633     }
16634   }
16635 
16636   // fold select C, 16, 0 -> shl C, 4
16637   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
16638       TLI.getBooleanContents(N0.getValueType()) ==
16639           TargetLowering::ZeroOrOneBooleanContent) {
16640 
16641     // If the caller doesn't want us to simplify this into a zext of a compare,
16642     // don't do it.
16643     if (NotExtCompare && N2C->isOne())
16644       return SDValue();
16645 
16646     // Get a SetCC of the condition
16647     // NOTE: Don't create a SETCC if it's not legal on this target.
16648     if (!LegalOperations ||
16649         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
16650       SDValue Temp, SCC;
16651       // cast from setcc result type to select result type
16652       if (LegalTypes) {
16653         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
16654                             N0, N1, CC);
16655         if (N2.getValueType().bitsLT(SCC.getValueType()))
16656           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
16657                                         N2.getValueType());
16658         else
16659           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16660                              N2.getValueType(), SCC);
16661       } else {
16662         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
16663         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16664                            N2.getValueType(), SCC);
16665       }
16666 
16667       AddToWorklist(SCC.getNode());
16668       AddToWorklist(Temp.getNode());
16669 
16670       if (N2C->isOne())
16671         return Temp;
16672 
16673       // shl setcc result by log2 n2c
16674       return DAG.getNode(
16675           ISD::SHL, DL, N2.getValueType(), Temp,
16676           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
16677                           getShiftAmountTy(Temp.getValueType())));
16678     }
16679   }
16680 
16681   // Check to see if this is an integer abs.
16682   // select_cc setg[te] X,  0,  X, -X ->
16683   // select_cc setgt    X, -1,  X, -X ->
16684   // select_cc setl[te] X,  0, -X,  X ->
16685   // select_cc setlt    X,  1, -X,  X ->
16686   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
16687   if (N1C) {
16688     ConstantSDNode *SubC = nullptr;
16689     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
16690          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
16691         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
16692       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
16693     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
16694               (N1C->isOne() && CC == ISD::SETLT)) &&
16695              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
16696       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
16697 
16698     EVT XType = N0.getValueType();
16699     if (SubC && SubC->isNullValue() && XType.isInteger()) {
16700       SDLoc DL(N0);
16701       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
16702                                   N0,
16703                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
16704                                          getShiftAmountTy(N0.getValueType())));
16705       SDValue Add = DAG.getNode(ISD::ADD, DL,
16706                                 XType, N0, Shift);
16707       AddToWorklist(Shift.getNode());
16708       AddToWorklist(Add.getNode());
16709       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
16710     }
16711   }
16712 
16713   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
16714   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
16715   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
16716   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
16717   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
16718   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
16719   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
16720   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
16721   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
16722     SDValue ValueOnZero = N2;
16723     SDValue Count = N3;
16724     // If the condition is NE instead of E, swap the operands.
16725     if (CC == ISD::SETNE)
16726       std::swap(ValueOnZero, Count);
16727     // Check if the value on zero is a constant equal to the bits in the type.
16728     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
16729       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
16730         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
16731         // legal, combine to just cttz.
16732         if ((Count.getOpcode() == ISD::CTTZ ||
16733              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
16734             N0 == Count.getOperand(0) &&
16735             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
16736           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
16737         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
16738         // legal, combine to just ctlz.
16739         if ((Count.getOpcode() == ISD::CTLZ ||
16740              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
16741             N0 == Count.getOperand(0) &&
16742             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
16743           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
16744       }
16745     }
16746   }
16747 
16748   return SDValue();
16749 }
16750 
16751 /// This is a stub for TargetLowering::SimplifySetCC.
16752 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
16753                                    ISD::CondCode Cond, const SDLoc &DL,
16754                                    bool foldBooleans) {
16755   TargetLowering::DAGCombinerInfo
16756     DagCombineInfo(DAG, Level, false, this);
16757   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
16758 }
16759 
16760 /// Given an ISD::SDIV node expressing a divide by constant, return
16761 /// a DAG expression to select that will generate the same value by multiplying
16762 /// by a magic number.
16763 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16764 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
16765   // when optimising for minimum size, we don't want to expand a div to a mul
16766   // and a shift.
16767   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16768     return SDValue();
16769 
16770   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16771   if (!C)
16772     return SDValue();
16773 
16774   // Avoid division by zero.
16775   if (C->isNullValue())
16776     return SDValue();
16777 
16778   std::vector<SDNode*> Built;
16779   SDValue S =
16780       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16781 
16782   for (SDNode *N : Built)
16783     AddToWorklist(N);
16784   return S;
16785 }
16786 
16787 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
16788 /// DAG expression that will generate the same value by right shifting.
16789 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
16790   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16791   if (!C)
16792     return SDValue();
16793 
16794   // Avoid division by zero.
16795   if (C->isNullValue())
16796     return SDValue();
16797 
16798   std::vector<SDNode *> Built;
16799   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
16800 
16801   for (SDNode *N : Built)
16802     AddToWorklist(N);
16803   return S;
16804 }
16805 
16806 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
16807 /// expression that will generate the same value by multiplying by a magic
16808 /// number.
16809 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16810 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
16811   // when optimising for minimum size, we don't want to expand a div to a mul
16812   // and a shift.
16813   if (DAG.getMachineFunction().getFunction()->optForMinSize())
16814     return SDValue();
16815 
16816   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16817   if (!C)
16818     return SDValue();
16819 
16820   // Avoid division by zero.
16821   if (C->isNullValue())
16822     return SDValue();
16823 
16824   std::vector<SDNode*> Built;
16825   SDValue S =
16826       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16827 
16828   for (SDNode *N : Built)
16829     AddToWorklist(N);
16830   return S;
16831 }
16832 
16833 /// Determines the LogBase2 value for a non-null input value using the
16834 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
16835 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
16836   EVT VT = V.getValueType();
16837   unsigned EltBits = VT.getScalarSizeInBits();
16838   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
16839   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
16840   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
16841   return LogBase2;
16842 }
16843 
16844 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16845 /// For the reciprocal, we need to find the zero of the function:
16846 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
16847 ///     =>
16848 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
16849 ///     does not require additional intermediate precision]
16850 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
16851   if (Level >= AfterLegalizeDAG)
16852     return SDValue();
16853 
16854   // TODO: Handle half and/or extended types?
16855   EVT VT = Op.getValueType();
16856   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16857     return SDValue();
16858 
16859   // If estimates are explicitly disabled for this function, we're done.
16860   MachineFunction &MF = DAG.getMachineFunction();
16861   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
16862   if (Enabled == TLI.ReciprocalEstimate::Disabled)
16863     return SDValue();
16864 
16865   // Estimates may be explicitly enabled for this type with a custom number of
16866   // refinement steps.
16867   int Iterations = TLI.getDivRefinementSteps(VT, MF);
16868   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
16869     AddToWorklist(Est.getNode());
16870 
16871     if (Iterations) {
16872       EVT VT = Op.getValueType();
16873       SDLoc DL(Op);
16874       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
16875 
16876       // Newton iterations: Est = Est + Est (1 - Arg * Est)
16877       for (int i = 0; i < Iterations; ++i) {
16878         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
16879         AddToWorklist(NewEst.getNode());
16880 
16881         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
16882         AddToWorklist(NewEst.getNode());
16883 
16884         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16885         AddToWorklist(NewEst.getNode());
16886 
16887         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
16888         AddToWorklist(Est.getNode());
16889       }
16890     }
16891     return Est;
16892   }
16893 
16894   return SDValue();
16895 }
16896 
16897 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16898 /// For the reciprocal sqrt, we need to find the zero of the function:
16899 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16900 ///     =>
16901 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
16902 /// As a result, we precompute A/2 prior to the iteration loop.
16903 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
16904                                          unsigned Iterations,
16905                                          SDNodeFlags Flags, bool Reciprocal) {
16906   EVT VT = Arg.getValueType();
16907   SDLoc DL(Arg);
16908   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
16909 
16910   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
16911   // this entire sequence requires only one FP constant.
16912   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
16913   AddToWorklist(HalfArg.getNode());
16914 
16915   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
16916   AddToWorklist(HalfArg.getNode());
16917 
16918   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
16919   for (unsigned i = 0; i < Iterations; ++i) {
16920     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
16921     AddToWorklist(NewEst.getNode());
16922 
16923     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
16924     AddToWorklist(NewEst.getNode());
16925 
16926     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
16927     AddToWorklist(NewEst.getNode());
16928 
16929     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16930     AddToWorklist(Est.getNode());
16931   }
16932 
16933   // If non-reciprocal square root is requested, multiply the result by Arg.
16934   if (!Reciprocal) {
16935     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
16936     AddToWorklist(Est.getNode());
16937   }
16938 
16939   return Est;
16940 }
16941 
16942 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16943 /// For the reciprocal sqrt, we need to find the zero of the function:
16944 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16945 ///     =>
16946 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
16947 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
16948                                          unsigned Iterations,
16949                                          SDNodeFlags Flags, bool Reciprocal) {
16950   EVT VT = Arg.getValueType();
16951   SDLoc DL(Arg);
16952   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
16953   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
16954 
16955   // This routine must enter the loop below to work correctly
16956   // when (Reciprocal == false).
16957   assert(Iterations > 0);
16958 
16959   // Newton iterations for reciprocal square root:
16960   // E = (E * -0.5) * ((A * E) * E + -3.0)
16961   for (unsigned i = 0; i < Iterations; ++i) {
16962     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
16963     AddToWorklist(AE.getNode());
16964 
16965     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
16966     AddToWorklist(AEE.getNode());
16967 
16968     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
16969     AddToWorklist(RHS.getNode());
16970 
16971     // When calculating a square root at the last iteration build:
16972     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
16973     // (notice a common subexpression)
16974     SDValue LHS;
16975     if (Reciprocal || (i + 1) < Iterations) {
16976       // RSQRT: LHS = (E * -0.5)
16977       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
16978     } else {
16979       // SQRT: LHS = (A * E) * -0.5
16980       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
16981     }
16982     AddToWorklist(LHS.getNode());
16983 
16984     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
16985     AddToWorklist(Est.getNode());
16986   }
16987 
16988   return Est;
16989 }
16990 
16991 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
16992 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
16993 /// Op can be zero.
16994 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
16995                                            bool Reciprocal) {
16996   if (Level >= AfterLegalizeDAG)
16997     return SDValue();
16998 
16999   // TODO: Handle half and/or extended types?
17000   EVT VT = Op.getValueType();
17001   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17002     return SDValue();
17003 
17004   // If estimates are explicitly disabled for this function, we're done.
17005   MachineFunction &MF = DAG.getMachineFunction();
17006   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
17007   if (Enabled == TLI.ReciprocalEstimate::Disabled)
17008     return SDValue();
17009 
17010   // Estimates may be explicitly enabled for this type with a custom number of
17011   // refinement steps.
17012   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
17013 
17014   bool UseOneConstNR = false;
17015   if (SDValue Est =
17016       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
17017                           Reciprocal)) {
17018     AddToWorklist(Est.getNode());
17019 
17020     if (Iterations) {
17021       Est = UseOneConstNR
17022             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
17023             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
17024 
17025       if (!Reciprocal) {
17026         // Unfortunately, Est is now NaN if the input was exactly 0.0.
17027         // Select out this case and force the answer to 0.0.
17028         EVT VT = Op.getValueType();
17029         SDLoc DL(Op);
17030 
17031         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
17032         EVT CCVT = getSetCCResultType(VT);
17033         SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
17034         AddToWorklist(ZeroCmp.getNode());
17035 
17036         Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
17037                           ZeroCmp, FPZero, Est);
17038         AddToWorklist(Est.getNode());
17039       }
17040     }
17041     return Est;
17042   }
17043 
17044   return SDValue();
17045 }
17046 
17047 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17048   return buildSqrtEstimateImpl(Op, Flags, true);
17049 }
17050 
17051 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17052   return buildSqrtEstimateImpl(Op, Flags, false);
17053 }
17054 
17055 /// Return true if base is a frame index, which is known not to alias with
17056 /// anything but itself.  Provides base object and offset as results.
17057 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
17058                            const GlobalValue *&GV, const void *&CV) {
17059   // Assume it is a primitive operation.
17060   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
17061 
17062   // If it's an adding a simple constant then integrate the offset.
17063   if (Base.getOpcode() == ISD::ADD) {
17064     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
17065       Base = Base.getOperand(0);
17066       Offset += C->getSExtValue();
17067     }
17068   }
17069 
17070   // Return the underlying GlobalValue, and update the Offset.  Return false
17071   // for GlobalAddressSDNode since the same GlobalAddress may be represented
17072   // by multiple nodes with different offsets.
17073   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
17074     GV = G->getGlobal();
17075     Offset += G->getOffset();
17076     return false;
17077   }
17078 
17079   // Return the underlying Constant value, and update the Offset.  Return false
17080   // for ConstantSDNodes since the same constant pool entry may be represented
17081   // by multiple nodes with different offsets.
17082   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
17083     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
17084                                          : (const void *)C->getConstVal();
17085     Offset += C->getOffset();
17086     return false;
17087   }
17088   // If it's any of the following then it can't alias with anything but itself.
17089   return isa<FrameIndexSDNode>(Base);
17090 }
17091 
17092 /// Return true if there is any possibility that the two addresses overlap.
17093 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
17094   // If they are the same then they must be aliases.
17095   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
17096 
17097   // If they are both volatile then they cannot be reordered.
17098   if (Op0->isVolatile() && Op1->isVolatile()) return true;
17099 
17100   // If one operation reads from invariant memory, and the other may store, they
17101   // cannot alias. These should really be checking the equivalent of mayWrite,
17102   // but it only matters for memory nodes other than load /store.
17103   if (Op0->isInvariant() && Op1->writeMem())
17104     return false;
17105 
17106   if (Op1->isInvariant() && Op0->writeMem())
17107     return false;
17108 
17109   unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
17110   unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
17111 
17112   // Check for BaseIndexOffset matching.
17113   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
17114   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
17115   int64_t PtrDiff;
17116   if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
17117     return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
17118 
17119   // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
17120   // able to calculate their relative offset if at least one arises
17121   // from an alloca. However, these allocas cannot overlap and we
17122   // can infer there is no alias.
17123   if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
17124     if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
17125       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17126       // If the base are the same frame index but the we couldn't find a
17127       // constant offset, (indices are different) be conservative.
17128       if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
17129                      !MFI.isFixedObjectIndex(B->getIndex())))
17130         return false;
17131     }
17132 
17133   // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
17134   // modified to use BaseIndexOffset.
17135 
17136   // Gather base node and offset information.
17137   SDValue Base0, Base1;
17138   int64_t Offset0, Offset1;
17139   const GlobalValue *GV0, *GV1;
17140   const void *CV0, *CV1;
17141   bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
17142                                       Base0, Offset0, GV0, CV0);
17143   bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
17144                                       Base1, Offset1, GV1, CV1);
17145 
17146   // If they have the same base address, then check to see if they overlap.
17147   if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
17148     return !((Offset0 + NumBytes0) <= Offset1 ||
17149              (Offset1 + NumBytes1) <= Offset0);
17150 
17151   // It is possible for different frame indices to alias each other, mostly
17152   // when tail call optimization reuses return address slots for arguments.
17153   // To catch this case, look up the actual index of frame indices to compute
17154   // the real alias relationship.
17155   if (IsFrameIndex0 && IsFrameIndex1) {
17156     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17157     Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
17158     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
17159     return !((Offset0 + NumBytes0) <= Offset1 ||
17160              (Offset1 + NumBytes1) <= Offset0);
17161   }
17162 
17163   // Otherwise, if we know what the bases are, and they aren't identical, then
17164   // we know they cannot alias.
17165   if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
17166     return false;
17167 
17168   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
17169   // compared to the size and offset of the access, we may be able to prove they
17170   // do not alias. This check is conservative for now to catch cases created by
17171   // splitting vector types.
17172   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
17173   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
17174   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
17175   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
17176   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
17177       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
17178     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
17179     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
17180 
17181     // There is no overlap between these relatively aligned accesses of similar
17182     // size. Return no alias.
17183     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
17184         (OffAlign1 + NumBytes1) <= OffAlign0)
17185       return false;
17186   }
17187 
17188   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
17189                    ? CombinerGlobalAA
17190                    : DAG.getSubtarget().useAA();
17191 #ifndef NDEBUG
17192   if (CombinerAAOnlyFunc.getNumOccurrences() &&
17193       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
17194     UseAA = false;
17195 #endif
17196 
17197   if (UseAA && AA &&
17198       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
17199     // Use alias analysis information.
17200     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
17201     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
17202     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
17203     AliasResult AAResult =
17204         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
17205                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
17206                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
17207                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
17208     if (AAResult == NoAlias)
17209       return false;
17210   }
17211 
17212   // Otherwise we have to assume they alias.
17213   return true;
17214 }
17215 
17216 /// Walk up chain skipping non-aliasing memory nodes,
17217 /// looking for aliasing nodes and adding them to the Aliases vector.
17218 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
17219                                    SmallVectorImpl<SDValue> &Aliases) {
17220   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
17221   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
17222 
17223   // Get alias information for node.
17224   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
17225 
17226   // Starting off.
17227   Chains.push_back(OriginalChain);
17228   unsigned Depth = 0;
17229 
17230   // Look at each chain and determine if it is an alias.  If so, add it to the
17231   // aliases list.  If not, then continue up the chain looking for the next
17232   // candidate.
17233   while (!Chains.empty()) {
17234     SDValue Chain = Chains.pop_back_val();
17235 
17236     // For TokenFactor nodes, look at each operand and only continue up the
17237     // chain until we reach the depth limit.
17238     //
17239     // FIXME: The depth check could be made to return the last non-aliasing
17240     // chain we found before we hit a tokenfactor rather than the original
17241     // chain.
17242     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
17243       Aliases.clear();
17244       Aliases.push_back(OriginalChain);
17245       return;
17246     }
17247 
17248     // Don't bother if we've been before.
17249     if (!Visited.insert(Chain.getNode()).second)
17250       continue;
17251 
17252     switch (Chain.getOpcode()) {
17253     case ISD::EntryToken:
17254       // Entry token is ideal chain operand, but handled in FindBetterChain.
17255       break;
17256 
17257     case ISD::LOAD:
17258     case ISD::STORE: {
17259       // Get alias information for Chain.
17260       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
17261           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
17262 
17263       // If chain is alias then stop here.
17264       if (!(IsLoad && IsOpLoad) &&
17265           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
17266         Aliases.push_back(Chain);
17267       } else {
17268         // Look further up the chain.
17269         Chains.push_back(Chain.getOperand(0));
17270         ++Depth;
17271       }
17272       break;
17273     }
17274 
17275     case ISD::TokenFactor:
17276       // We have to check each of the operands of the token factor for "small"
17277       // token factors, so we queue them up.  Adding the operands to the queue
17278       // (stack) in reverse order maintains the original order and increases the
17279       // likelihood that getNode will find a matching token factor (CSE.)
17280       if (Chain.getNumOperands() > 16) {
17281         Aliases.push_back(Chain);
17282         break;
17283       }
17284       for (unsigned n = Chain.getNumOperands(); n;)
17285         Chains.push_back(Chain.getOperand(--n));
17286       ++Depth;
17287       break;
17288 
17289     case ISD::CopyFromReg:
17290       // Forward past CopyFromReg.
17291       Chains.push_back(Chain.getOperand(0));
17292       ++Depth;
17293       break;
17294 
17295     default:
17296       // For all other instructions we will just have to take what we can get.
17297       Aliases.push_back(Chain);
17298       break;
17299     }
17300   }
17301 }
17302 
17303 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
17304 /// (aliasing node.)
17305 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
17306   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
17307 
17308   // Accumulate all the aliases to this node.
17309   GatherAllAliases(N, OldChain, Aliases);
17310 
17311   // If no operands then chain to entry token.
17312   if (Aliases.size() == 0)
17313     return DAG.getEntryNode();
17314 
17315   // If a single operand then chain to it.  We don't need to revisit it.
17316   if (Aliases.size() == 1)
17317     return Aliases[0];
17318 
17319   // Construct a custom tailored token factor.
17320   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
17321 }
17322 
17323 // This function tries to collect a bunch of potentially interesting
17324 // nodes to improve the chains of, all at once. This might seem
17325 // redundant, as this function gets called when visiting every store
17326 // node, so why not let the work be done on each store as it's visited?
17327 //
17328 // I believe this is mainly important because MergeConsecutiveStores
17329 // is unable to deal with merging stores of different sizes, so unless
17330 // we improve the chains of all the potential candidates up-front
17331 // before running MergeConsecutiveStores, it might only see some of
17332 // the nodes that will eventually be candidates, and then not be able
17333 // to go from a partially-merged state to the desired final
17334 // fully-merged state.
17335 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
17336   // This holds the base pointer, index, and the offset in bytes from the base
17337   // pointer.
17338   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
17339 
17340   // We must have a base and an offset.
17341   if (!BasePtr.getBase().getNode())
17342     return false;
17343 
17344   // Do not handle stores to undef base pointers.
17345   if (BasePtr.getBase().isUndef())
17346     return false;
17347 
17348   SmallVector<StoreSDNode *, 8> ChainedStores;
17349   ChainedStores.push_back(St);
17350 
17351   // Walk up the chain and look for nodes with offsets from the same
17352   // base pointer. Stop when reaching an instruction with a different kind
17353   // or instruction which has a different base pointer.
17354   StoreSDNode *Index = St;
17355   while (Index) {
17356     // If the chain has more than one use, then we can't reorder the mem ops.
17357     if (Index != St && !SDValue(Index, 0)->hasOneUse())
17358       break;
17359 
17360     if (Index->isVolatile() || Index->isIndexed())
17361       break;
17362 
17363     // Find the base pointer and offset for this memory node.
17364     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
17365 
17366     // Check that the base pointer is the same as the original one.
17367     if (!BasePtr.equalBaseIndex(Ptr, DAG))
17368       break;
17369 
17370     // Walk up the chain to find the next store node, ignoring any
17371     // intermediate loads. Any other kind of node will halt the loop.
17372     SDNode *NextInChain = Index->getChain().getNode();
17373     while (true) {
17374       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
17375         // We found a store node. Use it for the next iteration.
17376         if (STn->isVolatile() || STn->isIndexed()) {
17377           Index = nullptr;
17378           break;
17379         }
17380         ChainedStores.push_back(STn);
17381         Index = STn;
17382         break;
17383       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
17384         NextInChain = Ldn->getChain().getNode();
17385         continue;
17386       } else {
17387         Index = nullptr;
17388         break;
17389       }
17390     } // end while
17391   }
17392 
17393   // At this point, ChainedStores lists all of the Store nodes
17394   // reachable by iterating up through chain nodes matching the above
17395   // conditions.  For each such store identified, try to find an
17396   // earlier chain to attach the store to which won't violate the
17397   // required ordering.
17398   bool MadeChangeToSt = false;
17399   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
17400 
17401   for (StoreSDNode *ChainedStore : ChainedStores) {
17402     SDValue Chain = ChainedStore->getChain();
17403     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
17404 
17405     if (Chain != BetterChain) {
17406       if (ChainedStore == St)
17407         MadeChangeToSt = true;
17408       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
17409     }
17410   }
17411 
17412   // Do all replacements after finding the replacements to make to avoid making
17413   // the chains more complicated by introducing new TokenFactors.
17414   for (auto Replacement : BetterChains)
17415     replaceStoreChain(Replacement.first, Replacement.second);
17416 
17417   return MadeChangeToSt;
17418 }
17419 
17420 /// This is the entry point for the file.
17421 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
17422                            CodeGenOpt::Level OptLevel) {
17423   /// This is the main entry point to this class.
17424   DAGCombiner(*this, AA, OptLevel).Run(Level);
17425 }
17426