1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 #include <algorithm>
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "dagcombine"
45 
46 STATISTIC(NodesCombined   , "Number of dag nodes combined");
47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
49 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
50 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
51 STATISTIC(SlicedLoads, "Number of load sliced");
52 
53 namespace {
54   static cl::opt<bool>
55     CombinerAA("combiner-alias-analysis", cl::Hidden,
56                cl::desc("Enable DAG combiner alias-analysis heuristics"));
57 
58   static cl::opt<bool>
59     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60                cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 
62   static cl::opt<bool>
63     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
64                cl::desc("Enable DAG combiner's use of TBAA"));
65 
66 #ifndef NDEBUG
67   static cl::opt<std::string>
68     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
69                cl::desc("Only use DAG-combiner alias analysis in this"
70                         " function"));
71 #endif
72 
73   /// Hidden option to stress test load slicing, i.e., when this option
74   /// is enabled, load slicing bypasses most of its profitability guards.
75   static cl::opt<bool>
76   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
77                     cl::desc("Bypass the profitability model of load "
78                              "slicing"),
79                     cl::init(false));
80 
81   static cl::opt<bool>
82     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
83                       cl::desc("DAG combiner may split indexing from loads"));
84 
85 //------------------------------ DAGCombiner ---------------------------------//
86 
87   class DAGCombiner {
88     SelectionDAG &DAG;
89     const TargetLowering &TLI;
90     CombineLevel Level;
91     CodeGenOpt::Level OptLevel;
92     bool LegalOperations;
93     bool LegalTypes;
94     bool ForCodeSize;
95 
96     /// \brief Worklist of all of the nodes that need to be simplified.
97     ///
98     /// This must behave as a stack -- new nodes to process are pushed onto the
99     /// back and when processing we pop off of the back.
100     ///
101     /// The worklist will not contain duplicates but may contain null entries
102     /// due to nodes being deleted from the underlying DAG.
103     SmallVector<SDNode *, 64> Worklist;
104 
105     /// \brief Mapping from an SDNode to its position on the worklist.
106     ///
107     /// This is used to find and remove nodes from the worklist (by nulling
108     /// them) when they are deleted from the underlying DAG. It relies on
109     /// stable indices of nodes within the worklist.
110     DenseMap<SDNode *, unsigned> WorklistMap;
111 
112     /// \brief Set of nodes which have been combined (at least once).
113     ///
114     /// This is used to allow us to reliably add any operands of a DAG node
115     /// which have not yet been combined to the worklist.
116     SmallPtrSet<SDNode *, 32> CombinedNodes;
117 
118     // AA - Used for DAG load/store alias analysis.
119     AliasAnalysis &AA;
120 
121     /// When an instruction is simplified, add all users of the instruction to
122     /// the work lists because they might get more simplified now.
123     void AddUsersToWorklist(SDNode *N) {
124       for (SDNode *Node : N->uses())
125         AddToWorklist(Node);
126     }
127 
128     /// Call the node-specific routine that folds each particular type of node.
129     SDValue visit(SDNode *N);
130 
131   public:
132     /// Add to the worklist making sure its instance is at the back (next to be
133     /// processed.)
134     void AddToWorklist(SDNode *N) {
135       // Skip handle nodes as they can't usefully be combined and confuse the
136       // zero-use deletion strategy.
137       if (N->getOpcode() == ISD::HANDLENODE)
138         return;
139 
140       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
141         Worklist.push_back(N);
142     }
143 
144     /// Remove all instances of N from the worklist.
145     void removeFromWorklist(SDNode *N) {
146       CombinedNodes.erase(N);
147 
148       auto It = WorklistMap.find(N);
149       if (It == WorklistMap.end())
150         return; // Not in the worklist.
151 
152       // Null out the entry rather than erasing it to avoid a linear operation.
153       Worklist[It->second] = nullptr;
154       WorklistMap.erase(It);
155     }
156 
157     void deleteAndRecombine(SDNode *N);
158     bool recursivelyDeleteUnusedNodes(SDNode *N);
159 
160     /// Replaces all uses of the results of one DAG node with new values.
161     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162                       bool AddTo = true);
163 
164     /// Replaces all uses of the results of one DAG node with new values.
165     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
166       return CombineTo(N, &Res, 1, AddTo);
167     }
168 
169     /// Replaces all uses of the results of one DAG node with new values.
170     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
171                       bool AddTo = true) {
172       SDValue To[] = { Res0, Res1 };
173       return CombineTo(N, To, 2, AddTo);
174     }
175 
176     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
177 
178   private:
179 
180     /// Check the specified integer node value to see if it can be simplified or
181     /// if things it uses can be simplified by bit propagation.
182     /// If so, return true.
183     bool SimplifyDemandedBits(SDValue Op) {
184       unsigned BitWidth = Op.getScalarValueSizeInBits();
185       APInt Demanded = APInt::getAllOnesValue(BitWidth);
186       return SimplifyDemandedBits(Op, Demanded);
187     }
188 
189     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
190 
191     bool CombineToPreIndexedLoadStore(SDNode *N);
192     bool CombineToPostIndexedLoadStore(SDNode *N);
193     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
194     bool SliceUpLoad(SDNode *N);
195 
196     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
197     ///   load.
198     ///
199     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
200     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
201     /// \param EltNo index of the vector element to load.
202     /// \param OriginalLoad load that EVE came from to be replaced.
203     /// \returns EVE on success SDValue() on failure.
204     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
205         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
206     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
207     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
208     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
210     SDValue PromoteIntBinOp(SDValue Op);
211     SDValue PromoteIntShiftOp(SDValue Op);
212     SDValue PromoteExtend(SDValue Op);
213     bool PromoteLoad(SDValue Op);
214 
215     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
216                          SDValue ExtLoad, const SDLoc &DL,
217                          ISD::NodeType ExtType);
218 
219     /// Call the node-specific routine that knows how to fold each
220     /// particular type of node. If that doesn't do anything, try the
221     /// target-specific DAG combines.
222     SDValue combine(SDNode *N);
223 
224     // Visitation implementation - Implement dag node combining for different
225     // node types.  The semantics are as follows:
226     // Return Value:
227     //   SDValue.getNode() == 0 - No change was made
228     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
229     //   otherwise              - N should be replaced by the returned Operand.
230     //
231     SDValue visitTokenFactor(SDNode *N);
232     SDValue visitMERGE_VALUES(SDNode *N);
233     SDValue visitADD(SDNode *N);
234     SDValue visitSUB(SDNode *N);
235     SDValue visitADDC(SDNode *N);
236     SDValue visitSUBC(SDNode *N);
237     SDValue visitADDE(SDNode *N);
238     SDValue visitSUBE(SDNode *N);
239     SDValue visitMUL(SDNode *N);
240     SDValue useDivRem(SDNode *N);
241     SDValue visitSDIV(SDNode *N);
242     SDValue visitUDIV(SDNode *N);
243     SDValue visitREM(SDNode *N);
244     SDValue visitMULHU(SDNode *N);
245     SDValue visitMULHS(SDNode *N);
246     SDValue visitSMUL_LOHI(SDNode *N);
247     SDValue visitUMUL_LOHI(SDNode *N);
248     SDValue visitSMULO(SDNode *N);
249     SDValue visitUMULO(SDNode *N);
250     SDValue visitIMINMAX(SDNode *N);
251     SDValue visitAND(SDNode *N);
252     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitOR(SDNode *N);
254     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
255     SDValue visitXOR(SDNode *N);
256     SDValue SimplifyVBinOp(SDNode *N);
257     SDValue visitSHL(SDNode *N);
258     SDValue visitSRA(SDNode *N);
259     SDValue visitSRL(SDNode *N);
260     SDValue visitRotate(SDNode *N);
261     SDValue visitBSWAP(SDNode *N);
262     SDValue visitBITREVERSE(SDNode *N);
263     SDValue visitCTLZ(SDNode *N);
264     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
265     SDValue visitCTTZ(SDNode *N);
266     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
267     SDValue visitCTPOP(SDNode *N);
268     SDValue visitSELECT(SDNode *N);
269     SDValue visitVSELECT(SDNode *N);
270     SDValue visitSELECT_CC(SDNode *N);
271     SDValue visitSETCC(SDNode *N);
272     SDValue visitSETCCE(SDNode *N);
273     SDValue visitSIGN_EXTEND(SDNode *N);
274     SDValue visitZERO_EXTEND(SDNode *N);
275     SDValue visitANY_EXTEND(SDNode *N);
276     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
277     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
278     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
279     SDValue visitTRUNCATE(SDNode *N);
280     SDValue visitBITCAST(SDNode *N);
281     SDValue visitBUILD_PAIR(SDNode *N);
282     SDValue visitFADD(SDNode *N);
283     SDValue visitFSUB(SDNode *N);
284     SDValue visitFMUL(SDNode *N);
285     SDValue visitFMA(SDNode *N);
286     SDValue visitFDIV(SDNode *N);
287     SDValue visitFREM(SDNode *N);
288     SDValue visitFSQRT(SDNode *N);
289     SDValue visitFCOPYSIGN(SDNode *N);
290     SDValue visitSINT_TO_FP(SDNode *N);
291     SDValue visitUINT_TO_FP(SDNode *N);
292     SDValue visitFP_TO_SINT(SDNode *N);
293     SDValue visitFP_TO_UINT(SDNode *N);
294     SDValue visitFP_ROUND(SDNode *N);
295     SDValue visitFP_ROUND_INREG(SDNode *N);
296     SDValue visitFP_EXTEND(SDNode *N);
297     SDValue visitFNEG(SDNode *N);
298     SDValue visitFABS(SDNode *N);
299     SDValue visitFCEIL(SDNode *N);
300     SDValue visitFTRUNC(SDNode *N);
301     SDValue visitFFLOOR(SDNode *N);
302     SDValue visitFMINNUM(SDNode *N);
303     SDValue visitFMAXNUM(SDNode *N);
304     SDValue visitBRCOND(SDNode *N);
305     SDValue visitBR_CC(SDNode *N);
306     SDValue visitLOAD(SDNode *N);
307 
308     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
309     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
310 
311     SDValue visitSTORE(SDNode *N);
312     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
313     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
314     SDValue visitBUILD_VECTOR(SDNode *N);
315     SDValue visitCONCAT_VECTORS(SDNode *N);
316     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
317     SDValue visitVECTOR_SHUFFLE(SDNode *N);
318     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
319     SDValue visitINSERT_SUBVECTOR(SDNode *N);
320     SDValue visitMLOAD(SDNode *N);
321     SDValue visitMSTORE(SDNode *N);
322     SDValue visitMGATHER(SDNode *N);
323     SDValue visitMSCATTER(SDNode *N);
324     SDValue visitFP_TO_FP16(SDNode *N);
325     SDValue visitFP16_TO_FP(SDNode *N);
326 
327     SDValue visitFADDForFMACombine(SDNode *N);
328     SDValue visitFSUBForFMACombine(SDNode *N);
329     SDValue visitFMULForFMACombine(SDNode *N);
330 
331     SDValue XformToShuffleWithZero(SDNode *N);
332     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
333                            SDValue RHS);
334 
335     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
336 
337     SDValue foldSelectOfConstants(SDNode *N);
338     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
339     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
340     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
341     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
342                              SDValue N2, SDValue N3, ISD::CondCode CC,
343                              bool NotExtCompare = false);
344     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
345                           const SDLoc &DL, bool foldBooleans = true);
346 
347     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
348                            SDValue &CC) const;
349     bool isOneUseSetCC(SDValue N) const;
350 
351     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
352                                          unsigned HiOp);
353     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
354     SDValue CombineExtLoad(SDNode *N);
355     SDValue combineRepeatedFPDivisors(SDNode *N);
356     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
357     SDValue BuildSDIV(SDNode *N);
358     SDValue BuildSDIVPow2(SDNode *N);
359     SDValue BuildUDIV(SDNode *N);
360     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
361     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
362     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
363     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
364     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
365                                 SDNodeFlags *Flags, bool Reciprocal);
366     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
367                                 SDNodeFlags *Flags, bool Reciprocal);
368     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
369                                bool DemandHighBits = true);
370     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
371     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
372                               SDValue InnerPos, SDValue InnerNeg,
373                               unsigned PosOpcode, unsigned NegOpcode,
374                               const SDLoc &DL);
375     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
376     SDValue ReduceLoadWidth(SDNode *N);
377     SDValue ReduceLoadOpStoreWidth(SDNode *N);
378     SDValue splitMergedValStore(StoreSDNode *ST);
379     SDValue TransformFPLoadStorePair(SDNode *N);
380     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
381     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
382     SDValue reduceBuildVecToShuffle(SDNode *N);
383     SDValue createBuildVecShuffle(SDLoc DL, SDNode *N, ArrayRef<int> VectorMask,
384                                   SDValue VecIn1, SDValue VecIn2,
385                                   unsigned LeftIdx);
386 
387     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
388 
389     /// Walk up chain skipping non-aliasing memory nodes,
390     /// looking for aliasing nodes and adding them to the Aliases vector.
391     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
392                           SmallVectorImpl<SDValue> &Aliases);
393 
394     /// Return true if there is any possibility that the two addresses overlap.
395     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
396 
397     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
398     /// chain (aliasing node.)
399     SDValue FindBetterChain(SDNode *N, SDValue Chain);
400 
401     /// Try to replace a store and any possibly adjacent stores on
402     /// consecutive chains with better chains. Return true only if St is
403     /// replaced.
404     ///
405     /// Notice that other chains may still be replaced even if the function
406     /// returns false.
407     bool findBetterNeighborChains(StoreSDNode *St);
408 
409     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
410     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
411 
412     /// Holds a pointer to an LSBaseSDNode as well as information on where it
413     /// is located in a sequence of memory operations connected by a chain.
414     struct MemOpLink {
415       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
416       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
417       // Ptr to the mem node.
418       LSBaseSDNode *MemNode;
419       // Offset from the base ptr.
420       int64_t OffsetFromBase;
421       // What is the sequence number of this mem node.
422       // Lowest mem operand in the DAG starts at zero.
423       unsigned SequenceNum;
424     };
425 
426     /// This is a helper function for visitMUL to check the profitability
427     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
428     /// MulNode is the original multiply, AddNode is (add x, c1),
429     /// and ConstNode is c2.
430     bool isMulAddWithConstProfitable(SDNode *MulNode,
431                                      SDValue &AddNode,
432                                      SDValue &ConstNode);
433 
434     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
435     /// constant build_vector of the stored constant values in Stores.
436     SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL,
437                                          ArrayRef<MemOpLink> Stores,
438                                          SmallVectorImpl<SDValue> &Chains,
439                                          EVT Ty) const;
440 
441     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
442     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
443     /// the type of the loaded value to be extended.  LoadedVT returns the type
444     /// of the original loaded value.  NarrowLoad returns whether the load would
445     /// need to be narrowed in order to match.
446     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
447                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
448                           bool &NarrowLoad);
449 
450     /// This is a helper function for MergeConsecutiveStores. When the source
451     /// elements of the consecutive stores are all constants or all extracted
452     /// vector elements, try to merge them into one larger store.
453     /// \return True if a merged store was created.
454     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
455                                          EVT MemVT, unsigned NumStores,
456                                          bool IsConstantSrc, bool UseVector);
457 
458     /// This is a helper function for MergeConsecutiveStores.
459     /// Stores that may be merged are placed in StoreNodes.
460     /// Loads that may alias with those stores are placed in AliasLoadNodes.
461     void getStoreMergeAndAliasCandidates(
462         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
463         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
464 
465     /// Helper function for MergeConsecutiveStores. Checks if
466     /// Candidate stores have indirect dependency through their
467     /// operands. \return True if safe to merge
468     bool checkMergeStoreCandidatesForDependencies(
469         SmallVectorImpl<MemOpLink> &StoreNodes);
470 
471     /// Merge consecutive store operations into a wide store.
472     /// This optimization uses wide integers or vectors when possible.
473     /// \return True if some memory operations were changed.
474     bool MergeConsecutiveStores(StoreSDNode *N);
475 
476     /// \brief Try to transform a truncation where C is a constant:
477     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
478     ///
479     /// \p N needs to be a truncation and its first operand an AND. Other
480     /// requirements are checked by the function (e.g. that trunc is
481     /// single-use) and if missed an empty SDValue is returned.
482     SDValue distributeTruncateThroughAnd(SDNode *N);
483 
484   public:
485     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
486         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
487           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
488       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
489     }
490 
491     /// Runs the dag combiner on all nodes in the work list
492     void Run(CombineLevel AtLevel);
493 
494     SelectionDAG &getDAG() const { return DAG; }
495 
496     /// Returns a type large enough to hold any valid shift amount - before type
497     /// legalization these can be huge.
498     EVT getShiftAmountTy(EVT LHSTy) {
499       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
500       if (LHSTy.isVector())
501         return LHSTy;
502       auto &DL = DAG.getDataLayout();
503       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
504                         : TLI.getPointerTy(DL);
505     }
506 
507     /// This method returns true if we are running before type legalization or
508     /// if the specified VT is legal.
509     bool isTypeLegal(const EVT &VT) {
510       if (!LegalTypes) return true;
511       return TLI.isTypeLegal(VT);
512     }
513 
514     /// Convenience wrapper around TargetLowering::getSetCCResultType
515     EVT getSetCCResultType(EVT VT) const {
516       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
517     }
518   };
519 }
520 
521 
522 namespace {
523 /// This class is a DAGUpdateListener that removes any deleted
524 /// nodes from the worklist.
525 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
526   DAGCombiner &DC;
527 public:
528   explicit WorklistRemover(DAGCombiner &dc)
529     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
530 
531   void NodeDeleted(SDNode *N, SDNode *E) override {
532     DC.removeFromWorklist(N);
533   }
534 };
535 }
536 
537 //===----------------------------------------------------------------------===//
538 //  TargetLowering::DAGCombinerInfo implementation
539 //===----------------------------------------------------------------------===//
540 
541 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
542   ((DAGCombiner*)DC)->AddToWorklist(N);
543 }
544 
545 SDValue TargetLowering::DAGCombinerInfo::
546 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
547   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
548 }
549 
550 SDValue TargetLowering::DAGCombinerInfo::
551 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
552   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
553 }
554 
555 
556 SDValue TargetLowering::DAGCombinerInfo::
557 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
558   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
559 }
560 
561 void TargetLowering::DAGCombinerInfo::
562 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
563   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
564 }
565 
566 //===----------------------------------------------------------------------===//
567 // Helper Functions
568 //===----------------------------------------------------------------------===//
569 
570 void DAGCombiner::deleteAndRecombine(SDNode *N) {
571   removeFromWorklist(N);
572 
573   // If the operands of this node are only used by the node, they will now be
574   // dead. Make sure to re-visit them and recursively delete dead nodes.
575   for (const SDValue &Op : N->ops())
576     // For an operand generating multiple values, one of the values may
577     // become dead allowing further simplification (e.g. split index
578     // arithmetic from an indexed load).
579     if (Op->hasOneUse() || Op->getNumValues() > 1)
580       AddToWorklist(Op.getNode());
581 
582   DAG.DeleteNode(N);
583 }
584 
585 /// Return 1 if we can compute the negated form of the specified expression for
586 /// the same cost as the expression itself, or 2 if we can compute the negated
587 /// form more cheaply than the expression itself.
588 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
589                                const TargetLowering &TLI,
590                                const TargetOptions *Options,
591                                unsigned Depth = 0) {
592   // fneg is removable even if it has multiple uses.
593   if (Op.getOpcode() == ISD::FNEG) return 2;
594 
595   // Don't allow anything with multiple uses.
596   if (!Op.hasOneUse()) return 0;
597 
598   // Don't recurse exponentially.
599   if (Depth > 6) return 0;
600 
601   switch (Op.getOpcode()) {
602   default: return false;
603   case ISD::ConstantFP:
604     // Don't invert constant FP values after legalize.  The negated constant
605     // isn't necessarily legal.
606     return LegalOperations ? 0 : 1;
607   case ISD::FADD:
608     // FIXME: determine better conditions for this xform.
609     if (!Options->UnsafeFPMath) return 0;
610 
611     // After operation legalization, it might not be legal to create new FSUBs.
612     if (LegalOperations &&
613         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
614       return 0;
615 
616     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
617     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
618                                     Options, Depth + 1))
619       return V;
620     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
621     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
622                               Depth + 1);
623   case ISD::FSUB:
624     // We can't turn -(A-B) into B-A when we honor signed zeros.
625     if (!Options->UnsafeFPMath) return 0;
626 
627     // fold (fneg (fsub A, B)) -> (fsub B, A)
628     return 1;
629 
630   case ISD::FMUL:
631   case ISD::FDIV:
632     if (Options->HonorSignDependentRoundingFPMath()) return 0;
633 
634     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
635     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
636                                     Options, Depth + 1))
637       return V;
638 
639     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
640                               Depth + 1);
641 
642   case ISD::FP_EXTEND:
643   case ISD::FP_ROUND:
644   case ISD::FSIN:
645     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
646                               Depth + 1);
647   }
648 }
649 
650 /// If isNegatibleForFree returns true, return the newly negated expression.
651 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
652                                     bool LegalOperations, unsigned Depth = 0) {
653   const TargetOptions &Options = DAG.getTarget().Options;
654   // fneg is removable even if it has multiple uses.
655   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
656 
657   // Don't allow anything with multiple uses.
658   assert(Op.hasOneUse() && "Unknown reuse!");
659 
660   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
661 
662   const SDNodeFlags *Flags = Op.getNode()->getFlags();
663 
664   switch (Op.getOpcode()) {
665   default: llvm_unreachable("Unknown code");
666   case ISD::ConstantFP: {
667     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
668     V.changeSign();
669     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
670   }
671   case ISD::FADD:
672     // FIXME: determine better conditions for this xform.
673     assert(Options.UnsafeFPMath);
674 
675     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
676     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
677                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
678       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
679                          GetNegatedExpression(Op.getOperand(0), DAG,
680                                               LegalOperations, Depth+1),
681                          Op.getOperand(1), Flags);
682     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
683     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
684                        GetNegatedExpression(Op.getOperand(1), DAG,
685                                             LegalOperations, Depth+1),
686                        Op.getOperand(0), Flags);
687   case ISD::FSUB:
688     // We can't turn -(A-B) into B-A when we honor signed zeros.
689     assert(Options.UnsafeFPMath);
690 
691     // fold (fneg (fsub 0, B)) -> B
692     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
693       if (N0CFP->isZero())
694         return Op.getOperand(1);
695 
696     // fold (fneg (fsub A, B)) -> (fsub B, A)
697     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
698                        Op.getOperand(1), Op.getOperand(0), Flags);
699 
700   case ISD::FMUL:
701   case ISD::FDIV:
702     assert(!Options.HonorSignDependentRoundingFPMath());
703 
704     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
705     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
706                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
707       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
708                          GetNegatedExpression(Op.getOperand(0), DAG,
709                                               LegalOperations, Depth+1),
710                          Op.getOperand(1), Flags);
711 
712     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
713     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
714                        Op.getOperand(0),
715                        GetNegatedExpression(Op.getOperand(1), DAG,
716                                             LegalOperations, Depth+1), Flags);
717 
718   case ISD::FP_EXTEND:
719   case ISD::FSIN:
720     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
721                        GetNegatedExpression(Op.getOperand(0), DAG,
722                                             LegalOperations, Depth+1));
723   case ISD::FP_ROUND:
724       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
725                          GetNegatedExpression(Op.getOperand(0), DAG,
726                                               LegalOperations, Depth+1),
727                          Op.getOperand(1));
728   }
729 }
730 
731 // APInts must be the same size for most operations, this helper
732 // function zero extends the shorter of the pair so that they match.
733 // We provide an Offset so that we can create bitwidths that won't overflow.
734 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
735   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
736   LHS = LHS.zextOrSelf(Bits);
737   RHS = RHS.zextOrSelf(Bits);
738 }
739 
740 // Return true if this node is a setcc, or is a select_cc
741 // that selects between the target values used for true and false, making it
742 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
743 // the appropriate nodes based on the type of node we are checking. This
744 // simplifies life a bit for the callers.
745 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
746                                     SDValue &CC) const {
747   if (N.getOpcode() == ISD::SETCC) {
748     LHS = N.getOperand(0);
749     RHS = N.getOperand(1);
750     CC  = N.getOperand(2);
751     return true;
752   }
753 
754   if (N.getOpcode() != ISD::SELECT_CC ||
755       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
756       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
757     return false;
758 
759   if (TLI.getBooleanContents(N.getValueType()) ==
760       TargetLowering::UndefinedBooleanContent)
761     return false;
762 
763   LHS = N.getOperand(0);
764   RHS = N.getOperand(1);
765   CC  = N.getOperand(4);
766   return true;
767 }
768 
769 /// Return true if this is a SetCC-equivalent operation with only one use.
770 /// If this is true, it allows the users to invert the operation for free when
771 /// it is profitable to do so.
772 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
773   SDValue N0, N1, N2;
774   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
775     return true;
776   return false;
777 }
778 
779 // \brief Returns the SDNode if it is a constant float BuildVector
780 // or constant float.
781 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
782   if (isa<ConstantFPSDNode>(N))
783     return N.getNode();
784   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
785     return N.getNode();
786   return nullptr;
787 }
788 
789 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
790 // int.
791 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
792   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
793     return CN;
794 
795   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
796     BitVector UndefElements;
797     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
798 
799     // BuildVectors can truncate their operands. Ignore that case here.
800     // FIXME: We blindly ignore splats which include undef which is overly
801     // pessimistic.
802     if (CN && UndefElements.none() &&
803         CN->getValueType(0) == N.getValueType().getScalarType())
804       return CN;
805   }
806 
807   return nullptr;
808 }
809 
810 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
811 // float.
812 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
813   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
814     return CN;
815 
816   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
817     BitVector UndefElements;
818     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
819 
820     if (CN && UndefElements.none())
821       return CN;
822   }
823 
824   return nullptr;
825 }
826 
827 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
828                                     SDValue N1) {
829   EVT VT = N0.getValueType();
830   if (N0.getOpcode() == Opc) {
831     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
832       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
833         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
834         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
835           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
836         return SDValue();
837       }
838       if (N0.hasOneUse()) {
839         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
840         // use
841         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
842         if (!OpNode.getNode())
843           return SDValue();
844         AddToWorklist(OpNode.getNode());
845         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
846       }
847     }
848   }
849 
850   if (N1.getOpcode() == Opc) {
851     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
852       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
853         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
854         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
855           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
856         return SDValue();
857       }
858       if (N1.hasOneUse()) {
859         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
860         // use
861         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
862         if (!OpNode.getNode())
863           return SDValue();
864         AddToWorklist(OpNode.getNode());
865         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
866       }
867     }
868   }
869 
870   return SDValue();
871 }
872 
873 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
874                                bool AddTo) {
875   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
876   ++NodesCombined;
877   DEBUG(dbgs() << "\nReplacing.1 ";
878         N->dump(&DAG);
879         dbgs() << "\nWith: ";
880         To[0].getNode()->dump(&DAG);
881         dbgs() << " and " << NumTo-1 << " other values\n");
882   for (unsigned i = 0, e = NumTo; i != e; ++i)
883     assert((!To[i].getNode() ||
884             N->getValueType(i) == To[i].getValueType()) &&
885            "Cannot combine value to value of different type!");
886 
887   WorklistRemover DeadNodes(*this);
888   DAG.ReplaceAllUsesWith(N, To);
889   if (AddTo) {
890     // Push the new nodes and any users onto the worklist
891     for (unsigned i = 0, e = NumTo; i != e; ++i) {
892       if (To[i].getNode()) {
893         AddToWorklist(To[i].getNode());
894         AddUsersToWorklist(To[i].getNode());
895       }
896     }
897   }
898 
899   // Finally, if the node is now dead, remove it from the graph.  The node
900   // may not be dead if the replacement process recursively simplified to
901   // something else needing this node.
902   if (N->use_empty())
903     deleteAndRecombine(N);
904   return SDValue(N, 0);
905 }
906 
907 void DAGCombiner::
908 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
909   // Replace all uses.  If any nodes become isomorphic to other nodes and
910   // are deleted, make sure to remove them from our worklist.
911   WorklistRemover DeadNodes(*this);
912   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
913 
914   // Push the new node and any (possibly new) users onto the worklist.
915   AddToWorklist(TLO.New.getNode());
916   AddUsersToWorklist(TLO.New.getNode());
917 
918   // Finally, if the node is now dead, remove it from the graph.  The node
919   // may not be dead if the replacement process recursively simplified to
920   // something else needing this node.
921   if (TLO.Old.getNode()->use_empty())
922     deleteAndRecombine(TLO.Old.getNode());
923 }
924 
925 /// Check the specified integer node value to see if it can be simplified or if
926 /// things it uses can be simplified by bit propagation. If so, return true.
927 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
928   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
929   APInt KnownZero, KnownOne;
930   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
931     return false;
932 
933   // Revisit the node.
934   AddToWorklist(Op.getNode());
935 
936   // Replace the old value with the new one.
937   ++NodesCombined;
938   DEBUG(dbgs() << "\nReplacing.2 ";
939         TLO.Old.getNode()->dump(&DAG);
940         dbgs() << "\nWith: ";
941         TLO.New.getNode()->dump(&DAG);
942         dbgs() << '\n');
943 
944   CommitTargetLoweringOpt(TLO);
945   return true;
946 }
947 
948 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
949   SDLoc DL(Load);
950   EVT VT = Load->getValueType(0);
951   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
952 
953   DEBUG(dbgs() << "\nReplacing.9 ";
954         Load->dump(&DAG);
955         dbgs() << "\nWith: ";
956         Trunc.getNode()->dump(&DAG);
957         dbgs() << '\n');
958   WorklistRemover DeadNodes(*this);
959   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
960   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
961   deleteAndRecombine(Load);
962   AddToWorklist(Trunc.getNode());
963 }
964 
965 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
966   Replace = false;
967   SDLoc DL(Op);
968   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
969     LoadSDNode *LD = cast<LoadSDNode>(Op);
970     EVT MemVT = LD->getMemoryVT();
971     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
972       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
973                                                        : ISD::EXTLOAD)
974       : LD->getExtensionType();
975     Replace = true;
976     return DAG.getExtLoad(ExtType, DL, PVT,
977                           LD->getChain(), LD->getBasePtr(),
978                           MemVT, LD->getMemOperand());
979   }
980 
981   unsigned Opc = Op.getOpcode();
982   switch (Opc) {
983   default: break;
984   case ISD::AssertSext:
985     return DAG.getNode(ISD::AssertSext, DL, PVT,
986                        SExtPromoteOperand(Op.getOperand(0), PVT),
987                        Op.getOperand(1));
988   case ISD::AssertZext:
989     return DAG.getNode(ISD::AssertZext, DL, PVT,
990                        ZExtPromoteOperand(Op.getOperand(0), PVT),
991                        Op.getOperand(1));
992   case ISD::Constant: {
993     unsigned ExtOpc =
994       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
995     return DAG.getNode(ExtOpc, DL, PVT, Op);
996   }
997   }
998 
999   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1000     return SDValue();
1001   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1002 }
1003 
1004 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1005   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1006     return SDValue();
1007   EVT OldVT = Op.getValueType();
1008   SDLoc DL(Op);
1009   bool Replace = false;
1010   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1011   if (!NewOp.getNode())
1012     return SDValue();
1013   AddToWorklist(NewOp.getNode());
1014 
1015   if (Replace)
1016     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1017   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1018                      DAG.getValueType(OldVT));
1019 }
1020 
1021 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1022   EVT OldVT = Op.getValueType();
1023   SDLoc DL(Op);
1024   bool Replace = false;
1025   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1026   if (!NewOp.getNode())
1027     return SDValue();
1028   AddToWorklist(NewOp.getNode());
1029 
1030   if (Replace)
1031     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1032   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1033 }
1034 
1035 /// Promote the specified integer binary operation if the target indicates it is
1036 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1037 /// i32 since i16 instructions are longer.
1038 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1039   if (!LegalOperations)
1040     return SDValue();
1041 
1042   EVT VT = Op.getValueType();
1043   if (VT.isVector() || !VT.isInteger())
1044     return SDValue();
1045 
1046   // If operation type is 'undesirable', e.g. i16 on x86, consider
1047   // promoting it.
1048   unsigned Opc = Op.getOpcode();
1049   if (TLI.isTypeDesirableForOp(Opc, VT))
1050     return SDValue();
1051 
1052   EVT PVT = VT;
1053   // Consult target whether it is a good idea to promote this operation and
1054   // what's the right type to promote it to.
1055   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056     assert(PVT != VT && "Don't know what type to promote to!");
1057 
1058     bool Replace0 = false;
1059     SDValue N0 = Op.getOperand(0);
1060     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1061     if (!NN0.getNode())
1062       return SDValue();
1063 
1064     bool Replace1 = false;
1065     SDValue N1 = Op.getOperand(1);
1066     SDValue NN1;
1067     if (N0 == N1)
1068       NN1 = NN0;
1069     else {
1070       NN1 = PromoteOperand(N1, PVT, Replace1);
1071       if (!NN1.getNode())
1072         return SDValue();
1073     }
1074 
1075     AddToWorklist(NN0.getNode());
1076     if (NN1.getNode())
1077       AddToWorklist(NN1.getNode());
1078 
1079     if (Replace0)
1080       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1081     if (Replace1)
1082       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1083 
1084     DEBUG(dbgs() << "\nPromoting ";
1085           Op.getNode()->dump(&DAG));
1086     SDLoc DL(Op);
1087     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1088                        DAG.getNode(Opc, DL, PVT, NN0, NN1));
1089   }
1090   return SDValue();
1091 }
1092 
1093 /// Promote the specified integer shift operation if the target indicates it is
1094 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1095 /// i32 since i16 instructions are longer.
1096 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1097   if (!LegalOperations)
1098     return SDValue();
1099 
1100   EVT VT = Op.getValueType();
1101   if (VT.isVector() || !VT.isInteger())
1102     return SDValue();
1103 
1104   // If operation type is 'undesirable', e.g. i16 on x86, consider
1105   // promoting it.
1106   unsigned Opc = Op.getOpcode();
1107   if (TLI.isTypeDesirableForOp(Opc, VT))
1108     return SDValue();
1109 
1110   EVT PVT = VT;
1111   // Consult target whether it is a good idea to promote this operation and
1112   // what's the right type to promote it to.
1113   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1114     assert(PVT != VT && "Don't know what type to promote to!");
1115 
1116     bool Replace = false;
1117     SDValue N0 = Op.getOperand(0);
1118     if (Opc == ISD::SRA)
1119       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1120     else if (Opc == ISD::SRL)
1121       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1122     else
1123       N0 = PromoteOperand(N0, PVT, Replace);
1124     if (!N0.getNode())
1125       return SDValue();
1126 
1127     AddToWorklist(N0.getNode());
1128     if (Replace)
1129       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1130 
1131     DEBUG(dbgs() << "\nPromoting ";
1132           Op.getNode()->dump(&DAG));
1133     SDLoc DL(Op);
1134     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1135                        DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1)));
1136   }
1137   return SDValue();
1138 }
1139 
1140 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1141   if (!LegalOperations)
1142     return SDValue();
1143 
1144   EVT VT = Op.getValueType();
1145   if (VT.isVector() || !VT.isInteger())
1146     return SDValue();
1147 
1148   // If operation type is 'undesirable', e.g. i16 on x86, consider
1149   // promoting it.
1150   unsigned Opc = Op.getOpcode();
1151   if (TLI.isTypeDesirableForOp(Opc, VT))
1152     return SDValue();
1153 
1154   EVT PVT = VT;
1155   // Consult target whether it is a good idea to promote this operation and
1156   // what's the right type to promote it to.
1157   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1158     assert(PVT != VT && "Don't know what type to promote to!");
1159     // fold (aext (aext x)) -> (aext x)
1160     // fold (aext (zext x)) -> (zext x)
1161     // fold (aext (sext x)) -> (sext x)
1162     DEBUG(dbgs() << "\nPromoting ";
1163           Op.getNode()->dump(&DAG));
1164     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1165   }
1166   return SDValue();
1167 }
1168 
1169 bool DAGCombiner::PromoteLoad(SDValue Op) {
1170   if (!LegalOperations)
1171     return false;
1172 
1173   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1174     return false;
1175 
1176   EVT VT = Op.getValueType();
1177   if (VT.isVector() || !VT.isInteger())
1178     return false;
1179 
1180   // If operation type is 'undesirable', e.g. i16 on x86, consider
1181   // promoting it.
1182   unsigned Opc = Op.getOpcode();
1183   if (TLI.isTypeDesirableForOp(Opc, VT))
1184     return false;
1185 
1186   EVT PVT = VT;
1187   // Consult target whether it is a good idea to promote this operation and
1188   // what's the right type to promote it to.
1189   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1190     assert(PVT != VT && "Don't know what type to promote to!");
1191 
1192     SDLoc DL(Op);
1193     SDNode *N = Op.getNode();
1194     LoadSDNode *LD = cast<LoadSDNode>(N);
1195     EVT MemVT = LD->getMemoryVT();
1196     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1197       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1198                                                        : ISD::EXTLOAD)
1199       : LD->getExtensionType();
1200     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1201                                    LD->getChain(), LD->getBasePtr(),
1202                                    MemVT, LD->getMemOperand());
1203     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1204 
1205     DEBUG(dbgs() << "\nPromoting ";
1206           N->dump(&DAG);
1207           dbgs() << "\nTo: ";
1208           Result.getNode()->dump(&DAG);
1209           dbgs() << '\n');
1210     WorklistRemover DeadNodes(*this);
1211     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1212     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1213     deleteAndRecombine(N);
1214     AddToWorklist(Result.getNode());
1215     return true;
1216   }
1217   return false;
1218 }
1219 
1220 /// \brief Recursively delete a node which has no uses and any operands for
1221 /// which it is the only use.
1222 ///
1223 /// Note that this both deletes the nodes and removes them from the worklist.
1224 /// It also adds any nodes who have had a user deleted to the worklist as they
1225 /// may now have only one use and subject to other combines.
1226 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1227   if (!N->use_empty())
1228     return false;
1229 
1230   SmallSetVector<SDNode *, 16> Nodes;
1231   Nodes.insert(N);
1232   do {
1233     N = Nodes.pop_back_val();
1234     if (!N)
1235       continue;
1236 
1237     if (N->use_empty()) {
1238       for (const SDValue &ChildN : N->op_values())
1239         Nodes.insert(ChildN.getNode());
1240 
1241       removeFromWorklist(N);
1242       DAG.DeleteNode(N);
1243     } else {
1244       AddToWorklist(N);
1245     }
1246   } while (!Nodes.empty());
1247   return true;
1248 }
1249 
1250 //===----------------------------------------------------------------------===//
1251 //  Main DAG Combiner implementation
1252 //===----------------------------------------------------------------------===//
1253 
1254 void DAGCombiner::Run(CombineLevel AtLevel) {
1255   // set the instance variables, so that the various visit routines may use it.
1256   Level = AtLevel;
1257   LegalOperations = Level >= AfterLegalizeVectorOps;
1258   LegalTypes = Level >= AfterLegalizeTypes;
1259 
1260   // Add all the dag nodes to the worklist.
1261   for (SDNode &Node : DAG.allnodes())
1262     AddToWorklist(&Node);
1263 
1264   // Create a dummy node (which is not added to allnodes), that adds a reference
1265   // to the root node, preventing it from being deleted, and tracking any
1266   // changes of the root.
1267   HandleSDNode Dummy(DAG.getRoot());
1268 
1269   // While the worklist isn't empty, find a node and try to combine it.
1270   while (!WorklistMap.empty()) {
1271     SDNode *N;
1272     // The Worklist holds the SDNodes in order, but it may contain null entries.
1273     do {
1274       N = Worklist.pop_back_val();
1275     } while (!N);
1276 
1277     bool GoodWorklistEntry = WorklistMap.erase(N);
1278     (void)GoodWorklistEntry;
1279     assert(GoodWorklistEntry &&
1280            "Found a worklist entry without a corresponding map entry!");
1281 
1282     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1283     // N is deleted from the DAG, since they too may now be dead or may have a
1284     // reduced number of uses, allowing other xforms.
1285     if (recursivelyDeleteUnusedNodes(N))
1286       continue;
1287 
1288     WorklistRemover DeadNodes(*this);
1289 
1290     // If this combine is running after legalizing the DAG, re-legalize any
1291     // nodes pulled off the worklist.
1292     if (Level == AfterLegalizeDAG) {
1293       SmallSetVector<SDNode *, 16> UpdatedNodes;
1294       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1295 
1296       for (SDNode *LN : UpdatedNodes) {
1297         AddToWorklist(LN);
1298         AddUsersToWorklist(LN);
1299       }
1300       if (!NIsValid)
1301         continue;
1302     }
1303 
1304     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1305 
1306     // Add any operands of the new node which have not yet been combined to the
1307     // worklist as well. Because the worklist uniques things already, this
1308     // won't repeatedly process the same operand.
1309     CombinedNodes.insert(N);
1310     for (const SDValue &ChildN : N->op_values())
1311       if (!CombinedNodes.count(ChildN.getNode()))
1312         AddToWorklist(ChildN.getNode());
1313 
1314     SDValue RV = combine(N);
1315 
1316     if (!RV.getNode())
1317       continue;
1318 
1319     ++NodesCombined;
1320 
1321     // If we get back the same node we passed in, rather than a new node or
1322     // zero, we know that the node must have defined multiple values and
1323     // CombineTo was used.  Since CombineTo takes care of the worklist
1324     // mechanics for us, we have no work to do in this case.
1325     if (RV.getNode() == N)
1326       continue;
1327 
1328     assert(N->getOpcode() != ISD::DELETED_NODE &&
1329            RV.getOpcode() != ISD::DELETED_NODE &&
1330            "Node was deleted but visit returned new node!");
1331 
1332     DEBUG(dbgs() << " ... into: ";
1333           RV.getNode()->dump(&DAG));
1334 
1335     if (N->getNumValues() == RV.getNode()->getNumValues())
1336       DAG.ReplaceAllUsesWith(N, RV.getNode());
1337     else {
1338       assert(N->getValueType(0) == RV.getValueType() &&
1339              N->getNumValues() == 1 && "Type mismatch");
1340       SDValue OpV = RV;
1341       DAG.ReplaceAllUsesWith(N, &OpV);
1342     }
1343 
1344     // Push the new node and any users onto the worklist
1345     AddToWorklist(RV.getNode());
1346     AddUsersToWorklist(RV.getNode());
1347 
1348     // Finally, if the node is now dead, remove it from the graph.  The node
1349     // may not be dead if the replacement process recursively simplified to
1350     // something else needing this node. This will also take care of adding any
1351     // operands which have lost a user to the worklist.
1352     recursivelyDeleteUnusedNodes(N);
1353   }
1354 
1355   // If the root changed (e.g. it was a dead load, update the root).
1356   DAG.setRoot(Dummy.getValue());
1357   DAG.RemoveDeadNodes();
1358 }
1359 
1360 SDValue DAGCombiner::visit(SDNode *N) {
1361   switch (N->getOpcode()) {
1362   default: break;
1363   case ISD::TokenFactor:        return visitTokenFactor(N);
1364   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1365   case ISD::ADD:                return visitADD(N);
1366   case ISD::SUB:                return visitSUB(N);
1367   case ISD::ADDC:               return visitADDC(N);
1368   case ISD::SUBC:               return visitSUBC(N);
1369   case ISD::ADDE:               return visitADDE(N);
1370   case ISD::SUBE:               return visitSUBE(N);
1371   case ISD::MUL:                return visitMUL(N);
1372   case ISD::SDIV:               return visitSDIV(N);
1373   case ISD::UDIV:               return visitUDIV(N);
1374   case ISD::SREM:
1375   case ISD::UREM:               return visitREM(N);
1376   case ISD::MULHU:              return visitMULHU(N);
1377   case ISD::MULHS:              return visitMULHS(N);
1378   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1379   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1380   case ISD::SMULO:              return visitSMULO(N);
1381   case ISD::UMULO:              return visitUMULO(N);
1382   case ISD::SMIN:
1383   case ISD::SMAX:
1384   case ISD::UMIN:
1385   case ISD::UMAX:               return visitIMINMAX(N);
1386   case ISD::AND:                return visitAND(N);
1387   case ISD::OR:                 return visitOR(N);
1388   case ISD::XOR:                return visitXOR(N);
1389   case ISD::SHL:                return visitSHL(N);
1390   case ISD::SRA:                return visitSRA(N);
1391   case ISD::SRL:                return visitSRL(N);
1392   case ISD::ROTR:
1393   case ISD::ROTL:               return visitRotate(N);
1394   case ISD::BSWAP:              return visitBSWAP(N);
1395   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1396   case ISD::CTLZ:               return visitCTLZ(N);
1397   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1398   case ISD::CTTZ:               return visitCTTZ(N);
1399   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1400   case ISD::CTPOP:              return visitCTPOP(N);
1401   case ISD::SELECT:             return visitSELECT(N);
1402   case ISD::VSELECT:            return visitVSELECT(N);
1403   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1404   case ISD::SETCC:              return visitSETCC(N);
1405   case ISD::SETCCE:             return visitSETCCE(N);
1406   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1407   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1408   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1409   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1410   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1411   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1412   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1413   case ISD::BITCAST:            return visitBITCAST(N);
1414   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1415   case ISD::FADD:               return visitFADD(N);
1416   case ISD::FSUB:               return visitFSUB(N);
1417   case ISD::FMUL:               return visitFMUL(N);
1418   case ISD::FMA:                return visitFMA(N);
1419   case ISD::FDIV:               return visitFDIV(N);
1420   case ISD::FREM:               return visitFREM(N);
1421   case ISD::FSQRT:              return visitFSQRT(N);
1422   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1423   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1424   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1425   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1426   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1427   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1428   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1429   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1430   case ISD::FNEG:               return visitFNEG(N);
1431   case ISD::FABS:               return visitFABS(N);
1432   case ISD::FFLOOR:             return visitFFLOOR(N);
1433   case ISD::FMINNUM:            return visitFMINNUM(N);
1434   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1435   case ISD::FCEIL:              return visitFCEIL(N);
1436   case ISD::FTRUNC:             return visitFTRUNC(N);
1437   case ISD::BRCOND:             return visitBRCOND(N);
1438   case ISD::BR_CC:              return visitBR_CC(N);
1439   case ISD::LOAD:               return visitLOAD(N);
1440   case ISD::STORE:              return visitSTORE(N);
1441   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1442   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1443   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1444   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1445   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1446   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1447   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1448   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1449   case ISD::MGATHER:            return visitMGATHER(N);
1450   case ISD::MLOAD:              return visitMLOAD(N);
1451   case ISD::MSCATTER:           return visitMSCATTER(N);
1452   case ISD::MSTORE:             return visitMSTORE(N);
1453   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1454   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1455   }
1456   return SDValue();
1457 }
1458 
1459 SDValue DAGCombiner::combine(SDNode *N) {
1460   SDValue RV = visit(N);
1461 
1462   // If nothing happened, try a target-specific DAG combine.
1463   if (!RV.getNode()) {
1464     assert(N->getOpcode() != ISD::DELETED_NODE &&
1465            "Node was deleted but visit returned NULL!");
1466 
1467     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1468         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1469 
1470       // Expose the DAG combiner to the target combiner impls.
1471       TargetLowering::DAGCombinerInfo
1472         DagCombineInfo(DAG, Level, false, this);
1473 
1474       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1475     }
1476   }
1477 
1478   // If nothing happened still, try promoting the operation.
1479   if (!RV.getNode()) {
1480     switch (N->getOpcode()) {
1481     default: break;
1482     case ISD::ADD:
1483     case ISD::SUB:
1484     case ISD::MUL:
1485     case ISD::AND:
1486     case ISD::OR:
1487     case ISD::XOR:
1488       RV = PromoteIntBinOp(SDValue(N, 0));
1489       break;
1490     case ISD::SHL:
1491     case ISD::SRA:
1492     case ISD::SRL:
1493       RV = PromoteIntShiftOp(SDValue(N, 0));
1494       break;
1495     case ISD::SIGN_EXTEND:
1496     case ISD::ZERO_EXTEND:
1497     case ISD::ANY_EXTEND:
1498       RV = PromoteExtend(SDValue(N, 0));
1499       break;
1500     case ISD::LOAD:
1501       if (PromoteLoad(SDValue(N, 0)))
1502         RV = SDValue(N, 0);
1503       break;
1504     }
1505   }
1506 
1507   // If N is a commutative binary node, try commuting it to enable more
1508   // sdisel CSE.
1509   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1510       N->getNumValues() == 1) {
1511     SDValue N0 = N->getOperand(0);
1512     SDValue N1 = N->getOperand(1);
1513 
1514     // Constant operands are canonicalized to RHS.
1515     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1516       SDValue Ops[] = {N1, N0};
1517       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1518                                             N->getFlags());
1519       if (CSENode)
1520         return SDValue(CSENode, 0);
1521     }
1522   }
1523 
1524   return RV;
1525 }
1526 
1527 /// Given a node, return its input chain if it has one, otherwise return a null
1528 /// sd operand.
1529 static SDValue getInputChainForNode(SDNode *N) {
1530   if (unsigned NumOps = N->getNumOperands()) {
1531     if (N->getOperand(0).getValueType() == MVT::Other)
1532       return N->getOperand(0);
1533     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1534       return N->getOperand(NumOps-1);
1535     for (unsigned i = 1; i < NumOps-1; ++i)
1536       if (N->getOperand(i).getValueType() == MVT::Other)
1537         return N->getOperand(i);
1538   }
1539   return SDValue();
1540 }
1541 
1542 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1543   // If N has two operands, where one has an input chain equal to the other,
1544   // the 'other' chain is redundant.
1545   if (N->getNumOperands() == 2) {
1546     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1547       return N->getOperand(0);
1548     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1549       return N->getOperand(1);
1550   }
1551 
1552   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1553   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1554   SmallPtrSet<SDNode*, 16> SeenOps;
1555   bool Changed = false;             // If we should replace this token factor.
1556 
1557   // Start out with this token factor.
1558   TFs.push_back(N);
1559 
1560   // Iterate through token factors.  The TFs grows when new token factors are
1561   // encountered.
1562   for (unsigned i = 0; i < TFs.size(); ++i) {
1563     SDNode *TF = TFs[i];
1564 
1565     // Check each of the operands.
1566     for (const SDValue &Op : TF->op_values()) {
1567 
1568       switch (Op.getOpcode()) {
1569       case ISD::EntryToken:
1570         // Entry tokens don't need to be added to the list. They are
1571         // redundant.
1572         Changed = true;
1573         break;
1574 
1575       case ISD::TokenFactor:
1576         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1577           // Queue up for processing.
1578           TFs.push_back(Op.getNode());
1579           // Clean up in case the token factor is removed.
1580           AddToWorklist(Op.getNode());
1581           Changed = true;
1582           break;
1583         }
1584         LLVM_FALLTHROUGH;
1585 
1586       default:
1587         // Only add if it isn't already in the list.
1588         if (SeenOps.insert(Op.getNode()).second)
1589           Ops.push_back(Op);
1590         else
1591           Changed = true;
1592         break;
1593       }
1594     }
1595   }
1596 
1597   SDValue Result;
1598 
1599   // If we've changed things around then replace token factor.
1600   if (Changed) {
1601     if (Ops.empty()) {
1602       // The entry token is the only possible outcome.
1603       Result = DAG.getEntryNode();
1604     } else {
1605       // New and improved token factor.
1606       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1607     }
1608 
1609     // Add users to worklist if AA is enabled, since it may introduce
1610     // a lot of new chained token factors while removing memory deps.
1611     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1612       : DAG.getSubtarget().useAA();
1613     return CombineTo(N, Result, UseAA /*add to worklist*/);
1614   }
1615 
1616   return Result;
1617 }
1618 
1619 /// MERGE_VALUES can always be eliminated.
1620 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1621   WorklistRemover DeadNodes(*this);
1622   // Replacing results may cause a different MERGE_VALUES to suddenly
1623   // be CSE'd with N, and carry its uses with it. Iterate until no
1624   // uses remain, to ensure that the node can be safely deleted.
1625   // First add the users of this node to the work list so that they
1626   // can be tried again once they have new operands.
1627   AddUsersToWorklist(N);
1628   do {
1629     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1630       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1631   } while (!N->use_empty());
1632   deleteAndRecombine(N);
1633   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1634 }
1635 
1636 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1637 /// ConstantSDNode pointer else nullptr.
1638 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1639   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1640   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1641 }
1642 
1643 SDValue DAGCombiner::visitADD(SDNode *N) {
1644   SDValue N0 = N->getOperand(0);
1645   SDValue N1 = N->getOperand(1);
1646   EVT VT = N0.getValueType();
1647 
1648   // fold vector ops
1649   if (VT.isVector()) {
1650     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1651       return FoldedVOp;
1652 
1653     // fold (add x, 0) -> x, vector edition
1654     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1655       return N0;
1656     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1657       return N1;
1658   }
1659 
1660   // fold (add x, undef) -> undef
1661   if (N0.isUndef())
1662     return N0;
1663   if (N1.isUndef())
1664     return N1;
1665   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1666     // canonicalize constant to RHS
1667     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1668       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1669     // fold (add c1, c2) -> c1+c2
1670     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT,
1671                                       N0.getNode(), N1.getNode());
1672   }
1673   // fold (add x, 0) -> x
1674   if (isNullConstant(N1))
1675     return N0;
1676   // fold ((c1-A)+c2) -> (c1+c2)-A
1677   if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) {
1678     if (N0.getOpcode() == ISD::SUB)
1679       if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1680         SDLoc DL(N);
1681         return DAG.getNode(ISD::SUB, DL, VT,
1682                            DAG.getConstant(N1C->getAPIntValue()+
1683                                            N0C->getAPIntValue(), DL, VT),
1684                            N0.getOperand(1));
1685       }
1686   }
1687   // reassociate add
1688   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1689     return RADD;
1690   // fold ((0-A) + B) -> B-A
1691   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1692     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1693   // fold (A + (0-B)) -> A-B
1694   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1695     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1696   // fold (A+(B-A)) -> B
1697   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1698     return N1.getOperand(0);
1699   // fold ((B-A)+A) -> B
1700   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1701     return N0.getOperand(0);
1702   // fold (A+(B-(A+C))) to (B-C)
1703   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1704       N0 == N1.getOperand(1).getOperand(0))
1705     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1706                        N1.getOperand(1).getOperand(1));
1707   // fold (A+(B-(C+A))) to (B-C)
1708   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1709       N0 == N1.getOperand(1).getOperand(1))
1710     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1711                        N1.getOperand(1).getOperand(0));
1712   // fold (A+((B-A)+or-C)) to (B+or-C)
1713   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1714       N1.getOperand(0).getOpcode() == ISD::SUB &&
1715       N0 == N1.getOperand(0).getOperand(1))
1716     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1717                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1718 
1719   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1720   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1721     SDValue N00 = N0.getOperand(0);
1722     SDValue N01 = N0.getOperand(1);
1723     SDValue N10 = N1.getOperand(0);
1724     SDValue N11 = N1.getOperand(1);
1725 
1726     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1727       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1728                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1729                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1730   }
1731 
1732   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1733     return SDValue(N, 0);
1734 
1735   // fold (a+b) -> (a|b) iff a and b share no bits.
1736   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1737       VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1))
1738     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1739 
1740   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1741   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1742       isNullConstant(N1.getOperand(0).getOperand(0)))
1743     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1744                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1745                                    N1.getOperand(0).getOperand(1),
1746                                    N1.getOperand(1)));
1747   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1748       isNullConstant(N0.getOperand(0).getOperand(0)))
1749     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1750                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1751                                    N0.getOperand(0).getOperand(1),
1752                                    N0.getOperand(1)));
1753 
1754   if (N1.getOpcode() == ISD::AND) {
1755     SDValue AndOp0 = N1.getOperand(0);
1756     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1757     unsigned DestBits = VT.getScalarSizeInBits();
1758 
1759     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1760     // and similar xforms where the inner op is either ~0 or 0.
1761     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1762       SDLoc DL(N);
1763       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1764     }
1765   }
1766 
1767   // add (sext i1), X -> sub X, (zext i1)
1768   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1769       N0.getOperand(0).getValueType() == MVT::i1 &&
1770       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1771     SDLoc DL(N);
1772     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1773     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1774   }
1775 
1776   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1777   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1778     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1779     if (TN->getVT() == MVT::i1) {
1780       SDLoc DL(N);
1781       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1782                                  DAG.getConstant(1, DL, VT));
1783       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1784     }
1785   }
1786 
1787   return SDValue();
1788 }
1789 
1790 SDValue DAGCombiner::visitADDC(SDNode *N) {
1791   SDValue N0 = N->getOperand(0);
1792   SDValue N1 = N->getOperand(1);
1793   EVT VT = N0.getValueType();
1794 
1795   // If the flag result is dead, turn this into an ADD.
1796   if (!N->hasAnyUseOfValue(1))
1797     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1798                      DAG.getNode(ISD::CARRY_FALSE,
1799                                  SDLoc(N), MVT::Glue));
1800 
1801   // canonicalize constant to RHS.
1802   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1803   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1804   if (N0C && !N1C)
1805     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1806 
1807   // fold (addc x, 0) -> x + no carry out
1808   if (isNullConstant(N1))
1809     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1810                                         SDLoc(N), MVT::Glue));
1811 
1812   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1813   APInt LHSZero, LHSOne;
1814   APInt RHSZero, RHSOne;
1815   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1816 
1817   if (LHSZero.getBoolValue()) {
1818     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1819 
1820     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1821     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1822     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1823       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1824                        DAG.getNode(ISD::CARRY_FALSE,
1825                                    SDLoc(N), MVT::Glue));
1826   }
1827 
1828   return SDValue();
1829 }
1830 
1831 SDValue DAGCombiner::visitADDE(SDNode *N) {
1832   SDValue N0 = N->getOperand(0);
1833   SDValue N1 = N->getOperand(1);
1834   SDValue CarryIn = N->getOperand(2);
1835 
1836   // canonicalize constant to RHS
1837   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1838   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1839   if (N0C && !N1C)
1840     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1841                        N1, N0, CarryIn);
1842 
1843   // fold (adde x, y, false) -> (addc x, y)
1844   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1845     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1846 
1847   return SDValue();
1848 }
1849 
1850 // Since it may not be valid to emit a fold to zero for vector initializers
1851 // check if we can before folding.
1852 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
1853                              SelectionDAG &DAG, bool LegalOperations,
1854                              bool LegalTypes) {
1855   if (!VT.isVector())
1856     return DAG.getConstant(0, DL, VT);
1857   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1858     return DAG.getConstant(0, DL, VT);
1859   return SDValue();
1860 }
1861 
1862 SDValue DAGCombiner::visitSUB(SDNode *N) {
1863   SDValue N0 = N->getOperand(0);
1864   SDValue N1 = N->getOperand(1);
1865   EVT VT = N0.getValueType();
1866   SDLoc DL(N);
1867 
1868   // fold vector ops
1869   if (VT.isVector()) {
1870     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1871       return FoldedVOp;
1872 
1873     // fold (sub x, 0) -> x, vector edition
1874     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1875       return N0;
1876   }
1877 
1878   // fold (sub x, x) -> 0
1879   // FIXME: Refactor this and xor and other similar operations together.
1880   if (N0 == N1)
1881     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
1882   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1883       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1884     // fold (sub c1, c2) -> c1-c2
1885     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
1886                                       N1.getNode());
1887   }
1888 
1889   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1890   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1891 
1892   // fold (sub x, c) -> (add x, -c)
1893   if (N1C) {
1894     return DAG.getNode(ISD::ADD, DL, VT, N0,
1895                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1896   }
1897 
1898   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1899   if (isAllOnesConstant(N0))
1900     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
1901 
1902   // fold A-(A-B) -> B
1903   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1904     return N1.getOperand(1);
1905 
1906   // fold (A+B)-A -> B
1907   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1908     return N0.getOperand(1);
1909 
1910   // fold (A+B)-B -> A
1911   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1912     return N0.getOperand(0);
1913 
1914   // fold C2-(A+C1) -> (C2-C1)-A
1915   if (N1.getOpcode() == ISD::ADD && N0C) {
1916     if (auto *N1C1 = dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode())) {
1917       SDValue NewC =
1918           DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), DL, VT);
1919       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
1920     }
1921   }
1922 
1923   // fold ((A+(B+or-C))-B) -> A+or-C
1924   if (N0.getOpcode() == ISD::ADD &&
1925       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1926        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1927       N0.getOperand(1).getOperand(0) == N1)
1928     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
1929                        N0.getOperand(1).getOperand(1));
1930 
1931   // fold ((A+(C+B))-B) -> A+C
1932   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
1933       N0.getOperand(1).getOperand(1) == N1)
1934     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
1935                        N0.getOperand(1).getOperand(0));
1936 
1937   // fold ((A-(B-C))-C) -> A-B
1938   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
1939       N0.getOperand(1).getOperand(1) == N1)
1940     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
1941                        N0.getOperand(1).getOperand(0));
1942 
1943   // If either operand of a sub is undef, the result is undef
1944   if (N0.isUndef())
1945     return N0;
1946   if (N1.isUndef())
1947     return N1;
1948 
1949   // If the relocation model supports it, consider symbol offsets.
1950   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1951     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1952       // fold (sub Sym, c) -> Sym-c
1953       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1954         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1955                                     GA->getOffset() -
1956                                         (uint64_t)N1C->getSExtValue());
1957       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1958       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1959         if (GA->getGlobal() == GB->getGlobal())
1960           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1961                                  DL, VT);
1962     }
1963 
1964   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1965   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1966     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1967     if (TN->getVT() == MVT::i1) {
1968       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1969                                  DAG.getConstant(1, DL, VT));
1970       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1971     }
1972   }
1973 
1974   return SDValue();
1975 }
1976 
1977 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1978   SDValue N0 = N->getOperand(0);
1979   SDValue N1 = N->getOperand(1);
1980   EVT VT = N0.getValueType();
1981   SDLoc DL(N);
1982 
1983   // If the flag result is dead, turn this into an SUB.
1984   if (!N->hasAnyUseOfValue(1))
1985     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1986                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1987 
1988   // fold (subc x, x) -> 0 + no borrow
1989   if (N0 == N1)
1990     return CombineTo(N, DAG.getConstant(0, DL, VT),
1991                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1992 
1993   // fold (subc x, 0) -> x + no borrow
1994   if (isNullConstant(N1))
1995     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1996 
1997   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1998   if (isAllOnesConstant(N0))
1999     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2000                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2001 
2002   return SDValue();
2003 }
2004 
2005 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2006   SDValue N0 = N->getOperand(0);
2007   SDValue N1 = N->getOperand(1);
2008   SDValue CarryIn = N->getOperand(2);
2009 
2010   // fold (sube x, y, false) -> (subc x, y)
2011   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2012     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2013 
2014   return SDValue();
2015 }
2016 
2017 SDValue DAGCombiner::visitMUL(SDNode *N) {
2018   SDValue N0 = N->getOperand(0);
2019   SDValue N1 = N->getOperand(1);
2020   EVT VT = N0.getValueType();
2021 
2022   // fold (mul x, undef) -> 0
2023   if (N0.isUndef() || N1.isUndef())
2024     return DAG.getConstant(0, SDLoc(N), VT);
2025 
2026   bool N0IsConst = false;
2027   bool N1IsConst = false;
2028   bool N1IsOpaqueConst = false;
2029   bool N0IsOpaqueConst = false;
2030   APInt ConstValue0, ConstValue1;
2031   // fold vector ops
2032   if (VT.isVector()) {
2033     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2034       return FoldedVOp;
2035 
2036     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2037     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2038   } else {
2039     N0IsConst = isa<ConstantSDNode>(N0);
2040     if (N0IsConst) {
2041       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2042       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2043     }
2044     N1IsConst = isa<ConstantSDNode>(N1);
2045     if (N1IsConst) {
2046       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2047       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2048     }
2049   }
2050 
2051   // fold (mul c1, c2) -> c1*c2
2052   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2053     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2054                                       N0.getNode(), N1.getNode());
2055 
2056   // canonicalize constant to RHS (vector doesn't have to splat)
2057   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2058      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2059     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2060   // fold (mul x, 0) -> 0
2061   if (N1IsConst && ConstValue1 == 0)
2062     return N1;
2063   // We require a splat of the entire scalar bit width for non-contiguous
2064   // bit patterns.
2065   bool IsFullSplat =
2066     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2067   // fold (mul x, 1) -> x
2068   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2069     return N0;
2070   // fold (mul x, -1) -> 0-x
2071   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2072     SDLoc DL(N);
2073     return DAG.getNode(ISD::SUB, DL, VT,
2074                        DAG.getConstant(0, DL, VT), N0);
2075   }
2076   // fold (mul x, (1 << c)) -> x << c
2077   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2078       IsFullSplat) {
2079     SDLoc DL(N);
2080     return DAG.getNode(ISD::SHL, DL, VT, N0,
2081                        DAG.getConstant(ConstValue1.logBase2(), DL,
2082                                        getShiftAmountTy(N0.getValueType())));
2083   }
2084   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2085   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2086       IsFullSplat) {
2087     unsigned Log2Val = (-ConstValue1).logBase2();
2088     SDLoc DL(N);
2089     // FIXME: If the input is something that is easily negated (e.g. a
2090     // single-use add), we should put the negate there.
2091     return DAG.getNode(ISD::SUB, DL, VT,
2092                        DAG.getConstant(0, DL, VT),
2093                        DAG.getNode(ISD::SHL, DL, VT, N0,
2094                             DAG.getConstant(Log2Val, DL,
2095                                       getShiftAmountTy(N0.getValueType()))));
2096   }
2097 
2098   APInt Val;
2099   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2100   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2101       (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2102        isa<ConstantSDNode>(N0.getOperand(1)))) {
2103     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2104     AddToWorklist(C3.getNode());
2105     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2106   }
2107 
2108   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2109   // use.
2110   {
2111     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2112     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2113     if (N0.getOpcode() == ISD::SHL &&
2114         (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2115          isa<ConstantSDNode>(N0.getOperand(1))) &&
2116         N0.getNode()->hasOneUse()) {
2117       Sh = N0; Y = N1;
2118     } else if (N1.getOpcode() == ISD::SHL &&
2119                isa<ConstantSDNode>(N1.getOperand(1)) &&
2120                N1.getNode()->hasOneUse()) {
2121       Sh = N1; Y = N0;
2122     }
2123 
2124     if (Sh.getNode()) {
2125       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2126       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2127     }
2128   }
2129 
2130   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2131   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2132       N0.getOpcode() == ISD::ADD &&
2133       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2134       isMulAddWithConstProfitable(N, N0, N1))
2135       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2136                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2137                                      N0.getOperand(0), N1),
2138                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2139                                      N0.getOperand(1), N1));
2140 
2141   // reassociate mul
2142   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2143     return RMUL;
2144 
2145   return SDValue();
2146 }
2147 
2148 /// Return true if divmod libcall is available.
2149 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2150                                      const TargetLowering &TLI) {
2151   RTLIB::Libcall LC;
2152   EVT NodeType = Node->getValueType(0);
2153   if (!NodeType.isSimple())
2154     return false;
2155   switch (NodeType.getSimpleVT().SimpleTy) {
2156   default: return false; // No libcall for vector types.
2157   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2158   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2159   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2160   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2161   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2162   }
2163 
2164   return TLI.getLibcallName(LC) != nullptr;
2165 }
2166 
2167 /// Issue divrem if both quotient and remainder are needed.
2168 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2169   if (Node->use_empty())
2170     return SDValue(); // This is a dead node, leave it alone.
2171 
2172   unsigned Opcode = Node->getOpcode();
2173   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2174   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2175 
2176   // DivMod lib calls can still work on non-legal types if using lib-calls.
2177   EVT VT = Node->getValueType(0);
2178   if (VT.isVector() || !VT.isInteger())
2179     return SDValue();
2180 
2181   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2182     return SDValue();
2183 
2184   // If DIVREM is going to get expanded into a libcall,
2185   // but there is no libcall available, then don't combine.
2186   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2187       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2188     return SDValue();
2189 
2190   // If div is legal, it's better to do the normal expansion
2191   unsigned OtherOpcode = 0;
2192   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2193     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2194     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2195       return SDValue();
2196   } else {
2197     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2198     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2199       return SDValue();
2200   }
2201 
2202   SDValue Op0 = Node->getOperand(0);
2203   SDValue Op1 = Node->getOperand(1);
2204   SDValue combined;
2205   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2206          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2207     SDNode *User = *UI;
2208     if (User == Node || User->use_empty())
2209       continue;
2210     // Convert the other matching node(s), too;
2211     // otherwise, the DIVREM may get target-legalized into something
2212     // target-specific that we won't be able to recognize.
2213     unsigned UserOpc = User->getOpcode();
2214     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2215         User->getOperand(0) == Op0 &&
2216         User->getOperand(1) == Op1) {
2217       if (!combined) {
2218         if (UserOpc == OtherOpcode) {
2219           SDVTList VTs = DAG.getVTList(VT, VT);
2220           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2221         } else if (UserOpc == DivRemOpc) {
2222           combined = SDValue(User, 0);
2223         } else {
2224           assert(UserOpc == Opcode);
2225           continue;
2226         }
2227       }
2228       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2229         CombineTo(User, combined);
2230       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2231         CombineTo(User, combined.getValue(1));
2232     }
2233   }
2234   return combined;
2235 }
2236 
2237 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2238   SDValue N0 = N->getOperand(0);
2239   SDValue N1 = N->getOperand(1);
2240   EVT VT = N->getValueType(0);
2241 
2242   // fold vector ops
2243   if (VT.isVector())
2244     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2245       return FoldedVOp;
2246 
2247   SDLoc DL(N);
2248 
2249   // fold (sdiv c1, c2) -> c1/c2
2250   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2251   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2252   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2253     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2254   // fold (sdiv X, 1) -> X
2255   if (N1C && N1C->isOne())
2256     return N0;
2257   // fold (sdiv X, -1) -> 0-X
2258   if (N1C && N1C->isAllOnesValue())
2259     return DAG.getNode(ISD::SUB, DL, VT,
2260                        DAG.getConstant(0, DL, VT), N0);
2261 
2262   // If we know the sign bits of both operands are zero, strength reduce to a
2263   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2264   if (!VT.isVector()) {
2265     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2266       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2267   }
2268 
2269   // fold (sdiv X, pow2) -> simple ops after legalize
2270   // FIXME: We check for the exact bit here because the generic lowering gives
2271   // better results in that case. The target-specific lowering should learn how
2272   // to handle exact sdivs efficiently.
2273   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2274       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2275       (N1C->getAPIntValue().isPowerOf2() ||
2276        (-N1C->getAPIntValue()).isPowerOf2())) {
2277     // Target-specific implementation of sdiv x, pow2.
2278     if (SDValue Res = BuildSDIVPow2(N))
2279       return Res;
2280 
2281     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2282 
2283     // Splat the sign bit into the register
2284     SDValue SGN =
2285         DAG.getNode(ISD::SRA, DL, VT, N0,
2286                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2287                                     getShiftAmountTy(N0.getValueType())));
2288     AddToWorklist(SGN.getNode());
2289 
2290     // Add (N0 < 0) ? abs2 - 1 : 0;
2291     SDValue SRL =
2292         DAG.getNode(ISD::SRL, DL, VT, SGN,
2293                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2294                                     getShiftAmountTy(SGN.getValueType())));
2295     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2296     AddToWorklist(SRL.getNode());
2297     AddToWorklist(ADD.getNode());    // Divide by pow2
2298     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2299                   DAG.getConstant(lg2, DL,
2300                                   getShiftAmountTy(ADD.getValueType())));
2301 
2302     // If we're dividing by a positive value, we're done.  Otherwise, we must
2303     // negate the result.
2304     if (N1C->getAPIntValue().isNonNegative())
2305       return SRA;
2306 
2307     AddToWorklist(SRA.getNode());
2308     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2309   }
2310 
2311   // If integer divide is expensive and we satisfy the requirements, emit an
2312   // alternate sequence.  Targets may check function attributes for size/speed
2313   // trade-offs.
2314   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2315   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2316     if (SDValue Op = BuildSDIV(N))
2317       return Op;
2318 
2319   // sdiv, srem -> sdivrem
2320   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2321   // Otherwise, we break the simplification logic in visitREM().
2322   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2323     if (SDValue DivRem = useDivRem(N))
2324         return DivRem;
2325 
2326   // undef / X -> 0
2327   if (N0.isUndef())
2328     return DAG.getConstant(0, DL, VT);
2329   // X / undef -> undef
2330   if (N1.isUndef())
2331     return N1;
2332 
2333   return SDValue();
2334 }
2335 
2336 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2337   SDValue N0 = N->getOperand(0);
2338   SDValue N1 = N->getOperand(1);
2339   EVT VT = N->getValueType(0);
2340 
2341   // fold vector ops
2342   if (VT.isVector())
2343     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2344       return FoldedVOp;
2345 
2346   SDLoc DL(N);
2347 
2348   // fold (udiv c1, c2) -> c1/c2
2349   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2350   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2351   if (N0C && N1C)
2352     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2353                                                     N0C, N1C))
2354       return Folded;
2355   // fold (udiv x, (1 << c)) -> x >>u c
2356   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2357     return DAG.getNode(ISD::SRL, DL, VT, N0,
2358                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2359                                        getShiftAmountTy(N0.getValueType())));
2360 
2361   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2362   if (N1.getOpcode() == ISD::SHL) {
2363     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2364       if (SHC->getAPIntValue().isPowerOf2()) {
2365         EVT ADDVT = N1.getOperand(1).getValueType();
2366         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2367                                   N1.getOperand(1),
2368                                   DAG.getConstant(SHC->getAPIntValue()
2369                                                                   .logBase2(),
2370                                                   DL, ADDVT));
2371         AddToWorklist(Add.getNode());
2372         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2373       }
2374     }
2375   }
2376 
2377   // fold (udiv x, c) -> alternate
2378   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2379   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2380     if (SDValue Op = BuildUDIV(N))
2381       return Op;
2382 
2383   // sdiv, srem -> sdivrem
2384   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2385   // Otherwise, we break the simplification logic in visitREM().
2386   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2387     if (SDValue DivRem = useDivRem(N))
2388         return DivRem;
2389 
2390   // undef / X -> 0
2391   if (N0.isUndef())
2392     return DAG.getConstant(0, DL, VT);
2393   // X / undef -> undef
2394   if (N1.isUndef())
2395     return N1;
2396 
2397   return SDValue();
2398 }
2399 
2400 // handles ISD::SREM and ISD::UREM
2401 SDValue DAGCombiner::visitREM(SDNode *N) {
2402   unsigned Opcode = N->getOpcode();
2403   SDValue N0 = N->getOperand(0);
2404   SDValue N1 = N->getOperand(1);
2405   EVT VT = N->getValueType(0);
2406   bool isSigned = (Opcode == ISD::SREM);
2407   SDLoc DL(N);
2408 
2409   // fold (rem c1, c2) -> c1%c2
2410   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2411   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2412   if (N0C && N1C)
2413     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2414       return Folded;
2415 
2416   if (isSigned) {
2417     // If we know the sign bits of both operands are zero, strength reduce to a
2418     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2419     if (!VT.isVector()) {
2420       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2421         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2422     }
2423   } else {
2424     // fold (urem x, pow2) -> (and x, pow2-1)
2425     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2426         N1C->getAPIntValue().isPowerOf2()) {
2427       return DAG.getNode(ISD::AND, DL, VT, N0,
2428                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2429     }
2430     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2431     if (N1.getOpcode() == ISD::SHL) {
2432       ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0));
2433       if (SHC && SHC->getAPIntValue().isPowerOf2()) {
2434         APInt NegOne = APInt::getAllOnesValue(VT.getSizeInBits());
2435         SDValue Add =
2436             DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2437         AddToWorklist(Add.getNode());
2438         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2439       }
2440     }
2441   }
2442 
2443   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2444 
2445   // If X/C can be simplified by the division-by-constant logic, lower
2446   // X%C to the equivalent of X-X/C*C.
2447   // To avoid mangling nodes, this simplification requires that the combine()
2448   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2449   // against this by skipping the simplification if isIntDivCheap().  When
2450   // div is not cheap, combine will not return a DIVREM.  Regardless,
2451   // checking cheapness here makes sense since the simplification results in
2452   // fatter code.
2453   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2454     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2455     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2456     AddToWorklist(Div.getNode());
2457     SDValue OptimizedDiv = combine(Div.getNode());
2458     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2459       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2460              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2461       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2462       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2463       AddToWorklist(Mul.getNode());
2464       return Sub;
2465     }
2466   }
2467 
2468   // sdiv, srem -> sdivrem
2469   if (SDValue DivRem = useDivRem(N))
2470     return DivRem.getValue(1);
2471 
2472   // undef % X -> 0
2473   if (N0.isUndef())
2474     return DAG.getConstant(0, DL, VT);
2475   // X % undef -> undef
2476   if (N1.isUndef())
2477     return N1;
2478 
2479   return SDValue();
2480 }
2481 
2482 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2483   SDValue N0 = N->getOperand(0);
2484   SDValue N1 = N->getOperand(1);
2485   EVT VT = N->getValueType(0);
2486   SDLoc DL(N);
2487 
2488   // fold (mulhs x, 0) -> 0
2489   if (isNullConstant(N1))
2490     return N1;
2491   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2492   if (isOneConstant(N1)) {
2493     SDLoc DL(N);
2494     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2495                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2496                                        getShiftAmountTy(N0.getValueType())));
2497   }
2498   // fold (mulhs x, undef) -> 0
2499   if (N0.isUndef() || N1.isUndef())
2500     return DAG.getConstant(0, SDLoc(N), VT);
2501 
2502   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2503   // plus a shift.
2504   if (VT.isSimple() && !VT.isVector()) {
2505     MVT Simple = VT.getSimpleVT();
2506     unsigned SimpleSize = Simple.getSizeInBits();
2507     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2508     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2509       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2510       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2511       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2512       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2513             DAG.getConstant(SimpleSize, DL,
2514                             getShiftAmountTy(N1.getValueType())));
2515       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2516     }
2517   }
2518 
2519   return SDValue();
2520 }
2521 
2522 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2523   SDValue N0 = N->getOperand(0);
2524   SDValue N1 = N->getOperand(1);
2525   EVT VT = N->getValueType(0);
2526   SDLoc DL(N);
2527 
2528   // fold (mulhu x, 0) -> 0
2529   if (isNullConstant(N1))
2530     return N1;
2531   // fold (mulhu x, 1) -> 0
2532   if (isOneConstant(N1))
2533     return DAG.getConstant(0, DL, N0.getValueType());
2534   // fold (mulhu x, undef) -> 0
2535   if (N0.isUndef() || N1.isUndef())
2536     return DAG.getConstant(0, DL, VT);
2537 
2538   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2539   // plus a shift.
2540   if (VT.isSimple() && !VT.isVector()) {
2541     MVT Simple = VT.getSimpleVT();
2542     unsigned SimpleSize = Simple.getSizeInBits();
2543     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2544     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2545       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2546       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2547       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2548       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2549             DAG.getConstant(SimpleSize, DL,
2550                             getShiftAmountTy(N1.getValueType())));
2551       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2552     }
2553   }
2554 
2555   return SDValue();
2556 }
2557 
2558 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2559 /// give the opcodes for the two computations that are being performed. Return
2560 /// true if a simplification was made.
2561 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2562                                                 unsigned HiOp) {
2563   // If the high half is not needed, just compute the low half.
2564   bool HiExists = N->hasAnyUseOfValue(1);
2565   if (!HiExists &&
2566       (!LegalOperations ||
2567        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2568     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2569     return CombineTo(N, Res, Res);
2570   }
2571 
2572   // If the low half is not needed, just compute the high half.
2573   bool LoExists = N->hasAnyUseOfValue(0);
2574   if (!LoExists &&
2575       (!LegalOperations ||
2576        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2577     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2578     return CombineTo(N, Res, Res);
2579   }
2580 
2581   // If both halves are used, return as it is.
2582   if (LoExists && HiExists)
2583     return SDValue();
2584 
2585   // If the two computed results can be simplified separately, separate them.
2586   if (LoExists) {
2587     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2588     AddToWorklist(Lo.getNode());
2589     SDValue LoOpt = combine(Lo.getNode());
2590     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2591         (!LegalOperations ||
2592          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2593       return CombineTo(N, LoOpt, LoOpt);
2594   }
2595 
2596   if (HiExists) {
2597     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2598     AddToWorklist(Hi.getNode());
2599     SDValue HiOpt = combine(Hi.getNode());
2600     if (HiOpt.getNode() && HiOpt != Hi &&
2601         (!LegalOperations ||
2602          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2603       return CombineTo(N, HiOpt, HiOpt);
2604   }
2605 
2606   return SDValue();
2607 }
2608 
2609 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2610   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2611     return Res;
2612 
2613   EVT VT = N->getValueType(0);
2614   SDLoc DL(N);
2615 
2616   // If the type is twice as wide is legal, transform the mulhu to a wider
2617   // multiply plus a shift.
2618   if (VT.isSimple() && !VT.isVector()) {
2619     MVT Simple = VT.getSimpleVT();
2620     unsigned SimpleSize = Simple.getSizeInBits();
2621     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2622     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2623       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2624       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2625       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2626       // Compute the high part as N1.
2627       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2628             DAG.getConstant(SimpleSize, DL,
2629                             getShiftAmountTy(Lo.getValueType())));
2630       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2631       // Compute the low part as N0.
2632       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2633       return CombineTo(N, Lo, Hi);
2634     }
2635   }
2636 
2637   return SDValue();
2638 }
2639 
2640 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2641   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2642     return Res;
2643 
2644   EVT VT = N->getValueType(0);
2645   SDLoc DL(N);
2646 
2647   // If the type is twice as wide is legal, transform the mulhu to a wider
2648   // multiply plus a shift.
2649   if (VT.isSimple() && !VT.isVector()) {
2650     MVT Simple = VT.getSimpleVT();
2651     unsigned SimpleSize = Simple.getSizeInBits();
2652     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2653     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2654       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2655       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2656       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2657       // Compute the high part as N1.
2658       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2659             DAG.getConstant(SimpleSize, DL,
2660                             getShiftAmountTy(Lo.getValueType())));
2661       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2662       // Compute the low part as N0.
2663       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2664       return CombineTo(N, Lo, Hi);
2665     }
2666   }
2667 
2668   return SDValue();
2669 }
2670 
2671 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2672   // (smulo x, 2) -> (saddo x, x)
2673   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2674     if (C2->getAPIntValue() == 2)
2675       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2676                          N->getOperand(0), N->getOperand(0));
2677 
2678   return SDValue();
2679 }
2680 
2681 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2682   // (umulo x, 2) -> (uaddo x, x)
2683   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2684     if (C2->getAPIntValue() == 2)
2685       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2686                          N->getOperand(0), N->getOperand(0));
2687 
2688   return SDValue();
2689 }
2690 
2691 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2692   SDValue N0 = N->getOperand(0);
2693   SDValue N1 = N->getOperand(1);
2694   EVT VT = N0.getValueType();
2695 
2696   // fold vector ops
2697   if (VT.isVector())
2698     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2699       return FoldedVOp;
2700 
2701   // fold (add c1, c2) -> c1+c2
2702   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2703   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2704   if (N0C && N1C)
2705     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2706 
2707   // canonicalize constant to RHS
2708   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2709      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2710     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2711 
2712   return SDValue();
2713 }
2714 
2715 /// If this is a binary operator with two operands of the same opcode, try to
2716 /// simplify it.
2717 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2718   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2719   EVT VT = N0.getValueType();
2720   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2721 
2722   // Bail early if none of these transforms apply.
2723   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2724 
2725   // For each of OP in AND/OR/XOR:
2726   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2727   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2728   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2729   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2730   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2731   //
2732   // do not sink logical op inside of a vector extend, since it may combine
2733   // into a vsetcc.
2734   EVT Op0VT = N0.getOperand(0).getValueType();
2735   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2736        N0.getOpcode() == ISD::SIGN_EXTEND ||
2737        N0.getOpcode() == ISD::BSWAP ||
2738        // Avoid infinite looping with PromoteIntBinOp.
2739        (N0.getOpcode() == ISD::ANY_EXTEND &&
2740         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2741        (N0.getOpcode() == ISD::TRUNCATE &&
2742         (!TLI.isZExtFree(VT, Op0VT) ||
2743          !TLI.isTruncateFree(Op0VT, VT)) &&
2744         TLI.isTypeLegal(Op0VT))) &&
2745       !VT.isVector() &&
2746       Op0VT == N1.getOperand(0).getValueType() &&
2747       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2748     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2749                                  N0.getOperand(0).getValueType(),
2750                                  N0.getOperand(0), N1.getOperand(0));
2751     AddToWorklist(ORNode.getNode());
2752     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2753   }
2754 
2755   // For each of OP in SHL/SRL/SRA/AND...
2756   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2757   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2758   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2759   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2760        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2761       N0.getOperand(1) == N1.getOperand(1)) {
2762     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2763                                  N0.getOperand(0).getValueType(),
2764                                  N0.getOperand(0), N1.getOperand(0));
2765     AddToWorklist(ORNode.getNode());
2766     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2767                        ORNode, N0.getOperand(1));
2768   }
2769 
2770   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2771   // Only perform this optimization up until type legalization, before
2772   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2773   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2774   // we don't want to undo this promotion.
2775   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2776   // on scalars.
2777   if ((N0.getOpcode() == ISD::BITCAST ||
2778        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2779        Level <= AfterLegalizeTypes) {
2780     SDValue In0 = N0.getOperand(0);
2781     SDValue In1 = N1.getOperand(0);
2782     EVT In0Ty = In0.getValueType();
2783     EVT In1Ty = In1.getValueType();
2784     SDLoc DL(N);
2785     // If both incoming values are integers, and the original types are the
2786     // same.
2787     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2788       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2789       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2790       AddToWorklist(Op.getNode());
2791       return BC;
2792     }
2793   }
2794 
2795   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2796   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2797   // If both shuffles use the same mask, and both shuffle within a single
2798   // vector, then it is worthwhile to move the swizzle after the operation.
2799   // The type-legalizer generates this pattern when loading illegal
2800   // vector types from memory. In many cases this allows additional shuffle
2801   // optimizations.
2802   // There are other cases where moving the shuffle after the xor/and/or
2803   // is profitable even if shuffles don't perform a swizzle.
2804   // If both shuffles use the same mask, and both shuffles have the same first
2805   // or second operand, then it might still be profitable to move the shuffle
2806   // after the xor/and/or operation.
2807   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2808     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2809     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2810 
2811     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2812            "Inputs to shuffles are not the same type");
2813 
2814     // Check that both shuffles use the same mask. The masks are known to be of
2815     // the same length because the result vector type is the same.
2816     // Check also that shuffles have only one use to avoid introducing extra
2817     // instructions.
2818     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2819         SVN0->getMask().equals(SVN1->getMask())) {
2820       SDValue ShOp = N0->getOperand(1);
2821 
2822       // Don't try to fold this node if it requires introducing a
2823       // build vector of all zeros that might be illegal at this stage.
2824       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2825         if (!LegalTypes)
2826           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2827         else
2828           ShOp = SDValue();
2829       }
2830 
2831       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2832       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2833       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2834       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2835         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2836                                       N0->getOperand(0), N1->getOperand(0));
2837         AddToWorklist(NewNode.getNode());
2838         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2839                                     SVN0->getMask());
2840       }
2841 
2842       // Don't try to fold this node if it requires introducing a
2843       // build vector of all zeros that might be illegal at this stage.
2844       ShOp = N0->getOperand(0);
2845       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2846         if (!LegalTypes)
2847           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2848         else
2849           ShOp = SDValue();
2850       }
2851 
2852       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2853       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2854       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2855       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2856         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2857                                       N0->getOperand(1), N1->getOperand(1));
2858         AddToWorklist(NewNode.getNode());
2859         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2860                                     SVN0->getMask());
2861       }
2862     }
2863   }
2864 
2865   return SDValue();
2866 }
2867 
2868 /// This contains all DAGCombine rules which reduce two values combined by
2869 /// an And operation to a single value. This makes them reusable in the context
2870 /// of visitSELECT(). Rules involving constants are not included as
2871 /// visitSELECT() already handles those cases.
2872 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2873                                   SDNode *LocReference) {
2874   EVT VT = N1.getValueType();
2875 
2876   // fold (and x, undef) -> 0
2877   if (N0.isUndef() || N1.isUndef())
2878     return DAG.getConstant(0, SDLoc(LocReference), VT);
2879   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2880   SDValue LL, LR, RL, RR, CC0, CC1;
2881   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2882     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2883     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2884 
2885     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2886         LL.getValueType().isInteger()) {
2887       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2888       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2889         EVT CCVT = getSetCCResultType(LR.getValueType());
2890         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2891           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2892                                        LR.getValueType(), LL, RL);
2893           AddToWorklist(ORNode.getNode());
2894           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2895         }
2896       }
2897       if (isAllOnesConstant(LR)) {
2898         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2899         if (Op1 == ISD::SETEQ) {
2900           EVT CCVT = getSetCCResultType(LR.getValueType());
2901           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2902             SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2903                                           LR.getValueType(), LL, RL);
2904             AddToWorklist(ANDNode.getNode());
2905             return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2906           }
2907         }
2908         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2909         if (Op1 == ISD::SETGT) {
2910           EVT CCVT = getSetCCResultType(LR.getValueType());
2911           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2912             SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2913                                          LR.getValueType(), LL, RL);
2914             AddToWorklist(ORNode.getNode());
2915             return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2916           }
2917         }
2918       }
2919     }
2920     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2921     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2922         Op0 == Op1 && LL.getValueType().isInteger() &&
2923       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2924                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2925       EVT CCVT = getSetCCResultType(LL.getValueType());
2926       if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2927         SDLoc DL(N0);
2928         SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2929                                       LL, DAG.getConstant(1, DL,
2930                                                           LL.getValueType()));
2931         AddToWorklist(ADDNode.getNode());
2932         return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2933                             DAG.getConstant(2, DL, LL.getValueType()),
2934                             ISD::SETUGE);
2935       }
2936     }
2937     // canonicalize equivalent to ll == rl
2938     if (LL == RR && LR == RL) {
2939       Op1 = ISD::getSetCCSwappedOperands(Op1);
2940       std::swap(RL, RR);
2941     }
2942     if (LL == RL && LR == RR) {
2943       bool isInteger = LL.getValueType().isInteger();
2944       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2945       if (Result != ISD::SETCC_INVALID &&
2946           (!LegalOperations ||
2947            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2948             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2949         EVT CCVT = getSetCCResultType(LL.getValueType());
2950         if (N0.getValueType() == CCVT ||
2951             (!LegalOperations && N0.getValueType() == MVT::i1))
2952           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2953                               LL, LR, Result);
2954       }
2955     }
2956   }
2957 
2958   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2959       VT.getSizeInBits() <= 64) {
2960     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2961       APInt ADDC = ADDI->getAPIntValue();
2962       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2963         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2964         // immediate for an add, but it is legal if its top c2 bits are set,
2965         // transform the ADD so the immediate doesn't need to be materialized
2966         // in a register.
2967         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2968           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2969                                              SRLI->getZExtValue());
2970           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2971             ADDC |= Mask;
2972             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2973               SDLoc DL(N0);
2974               SDValue NewAdd =
2975                 DAG.getNode(ISD::ADD, DL, VT,
2976                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2977               CombineTo(N0.getNode(), NewAdd);
2978               // Return N so it doesn't get rechecked!
2979               return SDValue(LocReference, 0);
2980             }
2981           }
2982         }
2983       }
2984     }
2985   }
2986 
2987   // Reduce bit extract of low half of an integer to the narrower type.
2988   // (and (srl i64:x, K), KMask) ->
2989   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
2990   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
2991     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
2992       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2993         unsigned Size = VT.getSizeInBits();
2994         const APInt &AndMask = CAnd->getAPIntValue();
2995         unsigned ShiftBits = CShift->getZExtValue();
2996         unsigned MaskBits = AndMask.countTrailingOnes();
2997         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
2998 
2999         if (APIntOps::isMask(AndMask) &&
3000             // Required bits must not span the two halves of the integer and
3001             // must fit in the half size type.
3002             (ShiftBits + MaskBits <= Size / 2) &&
3003             TLI.isNarrowingProfitable(VT, HalfVT) &&
3004             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3005             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3006             TLI.isTruncateFree(VT, HalfVT) &&
3007             TLI.isZExtFree(HalfVT, VT)) {
3008           // The isNarrowingProfitable is to avoid regressions on PPC and
3009           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3010           // on downstream users of this. Those patterns could probably be
3011           // extended to handle extensions mixed in.
3012 
3013           SDValue SL(N0);
3014           assert(ShiftBits != 0 && MaskBits <= Size);
3015 
3016           // Extracting the highest bit of the low half.
3017           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3018           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3019                                       N0.getOperand(0));
3020 
3021           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3022           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3023           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3024           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3025           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3026         }
3027       }
3028     }
3029   }
3030 
3031   return SDValue();
3032 }
3033 
3034 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3035                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3036                                    bool &NarrowLoad) {
3037   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3038 
3039   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3040     return false;
3041 
3042   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3043   LoadedVT = LoadN->getMemoryVT();
3044 
3045   if (ExtVT == LoadedVT &&
3046       (!LegalOperations ||
3047        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3048     // ZEXTLOAD will match without needing to change the size of the value being
3049     // loaded.
3050     NarrowLoad = false;
3051     return true;
3052   }
3053 
3054   // Do not change the width of a volatile load.
3055   if (LoadN->isVolatile())
3056     return false;
3057 
3058   // Do not generate loads of non-round integer types since these can
3059   // be expensive (and would be wrong if the type is not byte sized).
3060   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3061     return false;
3062 
3063   if (LegalOperations &&
3064       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3065     return false;
3066 
3067   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3068     return false;
3069 
3070   NarrowLoad = true;
3071   return true;
3072 }
3073 
3074 SDValue DAGCombiner::visitAND(SDNode *N) {
3075   SDValue N0 = N->getOperand(0);
3076   SDValue N1 = N->getOperand(1);
3077   EVT VT = N1.getValueType();
3078 
3079   // fold vector ops
3080   if (VT.isVector()) {
3081     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3082       return FoldedVOp;
3083 
3084     // fold (and x, 0) -> 0, vector edition
3085     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3086       // do not return N0, because undef node may exist in N0
3087       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3088                              SDLoc(N), N0.getValueType());
3089     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3090       // do not return N1, because undef node may exist in N1
3091       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3092                              SDLoc(N), N1.getValueType());
3093 
3094     // fold (and x, -1) -> x, vector edition
3095     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3096       return N1;
3097     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3098       return N0;
3099   }
3100 
3101   // fold (and c1, c2) -> c1&c2
3102   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3103   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3104   if (N0C && N1C && !N1C->isOpaque())
3105     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3106   // canonicalize constant to RHS
3107   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3108      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3109     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3110   // fold (and x, -1) -> x
3111   if (isAllOnesConstant(N1))
3112     return N0;
3113   // if (and x, c) is known to be zero, return 0
3114   unsigned BitWidth = VT.getScalarSizeInBits();
3115   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3116                                    APInt::getAllOnesValue(BitWidth)))
3117     return DAG.getConstant(0, SDLoc(N), VT);
3118   // reassociate and
3119   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3120     return RAND;
3121   // fold (and (or x, C), D) -> D if (C & D) == D
3122   if (N1C && N0.getOpcode() == ISD::OR)
3123     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3124       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3125         return N1;
3126   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3127   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3128     SDValue N0Op0 = N0.getOperand(0);
3129     APInt Mask = ~N1C->getAPIntValue();
3130     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3131     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3132       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3133                                  N0.getValueType(), N0Op0);
3134 
3135       // Replace uses of the AND with uses of the Zero extend node.
3136       CombineTo(N, Zext);
3137 
3138       // We actually want to replace all uses of the any_extend with the
3139       // zero_extend, to avoid duplicating things.  This will later cause this
3140       // AND to be folded.
3141       CombineTo(N0.getNode(), Zext);
3142       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3143     }
3144   }
3145   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3146   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3147   // already be zero by virtue of the width of the base type of the load.
3148   //
3149   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3150   // more cases.
3151   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3152        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3153        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3154        N0.getOperand(0).getResNo() == 0) ||
3155       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3156     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3157                                          N0 : N0.getOperand(0) );
3158 
3159     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3160     // This can be a pure constant or a vector splat, in which case we treat the
3161     // vector as a scalar and use the splat value.
3162     APInt Constant = APInt::getNullValue(1);
3163     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3164       Constant = C->getAPIntValue();
3165     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3166       APInt SplatValue, SplatUndef;
3167       unsigned SplatBitSize;
3168       bool HasAnyUndefs;
3169       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3170                                              SplatBitSize, HasAnyUndefs);
3171       if (IsSplat) {
3172         // Undef bits can contribute to a possible optimisation if set, so
3173         // set them.
3174         SplatValue |= SplatUndef;
3175 
3176         // The splat value may be something like "0x00FFFFFF", which means 0 for
3177         // the first vector value and FF for the rest, repeating. We need a mask
3178         // that will apply equally to all members of the vector, so AND all the
3179         // lanes of the constant together.
3180         EVT VT = Vector->getValueType(0);
3181         unsigned BitWidth = VT.getScalarSizeInBits();
3182 
3183         // If the splat value has been compressed to a bitlength lower
3184         // than the size of the vector lane, we need to re-expand it to
3185         // the lane size.
3186         if (BitWidth > SplatBitSize)
3187           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3188                SplatBitSize < BitWidth;
3189                SplatBitSize = SplatBitSize * 2)
3190             SplatValue |= SplatValue.shl(SplatBitSize);
3191 
3192         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3193         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3194         if (SplatBitSize % BitWidth == 0) {
3195           Constant = APInt::getAllOnesValue(BitWidth);
3196           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3197             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3198         }
3199       }
3200     }
3201 
3202     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3203     // actually legal and isn't going to get expanded, else this is a false
3204     // optimisation.
3205     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3206                                                     Load->getValueType(0),
3207                                                     Load->getMemoryVT());
3208 
3209     // Resize the constant to the same size as the original memory access before
3210     // extension. If it is still the AllOnesValue then this AND is completely
3211     // unneeded.
3212     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3213 
3214     bool B;
3215     switch (Load->getExtensionType()) {
3216     default: B = false; break;
3217     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3218     case ISD::ZEXTLOAD:
3219     case ISD::NON_EXTLOAD: B = true; break;
3220     }
3221 
3222     if (B && Constant.isAllOnesValue()) {
3223       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3224       // preserve semantics once we get rid of the AND.
3225       SDValue NewLoad(Load, 0);
3226       if (Load->getExtensionType() == ISD::EXTLOAD) {
3227         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3228                               Load->getValueType(0), SDLoc(Load),
3229                               Load->getChain(), Load->getBasePtr(),
3230                               Load->getOffset(), Load->getMemoryVT(),
3231                               Load->getMemOperand());
3232         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3233         if (Load->getNumValues() == 3) {
3234           // PRE/POST_INC loads have 3 values.
3235           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3236                            NewLoad.getValue(2) };
3237           CombineTo(Load, To, 3, true);
3238         } else {
3239           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3240         }
3241       }
3242 
3243       // Fold the AND away, taking care not to fold to the old load node if we
3244       // replaced it.
3245       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3246 
3247       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3248     }
3249   }
3250 
3251   // fold (and (load x), 255) -> (zextload x, i8)
3252   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3253   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3254   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3255                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3256                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3257     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3258     LoadSDNode *LN0 = HasAnyExt
3259       ? cast<LoadSDNode>(N0.getOperand(0))
3260       : cast<LoadSDNode>(N0);
3261     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3262         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3263       auto NarrowLoad = false;
3264       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3265       EVT ExtVT, LoadedVT;
3266       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3267                            NarrowLoad)) {
3268         if (!NarrowLoad) {
3269           SDValue NewLoad =
3270             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3271                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3272                            LN0->getMemOperand());
3273           AddToWorklist(N);
3274           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3275           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3276         } else {
3277           EVT PtrType = LN0->getOperand(1).getValueType();
3278 
3279           unsigned Alignment = LN0->getAlignment();
3280           SDValue NewPtr = LN0->getBasePtr();
3281 
3282           // For big endian targets, we need to add an offset to the pointer
3283           // to load the correct bytes.  For little endian systems, we merely
3284           // need to read fewer bytes from the same pointer.
3285           if (DAG.getDataLayout().isBigEndian()) {
3286             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3287             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3288             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3289             SDLoc DL(LN0);
3290             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3291                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3292             Alignment = MinAlign(Alignment, PtrOff);
3293           }
3294 
3295           AddToWorklist(NewPtr.getNode());
3296 
3297           SDValue Load = DAG.getExtLoad(
3298               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3299               LN0->getPointerInfo(), ExtVT, Alignment,
3300               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3301           AddToWorklist(N);
3302           CombineTo(LN0, Load, Load.getValue(1));
3303           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3304         }
3305       }
3306     }
3307   }
3308 
3309   if (SDValue Combined = visitANDLike(N0, N1, N))
3310     return Combined;
3311 
3312   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3313   if (N0.getOpcode() == N1.getOpcode())
3314     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3315       return Tmp;
3316 
3317   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3318   // fold (and (sra)) -> (and (srl)) when possible.
3319   if (!VT.isVector() &&
3320       SimplifyDemandedBits(SDValue(N, 0)))
3321     return SDValue(N, 0);
3322 
3323   // fold (zext_inreg (extload x)) -> (zextload x)
3324   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3325     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3326     EVT MemVT = LN0->getMemoryVT();
3327     // If we zero all the possible extended bits, then we can turn this into
3328     // a zextload if we are running before legalize or the operation is legal.
3329     unsigned BitWidth = N1.getScalarValueSizeInBits();
3330     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3331                            BitWidth - MemVT.getScalarSizeInBits())) &&
3332         ((!LegalOperations && !LN0->isVolatile()) ||
3333          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3334       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3335                                        LN0->getChain(), LN0->getBasePtr(),
3336                                        MemVT, LN0->getMemOperand());
3337       AddToWorklist(N);
3338       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3339       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3340     }
3341   }
3342   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3343   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3344       N0.hasOneUse()) {
3345     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3346     EVT MemVT = LN0->getMemoryVT();
3347     // If we zero all the possible extended bits, then we can turn this into
3348     // a zextload if we are running before legalize or the operation is legal.
3349     unsigned BitWidth = N1.getScalarValueSizeInBits();
3350     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3351                            BitWidth - MemVT.getScalarSizeInBits())) &&
3352         ((!LegalOperations && !LN0->isVolatile()) ||
3353          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3354       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3355                                        LN0->getChain(), LN0->getBasePtr(),
3356                                        MemVT, LN0->getMemOperand());
3357       AddToWorklist(N);
3358       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3359       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3360     }
3361   }
3362   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3363   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3364     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3365                                            N0.getOperand(1), false))
3366       return BSwap;
3367   }
3368 
3369   return SDValue();
3370 }
3371 
3372 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3373 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3374                                         bool DemandHighBits) {
3375   if (!LegalOperations)
3376     return SDValue();
3377 
3378   EVT VT = N->getValueType(0);
3379   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3380     return SDValue();
3381   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3382     return SDValue();
3383 
3384   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3385   bool LookPassAnd0 = false;
3386   bool LookPassAnd1 = false;
3387   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3388       std::swap(N0, N1);
3389   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3390       std::swap(N0, N1);
3391   if (N0.getOpcode() == ISD::AND) {
3392     if (!N0.getNode()->hasOneUse())
3393       return SDValue();
3394     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3395     if (!N01C || N01C->getZExtValue() != 0xFF00)
3396       return SDValue();
3397     N0 = N0.getOperand(0);
3398     LookPassAnd0 = true;
3399   }
3400 
3401   if (N1.getOpcode() == ISD::AND) {
3402     if (!N1.getNode()->hasOneUse())
3403       return SDValue();
3404     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3405     if (!N11C || N11C->getZExtValue() != 0xFF)
3406       return SDValue();
3407     N1 = N1.getOperand(0);
3408     LookPassAnd1 = true;
3409   }
3410 
3411   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3412     std::swap(N0, N1);
3413   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3414     return SDValue();
3415   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3416     return SDValue();
3417 
3418   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3419   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3420   if (!N01C || !N11C)
3421     return SDValue();
3422   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3423     return SDValue();
3424 
3425   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3426   SDValue N00 = N0->getOperand(0);
3427   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3428     if (!N00.getNode()->hasOneUse())
3429       return SDValue();
3430     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3431     if (!N001C || N001C->getZExtValue() != 0xFF)
3432       return SDValue();
3433     N00 = N00.getOperand(0);
3434     LookPassAnd0 = true;
3435   }
3436 
3437   SDValue N10 = N1->getOperand(0);
3438   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3439     if (!N10.getNode()->hasOneUse())
3440       return SDValue();
3441     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3442     if (!N101C || N101C->getZExtValue() != 0xFF00)
3443       return SDValue();
3444     N10 = N10.getOperand(0);
3445     LookPassAnd1 = true;
3446   }
3447 
3448   if (N00 != N10)
3449     return SDValue();
3450 
3451   // Make sure everything beyond the low halfword gets set to zero since the SRL
3452   // 16 will clear the top bits.
3453   unsigned OpSizeInBits = VT.getSizeInBits();
3454   if (DemandHighBits && OpSizeInBits > 16) {
3455     // If the left-shift isn't masked out then the only way this is a bswap is
3456     // if all bits beyond the low 8 are 0. In that case the entire pattern
3457     // reduces to a left shift anyway: leave it for other parts of the combiner.
3458     if (!LookPassAnd0)
3459       return SDValue();
3460 
3461     // However, if the right shift isn't masked out then it might be because
3462     // it's not needed. See if we can spot that too.
3463     if (!LookPassAnd1 &&
3464         !DAG.MaskedValueIsZero(
3465             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3466       return SDValue();
3467   }
3468 
3469   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3470   if (OpSizeInBits > 16) {
3471     SDLoc DL(N);
3472     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3473                       DAG.getConstant(OpSizeInBits - 16, DL,
3474                                       getShiftAmountTy(VT)));
3475   }
3476   return Res;
3477 }
3478 
3479 /// Return true if the specified node is an element that makes up a 32-bit
3480 /// packed halfword byteswap.
3481 /// ((x & 0x000000ff) << 8) |
3482 /// ((x & 0x0000ff00) >> 8) |
3483 /// ((x & 0x00ff0000) << 8) |
3484 /// ((x & 0xff000000) >> 8)
3485 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3486   if (!N.getNode()->hasOneUse())
3487     return false;
3488 
3489   unsigned Opc = N.getOpcode();
3490   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3491     return false;
3492 
3493   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3494   if (!N1C)
3495     return false;
3496 
3497   unsigned Num;
3498   switch (N1C->getZExtValue()) {
3499   default:
3500     return false;
3501   case 0xFF:       Num = 0; break;
3502   case 0xFF00:     Num = 1; break;
3503   case 0xFF0000:   Num = 2; break;
3504   case 0xFF000000: Num = 3; break;
3505   }
3506 
3507   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3508   SDValue N0 = N.getOperand(0);
3509   if (Opc == ISD::AND) {
3510     if (Num == 0 || Num == 2) {
3511       // (x >> 8) & 0xff
3512       // (x >> 8) & 0xff0000
3513       if (N0.getOpcode() != ISD::SRL)
3514         return false;
3515       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3516       if (!C || C->getZExtValue() != 8)
3517         return false;
3518     } else {
3519       // (x << 8) & 0xff00
3520       // (x << 8) & 0xff000000
3521       if (N0.getOpcode() != ISD::SHL)
3522         return false;
3523       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3524       if (!C || C->getZExtValue() != 8)
3525         return false;
3526     }
3527   } else if (Opc == ISD::SHL) {
3528     // (x & 0xff) << 8
3529     // (x & 0xff0000) << 8
3530     if (Num != 0 && Num != 2)
3531       return false;
3532     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3533     if (!C || C->getZExtValue() != 8)
3534       return false;
3535   } else { // Opc == ISD::SRL
3536     // (x & 0xff00) >> 8
3537     // (x & 0xff000000) >> 8
3538     if (Num != 1 && Num != 3)
3539       return false;
3540     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3541     if (!C || C->getZExtValue() != 8)
3542       return false;
3543   }
3544 
3545   if (Parts[Num])
3546     return false;
3547 
3548   Parts[Num] = N0.getOperand(0).getNode();
3549   return true;
3550 }
3551 
3552 /// Match a 32-bit packed halfword bswap. That is
3553 /// ((x & 0x000000ff) << 8) |
3554 /// ((x & 0x0000ff00) >> 8) |
3555 /// ((x & 0x00ff0000) << 8) |
3556 /// ((x & 0xff000000) >> 8)
3557 /// => (rotl (bswap x), 16)
3558 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3559   if (!LegalOperations)
3560     return SDValue();
3561 
3562   EVT VT = N->getValueType(0);
3563   if (VT != MVT::i32)
3564     return SDValue();
3565   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3566     return SDValue();
3567 
3568   // Look for either
3569   // (or (or (and), (and)), (or (and), (and)))
3570   // (or (or (or (and), (and)), (and)), (and))
3571   if (N0.getOpcode() != ISD::OR)
3572     return SDValue();
3573   SDValue N00 = N0.getOperand(0);
3574   SDValue N01 = N0.getOperand(1);
3575   SDNode *Parts[4] = {};
3576 
3577   if (N1.getOpcode() == ISD::OR &&
3578       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3579     // (or (or (and), (and)), (or (and), (and)))
3580     SDValue N000 = N00.getOperand(0);
3581     if (!isBSwapHWordElement(N000, Parts))
3582       return SDValue();
3583 
3584     SDValue N001 = N00.getOperand(1);
3585     if (!isBSwapHWordElement(N001, Parts))
3586       return SDValue();
3587     SDValue N010 = N01.getOperand(0);
3588     if (!isBSwapHWordElement(N010, Parts))
3589       return SDValue();
3590     SDValue N011 = N01.getOperand(1);
3591     if (!isBSwapHWordElement(N011, Parts))
3592       return SDValue();
3593   } else {
3594     // (or (or (or (and), (and)), (and)), (and))
3595     if (!isBSwapHWordElement(N1, Parts))
3596       return SDValue();
3597     if (!isBSwapHWordElement(N01, Parts))
3598       return SDValue();
3599     if (N00.getOpcode() != ISD::OR)
3600       return SDValue();
3601     SDValue N000 = N00.getOperand(0);
3602     if (!isBSwapHWordElement(N000, Parts))
3603       return SDValue();
3604     SDValue N001 = N00.getOperand(1);
3605     if (!isBSwapHWordElement(N001, Parts))
3606       return SDValue();
3607   }
3608 
3609   // Make sure the parts are all coming from the same node.
3610   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3611     return SDValue();
3612 
3613   SDLoc DL(N);
3614   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3615                               SDValue(Parts[0], 0));
3616 
3617   // Result of the bswap should be rotated by 16. If it's not legal, then
3618   // do  (x << 16) | (x >> 16).
3619   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3620   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3621     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3622   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3623     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3624   return DAG.getNode(ISD::OR, DL, VT,
3625                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3626                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3627 }
3628 
3629 /// This contains all DAGCombine rules which reduce two values combined by
3630 /// an Or operation to a single value \see visitANDLike().
3631 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3632   EVT VT = N1.getValueType();
3633   // fold (or x, undef) -> -1
3634   if (!LegalOperations &&
3635       (N0.isUndef() || N1.isUndef())) {
3636     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3637     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3638                            SDLoc(LocReference), VT);
3639   }
3640   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3641   SDValue LL, LR, RL, RR, CC0, CC1;
3642   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3643     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3644     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3645 
3646     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3647       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3648       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3649       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3650         EVT CCVT = getSetCCResultType(LR.getValueType());
3651         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3652           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3653                                        LR.getValueType(), LL, RL);
3654           AddToWorklist(ORNode.getNode());
3655           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3656         }
3657       }
3658       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3659       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3660       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3661         EVT CCVT = getSetCCResultType(LR.getValueType());
3662         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3663           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3664                                         LR.getValueType(), LL, RL);
3665           AddToWorklist(ANDNode.getNode());
3666           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3667         }
3668       }
3669     }
3670     // canonicalize equivalent to ll == rl
3671     if (LL == RR && LR == RL) {
3672       Op1 = ISD::getSetCCSwappedOperands(Op1);
3673       std::swap(RL, RR);
3674     }
3675     if (LL == RL && LR == RR) {
3676       bool isInteger = LL.getValueType().isInteger();
3677       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3678       if (Result != ISD::SETCC_INVALID &&
3679           (!LegalOperations ||
3680            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3681             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3682         EVT CCVT = getSetCCResultType(LL.getValueType());
3683         if (N0.getValueType() == CCVT ||
3684             (!LegalOperations && N0.getValueType() == MVT::i1))
3685           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3686                               LL, LR, Result);
3687       }
3688     }
3689   }
3690 
3691   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3692   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3693       // Don't increase # computations.
3694       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3695     // We can only do this xform if we know that bits from X that are set in C2
3696     // but not in C1 are already zero.  Likewise for Y.
3697     if (const ConstantSDNode *N0O1C =
3698         getAsNonOpaqueConstant(N0.getOperand(1))) {
3699       if (const ConstantSDNode *N1O1C =
3700           getAsNonOpaqueConstant(N1.getOperand(1))) {
3701         // We can only do this xform if we know that bits from X that are set in
3702         // C2 but not in C1 are already zero.  Likewise for Y.
3703         const APInt &LHSMask = N0O1C->getAPIntValue();
3704         const APInt &RHSMask = N1O1C->getAPIntValue();
3705 
3706         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3707             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3708           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3709                                   N0.getOperand(0), N1.getOperand(0));
3710           SDLoc DL(LocReference);
3711           return DAG.getNode(ISD::AND, DL, VT, X,
3712                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3713         }
3714       }
3715     }
3716   }
3717 
3718   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3719   if (N0.getOpcode() == ISD::AND &&
3720       N1.getOpcode() == ISD::AND &&
3721       N0.getOperand(0) == N1.getOperand(0) &&
3722       // Don't increase # computations.
3723       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3724     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3725                             N0.getOperand(1), N1.getOperand(1));
3726     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3727   }
3728 
3729   return SDValue();
3730 }
3731 
3732 SDValue DAGCombiner::visitOR(SDNode *N) {
3733   SDValue N0 = N->getOperand(0);
3734   SDValue N1 = N->getOperand(1);
3735   EVT VT = N1.getValueType();
3736 
3737   // fold vector ops
3738   if (VT.isVector()) {
3739     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3740       return FoldedVOp;
3741 
3742     // fold (or x, 0) -> x, vector edition
3743     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3744       return N1;
3745     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3746       return N0;
3747 
3748     // fold (or x, -1) -> -1, vector edition
3749     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3750       // do not return N0, because undef node may exist in N0
3751       return DAG.getConstant(
3752           APInt::getAllOnesValue(N0.getScalarValueSizeInBits()), SDLoc(N),
3753           N0.getValueType());
3754     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3755       // do not return N1, because undef node may exist in N1
3756       return DAG.getConstant(
3757           APInt::getAllOnesValue(N1.getScalarValueSizeInBits()), SDLoc(N),
3758           N1.getValueType());
3759 
3760     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
3761     // Do this only if the resulting shuffle is legal.
3762     if (isa<ShuffleVectorSDNode>(N0) &&
3763         isa<ShuffleVectorSDNode>(N1) &&
3764         // Avoid folding a node with illegal type.
3765         TLI.isTypeLegal(VT)) {
3766       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
3767       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
3768       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
3769       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
3770       // Ensure both shuffles have a zero input.
3771       if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) {
3772         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
3773         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
3774         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3775         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3776         bool CanFold = true;
3777         int NumElts = VT.getVectorNumElements();
3778         SmallVector<int, 4> Mask(NumElts);
3779 
3780         for (int i = 0; i != NumElts; ++i) {
3781           int M0 = SV0->getMaskElt(i);
3782           int M1 = SV1->getMaskElt(i);
3783 
3784           // Determine if either index is pointing to a zero vector.
3785           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
3786           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
3787 
3788           // If one element is zero and the otherside is undef, keep undef.
3789           // This also handles the case that both are undef.
3790           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
3791             Mask[i] = -1;
3792             continue;
3793           }
3794 
3795           // Make sure only one of the elements is zero.
3796           if (M0Zero == M1Zero) {
3797             CanFold = false;
3798             break;
3799           }
3800 
3801           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
3802 
3803           // We have a zero and non-zero element. If the non-zero came from
3804           // SV0 make the index a LHS index. If it came from SV1, make it
3805           // a RHS index. We need to mod by NumElts because we don't care
3806           // which operand it came from in the original shuffles.
3807           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
3808         }
3809 
3810         if (CanFold) {
3811           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
3812           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
3813 
3814           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3815           if (!LegalMask) {
3816             std::swap(NewLHS, NewRHS);
3817             ShuffleVectorSDNode::commuteMask(Mask);
3818             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3819           }
3820 
3821           if (LegalMask)
3822             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
3823         }
3824       }
3825     }
3826   }
3827 
3828   // fold (or c1, c2) -> c1|c2
3829   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3830   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3831   if (N0C && N1C && !N1C->isOpaque())
3832     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3833   // canonicalize constant to RHS
3834   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3835      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3836     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3837   // fold (or x, 0) -> x
3838   if (isNullConstant(N1))
3839     return N0;
3840   // fold (or x, -1) -> -1
3841   if (isAllOnesConstant(N1))
3842     return N1;
3843   // fold (or x, c) -> c iff (x & ~c) == 0
3844   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3845     return N1;
3846 
3847   if (SDValue Combined = visitORLike(N0, N1, N))
3848     return Combined;
3849 
3850   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3851   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3852     return BSwap;
3853   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3854     return BSwap;
3855 
3856   // reassociate or
3857   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3858     return ROR;
3859   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3860   // iff (c1 & c2) == 0.
3861   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3862              isa<ConstantSDNode>(N0.getOperand(1))) {
3863     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3864     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3865       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3866                                                    N1C, C1))
3867         return DAG.getNode(
3868             ISD::AND, SDLoc(N), VT,
3869             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3870       return SDValue();
3871     }
3872   }
3873   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3874   if (N0.getOpcode() == N1.getOpcode())
3875     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3876       return Tmp;
3877 
3878   // See if this is some rotate idiom.
3879   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3880     return SDValue(Rot, 0);
3881 
3882   // Simplify the operands using demanded-bits information.
3883   if (!VT.isVector() &&
3884       SimplifyDemandedBits(SDValue(N, 0)))
3885     return SDValue(N, 0);
3886 
3887   return SDValue();
3888 }
3889 
3890 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3891 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3892   if (Op.getOpcode() == ISD::AND) {
3893     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3894       Mask = Op.getOperand(1);
3895       Op = Op.getOperand(0);
3896     } else {
3897       return false;
3898     }
3899   }
3900 
3901   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3902     Shift = Op;
3903     return true;
3904   }
3905 
3906   return false;
3907 }
3908 
3909 // Return true if we can prove that, whenever Neg and Pos are both in the
3910 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3911 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3912 //
3913 //     (or (shift1 X, Neg), (shift2 X, Pos))
3914 //
3915 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3916 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3917 // to consider shift amounts with defined behavior.
3918 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3919   // If EltSize is a power of 2 then:
3920   //
3921   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3922   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3923   //
3924   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3925   // for the stronger condition:
3926   //
3927   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3928   //
3929   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3930   // we can just replace Neg with Neg' for the rest of the function.
3931   //
3932   // In other cases we check for the even stronger condition:
3933   //
3934   //     Neg == EltSize - Pos                                    [B]
3935   //
3936   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3937   // behavior if Pos == 0 (and consequently Neg == EltSize).
3938   //
3939   // We could actually use [A] whenever EltSize is a power of 2, but the
3940   // only extra cases that it would match are those uninteresting ones
3941   // where Neg and Pos are never in range at the same time.  E.g. for
3942   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3943   // as well as (sub 32, Pos), but:
3944   //
3945   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3946   //
3947   // always invokes undefined behavior for 32-bit X.
3948   //
3949   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3950   unsigned MaskLoBits = 0;
3951   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3952     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3953       if (NegC->getAPIntValue() == EltSize - 1) {
3954         Neg = Neg.getOperand(0);
3955         MaskLoBits = Log2_64(EltSize);
3956       }
3957     }
3958   }
3959 
3960   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3961   if (Neg.getOpcode() != ISD::SUB)
3962     return false;
3963   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3964   if (!NegC)
3965     return false;
3966   SDValue NegOp1 = Neg.getOperand(1);
3967 
3968   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3969   // Pos'.  The truncation is redundant for the purpose of the equality.
3970   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3971     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3972       if (PosC->getAPIntValue() == EltSize - 1)
3973         Pos = Pos.getOperand(0);
3974 
3975   // The condition we need is now:
3976   //
3977   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3978   //
3979   // If NegOp1 == Pos then we need:
3980   //
3981   //              EltSize & Mask == NegC & Mask
3982   //
3983   // (because "x & Mask" is a truncation and distributes through subtraction).
3984   APInt Width;
3985   if (Pos == NegOp1)
3986     Width = NegC->getAPIntValue();
3987 
3988   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3989   // Then the condition we want to prove becomes:
3990   //
3991   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3992   //
3993   // which, again because "x & Mask" is a truncation, becomes:
3994   //
3995   //                NegC & Mask == (EltSize - PosC) & Mask
3996   //             EltSize & Mask == (NegC + PosC) & Mask
3997   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3998     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3999       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4000     else
4001       return false;
4002   } else
4003     return false;
4004 
4005   // Now we just need to check that EltSize & Mask == Width & Mask.
4006   if (MaskLoBits)
4007     // EltSize & Mask is 0 since Mask is EltSize - 1.
4008     return Width.getLoBits(MaskLoBits) == 0;
4009   return Width == EltSize;
4010 }
4011 
4012 // A subroutine of MatchRotate used once we have found an OR of two opposite
4013 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4014 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4015 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4016 // Neg with outer conversions stripped away.
4017 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4018                                        SDValue Neg, SDValue InnerPos,
4019                                        SDValue InnerNeg, unsigned PosOpcode,
4020                                        unsigned NegOpcode, const SDLoc &DL) {
4021   // fold (or (shl x, (*ext y)),
4022   //          (srl x, (*ext (sub 32, y)))) ->
4023   //   (rotl x, y) or (rotr x, (sub 32, y))
4024   //
4025   // fold (or (shl x, (*ext (sub 32, y))),
4026   //          (srl x, (*ext y))) ->
4027   //   (rotr x, y) or (rotl x, (sub 32, y))
4028   EVT VT = Shifted.getValueType();
4029   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4030     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4031     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4032                        HasPos ? Pos : Neg).getNode();
4033   }
4034 
4035   return nullptr;
4036 }
4037 
4038 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4039 // idioms for rotate, and if the target supports rotation instructions, generate
4040 // a rot[lr].
4041 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4042   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4043   EVT VT = LHS.getValueType();
4044   if (!TLI.isTypeLegal(VT)) return nullptr;
4045 
4046   // The target must have at least one rotate flavor.
4047   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4048   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4049   if (!HasROTL && !HasROTR) return nullptr;
4050 
4051   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4052   SDValue LHSShift;   // The shift.
4053   SDValue LHSMask;    // AND value if any.
4054   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4055     return nullptr; // Not part of a rotate.
4056 
4057   SDValue RHSShift;   // The shift.
4058   SDValue RHSMask;    // AND value if any.
4059   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4060     return nullptr; // Not part of a rotate.
4061 
4062   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4063     return nullptr;   // Not shifting the same value.
4064 
4065   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4066     return nullptr;   // Shifts must disagree.
4067 
4068   // Canonicalize shl to left side in a shl/srl pair.
4069   if (RHSShift.getOpcode() == ISD::SHL) {
4070     std::swap(LHS, RHS);
4071     std::swap(LHSShift, RHSShift);
4072     std::swap(LHSMask, RHSMask);
4073   }
4074 
4075   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4076   SDValue LHSShiftArg = LHSShift.getOperand(0);
4077   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4078   SDValue RHSShiftArg = RHSShift.getOperand(0);
4079   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4080 
4081   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4082   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4083   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4084     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4085     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4086     if ((LShVal + RShVal) != EltSizeInBits)
4087       return nullptr;
4088 
4089     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4090                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4091 
4092     // If there is an AND of either shifted operand, apply it to the result.
4093     if (LHSMask.getNode() || RHSMask.getNode()) {
4094       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4095       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4096 
4097       if (LHSMask.getNode()) {
4098         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4099         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4100                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4101                                        DAG.getConstant(RHSBits, DL, VT)));
4102       }
4103       if (RHSMask.getNode()) {
4104         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4105         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4106                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4107                                        DAG.getConstant(LHSBits, DL, VT)));
4108       }
4109 
4110       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4111     }
4112 
4113     return Rot.getNode();
4114   }
4115 
4116   // If there is a mask here, and we have a variable shift, we can't be sure
4117   // that we're masking out the right stuff.
4118   if (LHSMask.getNode() || RHSMask.getNode())
4119     return nullptr;
4120 
4121   // If the shift amount is sign/zext/any-extended just peel it off.
4122   SDValue LExtOp0 = LHSShiftAmt;
4123   SDValue RExtOp0 = RHSShiftAmt;
4124   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4125        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4126        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4127        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4128       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4129        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4130        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4131        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4132     LExtOp0 = LHSShiftAmt.getOperand(0);
4133     RExtOp0 = RHSShiftAmt.getOperand(0);
4134   }
4135 
4136   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4137                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4138   if (TryL)
4139     return TryL;
4140 
4141   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4142                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4143   if (TryR)
4144     return TryR;
4145 
4146   return nullptr;
4147 }
4148 
4149 SDValue DAGCombiner::visitXOR(SDNode *N) {
4150   SDValue N0 = N->getOperand(0);
4151   SDValue N1 = N->getOperand(1);
4152   EVT VT = N0.getValueType();
4153 
4154   // fold vector ops
4155   if (VT.isVector()) {
4156     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4157       return FoldedVOp;
4158 
4159     // fold (xor x, 0) -> x, vector edition
4160     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4161       return N1;
4162     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4163       return N0;
4164   }
4165 
4166   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4167   if (N0.isUndef() && N1.isUndef())
4168     return DAG.getConstant(0, SDLoc(N), VT);
4169   // fold (xor x, undef) -> undef
4170   if (N0.isUndef())
4171     return N0;
4172   if (N1.isUndef())
4173     return N1;
4174   // fold (xor c1, c2) -> c1^c2
4175   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4176   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4177   if (N0C && N1C)
4178     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4179   // canonicalize constant to RHS
4180   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4181      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4182     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4183   // fold (xor x, 0) -> x
4184   if (isNullConstant(N1))
4185     return N0;
4186   // reassociate xor
4187   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4188     return RXOR;
4189 
4190   // fold !(x cc y) -> (x !cc y)
4191   SDValue LHS, RHS, CC;
4192   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4193     bool isInt = LHS.getValueType().isInteger();
4194     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4195                                                isInt);
4196 
4197     if (!LegalOperations ||
4198         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4199       switch (N0.getOpcode()) {
4200       default:
4201         llvm_unreachable("Unhandled SetCC Equivalent!");
4202       case ISD::SETCC:
4203         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4204       case ISD::SELECT_CC:
4205         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4206                                N0.getOperand(3), NotCC);
4207       }
4208     }
4209   }
4210 
4211   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4212   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4213       N0.getNode()->hasOneUse() &&
4214       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4215     SDValue V = N0.getOperand(0);
4216     SDLoc DL(N0);
4217     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4218                     DAG.getConstant(1, DL, V.getValueType()));
4219     AddToWorklist(V.getNode());
4220     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4221   }
4222 
4223   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4224   if (isOneConstant(N1) && VT == MVT::i1 &&
4225       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4226     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4227     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4228       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4229       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4230       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4231       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4232       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4233     }
4234   }
4235   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4236   if (isAllOnesConstant(N1) &&
4237       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4238     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4239     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4240       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4241       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4242       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4243       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4244       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4245     }
4246   }
4247   // fold (xor (and x, y), y) -> (and (not x), y)
4248   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4249       N0->getOperand(1) == N1) {
4250     SDValue X = N0->getOperand(0);
4251     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4252     AddToWorklist(NotX.getNode());
4253     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4254   }
4255   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4256   if (N1C && N0.getOpcode() == ISD::XOR) {
4257     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4258       SDLoc DL(N);
4259       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4260                          DAG.getConstant(N1C->getAPIntValue() ^
4261                                          N00C->getAPIntValue(), DL, VT));
4262     }
4263     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4264       SDLoc DL(N);
4265       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4266                          DAG.getConstant(N1C->getAPIntValue() ^
4267                                          N01C->getAPIntValue(), DL, VT));
4268     }
4269   }
4270   // fold (xor x, x) -> 0
4271   if (N0 == N1)
4272     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4273 
4274   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4275   // Here is a concrete example of this equivalence:
4276   // i16   x ==  14
4277   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4278   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4279   //
4280   // =>
4281   //
4282   // i16     ~1      == 0b1111111111111110
4283   // i16 rol(~1, 14) == 0b1011111111111111
4284   //
4285   // Some additional tips to help conceptualize this transform:
4286   // - Try to see the operation as placing a single zero in a value of all ones.
4287   // - There exists no value for x which would allow the result to contain zero.
4288   // - Values of x larger than the bitwidth are undefined and do not require a
4289   //   consistent result.
4290   // - Pushing the zero left requires shifting one bits in from the right.
4291   // A rotate left of ~1 is a nice way of achieving the desired result.
4292   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4293       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4294     SDLoc DL(N);
4295     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4296                        N0.getOperand(1));
4297   }
4298 
4299   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4300   if (N0.getOpcode() == N1.getOpcode())
4301     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4302       return Tmp;
4303 
4304   // Simplify the expression using non-local knowledge.
4305   if (!VT.isVector() &&
4306       SimplifyDemandedBits(SDValue(N, 0)))
4307     return SDValue(N, 0);
4308 
4309   return SDValue();
4310 }
4311 
4312 /// Handle transforms common to the three shifts, when the shift amount is a
4313 /// constant.
4314 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4315   SDNode *LHS = N->getOperand(0).getNode();
4316   if (!LHS->hasOneUse()) return SDValue();
4317 
4318   // We want to pull some binops through shifts, so that we have (and (shift))
4319   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4320   // thing happens with address calculations, so it's important to canonicalize
4321   // it.
4322   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4323 
4324   switch (LHS->getOpcode()) {
4325   default: return SDValue();
4326   case ISD::OR:
4327   case ISD::XOR:
4328     HighBitSet = false; // We can only transform sra if the high bit is clear.
4329     break;
4330   case ISD::AND:
4331     HighBitSet = true;  // We can only transform sra if the high bit is set.
4332     break;
4333   case ISD::ADD:
4334     if (N->getOpcode() != ISD::SHL)
4335       return SDValue(); // only shl(add) not sr[al](add).
4336     HighBitSet = false; // We can only transform sra if the high bit is clear.
4337     break;
4338   }
4339 
4340   // We require the RHS of the binop to be a constant and not opaque as well.
4341   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4342   if (!BinOpCst) return SDValue();
4343 
4344   // FIXME: disable this unless the input to the binop is a shift by a constant.
4345   // If it is not a shift, it pessimizes some common cases like:
4346   //
4347   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4348   //    int bar(int *X, int i) { return X[i & 255]; }
4349   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4350   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4351        BinOpLHSVal->getOpcode() != ISD::SRA &&
4352        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4353       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4354     return SDValue();
4355 
4356   EVT VT = N->getValueType(0);
4357 
4358   // If this is a signed shift right, and the high bit is modified by the
4359   // logical operation, do not perform the transformation. The highBitSet
4360   // boolean indicates the value of the high bit of the constant which would
4361   // cause it to be modified for this operation.
4362   if (N->getOpcode() == ISD::SRA) {
4363     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4364     if (BinOpRHSSignSet != HighBitSet)
4365       return SDValue();
4366   }
4367 
4368   if (!TLI.isDesirableToCommuteWithShift(LHS))
4369     return SDValue();
4370 
4371   // Fold the constants, shifting the binop RHS by the shift amount.
4372   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4373                                N->getValueType(0),
4374                                LHS->getOperand(1), N->getOperand(1));
4375   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4376 
4377   // Create the new shift.
4378   SDValue NewShift = DAG.getNode(N->getOpcode(),
4379                                  SDLoc(LHS->getOperand(0)),
4380                                  VT, LHS->getOperand(0), N->getOperand(1));
4381 
4382   // Create the new binop.
4383   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4384 }
4385 
4386 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4387   assert(N->getOpcode() == ISD::TRUNCATE);
4388   assert(N->getOperand(0).getOpcode() == ISD::AND);
4389 
4390   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4391   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4392     SDValue N01 = N->getOperand(0).getOperand(1);
4393 
4394     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4395       if (!N01C->isOpaque()) {
4396         EVT TruncVT = N->getValueType(0);
4397         SDValue N00 = N->getOperand(0).getOperand(0);
4398         APInt TruncC = N01C->getAPIntValue();
4399         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4400         SDLoc DL(N);
4401 
4402         return DAG.getNode(ISD::AND, DL, TruncVT,
4403                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4404                            DAG.getConstant(TruncC, DL, TruncVT));
4405       }
4406     }
4407   }
4408 
4409   return SDValue();
4410 }
4411 
4412 SDValue DAGCombiner::visitRotate(SDNode *N) {
4413   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4414   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4415       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4416     if (SDValue NewOp1 =
4417             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4418       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4419                          N->getOperand(0), NewOp1);
4420   }
4421   return SDValue();
4422 }
4423 
4424 SDValue DAGCombiner::visitSHL(SDNode *N) {
4425   SDValue N0 = N->getOperand(0);
4426   SDValue N1 = N->getOperand(1);
4427   EVT VT = N0.getValueType();
4428   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4429 
4430   // fold vector ops
4431   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4432   if (VT.isVector()) {
4433     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4434       return FoldedVOp;
4435 
4436     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4437     // If setcc produces all-one true value then:
4438     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4439     if (N1CV && N1CV->isConstant()) {
4440       if (N0.getOpcode() == ISD::AND) {
4441         SDValue N00 = N0->getOperand(0);
4442         SDValue N01 = N0->getOperand(1);
4443         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4444 
4445         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4446             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4447                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4448           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4449                                                      N01CV, N1CV))
4450             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4451         }
4452       } else {
4453         N1C = isConstOrConstSplat(N1);
4454       }
4455     }
4456   }
4457 
4458   // fold (shl c1, c2) -> c1<<c2
4459   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4460   if (N0C && N1C && !N1C->isOpaque())
4461     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4462   // fold (shl 0, x) -> 0
4463   if (isNullConstant(N0))
4464     return N0;
4465   // fold (shl x, c >= size(x)) -> undef
4466   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4467     return DAG.getUNDEF(VT);
4468   // fold (shl x, 0) -> x
4469   if (N1C && N1C->isNullValue())
4470     return N0;
4471   // fold (shl undef, x) -> 0
4472   if (N0.isUndef())
4473     return DAG.getConstant(0, SDLoc(N), VT);
4474   // if (shl x, c) is known to be zero, return 0
4475   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4476                             APInt::getAllOnesValue(OpSizeInBits)))
4477     return DAG.getConstant(0, SDLoc(N), VT);
4478   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4479   if (N1.getOpcode() == ISD::TRUNCATE &&
4480       N1.getOperand(0).getOpcode() == ISD::AND) {
4481     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4482       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4483   }
4484 
4485   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4486     return SDValue(N, 0);
4487 
4488   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4489   if (N1C && N0.getOpcode() == ISD::SHL) {
4490     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4491       SDLoc DL(N);
4492       APInt c1 = N0C1->getAPIntValue();
4493       APInt c2 = N1C->getAPIntValue();
4494       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4495 
4496       APInt Sum = c1 + c2;
4497       if (Sum.uge(OpSizeInBits))
4498         return DAG.getConstant(0, DL, VT);
4499 
4500       return DAG.getNode(
4501           ISD::SHL, DL, VT, N0.getOperand(0),
4502           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4503     }
4504   }
4505 
4506   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4507   // For this to be valid, the second form must not preserve any of the bits
4508   // that are shifted out by the inner shift in the first form.  This means
4509   // the outer shift size must be >= the number of bits added by the ext.
4510   // As a corollary, we don't care what kind of ext it is.
4511   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4512               N0.getOpcode() == ISD::ANY_EXTEND ||
4513               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4514       N0.getOperand(0).getOpcode() == ISD::SHL) {
4515     SDValue N0Op0 = N0.getOperand(0);
4516     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4517       APInt c1 = N0Op0C1->getAPIntValue();
4518       APInt c2 = N1C->getAPIntValue();
4519       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4520 
4521       EVT InnerShiftVT = N0Op0.getValueType();
4522       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4523       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
4524         SDLoc DL(N0);
4525         APInt Sum = c1 + c2;
4526         if (Sum.uge(OpSizeInBits))
4527           return DAG.getConstant(0, DL, VT);
4528 
4529         return DAG.getNode(
4530             ISD::SHL, DL, VT,
4531             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
4532             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4533       }
4534     }
4535   }
4536 
4537   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4538   // Only fold this if the inner zext has no other uses to avoid increasing
4539   // the total number of instructions.
4540   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4541       N0.getOperand(0).getOpcode() == ISD::SRL) {
4542     SDValue N0Op0 = N0.getOperand(0);
4543     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4544       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
4545         uint64_t c1 = N0Op0C1->getZExtValue();
4546         uint64_t c2 = N1C->getZExtValue();
4547         if (c1 == c2) {
4548           SDValue NewOp0 = N0.getOperand(0);
4549           EVT CountVT = NewOp0.getOperand(1).getValueType();
4550           SDLoc DL(N);
4551           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4552                                        NewOp0,
4553                                        DAG.getConstant(c2, DL, CountVT));
4554           AddToWorklist(NewSHL.getNode());
4555           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4556         }
4557       }
4558     }
4559   }
4560 
4561   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4562   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4563   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4564       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4565     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4566       uint64_t C1 = N0C1->getZExtValue();
4567       uint64_t C2 = N1C->getZExtValue();
4568       SDLoc DL(N);
4569       if (C1 <= C2)
4570         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4571                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4572       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4573                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4574     }
4575   }
4576 
4577   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4578   //                               (and (srl x, (sub c1, c2), MASK)
4579   // Only fold this if the inner shift has no other uses -- if it does, folding
4580   // this will increase the total number of instructions.
4581   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4582     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4583       uint64_t c1 = N0C1->getZExtValue();
4584       if (c1 < OpSizeInBits) {
4585         uint64_t c2 = N1C->getZExtValue();
4586         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4587         SDValue Shift;
4588         if (c2 > c1) {
4589           Mask = Mask.shl(c2 - c1);
4590           SDLoc DL(N);
4591           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4592                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4593         } else {
4594           Mask = Mask.lshr(c1 - c2);
4595           SDLoc DL(N);
4596           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4597                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4598         }
4599         SDLoc DL(N0);
4600         return DAG.getNode(ISD::AND, DL, VT, Shift,
4601                            DAG.getConstant(Mask, DL, VT));
4602       }
4603     }
4604   }
4605   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4606   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4607     unsigned BitSize = VT.getScalarSizeInBits();
4608     SDLoc DL(N);
4609     SDValue HiBitsMask =
4610       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4611                                             BitSize - N1C->getZExtValue()),
4612                       DL, VT);
4613     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4614                        HiBitsMask);
4615   }
4616 
4617   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4618   // Variant of version done on multiply, except mul by a power of 2 is turned
4619   // into a shift.
4620   APInt Val;
4621   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4622       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4623        ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4624     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4625     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4626     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4627   }
4628 
4629   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4630   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4631     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4632       if (SDValue Folded =
4633               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4634         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4635     }
4636   }
4637 
4638   if (N1C && !N1C->isOpaque())
4639     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4640       return NewSHL;
4641 
4642   return SDValue();
4643 }
4644 
4645 SDValue DAGCombiner::visitSRA(SDNode *N) {
4646   SDValue N0 = N->getOperand(0);
4647   SDValue N1 = N->getOperand(1);
4648   EVT VT = N0.getValueType();
4649   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4650 
4651   // fold vector ops
4652   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4653   if (VT.isVector()) {
4654     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4655       return FoldedVOp;
4656 
4657     N1C = isConstOrConstSplat(N1);
4658   }
4659 
4660   // fold (sra c1, c2) -> (sra c1, c2)
4661   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4662   if (N0C && N1C && !N1C->isOpaque())
4663     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4664   // fold (sra 0, x) -> 0
4665   if (isNullConstant(N0))
4666     return N0;
4667   // fold (sra -1, x) -> -1
4668   if (isAllOnesConstant(N0))
4669     return N0;
4670   // fold (sra x, c >= size(x)) -> undef
4671   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4672     return DAG.getUNDEF(VT);
4673   // fold (sra x, 0) -> x
4674   if (N1C && N1C->isNullValue())
4675     return N0;
4676   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4677   // sext_inreg.
4678   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4679     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4680     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4681     if (VT.isVector())
4682       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4683                                ExtVT, VT.getVectorNumElements());
4684     if ((!LegalOperations ||
4685          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4686       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4687                          N0.getOperand(0), DAG.getValueType(ExtVT));
4688   }
4689 
4690   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4691   if (N1C && N0.getOpcode() == ISD::SRA) {
4692     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4693       SDLoc DL(N);
4694       APInt c1 = N0C1->getAPIntValue();
4695       APInt c2 = N1C->getAPIntValue();
4696       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4697 
4698       APInt Sum = c1 + c2;
4699       if (Sum.uge(OpSizeInBits))
4700         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
4701 
4702       return DAG.getNode(
4703           ISD::SRA, DL, VT, N0.getOperand(0),
4704           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4705     }
4706   }
4707 
4708   // fold (sra (shl X, m), (sub result_size, n))
4709   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4710   // result_size - n != m.
4711   // If truncate is free for the target sext(shl) is likely to result in better
4712   // code.
4713   if (N0.getOpcode() == ISD::SHL && N1C) {
4714     // Get the two constanst of the shifts, CN0 = m, CN = n.
4715     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4716     if (N01C) {
4717       LLVMContext &Ctx = *DAG.getContext();
4718       // Determine what the truncate's result bitsize and type would be.
4719       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4720 
4721       if (VT.isVector())
4722         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4723 
4724       // Determine the residual right-shift amount.
4725       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4726 
4727       // If the shift is not a no-op (in which case this should be just a sign
4728       // extend already), the truncated to type is legal, sign_extend is legal
4729       // on that type, and the truncate to that type is both legal and free,
4730       // perform the transform.
4731       if ((ShiftAmt > 0) &&
4732           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4733           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4734           TLI.isTruncateFree(VT, TruncVT)) {
4735 
4736         SDLoc DL(N);
4737         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4738             getShiftAmountTy(N0.getOperand(0).getValueType()));
4739         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4740                                     N0.getOperand(0), Amt);
4741         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4742                                     Shift);
4743         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4744                            N->getValueType(0), Trunc);
4745       }
4746     }
4747   }
4748 
4749   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4750   if (N1.getOpcode() == ISD::TRUNCATE &&
4751       N1.getOperand(0).getOpcode() == ISD::AND) {
4752     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4753       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4754   }
4755 
4756   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4757   //      if c1 is equal to the number of bits the trunc removes
4758   if (N0.getOpcode() == ISD::TRUNCATE &&
4759       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4760        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4761       N0.getOperand(0).hasOneUse() &&
4762       N0.getOperand(0).getOperand(1).hasOneUse() &&
4763       N1C) {
4764     SDValue N0Op0 = N0.getOperand(0);
4765     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4766       unsigned LargeShiftVal = LargeShift->getZExtValue();
4767       EVT LargeVT = N0Op0.getValueType();
4768 
4769       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4770         SDLoc DL(N);
4771         SDValue Amt =
4772           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4773                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4774         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4775                                   N0Op0.getOperand(0), Amt);
4776         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4777       }
4778     }
4779   }
4780 
4781   // Simplify, based on bits shifted out of the LHS.
4782   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4783     return SDValue(N, 0);
4784 
4785 
4786   // If the sign bit is known to be zero, switch this to a SRL.
4787   if (DAG.SignBitIsZero(N0))
4788     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4789 
4790   if (N1C && !N1C->isOpaque())
4791     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4792       return NewSRA;
4793 
4794   return SDValue();
4795 }
4796 
4797 SDValue DAGCombiner::visitSRL(SDNode *N) {
4798   SDValue N0 = N->getOperand(0);
4799   SDValue N1 = N->getOperand(1);
4800   EVT VT = N0.getValueType();
4801   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4802 
4803   // fold vector ops
4804   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4805   if (VT.isVector()) {
4806     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4807       return FoldedVOp;
4808 
4809     N1C = isConstOrConstSplat(N1);
4810   }
4811 
4812   // fold (srl c1, c2) -> c1 >>u c2
4813   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4814   if (N0C && N1C && !N1C->isOpaque())
4815     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4816   // fold (srl 0, x) -> 0
4817   if (isNullConstant(N0))
4818     return N0;
4819   // fold (srl x, c >= size(x)) -> undef
4820   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4821     return DAG.getUNDEF(VT);
4822   // fold (srl x, 0) -> x
4823   if (N1C && N1C->isNullValue())
4824     return N0;
4825   // if (srl x, c) is known to be zero, return 0
4826   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4827                                    APInt::getAllOnesValue(OpSizeInBits)))
4828     return DAG.getConstant(0, SDLoc(N), VT);
4829 
4830   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4831   if (N1C && N0.getOpcode() == ISD::SRL) {
4832     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4833       SDLoc DL(N);
4834       APInt c1 = N0C1->getAPIntValue();
4835       APInt c2 = N1C->getAPIntValue();
4836       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4837 
4838       APInt Sum = c1 + c2;
4839       if (Sum.uge(OpSizeInBits))
4840         return DAG.getConstant(0, DL, VT);
4841 
4842       return DAG.getNode(
4843           ISD::SRL, DL, VT, N0.getOperand(0),
4844           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4845     }
4846   }
4847 
4848   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4849   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4850       N0.getOperand(0).getOpcode() == ISD::SRL &&
4851       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4852     uint64_t c1 =
4853       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4854     uint64_t c2 = N1C->getZExtValue();
4855     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4856     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4857     uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4858     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4859     if (c1 + OpSizeInBits == InnerShiftSize) {
4860       SDLoc DL(N0);
4861       if (c1 + c2 >= InnerShiftSize)
4862         return DAG.getConstant(0, DL, VT);
4863       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4864                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4865                                      N0.getOperand(0)->getOperand(0),
4866                                      DAG.getConstant(c1 + c2, DL,
4867                                                      ShiftCountVT)));
4868     }
4869   }
4870 
4871   // fold (srl (shl x, c), c) -> (and x, cst2)
4872   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4873     unsigned BitSize = N0.getScalarValueSizeInBits();
4874     if (BitSize <= 64) {
4875       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4876       SDLoc DL(N);
4877       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4878                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4879     }
4880   }
4881 
4882   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4883   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4884     // Shifting in all undef bits?
4885     EVT SmallVT = N0.getOperand(0).getValueType();
4886     unsigned BitSize = SmallVT.getScalarSizeInBits();
4887     if (N1C->getZExtValue() >= BitSize)
4888       return DAG.getUNDEF(VT);
4889 
4890     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4891       uint64_t ShiftAmt = N1C->getZExtValue();
4892       SDLoc DL0(N0);
4893       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4894                                        N0.getOperand(0),
4895                           DAG.getConstant(ShiftAmt, DL0,
4896                                           getShiftAmountTy(SmallVT)));
4897       AddToWorklist(SmallShift.getNode());
4898       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4899       SDLoc DL(N);
4900       return DAG.getNode(ISD::AND, DL, VT,
4901                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4902                          DAG.getConstant(Mask, DL, VT));
4903     }
4904   }
4905 
4906   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4907   // bit, which is unmodified by sra.
4908   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4909     if (N0.getOpcode() == ISD::SRA)
4910       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4911   }
4912 
4913   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4914   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4915       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4916     APInt KnownZero, KnownOne;
4917     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4918 
4919     // If any of the input bits are KnownOne, then the input couldn't be all
4920     // zeros, thus the result of the srl will always be zero.
4921     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4922 
4923     // If all of the bits input the to ctlz node are known to be zero, then
4924     // the result of the ctlz is "32" and the result of the shift is one.
4925     APInt UnknownBits = ~KnownZero;
4926     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4927 
4928     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4929     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4930       // Okay, we know that only that the single bit specified by UnknownBits
4931       // could be set on input to the CTLZ node. If this bit is set, the SRL
4932       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4933       // to an SRL/XOR pair, which is likely to simplify more.
4934       unsigned ShAmt = UnknownBits.countTrailingZeros();
4935       SDValue Op = N0.getOperand(0);
4936 
4937       if (ShAmt) {
4938         SDLoc DL(N0);
4939         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4940                   DAG.getConstant(ShAmt, DL,
4941                                   getShiftAmountTy(Op.getValueType())));
4942         AddToWorklist(Op.getNode());
4943       }
4944 
4945       SDLoc DL(N);
4946       return DAG.getNode(ISD::XOR, DL, VT,
4947                          Op, DAG.getConstant(1, DL, VT));
4948     }
4949   }
4950 
4951   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4952   if (N1.getOpcode() == ISD::TRUNCATE &&
4953       N1.getOperand(0).getOpcode() == ISD::AND) {
4954     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4955       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4956   }
4957 
4958   // fold operands of srl based on knowledge that the low bits are not
4959   // demanded.
4960   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4961     return SDValue(N, 0);
4962 
4963   if (N1C && !N1C->isOpaque())
4964     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4965       return NewSRL;
4966 
4967   // Attempt to convert a srl of a load into a narrower zero-extending load.
4968   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4969     return NarrowLoad;
4970 
4971   // Here is a common situation. We want to optimize:
4972   //
4973   //   %a = ...
4974   //   %b = and i32 %a, 2
4975   //   %c = srl i32 %b, 1
4976   //   brcond i32 %c ...
4977   //
4978   // into
4979   //
4980   //   %a = ...
4981   //   %b = and %a, 2
4982   //   %c = setcc eq %b, 0
4983   //   brcond %c ...
4984   //
4985   // However when after the source operand of SRL is optimized into AND, the SRL
4986   // itself may not be optimized further. Look for it and add the BRCOND into
4987   // the worklist.
4988   if (N->hasOneUse()) {
4989     SDNode *Use = *N->use_begin();
4990     if (Use->getOpcode() == ISD::BRCOND)
4991       AddToWorklist(Use);
4992     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4993       // Also look pass the truncate.
4994       Use = *Use->use_begin();
4995       if (Use->getOpcode() == ISD::BRCOND)
4996         AddToWorklist(Use);
4997     }
4998   }
4999 
5000   return SDValue();
5001 }
5002 
5003 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5004   SDValue N0 = N->getOperand(0);
5005   EVT VT = N->getValueType(0);
5006 
5007   // fold (bswap c1) -> c2
5008   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5009     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5010   // fold (bswap (bswap x)) -> x
5011   if (N0.getOpcode() == ISD::BSWAP)
5012     return N0->getOperand(0);
5013   return SDValue();
5014 }
5015 
5016 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5017   SDValue N0 = N->getOperand(0);
5018 
5019   // fold (bitreverse (bitreverse x)) -> x
5020   if (N0.getOpcode() == ISD::BITREVERSE)
5021     return N0.getOperand(0);
5022   return SDValue();
5023 }
5024 
5025 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5026   SDValue N0 = N->getOperand(0);
5027   EVT VT = N->getValueType(0);
5028 
5029   // fold (ctlz c1) -> c2
5030   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5031     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5032   return SDValue();
5033 }
5034 
5035 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5036   SDValue N0 = N->getOperand(0);
5037   EVT VT = N->getValueType(0);
5038 
5039   // fold (ctlz_zero_undef c1) -> c2
5040   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5041     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5042   return SDValue();
5043 }
5044 
5045 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5046   SDValue N0 = N->getOperand(0);
5047   EVT VT = N->getValueType(0);
5048 
5049   // fold (cttz c1) -> c2
5050   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5051     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5052   return SDValue();
5053 }
5054 
5055 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5056   SDValue N0 = N->getOperand(0);
5057   EVT VT = N->getValueType(0);
5058 
5059   // fold (cttz_zero_undef c1) -> c2
5060   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5061     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5062   return SDValue();
5063 }
5064 
5065 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5066   SDValue N0 = N->getOperand(0);
5067   EVT VT = N->getValueType(0);
5068 
5069   // fold (ctpop c1) -> c2
5070   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5071     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5072   return SDValue();
5073 }
5074 
5075 
5076 /// \brief Generate Min/Max node
5077 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5078                                    SDValue RHS, SDValue True, SDValue False,
5079                                    ISD::CondCode CC, const TargetLowering &TLI,
5080                                    SelectionDAG &DAG) {
5081   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5082     return SDValue();
5083 
5084   switch (CC) {
5085   case ISD::SETOLT:
5086   case ISD::SETOLE:
5087   case ISD::SETLT:
5088   case ISD::SETLE:
5089   case ISD::SETULT:
5090   case ISD::SETULE: {
5091     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5092     if (TLI.isOperationLegal(Opcode, VT))
5093       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5094     return SDValue();
5095   }
5096   case ISD::SETOGT:
5097   case ISD::SETOGE:
5098   case ISD::SETGT:
5099   case ISD::SETGE:
5100   case ISD::SETUGT:
5101   case ISD::SETUGE: {
5102     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5103     if (TLI.isOperationLegal(Opcode, VT))
5104       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5105     return SDValue();
5106   }
5107   default:
5108     return SDValue();
5109   }
5110 }
5111 
5112 // TODO: We should handle other cases of selecting between {-1,0,1} here.
5113 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5114   SDValue Cond = N->getOperand(0);
5115   SDValue N1 = N->getOperand(1);
5116   SDValue N2 = N->getOperand(2);
5117   EVT VT = N->getValueType(0);
5118   EVT CondVT = Cond.getValueType();
5119   SDLoc DL(N);
5120 
5121   // fold (select Cond, 0, 1) -> (xor Cond, 1)
5122   // We can't do this reliably if integer based booleans have different contents
5123   // to floating point based booleans. This is because we can't tell whether we
5124   // have an integer-based boolean or a floating-point-based boolean unless we
5125   // can find the SETCC that produced it and inspect its operands. This is
5126   // fairly easy if C is the SETCC node, but it can potentially be
5127   // undiscoverable (or not reasonably discoverable). For example, it could be
5128   // in another basic block or it could require searching a complicated
5129   // expression.
5130   if (VT.isInteger() &&
5131       (CondVT == MVT::i1 || (CondVT.isInteger() &&
5132                              TLI.getBooleanContents(false, true) ==
5133                                  TargetLowering::ZeroOrOneBooleanContent &&
5134                              TLI.getBooleanContents(false, false) ==
5135                                  TargetLowering::ZeroOrOneBooleanContent)) &&
5136       isNullConstant(N1) && isOneConstant(N2)) {
5137     SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond,
5138                                   DAG.getConstant(1, DL, CondVT));
5139     if (VT.bitsEq(CondVT))
5140       return NotCond;
5141     return DAG.getZExtOrTrunc(NotCond, DL, VT);
5142   }
5143 
5144   return SDValue();
5145 }
5146 
5147 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5148   SDValue N0 = N->getOperand(0);
5149   SDValue N1 = N->getOperand(1);
5150   SDValue N2 = N->getOperand(2);
5151   EVT VT = N->getValueType(0);
5152   EVT VT0 = N0.getValueType();
5153 
5154   // fold (select C, X, X) -> X
5155   if (N1 == N2)
5156     return N1;
5157   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5158     // fold (select true, X, Y) -> X
5159     // fold (select false, X, Y) -> Y
5160     return !N0C->isNullValue() ? N1 : N2;
5161   }
5162   // fold (select C, 1, X) -> (or C, X)
5163   if (VT == MVT::i1 && isOneConstant(N1))
5164     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5165 
5166   if (SDValue V = foldSelectOfConstants(N))
5167     return V;
5168 
5169   // fold (select C, 0, X) -> (and (not C), X)
5170   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5171     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5172     AddToWorklist(NOTNode.getNode());
5173     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5174   }
5175   // fold (select C, X, 1) -> (or (not C), X)
5176   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5177     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5178     AddToWorklist(NOTNode.getNode());
5179     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5180   }
5181   // fold (select C, X, 0) -> (and C, X)
5182   if (VT == MVT::i1 && isNullConstant(N2))
5183     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5184   // fold (select X, X, Y) -> (or X, Y)
5185   // fold (select X, 1, Y) -> (or X, Y)
5186   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5187     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5188   // fold (select X, Y, X) -> (and X, Y)
5189   // fold (select X, Y, 0) -> (and X, Y)
5190   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5191     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5192 
5193   // If we can fold this based on the true/false value, do so.
5194   if (SimplifySelectOps(N, N1, N2))
5195     return SDValue(N, 0);  // Don't revisit N.
5196 
5197   if (VT0 == MVT::i1) {
5198     // The code in this block deals with the following 2 equivalences:
5199     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5200     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5201     // The target can specify its prefered form with the
5202     // shouldNormalizeToSelectSequence() callback. However we always transform
5203     // to the right anyway if we find the inner select exists in the DAG anyway
5204     // and we always transform to the left side if we know that we can further
5205     // optimize the combination of the conditions.
5206     bool normalizeToSequence
5207       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5208     // select (and Cond0, Cond1), X, Y
5209     //   -> select Cond0, (select Cond1, X, Y), Y
5210     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5211       SDValue Cond0 = N0->getOperand(0);
5212       SDValue Cond1 = N0->getOperand(1);
5213       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5214                                         N1.getValueType(), Cond1, N1, N2);
5215       if (normalizeToSequence || !InnerSelect.use_empty())
5216         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5217                            InnerSelect, N2);
5218     }
5219     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5220     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5221       SDValue Cond0 = N0->getOperand(0);
5222       SDValue Cond1 = N0->getOperand(1);
5223       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5224                                         N1.getValueType(), Cond1, N1, N2);
5225       if (normalizeToSequence || !InnerSelect.use_empty())
5226         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5227                            InnerSelect);
5228     }
5229 
5230     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5231     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5232       SDValue N1_0 = N1->getOperand(0);
5233       SDValue N1_1 = N1->getOperand(1);
5234       SDValue N1_2 = N1->getOperand(2);
5235       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5236         // Create the actual and node if we can generate good code for it.
5237         if (!normalizeToSequence) {
5238           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5239                                     N0, N1_0);
5240           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5241                              N1_1, N2);
5242         }
5243         // Otherwise see if we can optimize the "and" to a better pattern.
5244         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5245           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5246                              N1_1, N2);
5247       }
5248     }
5249     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5250     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5251       SDValue N2_0 = N2->getOperand(0);
5252       SDValue N2_1 = N2->getOperand(1);
5253       SDValue N2_2 = N2->getOperand(2);
5254       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5255         // Create the actual or node if we can generate good code for it.
5256         if (!normalizeToSequence) {
5257           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5258                                    N0, N2_0);
5259           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5260                              N1, N2_2);
5261         }
5262         // Otherwise see if we can optimize to a better pattern.
5263         if (SDValue Combined = visitORLike(N0, N2_0, N))
5264           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5265                              N1, N2_2);
5266       }
5267     }
5268   }
5269 
5270   // select (xor Cond, 1), X, Y -> select Cond, Y, X
5271   // select (xor Cond, 0), X, Y -> selext Cond, X, Y
5272   if (VT0 == MVT::i1) {
5273     if (N0->getOpcode() == ISD::XOR) {
5274       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
5275         SDValue Cond0 = N0->getOperand(0);
5276         if (C->isOne())
5277           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5278                              Cond0, N2, N1);
5279         else
5280           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5281                              Cond0, N1, N2);
5282       }
5283     }
5284   }
5285 
5286   // fold selects based on a setcc into other things, such as min/max/abs
5287   if (N0.getOpcode() == ISD::SETCC) {
5288     // select x, y (fcmp lt x, y) -> fminnum x, y
5289     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5290     //
5291     // This is OK if we don't care about what happens if either operand is a
5292     // NaN.
5293     //
5294 
5295     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5296     // no signed zeros as well as no nans.
5297     const TargetOptions &Options = DAG.getTarget().Options;
5298     if (Options.UnsafeFPMath &&
5299         VT.isFloatingPoint() && N0.hasOneUse() &&
5300         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5301       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5302 
5303       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5304                                                 N0.getOperand(1), N1, N2, CC,
5305                                                 TLI, DAG))
5306         return FMinMax;
5307     }
5308 
5309     if ((!LegalOperations &&
5310          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5311         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5312       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5313                          N0.getOperand(0), N0.getOperand(1),
5314                          N1, N2, N0.getOperand(2));
5315     return SimplifySelect(SDLoc(N), N0, N1, N2);
5316   }
5317 
5318   return SDValue();
5319 }
5320 
5321 static
5322 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5323   SDLoc DL(N);
5324   EVT LoVT, HiVT;
5325   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5326 
5327   // Split the inputs.
5328   SDValue Lo, Hi, LL, LH, RL, RH;
5329   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5330   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5331 
5332   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5333   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5334 
5335   return std::make_pair(Lo, Hi);
5336 }
5337 
5338 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5339 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5340 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5341   SDLoc DL(N);
5342   SDValue Cond = N->getOperand(0);
5343   SDValue LHS = N->getOperand(1);
5344   SDValue RHS = N->getOperand(2);
5345   EVT VT = N->getValueType(0);
5346   int NumElems = VT.getVectorNumElements();
5347   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5348          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5349          Cond.getOpcode() == ISD::BUILD_VECTOR);
5350 
5351   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5352   // binary ones here.
5353   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5354     return SDValue();
5355 
5356   // We're sure we have an even number of elements due to the
5357   // concat_vectors we have as arguments to vselect.
5358   // Skip BV elements until we find one that's not an UNDEF
5359   // After we find an UNDEF element, keep looping until we get to half the
5360   // length of the BV and see if all the non-undef nodes are the same.
5361   ConstantSDNode *BottomHalf = nullptr;
5362   for (int i = 0; i < NumElems / 2; ++i) {
5363     if (Cond->getOperand(i)->isUndef())
5364       continue;
5365 
5366     if (BottomHalf == nullptr)
5367       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5368     else if (Cond->getOperand(i).getNode() != BottomHalf)
5369       return SDValue();
5370   }
5371 
5372   // Do the same for the second half of the BuildVector
5373   ConstantSDNode *TopHalf = nullptr;
5374   for (int i = NumElems / 2; i < NumElems; ++i) {
5375     if (Cond->getOperand(i)->isUndef())
5376       continue;
5377 
5378     if (TopHalf == nullptr)
5379       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5380     else if (Cond->getOperand(i).getNode() != TopHalf)
5381       return SDValue();
5382   }
5383 
5384   assert(TopHalf && BottomHalf &&
5385          "One half of the selector was all UNDEFs and the other was all the "
5386          "same value. This should have been addressed before this function.");
5387   return DAG.getNode(
5388       ISD::CONCAT_VECTORS, DL, VT,
5389       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5390       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5391 }
5392 
5393 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5394 
5395   if (Level >= AfterLegalizeTypes)
5396     return SDValue();
5397 
5398   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5399   SDValue Mask = MSC->getMask();
5400   SDValue Data  = MSC->getValue();
5401   SDLoc DL(N);
5402 
5403   // If the MSCATTER data type requires splitting and the mask is provided by a
5404   // SETCC, then split both nodes and its operands before legalization. This
5405   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5406   // and enables future optimizations (e.g. min/max pattern matching on X86).
5407   if (Mask.getOpcode() != ISD::SETCC)
5408     return SDValue();
5409 
5410   // Check if any splitting is required.
5411   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5412       TargetLowering::TypeSplitVector)
5413     return SDValue();
5414   SDValue MaskLo, MaskHi, Lo, Hi;
5415   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5416 
5417   EVT LoVT, HiVT;
5418   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5419 
5420   SDValue Chain = MSC->getChain();
5421 
5422   EVT MemoryVT = MSC->getMemoryVT();
5423   unsigned Alignment = MSC->getOriginalAlignment();
5424 
5425   EVT LoMemVT, HiMemVT;
5426   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5427 
5428   SDValue DataLo, DataHi;
5429   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5430 
5431   SDValue BasePtr = MSC->getBasePtr();
5432   SDValue IndexLo, IndexHi;
5433   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5434 
5435   MachineMemOperand *MMO = DAG.getMachineFunction().
5436     getMachineMemOperand(MSC->getPointerInfo(),
5437                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5438                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5439 
5440   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5441   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5442                             DL, OpsLo, MMO);
5443 
5444   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5445   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5446                             DL, OpsHi, MMO);
5447 
5448   AddToWorklist(Lo.getNode());
5449   AddToWorklist(Hi.getNode());
5450 
5451   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5452 }
5453 
5454 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5455 
5456   if (Level >= AfterLegalizeTypes)
5457     return SDValue();
5458 
5459   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5460   SDValue Mask = MST->getMask();
5461   SDValue Data  = MST->getValue();
5462   SDLoc DL(N);
5463 
5464   // If the MSTORE data type requires splitting and the mask is provided by a
5465   // SETCC, then split both nodes and its operands before legalization. This
5466   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5467   // and enables future optimizations (e.g. min/max pattern matching on X86).
5468   if (Mask.getOpcode() == ISD::SETCC) {
5469 
5470     // Check if any splitting is required.
5471     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5472         TargetLowering::TypeSplitVector)
5473       return SDValue();
5474 
5475     SDValue MaskLo, MaskHi, Lo, Hi;
5476     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5477 
5478     EVT LoVT, HiVT;
5479     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5480 
5481     SDValue Chain = MST->getChain();
5482     SDValue Ptr   = MST->getBasePtr();
5483 
5484     EVT MemoryVT = MST->getMemoryVT();
5485     unsigned Alignment = MST->getOriginalAlignment();
5486 
5487     // if Alignment is equal to the vector size,
5488     // take the half of it for the second part
5489     unsigned SecondHalfAlignment =
5490       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5491          Alignment/2 : Alignment;
5492 
5493     EVT LoMemVT, HiMemVT;
5494     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5495 
5496     SDValue DataLo, DataHi;
5497     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5498 
5499     MachineMemOperand *MMO = DAG.getMachineFunction().
5500       getMachineMemOperand(MST->getPointerInfo(),
5501                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5502                            Alignment, MST->getAAInfo(), MST->getRanges());
5503 
5504     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5505                             MST->isTruncatingStore());
5506 
5507     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5508     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5509                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5510 
5511     MMO = DAG.getMachineFunction().
5512       getMachineMemOperand(MST->getPointerInfo(),
5513                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5514                            SecondHalfAlignment, MST->getAAInfo(),
5515                            MST->getRanges());
5516 
5517     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5518                             MST->isTruncatingStore());
5519 
5520     AddToWorklist(Lo.getNode());
5521     AddToWorklist(Hi.getNode());
5522 
5523     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5524   }
5525   return SDValue();
5526 }
5527 
5528 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5529 
5530   if (Level >= AfterLegalizeTypes)
5531     return SDValue();
5532 
5533   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5534   SDValue Mask = MGT->getMask();
5535   SDLoc DL(N);
5536 
5537   // If the MGATHER result requires splitting and the mask is provided by a
5538   // SETCC, then split both nodes and its operands before legalization. This
5539   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5540   // and enables future optimizations (e.g. min/max pattern matching on X86).
5541 
5542   if (Mask.getOpcode() != ISD::SETCC)
5543     return SDValue();
5544 
5545   EVT VT = N->getValueType(0);
5546 
5547   // Check if any splitting is required.
5548   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5549       TargetLowering::TypeSplitVector)
5550     return SDValue();
5551 
5552   SDValue MaskLo, MaskHi, Lo, Hi;
5553   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5554 
5555   SDValue Src0 = MGT->getValue();
5556   SDValue Src0Lo, Src0Hi;
5557   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5558 
5559   EVT LoVT, HiVT;
5560   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5561 
5562   SDValue Chain = MGT->getChain();
5563   EVT MemoryVT = MGT->getMemoryVT();
5564   unsigned Alignment = MGT->getOriginalAlignment();
5565 
5566   EVT LoMemVT, HiMemVT;
5567   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5568 
5569   SDValue BasePtr = MGT->getBasePtr();
5570   SDValue Index = MGT->getIndex();
5571   SDValue IndexLo, IndexHi;
5572   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5573 
5574   MachineMemOperand *MMO = DAG.getMachineFunction().
5575     getMachineMemOperand(MGT->getPointerInfo(),
5576                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5577                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5578 
5579   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5580   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5581                             MMO);
5582 
5583   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5584   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5585                             MMO);
5586 
5587   AddToWorklist(Lo.getNode());
5588   AddToWorklist(Hi.getNode());
5589 
5590   // Build a factor node to remember that this load is independent of the
5591   // other one.
5592   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5593                       Hi.getValue(1));
5594 
5595   // Legalized the chain result - switch anything that used the old chain to
5596   // use the new one.
5597   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5598 
5599   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5600 
5601   SDValue RetOps[] = { GatherRes, Chain };
5602   return DAG.getMergeValues(RetOps, DL);
5603 }
5604 
5605 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5606 
5607   if (Level >= AfterLegalizeTypes)
5608     return SDValue();
5609 
5610   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5611   SDValue Mask = MLD->getMask();
5612   SDLoc DL(N);
5613 
5614   // If the MLOAD result requires splitting and the mask is provided by a
5615   // SETCC, then split both nodes and its operands before legalization. This
5616   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5617   // and enables future optimizations (e.g. min/max pattern matching on X86).
5618 
5619   if (Mask.getOpcode() == ISD::SETCC) {
5620     EVT VT = N->getValueType(0);
5621 
5622     // Check if any splitting is required.
5623     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5624         TargetLowering::TypeSplitVector)
5625       return SDValue();
5626 
5627     SDValue MaskLo, MaskHi, Lo, Hi;
5628     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5629 
5630     SDValue Src0 = MLD->getSrc0();
5631     SDValue Src0Lo, Src0Hi;
5632     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5633 
5634     EVT LoVT, HiVT;
5635     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5636 
5637     SDValue Chain = MLD->getChain();
5638     SDValue Ptr   = MLD->getBasePtr();
5639     EVT MemoryVT = MLD->getMemoryVT();
5640     unsigned Alignment = MLD->getOriginalAlignment();
5641 
5642     // if Alignment is equal to the vector size,
5643     // take the half of it for the second part
5644     unsigned SecondHalfAlignment =
5645       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5646          Alignment/2 : Alignment;
5647 
5648     EVT LoMemVT, HiMemVT;
5649     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5650 
5651     MachineMemOperand *MMO = DAG.getMachineFunction().
5652     getMachineMemOperand(MLD->getPointerInfo(),
5653                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5654                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5655 
5656     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5657                            ISD::NON_EXTLOAD);
5658 
5659     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5660     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5661                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5662 
5663     MMO = DAG.getMachineFunction().
5664     getMachineMemOperand(MLD->getPointerInfo(),
5665                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5666                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5667 
5668     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5669                            ISD::NON_EXTLOAD);
5670 
5671     AddToWorklist(Lo.getNode());
5672     AddToWorklist(Hi.getNode());
5673 
5674     // Build a factor node to remember that this load is independent of the
5675     // other one.
5676     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5677                         Hi.getValue(1));
5678 
5679     // Legalized the chain result - switch anything that used the old chain to
5680     // use the new one.
5681     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5682 
5683     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5684 
5685     SDValue RetOps[] = { LoadRes, Chain };
5686     return DAG.getMergeValues(RetOps, DL);
5687   }
5688   return SDValue();
5689 }
5690 
5691 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5692   SDValue N0 = N->getOperand(0);
5693   SDValue N1 = N->getOperand(1);
5694   SDValue N2 = N->getOperand(2);
5695   SDLoc DL(N);
5696 
5697   // Canonicalize integer abs.
5698   // vselect (setg[te] X,  0),  X, -X ->
5699   // vselect (setgt    X, -1),  X, -X ->
5700   // vselect (setl[te] X,  0), -X,  X ->
5701   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5702   if (N0.getOpcode() == ISD::SETCC) {
5703     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5704     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5705     bool isAbs = false;
5706     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5707 
5708     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5709          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5710         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5711       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5712     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5713              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5714       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5715 
5716     if (isAbs) {
5717       EVT VT = LHS.getValueType();
5718       SDValue Shift = DAG.getNode(
5719           ISD::SRA, DL, VT, LHS,
5720           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
5721       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5722       AddToWorklist(Shift.getNode());
5723       AddToWorklist(Add.getNode());
5724       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5725     }
5726   }
5727 
5728   if (SimplifySelectOps(N, N1, N2))
5729     return SDValue(N, 0);  // Don't revisit N.
5730 
5731   // If the VSELECT result requires splitting and the mask is provided by a
5732   // SETCC, then split both nodes and its operands before legalization. This
5733   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5734   // and enables future optimizations (e.g. min/max pattern matching on X86).
5735   if (N0.getOpcode() == ISD::SETCC) {
5736     EVT VT = N->getValueType(0);
5737 
5738     // Check if any splitting is required.
5739     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5740         TargetLowering::TypeSplitVector)
5741       return SDValue();
5742 
5743     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5744     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5745     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5746     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5747 
5748     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5749     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5750 
5751     // Add the new VSELECT nodes to the work list in case they need to be split
5752     // again.
5753     AddToWorklist(Lo.getNode());
5754     AddToWorklist(Hi.getNode());
5755 
5756     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5757   }
5758 
5759   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5760   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5761     return N1;
5762   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5763   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5764     return N2;
5765 
5766   // The ConvertSelectToConcatVector function is assuming both the above
5767   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5768   // and addressed.
5769   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5770       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5771       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5772     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5773       return CV;
5774   }
5775 
5776   return SDValue();
5777 }
5778 
5779 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5780   SDValue N0 = N->getOperand(0);
5781   SDValue N1 = N->getOperand(1);
5782   SDValue N2 = N->getOperand(2);
5783   SDValue N3 = N->getOperand(3);
5784   SDValue N4 = N->getOperand(4);
5785   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5786 
5787   // fold select_cc lhs, rhs, x, x, cc -> x
5788   if (N2 == N3)
5789     return N2;
5790 
5791   // Determine if the condition we're dealing with is constant
5792   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5793                                   CC, SDLoc(N), false)) {
5794     AddToWorklist(SCC.getNode());
5795 
5796     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5797       if (!SCCC->isNullValue())
5798         return N2;    // cond always true -> true val
5799       else
5800         return N3;    // cond always false -> false val
5801     } else if (SCC->isUndef()) {
5802       // When the condition is UNDEF, just return the first operand. This is
5803       // coherent the DAG creation, no setcc node is created in this case
5804       return N2;
5805     } else if (SCC.getOpcode() == ISD::SETCC) {
5806       // Fold to a simpler select_cc
5807       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5808                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5809                          SCC.getOperand(2));
5810     }
5811   }
5812 
5813   // If we can fold this based on the true/false value, do so.
5814   if (SimplifySelectOps(N, N2, N3))
5815     return SDValue(N, 0);  // Don't revisit N.
5816 
5817   // fold select_cc into other things, such as min/max/abs
5818   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5819 }
5820 
5821 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5822   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5823                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5824                        SDLoc(N));
5825 }
5826 
5827 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5828   SDValue LHS = N->getOperand(0);
5829   SDValue RHS = N->getOperand(1);
5830   SDValue Carry = N->getOperand(2);
5831   SDValue Cond = N->getOperand(3);
5832 
5833   // If Carry is false, fold to a regular SETCC.
5834   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5835     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5836 
5837   return SDValue();
5838 }
5839 
5840 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5841 /// a build_vector of constants.
5842 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5843 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5844 /// Vector extends are not folded if operations are legal; this is to
5845 /// avoid introducing illegal build_vector dag nodes.
5846 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5847                                          SelectionDAG &DAG, bool LegalTypes,
5848                                          bool LegalOperations) {
5849   unsigned Opcode = N->getOpcode();
5850   SDValue N0 = N->getOperand(0);
5851   EVT VT = N->getValueType(0);
5852 
5853   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5854          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5855          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5856          && "Expected EXTEND dag node in input!");
5857 
5858   // fold (sext c1) -> c1
5859   // fold (zext c1) -> c1
5860   // fold (aext c1) -> c1
5861   if (isa<ConstantSDNode>(N0))
5862     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5863 
5864   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5865   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5866   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5867   EVT SVT = VT.getScalarType();
5868   if (!(VT.isVector() &&
5869       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5870       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5871     return nullptr;
5872 
5873   // We can fold this node into a build_vector.
5874   unsigned VTBits = SVT.getSizeInBits();
5875   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
5876   SmallVector<SDValue, 8> Elts;
5877   unsigned NumElts = VT.getVectorNumElements();
5878   SDLoc DL(N);
5879 
5880   for (unsigned i=0; i != NumElts; ++i) {
5881     SDValue Op = N0->getOperand(i);
5882     if (Op->isUndef()) {
5883       Elts.push_back(DAG.getUNDEF(SVT));
5884       continue;
5885     }
5886 
5887     SDLoc DL(Op);
5888     // Get the constant value and if needed trunc it to the size of the type.
5889     // Nodes like build_vector might have constants wider than the scalar type.
5890     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5891     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5892       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5893     else
5894       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5895   }
5896 
5897   return DAG.getBuildVector(VT, DL, Elts).getNode();
5898 }
5899 
5900 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5901 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5902 // transformation. Returns true if extension are possible and the above
5903 // mentioned transformation is profitable.
5904 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5905                                     unsigned ExtOpc,
5906                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5907                                     const TargetLowering &TLI) {
5908   bool HasCopyToRegUses = false;
5909   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5910   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5911                             UE = N0.getNode()->use_end();
5912        UI != UE; ++UI) {
5913     SDNode *User = *UI;
5914     if (User == N)
5915       continue;
5916     if (UI.getUse().getResNo() != N0.getResNo())
5917       continue;
5918     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5919     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5920       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5921       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5922         // Sign bits will be lost after a zext.
5923         return false;
5924       bool Add = false;
5925       for (unsigned i = 0; i != 2; ++i) {
5926         SDValue UseOp = User->getOperand(i);
5927         if (UseOp == N0)
5928           continue;
5929         if (!isa<ConstantSDNode>(UseOp))
5930           return false;
5931         Add = true;
5932       }
5933       if (Add)
5934         ExtendNodes.push_back(User);
5935       continue;
5936     }
5937     // If truncates aren't free and there are users we can't
5938     // extend, it isn't worthwhile.
5939     if (!isTruncFree)
5940       return false;
5941     // Remember if this value is live-out.
5942     if (User->getOpcode() == ISD::CopyToReg)
5943       HasCopyToRegUses = true;
5944   }
5945 
5946   if (HasCopyToRegUses) {
5947     bool BothLiveOut = false;
5948     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5949          UI != UE; ++UI) {
5950       SDUse &Use = UI.getUse();
5951       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5952         BothLiveOut = true;
5953         break;
5954       }
5955     }
5956     if (BothLiveOut)
5957       // Both unextended and extended values are live out. There had better be
5958       // a good reason for the transformation.
5959       return ExtendNodes.size();
5960   }
5961   return true;
5962 }
5963 
5964 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5965                                   SDValue Trunc, SDValue ExtLoad,
5966                                   const SDLoc &DL, ISD::NodeType ExtType) {
5967   // Extend SetCC uses if necessary.
5968   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5969     SDNode *SetCC = SetCCs[i];
5970     SmallVector<SDValue, 4> Ops;
5971 
5972     for (unsigned j = 0; j != 2; ++j) {
5973       SDValue SOp = SetCC->getOperand(j);
5974       if (SOp == Trunc)
5975         Ops.push_back(ExtLoad);
5976       else
5977         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5978     }
5979 
5980     Ops.push_back(SetCC->getOperand(2));
5981     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5982   }
5983 }
5984 
5985 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5986 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5987   SDValue N0 = N->getOperand(0);
5988   EVT DstVT = N->getValueType(0);
5989   EVT SrcVT = N0.getValueType();
5990 
5991   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5992           N->getOpcode() == ISD::ZERO_EXTEND) &&
5993          "Unexpected node type (not an extend)!");
5994 
5995   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5996   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5997   //   (v8i32 (sext (v8i16 (load x))))
5998   // into:
5999   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6000   //                          (v4i32 (sextload (x + 16)))))
6001   // Where uses of the original load, i.e.:
6002   //   (v8i16 (load x))
6003   // are replaced with:
6004   //   (v8i16 (truncate
6005   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6006   //                            (v4i32 (sextload (x + 16)))))))
6007   //
6008   // This combine is only applicable to illegal, but splittable, vectors.
6009   // All legal types, and illegal non-vector types, are handled elsewhere.
6010   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6011   //
6012   if (N0->getOpcode() != ISD::LOAD)
6013     return SDValue();
6014 
6015   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6016 
6017   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6018       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6019       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6020     return SDValue();
6021 
6022   SmallVector<SDNode *, 4> SetCCs;
6023   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6024     return SDValue();
6025 
6026   ISD::LoadExtType ExtType =
6027       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6028 
6029   // Try to split the vector types to get down to legal types.
6030   EVT SplitSrcVT = SrcVT;
6031   EVT SplitDstVT = DstVT;
6032   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6033          SplitSrcVT.getVectorNumElements() > 1) {
6034     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6035     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6036   }
6037 
6038   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6039     return SDValue();
6040 
6041   SDLoc DL(N);
6042   const unsigned NumSplits =
6043       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6044   const unsigned Stride = SplitSrcVT.getStoreSize();
6045   SmallVector<SDValue, 4> Loads;
6046   SmallVector<SDValue, 4> Chains;
6047 
6048   SDValue BasePtr = LN0->getBasePtr();
6049   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6050     const unsigned Offset = Idx * Stride;
6051     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6052 
6053     SDValue SplitLoad = DAG.getExtLoad(
6054         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6055         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6056         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6057 
6058     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6059                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6060 
6061     Loads.push_back(SplitLoad.getValue(0));
6062     Chains.push_back(SplitLoad.getValue(1));
6063   }
6064 
6065   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6066   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6067 
6068   CombineTo(N, NewValue);
6069 
6070   // Replace uses of the original load (before extension)
6071   // with a truncate of the concatenated sextloaded vectors.
6072   SDValue Trunc =
6073       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6074   CombineTo(N0.getNode(), Trunc, NewChain);
6075   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6076                   (ISD::NodeType)N->getOpcode());
6077   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6078 }
6079 
6080 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6081   SDValue N0 = N->getOperand(0);
6082   EVT VT = N->getValueType(0);
6083 
6084   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6085                                               LegalOperations))
6086     return SDValue(Res, 0);
6087 
6088   // fold (sext (sext x)) -> (sext x)
6089   // fold (sext (aext x)) -> (sext x)
6090   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6091     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6092                        N0.getOperand(0));
6093 
6094   if (N0.getOpcode() == ISD::TRUNCATE) {
6095     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6096     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6097     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6098       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6099       if (NarrowLoad.getNode() != N0.getNode()) {
6100         CombineTo(N0.getNode(), NarrowLoad);
6101         // CombineTo deleted the truncate, if needed, but not what's under it.
6102         AddToWorklist(oye);
6103       }
6104       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6105     }
6106 
6107     // See if the value being truncated is already sign extended.  If so, just
6108     // eliminate the trunc/sext pair.
6109     SDValue Op = N0.getOperand(0);
6110     unsigned OpBits   = Op.getScalarValueSizeInBits();
6111     unsigned MidBits  = N0.getScalarValueSizeInBits();
6112     unsigned DestBits = VT.getScalarSizeInBits();
6113     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6114 
6115     if (OpBits == DestBits) {
6116       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6117       // bits, it is already ready.
6118       if (NumSignBits > DestBits-MidBits)
6119         return Op;
6120     } else if (OpBits < DestBits) {
6121       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6122       // bits, just sext from i32.
6123       if (NumSignBits > OpBits-MidBits)
6124         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6125     } else {
6126       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6127       // bits, just truncate to i32.
6128       if (NumSignBits > OpBits-MidBits)
6129         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6130     }
6131 
6132     // fold (sext (truncate x)) -> (sextinreg x).
6133     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6134                                                  N0.getValueType())) {
6135       if (OpBits < DestBits)
6136         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6137       else if (OpBits > DestBits)
6138         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6139       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6140                          DAG.getValueType(N0.getValueType()));
6141     }
6142   }
6143 
6144   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6145   // Only generate vector extloads when 1) they're legal, and 2) they are
6146   // deemed desirable by the target.
6147   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6148       ((!LegalOperations && !VT.isVector() &&
6149         !cast<LoadSDNode>(N0)->isVolatile()) ||
6150        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6151     bool DoXform = true;
6152     SmallVector<SDNode*, 4> SetCCs;
6153     if (!N0.hasOneUse())
6154       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6155     if (VT.isVector())
6156       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6157     if (DoXform) {
6158       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6159       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6160                                        LN0->getChain(),
6161                                        LN0->getBasePtr(), N0.getValueType(),
6162                                        LN0->getMemOperand());
6163       CombineTo(N, ExtLoad);
6164       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6165                                   N0.getValueType(), ExtLoad);
6166       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6167       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6168                       ISD::SIGN_EXTEND);
6169       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6170     }
6171   }
6172 
6173   // fold (sext (load x)) to multiple smaller sextloads.
6174   // Only on illegal but splittable vectors.
6175   if (SDValue ExtLoad = CombineExtLoad(N))
6176     return ExtLoad;
6177 
6178   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6179   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6180   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6181       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6182     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6183     EVT MemVT = LN0->getMemoryVT();
6184     if ((!LegalOperations && !LN0->isVolatile()) ||
6185         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6186       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6187                                        LN0->getChain(),
6188                                        LN0->getBasePtr(), MemVT,
6189                                        LN0->getMemOperand());
6190       CombineTo(N, ExtLoad);
6191       CombineTo(N0.getNode(),
6192                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6193                             N0.getValueType(), ExtLoad),
6194                 ExtLoad.getValue(1));
6195       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6196     }
6197   }
6198 
6199   // fold (sext (and/or/xor (load x), cst)) ->
6200   //      (and/or/xor (sextload x), (sext cst))
6201   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6202        N0.getOpcode() == ISD::XOR) &&
6203       isa<LoadSDNode>(N0.getOperand(0)) &&
6204       N0.getOperand(1).getOpcode() == ISD::Constant &&
6205       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6206       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6207     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6208     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6209       bool DoXform = true;
6210       SmallVector<SDNode*, 4> SetCCs;
6211       if (!N0.hasOneUse())
6212         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6213                                           SetCCs, TLI);
6214       if (DoXform) {
6215         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6216                                          LN0->getChain(), LN0->getBasePtr(),
6217                                          LN0->getMemoryVT(),
6218                                          LN0->getMemOperand());
6219         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6220         Mask = Mask.sext(VT.getSizeInBits());
6221         SDLoc DL(N);
6222         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6223                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6224         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6225                                     SDLoc(N0.getOperand(0)),
6226                                     N0.getOperand(0).getValueType(), ExtLoad);
6227         CombineTo(N, And);
6228         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6229         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6230                         ISD::SIGN_EXTEND);
6231         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6232       }
6233     }
6234   }
6235 
6236   if (N0.getOpcode() == ISD::SETCC) {
6237     EVT N0VT = N0.getOperand(0).getValueType();
6238     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6239     // Only do this before legalize for now.
6240     if (VT.isVector() && !LegalOperations &&
6241         TLI.getBooleanContents(N0VT) ==
6242             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6243       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6244       // of the same size as the compared operands. Only optimize sext(setcc())
6245       // if this is the case.
6246       EVT SVT = getSetCCResultType(N0VT);
6247 
6248       // We know that the # elements of the results is the same as the
6249       // # elements of the compare (and the # elements of the compare result
6250       // for that matter).  Check to see that they are the same size.  If so,
6251       // we know that the element size of the sext'd result matches the
6252       // element size of the compare operands.
6253       if (VT.getSizeInBits() == SVT.getSizeInBits())
6254         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6255                              N0.getOperand(1),
6256                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6257 
6258       // If the desired elements are smaller or larger than the source
6259       // elements we can use a matching integer vector type and then
6260       // truncate/sign extend
6261       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6262       if (SVT == MatchingVectorType) {
6263         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6264                                N0.getOperand(0), N0.getOperand(1),
6265                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6266         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6267       }
6268     }
6269 
6270     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
6271     // Here, T can be 1 or -1, depending on the type of the setcc and
6272     // getBooleanContents().
6273     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
6274 
6275     SDLoc DL(N);
6276     // To determine the "true" side of the select, we need to know the high bit
6277     // of the value returned by the setcc if it evaluates to true.
6278     // If the type of the setcc is i1, then the true case of the select is just
6279     // sext(i1 1), that is, -1.
6280     // If the type of the setcc is larger (say, i8) then the value of the high
6281     // bit depends on getBooleanContents(). So, ask TLI for a real "true" value
6282     // of the appropriate width.
6283     SDValue ExtTrueVal =
6284         (SetCCWidth == 1)
6285             ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()),
6286                               DL, VT)
6287             : TLI.getConstTrueVal(DAG, VT, DL);
6288 
6289     if (SDValue SCC = SimplifySelectCC(
6290             DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal,
6291             DAG.getConstant(0, DL, VT),
6292             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6293       return SCC;
6294 
6295     if (!VT.isVector()) {
6296       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6297       if (!LegalOperations ||
6298           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6299         SDLoc DL(N);
6300         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6301         SDValue SetCC =
6302             DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC);
6303         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal,
6304                              DAG.getConstant(0, DL, VT));
6305       }
6306     }
6307   }
6308 
6309   // fold (sext x) -> (zext x) if the sign bit is known zero.
6310   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6311       DAG.SignBitIsZero(N0))
6312     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6313 
6314   return SDValue();
6315 }
6316 
6317 // isTruncateOf - If N is a truncate of some other value, return true, record
6318 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6319 // This function computes KnownZero to avoid a duplicated call to
6320 // computeKnownBits in the caller.
6321 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6322                          APInt &KnownZero) {
6323   APInt KnownOne;
6324   if (N->getOpcode() == ISD::TRUNCATE) {
6325     Op = N->getOperand(0);
6326     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6327     return true;
6328   }
6329 
6330   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6331       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6332     return false;
6333 
6334   SDValue Op0 = N->getOperand(0);
6335   SDValue Op1 = N->getOperand(1);
6336   assert(Op0.getValueType() == Op1.getValueType());
6337 
6338   if (isNullConstant(Op0))
6339     Op = Op1;
6340   else if (isNullConstant(Op1))
6341     Op = Op0;
6342   else
6343     return false;
6344 
6345   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6346 
6347   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6348     return false;
6349 
6350   return true;
6351 }
6352 
6353 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6354   SDValue N0 = N->getOperand(0);
6355   EVT VT = N->getValueType(0);
6356 
6357   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6358                                               LegalOperations))
6359     return SDValue(Res, 0);
6360 
6361   // fold (zext (zext x)) -> (zext x)
6362   // fold (zext (aext x)) -> (zext x)
6363   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6364     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6365                        N0.getOperand(0));
6366 
6367   // fold (zext (truncate x)) -> (zext x) or
6368   //      (zext (truncate x)) -> (truncate x)
6369   // This is valid when the truncated bits of x are already zero.
6370   // FIXME: We should extend this to work for vectors too.
6371   SDValue Op;
6372   APInt KnownZero;
6373   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6374     APInt TruncatedBits =
6375       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6376       APInt(Op.getValueSizeInBits(), 0) :
6377       APInt::getBitsSet(Op.getValueSizeInBits(),
6378                         N0.getValueSizeInBits(),
6379                         std::min(Op.getValueSizeInBits(),
6380                                  VT.getSizeInBits()));
6381     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6382       if (VT.bitsGT(Op.getValueType()))
6383         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6384       if (VT.bitsLT(Op.getValueType()))
6385         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6386 
6387       return Op;
6388     }
6389   }
6390 
6391   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6392   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6393   if (N0.getOpcode() == ISD::TRUNCATE) {
6394     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6395       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6396       if (NarrowLoad.getNode() != N0.getNode()) {
6397         CombineTo(N0.getNode(), NarrowLoad);
6398         // CombineTo deleted the truncate, if needed, but not what's under it.
6399         AddToWorklist(oye);
6400       }
6401       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6402     }
6403   }
6404 
6405   // fold (zext (truncate x)) -> (and x, mask)
6406   if (N0.getOpcode() == ISD::TRUNCATE) {
6407     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6408     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6409     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6410       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6411       if (NarrowLoad.getNode() != N0.getNode()) {
6412         CombineTo(N0.getNode(), NarrowLoad);
6413         // CombineTo deleted the truncate, if needed, but not what's under it.
6414         AddToWorklist(oye);
6415       }
6416       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6417     }
6418 
6419     EVT SrcVT = N0.getOperand(0).getValueType();
6420     EVT MinVT = N0.getValueType();
6421 
6422     // Try to mask before the extension to avoid having to generate a larger mask,
6423     // possibly over several sub-vectors.
6424     if (SrcVT.bitsLT(VT)) {
6425       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6426                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6427         SDValue Op = N0.getOperand(0);
6428         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6429         AddToWorklist(Op.getNode());
6430         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6431       }
6432     }
6433 
6434     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6435       SDValue Op = N0.getOperand(0);
6436       if (SrcVT.bitsLT(VT)) {
6437         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6438         AddToWorklist(Op.getNode());
6439       } else if (SrcVT.bitsGT(VT)) {
6440         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6441         AddToWorklist(Op.getNode());
6442       }
6443       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6444     }
6445   }
6446 
6447   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6448   // if either of the casts is not free.
6449   if (N0.getOpcode() == ISD::AND &&
6450       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6451       N0.getOperand(1).getOpcode() == ISD::Constant &&
6452       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6453                            N0.getValueType()) ||
6454        !TLI.isZExtFree(N0.getValueType(), VT))) {
6455     SDValue X = N0.getOperand(0).getOperand(0);
6456     if (X.getValueType().bitsLT(VT)) {
6457       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6458     } else if (X.getValueType().bitsGT(VT)) {
6459       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6460     }
6461     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6462     Mask = Mask.zext(VT.getSizeInBits());
6463     SDLoc DL(N);
6464     return DAG.getNode(ISD::AND, DL, VT,
6465                        X, DAG.getConstant(Mask, DL, VT));
6466   }
6467 
6468   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6469   // Only generate vector extloads when 1) they're legal, and 2) they are
6470   // deemed desirable by the target.
6471   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6472       ((!LegalOperations && !VT.isVector() &&
6473         !cast<LoadSDNode>(N0)->isVolatile()) ||
6474        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6475     bool DoXform = true;
6476     SmallVector<SDNode*, 4> SetCCs;
6477     if (!N0.hasOneUse())
6478       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6479     if (VT.isVector())
6480       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6481     if (DoXform) {
6482       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6483       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6484                                        LN0->getChain(),
6485                                        LN0->getBasePtr(), N0.getValueType(),
6486                                        LN0->getMemOperand());
6487       CombineTo(N, ExtLoad);
6488       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6489                                   N0.getValueType(), ExtLoad);
6490       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6491 
6492       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6493                       ISD::ZERO_EXTEND);
6494       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6495     }
6496   }
6497 
6498   // fold (zext (load x)) to multiple smaller zextloads.
6499   // Only on illegal but splittable vectors.
6500   if (SDValue ExtLoad = CombineExtLoad(N))
6501     return ExtLoad;
6502 
6503   // fold (zext (and/or/xor (load x), cst)) ->
6504   //      (and/or/xor (zextload x), (zext cst))
6505   // Unless (and (load x) cst) will match as a zextload already and has
6506   // additional users.
6507   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6508        N0.getOpcode() == ISD::XOR) &&
6509       isa<LoadSDNode>(N0.getOperand(0)) &&
6510       N0.getOperand(1).getOpcode() == ISD::Constant &&
6511       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6512       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6513     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6514     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6515       bool DoXform = true;
6516       SmallVector<SDNode*, 4> SetCCs;
6517       if (!N0.hasOneUse()) {
6518         if (N0.getOpcode() == ISD::AND) {
6519           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6520           auto NarrowLoad = false;
6521           EVT LoadResultTy = AndC->getValueType(0);
6522           EVT ExtVT, LoadedVT;
6523           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6524                                NarrowLoad))
6525             DoXform = false;
6526         }
6527         if (DoXform)
6528           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6529                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6530       }
6531       if (DoXform) {
6532         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6533                                          LN0->getChain(), LN0->getBasePtr(),
6534                                          LN0->getMemoryVT(),
6535                                          LN0->getMemOperand());
6536         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6537         Mask = Mask.zext(VT.getSizeInBits());
6538         SDLoc DL(N);
6539         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6540                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6541         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6542                                     SDLoc(N0.getOperand(0)),
6543                                     N0.getOperand(0).getValueType(), ExtLoad);
6544         CombineTo(N, And);
6545         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6546         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6547                         ISD::ZERO_EXTEND);
6548         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6549       }
6550     }
6551   }
6552 
6553   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6554   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6555   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6556       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6557     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6558     EVT MemVT = LN0->getMemoryVT();
6559     if ((!LegalOperations && !LN0->isVolatile()) ||
6560         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6561       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6562                                        LN0->getChain(),
6563                                        LN0->getBasePtr(), MemVT,
6564                                        LN0->getMemOperand());
6565       CombineTo(N, ExtLoad);
6566       CombineTo(N0.getNode(),
6567                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6568                             ExtLoad),
6569                 ExtLoad.getValue(1));
6570       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6571     }
6572   }
6573 
6574   if (N0.getOpcode() == ISD::SETCC) {
6575     // Only do this before legalize for now.
6576     if (!LegalOperations && VT.isVector() &&
6577         N0.getValueType().getVectorElementType() == MVT::i1) {
6578       EVT N00VT = N0.getOperand(0).getValueType();
6579       if (getSetCCResultType(N00VT) == N0.getValueType())
6580         return SDValue();
6581 
6582       // We know that the # elements of the results is the same as the #
6583       // elements of the compare (and the # elements of the compare result for
6584       // that matter). Check to see that they are the same size. If so, we know
6585       // that the element size of the sext'd result matches the element size of
6586       // the compare operands.
6587       SDLoc DL(N);
6588       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6589       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
6590         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6591         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
6592                                      N0.getOperand(1), N0.getOperand(2));
6593         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
6594       }
6595 
6596       // If the desired elements are smaller or larger than the source
6597       // elements we can use a matching integer vector type and then
6598       // truncate/sign extend.
6599       EVT MatchingElementType = EVT::getIntegerVT(
6600           *DAG.getContext(), N00VT.getScalarSizeInBits());
6601       EVT MatchingVectorType = EVT::getVectorVT(
6602           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
6603       SDValue VsetCC =
6604           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
6605                       N0.getOperand(1), N0.getOperand(2));
6606       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
6607                          VecOnes);
6608     }
6609 
6610     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6611     SDLoc DL(N);
6612     if (SDValue SCC = SimplifySelectCC(
6613             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6614             DAG.getConstant(0, DL, VT),
6615             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6616       return SCC;
6617   }
6618 
6619   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6620   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6621       isa<ConstantSDNode>(N0.getOperand(1)) &&
6622       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6623       N0.hasOneUse()) {
6624     SDValue ShAmt = N0.getOperand(1);
6625     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6626     if (N0.getOpcode() == ISD::SHL) {
6627       SDValue InnerZExt = N0.getOperand(0);
6628       // If the original shl may be shifting out bits, do not perform this
6629       // transformation.
6630       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
6631         InnerZExt.getOperand(0).getValueSizeInBits();
6632       if (ShAmtVal > KnownZeroBits)
6633         return SDValue();
6634     }
6635 
6636     SDLoc DL(N);
6637 
6638     // Ensure that the shift amount is wide enough for the shifted value.
6639     if (VT.getSizeInBits() >= 256)
6640       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6641 
6642     return DAG.getNode(N0.getOpcode(), DL, VT,
6643                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6644                        ShAmt);
6645   }
6646 
6647   return SDValue();
6648 }
6649 
6650 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6651   SDValue N0 = N->getOperand(0);
6652   EVT VT = N->getValueType(0);
6653 
6654   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6655                                               LegalOperations))
6656     return SDValue(Res, 0);
6657 
6658   // fold (aext (aext x)) -> (aext x)
6659   // fold (aext (zext x)) -> (zext x)
6660   // fold (aext (sext x)) -> (sext x)
6661   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6662       N0.getOpcode() == ISD::ZERO_EXTEND ||
6663       N0.getOpcode() == ISD::SIGN_EXTEND)
6664     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6665 
6666   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6667   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6668   if (N0.getOpcode() == ISD::TRUNCATE) {
6669     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6670       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6671       if (NarrowLoad.getNode() != N0.getNode()) {
6672         CombineTo(N0.getNode(), NarrowLoad);
6673         // CombineTo deleted the truncate, if needed, but not what's under it.
6674         AddToWorklist(oye);
6675       }
6676       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6677     }
6678   }
6679 
6680   // fold (aext (truncate x))
6681   if (N0.getOpcode() == ISD::TRUNCATE) {
6682     SDValue TruncOp = N0.getOperand(0);
6683     if (TruncOp.getValueType() == VT)
6684       return TruncOp; // x iff x size == zext size.
6685     if (TruncOp.getValueType().bitsGT(VT))
6686       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6687     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6688   }
6689 
6690   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6691   // if the trunc is not free.
6692   if (N0.getOpcode() == ISD::AND &&
6693       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6694       N0.getOperand(1).getOpcode() == ISD::Constant &&
6695       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6696                           N0.getValueType())) {
6697     SDValue X = N0.getOperand(0).getOperand(0);
6698     if (X.getValueType().bitsLT(VT)) {
6699       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6700     } else if (X.getValueType().bitsGT(VT)) {
6701       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6702     }
6703     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6704     Mask = Mask.zext(VT.getSizeInBits());
6705     SDLoc DL(N);
6706     return DAG.getNode(ISD::AND, DL, VT,
6707                        X, DAG.getConstant(Mask, DL, VT));
6708   }
6709 
6710   // fold (aext (load x)) -> (aext (truncate (extload x)))
6711   // None of the supported targets knows how to perform load and any_ext
6712   // on vectors in one instruction.  We only perform this transformation on
6713   // scalars.
6714   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6715       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6716       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6717     bool DoXform = true;
6718     SmallVector<SDNode*, 4> SetCCs;
6719     if (!N0.hasOneUse())
6720       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6721     if (DoXform) {
6722       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6723       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6724                                        LN0->getChain(),
6725                                        LN0->getBasePtr(), N0.getValueType(),
6726                                        LN0->getMemOperand());
6727       CombineTo(N, ExtLoad);
6728       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6729                                   N0.getValueType(), ExtLoad);
6730       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6731       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6732                       ISD::ANY_EXTEND);
6733       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6734     }
6735   }
6736 
6737   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6738   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6739   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6740   if (N0.getOpcode() == ISD::LOAD &&
6741       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6742       N0.hasOneUse()) {
6743     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6744     ISD::LoadExtType ExtType = LN0->getExtensionType();
6745     EVT MemVT = LN0->getMemoryVT();
6746     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6747       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6748                                        VT, LN0->getChain(), LN0->getBasePtr(),
6749                                        MemVT, LN0->getMemOperand());
6750       CombineTo(N, ExtLoad);
6751       CombineTo(N0.getNode(),
6752                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6753                             N0.getValueType(), ExtLoad),
6754                 ExtLoad.getValue(1));
6755       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6756     }
6757   }
6758 
6759   if (N0.getOpcode() == ISD::SETCC) {
6760     // For vectors:
6761     // aext(setcc) -> vsetcc
6762     // aext(setcc) -> truncate(vsetcc)
6763     // aext(setcc) -> aext(vsetcc)
6764     // Only do this before legalize for now.
6765     if (VT.isVector() && !LegalOperations) {
6766       EVT N0VT = N0.getOperand(0).getValueType();
6767         // We know that the # elements of the results is the same as the
6768         // # elements of the compare (and the # elements of the compare result
6769         // for that matter).  Check to see that they are the same size.  If so,
6770         // we know that the element size of the sext'd result matches the
6771         // element size of the compare operands.
6772       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6773         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6774                              N0.getOperand(1),
6775                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6776       // If the desired elements are smaller or larger than the source
6777       // elements we can use a matching integer vector type and then
6778       // truncate/any extend
6779       else {
6780         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6781         SDValue VsetCC =
6782           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6783                         N0.getOperand(1),
6784                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6785         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6786       }
6787     }
6788 
6789     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6790     SDLoc DL(N);
6791     if (SDValue SCC = SimplifySelectCC(
6792             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6793             DAG.getConstant(0, DL, VT),
6794             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6795       return SCC;
6796   }
6797 
6798   return SDValue();
6799 }
6800 
6801 /// See if the specified operand can be simplified with the knowledge that only
6802 /// the bits specified by Mask are used.  If so, return the simpler operand,
6803 /// otherwise return a null SDValue.
6804 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6805   switch (V.getOpcode()) {
6806   default: break;
6807   case ISD::Constant: {
6808     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6809     assert(CV && "Const value should be ConstSDNode.");
6810     const APInt &CVal = CV->getAPIntValue();
6811     APInt NewVal = CVal & Mask;
6812     if (NewVal != CVal)
6813       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6814     break;
6815   }
6816   case ISD::OR:
6817   case ISD::XOR:
6818     // If the LHS or RHS don't contribute bits to the or, drop them.
6819     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6820       return V.getOperand(1);
6821     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6822       return V.getOperand(0);
6823     break;
6824   case ISD::SRL:
6825     // Only look at single-use SRLs.
6826     if (!V.getNode()->hasOneUse())
6827       break;
6828     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6829       // See if we can recursively simplify the LHS.
6830       unsigned Amt = RHSC->getZExtValue();
6831 
6832       // Watch out for shift count overflow though.
6833       if (Amt >= Mask.getBitWidth()) break;
6834       APInt NewMask = Mask << Amt;
6835       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6836         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6837                            SimplifyLHS, V.getOperand(1));
6838     }
6839   }
6840   return SDValue();
6841 }
6842 
6843 /// If the result of a wider load is shifted to right of N  bits and then
6844 /// truncated to a narrower type and where N is a multiple of number of bits of
6845 /// the narrower type, transform it to a narrower load from address + N / num of
6846 /// bits of new type. If the result is to be extended, also fold the extension
6847 /// to form a extending load.
6848 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6849   unsigned Opc = N->getOpcode();
6850 
6851   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6852   SDValue N0 = N->getOperand(0);
6853   EVT VT = N->getValueType(0);
6854   EVT ExtVT = VT;
6855 
6856   // This transformation isn't valid for vector loads.
6857   if (VT.isVector())
6858     return SDValue();
6859 
6860   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6861   // extended to VT.
6862   if (Opc == ISD::SIGN_EXTEND_INREG) {
6863     ExtType = ISD::SEXTLOAD;
6864     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6865   } else if (Opc == ISD::SRL) {
6866     // Another special-case: SRL is basically zero-extending a narrower value.
6867     ExtType = ISD::ZEXTLOAD;
6868     N0 = SDValue(N, 0);
6869     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6870     if (!N01) return SDValue();
6871     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6872                               VT.getSizeInBits() - N01->getZExtValue());
6873   }
6874   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6875     return SDValue();
6876 
6877   unsigned EVTBits = ExtVT.getSizeInBits();
6878 
6879   // Do not generate loads of non-round integer types since these can
6880   // be expensive (and would be wrong if the type is not byte sized).
6881   if (!ExtVT.isRound())
6882     return SDValue();
6883 
6884   unsigned ShAmt = 0;
6885   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6886     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6887       ShAmt = N01->getZExtValue();
6888       // Is the shift amount a multiple of size of VT?
6889       if ((ShAmt & (EVTBits-1)) == 0) {
6890         N0 = N0.getOperand(0);
6891         // Is the load width a multiple of size of VT?
6892         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
6893           return SDValue();
6894       }
6895 
6896       // At this point, we must have a load or else we can't do the transform.
6897       if (!isa<LoadSDNode>(N0)) return SDValue();
6898 
6899       // Because a SRL must be assumed to *need* to zero-extend the high bits
6900       // (as opposed to anyext the high bits), we can't combine the zextload
6901       // lowering of SRL and an sextload.
6902       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6903         return SDValue();
6904 
6905       // If the shift amount is larger than the input type then we're not
6906       // accessing any of the loaded bytes.  If the load was a zextload/extload
6907       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6908       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6909         return SDValue();
6910     }
6911   }
6912 
6913   // If the load is shifted left (and the result isn't shifted back right),
6914   // we can fold the truncate through the shift.
6915   unsigned ShLeftAmt = 0;
6916   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6917       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6918     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6919       ShLeftAmt = N01->getZExtValue();
6920       N0 = N0.getOperand(0);
6921     }
6922   }
6923 
6924   // If we haven't found a load, we can't narrow it.  Don't transform one with
6925   // multiple uses, this would require adding a new load.
6926   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6927     return SDValue();
6928 
6929   // Don't change the width of a volatile load.
6930   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6931   if (LN0->isVolatile())
6932     return SDValue();
6933 
6934   // Verify that we are actually reducing a load width here.
6935   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6936     return SDValue();
6937 
6938   // For the transform to be legal, the load must produce only two values
6939   // (the value loaded and the chain).  Don't transform a pre-increment
6940   // load, for example, which produces an extra value.  Otherwise the
6941   // transformation is not equivalent, and the downstream logic to replace
6942   // uses gets things wrong.
6943   if (LN0->getNumValues() > 2)
6944     return SDValue();
6945 
6946   // If the load that we're shrinking is an extload and we're not just
6947   // discarding the extension we can't simply shrink the load. Bail.
6948   // TODO: It would be possible to merge the extensions in some cases.
6949   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6950       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6951     return SDValue();
6952 
6953   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6954     return SDValue();
6955 
6956   EVT PtrType = N0.getOperand(1).getValueType();
6957 
6958   if (PtrType == MVT::Untyped || PtrType.isExtended())
6959     // It's not possible to generate a constant of extended or untyped type.
6960     return SDValue();
6961 
6962   // For big endian targets, we need to adjust the offset to the pointer to
6963   // load the correct bytes.
6964   if (DAG.getDataLayout().isBigEndian()) {
6965     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6966     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6967     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6968   }
6969 
6970   uint64_t PtrOff = ShAmt / 8;
6971   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6972   SDLoc DL(LN0);
6973   // The original load itself didn't wrap, so an offset within it doesn't.
6974   SDNodeFlags Flags;
6975   Flags.setNoUnsignedWrap(true);
6976   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6977                                PtrType, LN0->getBasePtr(),
6978                                DAG.getConstant(PtrOff, DL, PtrType),
6979                                &Flags);
6980   AddToWorklist(NewPtr.getNode());
6981 
6982   SDValue Load;
6983   if (ExtType == ISD::NON_EXTLOAD)
6984     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6985                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
6986                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6987   else
6988     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
6989                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
6990                           NewAlign, LN0->getMemOperand()->getFlags(),
6991                           LN0->getAAInfo());
6992 
6993   // Replace the old load's chain with the new load's chain.
6994   WorklistRemover DeadNodes(*this);
6995   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6996 
6997   // Shift the result left, if we've swallowed a left shift.
6998   SDValue Result = Load;
6999   if (ShLeftAmt != 0) {
7000     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7001     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7002       ShImmTy = VT;
7003     // If the shift amount is as large as the result size (but, presumably,
7004     // no larger than the source) then the useful bits of the result are
7005     // zero; we can't simply return the shortened shift, because the result
7006     // of that operation is undefined.
7007     SDLoc DL(N0);
7008     if (ShLeftAmt >= VT.getSizeInBits())
7009       Result = DAG.getConstant(0, DL, VT);
7010     else
7011       Result = DAG.getNode(ISD::SHL, DL, VT,
7012                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7013   }
7014 
7015   // Return the new loaded value.
7016   return Result;
7017 }
7018 
7019 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7020   SDValue N0 = N->getOperand(0);
7021   SDValue N1 = N->getOperand(1);
7022   EVT VT = N->getValueType(0);
7023   EVT EVT = cast<VTSDNode>(N1)->getVT();
7024   unsigned VTBits = VT.getScalarSizeInBits();
7025   unsigned EVTBits = EVT.getScalarSizeInBits();
7026 
7027   if (N0.isUndef())
7028     return DAG.getUNDEF(VT);
7029 
7030   // fold (sext_in_reg c1) -> c1
7031   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7032     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7033 
7034   // If the input is already sign extended, just drop the extension.
7035   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7036     return N0;
7037 
7038   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7039   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7040       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7041     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7042                        N0.getOperand(0), N1);
7043 
7044   // fold (sext_in_reg (sext x)) -> (sext x)
7045   // fold (sext_in_reg (aext x)) -> (sext x)
7046   // if x is small enough.
7047   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7048     SDValue N00 = N0.getOperand(0);
7049     if (N00.getScalarValueSizeInBits() <= EVTBits &&
7050         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7051       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7052   }
7053 
7054   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7055   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7056     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7057 
7058   // fold operands of sext_in_reg based on knowledge that the top bits are not
7059   // demanded.
7060   if (SimplifyDemandedBits(SDValue(N, 0)))
7061     return SDValue(N, 0);
7062 
7063   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7064   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7065   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7066     return NarrowLoad;
7067 
7068   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7069   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7070   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7071   if (N0.getOpcode() == ISD::SRL) {
7072     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7073       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7074         // We can turn this into an SRA iff the input to the SRL is already sign
7075         // extended enough.
7076         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7077         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7078           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7079                              N0.getOperand(0), N0.getOperand(1));
7080       }
7081   }
7082 
7083   // fold (sext_inreg (extload x)) -> (sextload x)
7084   if (ISD::isEXTLoad(N0.getNode()) &&
7085       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7086       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7087       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7088        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7089     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7090     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7091                                      LN0->getChain(),
7092                                      LN0->getBasePtr(), EVT,
7093                                      LN0->getMemOperand());
7094     CombineTo(N, ExtLoad);
7095     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7096     AddToWorklist(ExtLoad.getNode());
7097     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7098   }
7099   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7100   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7101       N0.hasOneUse() &&
7102       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7103       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7104        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7105     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7106     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7107                                      LN0->getChain(),
7108                                      LN0->getBasePtr(), EVT,
7109                                      LN0->getMemOperand());
7110     CombineTo(N, ExtLoad);
7111     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7112     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7113   }
7114 
7115   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7116   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7117     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7118                                            N0.getOperand(1), false))
7119       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7120                          BSwap, N1);
7121   }
7122 
7123   return SDValue();
7124 }
7125 
7126 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7127   SDValue N0 = N->getOperand(0);
7128   EVT VT = N->getValueType(0);
7129 
7130   if (N0.isUndef())
7131     return DAG.getUNDEF(VT);
7132 
7133   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7134                                               LegalOperations))
7135     return SDValue(Res, 0);
7136 
7137   return SDValue();
7138 }
7139 
7140 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7141   SDValue N0 = N->getOperand(0);
7142   EVT VT = N->getValueType(0);
7143 
7144   if (N0.isUndef())
7145     return DAG.getUNDEF(VT);
7146 
7147   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7148                                               LegalOperations))
7149     return SDValue(Res, 0);
7150 
7151   return SDValue();
7152 }
7153 
7154 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7155   SDValue N0 = N->getOperand(0);
7156   EVT VT = N->getValueType(0);
7157   bool isLE = DAG.getDataLayout().isLittleEndian();
7158 
7159   // noop truncate
7160   if (N0.getValueType() == N->getValueType(0))
7161     return N0;
7162   // fold (truncate c1) -> c1
7163   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7164     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7165   // fold (truncate (truncate x)) -> (truncate x)
7166   if (N0.getOpcode() == ISD::TRUNCATE)
7167     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7168   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7169   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7170       N0.getOpcode() == ISD::SIGN_EXTEND ||
7171       N0.getOpcode() == ISD::ANY_EXTEND) {
7172     // if the source is smaller than the dest, we still need an extend.
7173     if (N0.getOperand(0).getValueType().bitsLT(VT))
7174       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7175     // if the source is larger than the dest, than we just need the truncate.
7176     if (N0.getOperand(0).getValueType().bitsGT(VT))
7177       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7178     // if the source and dest are the same type, we can drop both the extend
7179     // and the truncate.
7180     return N0.getOperand(0);
7181   }
7182 
7183   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
7184   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
7185     return SDValue();
7186 
7187   // Fold extract-and-trunc into a narrow extract. For example:
7188   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7189   //   i32 y = TRUNCATE(i64 x)
7190   //        -- becomes --
7191   //   v16i8 b = BITCAST (v2i64 val)
7192   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7193   //
7194   // Note: We only run this optimization after type legalization (which often
7195   // creates this pattern) and before operation legalization after which
7196   // we need to be more careful about the vector instructions that we generate.
7197   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7198       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7199 
7200     EVT VecTy = N0.getOperand(0).getValueType();
7201     EVT ExTy = N0.getValueType();
7202     EVT TrTy = N->getValueType(0);
7203 
7204     unsigned NumElem = VecTy.getVectorNumElements();
7205     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7206 
7207     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7208     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7209 
7210     SDValue EltNo = N0->getOperand(1);
7211     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7212       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7213       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7214       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7215 
7216       SDLoc DL(N);
7217       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7218                          DAG.getBitcast(NVT, N0.getOperand(0)),
7219                          DAG.getConstant(Index, DL, IndexTy));
7220     }
7221   }
7222 
7223   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7224   if (N0.getOpcode() == ISD::SELECT) {
7225     EVT SrcVT = N0.getValueType();
7226     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7227         TLI.isTruncateFree(SrcVT, VT)) {
7228       SDLoc SL(N0);
7229       SDValue Cond = N0.getOperand(0);
7230       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7231       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7232       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7233     }
7234   }
7235 
7236   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
7237   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7238       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7239       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7240     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7241       uint64_t Amt = CAmt->getZExtValue();
7242       unsigned Size = VT.getScalarSizeInBits();
7243 
7244       if (Amt < Size) {
7245         SDLoc SL(N);
7246         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7247 
7248         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7249         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7250                            DAG.getConstant(Amt, SL, AmtVT));
7251       }
7252     }
7253   }
7254 
7255   // Fold a series of buildvector, bitcast, and truncate if possible.
7256   // For example fold
7257   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7258   //   (2xi32 (buildvector x, y)).
7259   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7260       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7261       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7262       N0.getOperand(0).hasOneUse()) {
7263 
7264     SDValue BuildVect = N0.getOperand(0);
7265     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7266     EVT TruncVecEltTy = VT.getVectorElementType();
7267 
7268     // Check that the element types match.
7269     if (BuildVectEltTy == TruncVecEltTy) {
7270       // Now we only need to compute the offset of the truncated elements.
7271       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7272       unsigned TruncVecNumElts = VT.getVectorNumElements();
7273       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7274 
7275       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7276              "Invalid number of elements");
7277 
7278       SmallVector<SDValue, 8> Opnds;
7279       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7280         Opnds.push_back(BuildVect.getOperand(i));
7281 
7282       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7283     }
7284   }
7285 
7286   // See if we can simplify the input to this truncate through knowledge that
7287   // only the low bits are being used.
7288   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7289   // Currently we only perform this optimization on scalars because vectors
7290   // may have different active low bits.
7291   if (!VT.isVector()) {
7292     if (SDValue Shorter =
7293             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7294                                                      VT.getSizeInBits())))
7295       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7296   }
7297   // fold (truncate (load x)) -> (smaller load x)
7298   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7299   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7300     if (SDValue Reduced = ReduceLoadWidth(N))
7301       return Reduced;
7302 
7303     // Handle the case where the load remains an extending load even
7304     // after truncation.
7305     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7306       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7307       if (!LN0->isVolatile() &&
7308           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7309         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7310                                          VT, LN0->getChain(), LN0->getBasePtr(),
7311                                          LN0->getMemoryVT(),
7312                                          LN0->getMemOperand());
7313         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7314         return NewLoad;
7315       }
7316     }
7317   }
7318   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7319   // where ... are all 'undef'.
7320   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7321     SmallVector<EVT, 8> VTs;
7322     SDValue V;
7323     unsigned Idx = 0;
7324     unsigned NumDefs = 0;
7325 
7326     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7327       SDValue X = N0.getOperand(i);
7328       if (!X.isUndef()) {
7329         V = X;
7330         Idx = i;
7331         NumDefs++;
7332       }
7333       // Stop if more than one members are non-undef.
7334       if (NumDefs > 1)
7335         break;
7336       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7337                                      VT.getVectorElementType(),
7338                                      X.getValueType().getVectorNumElements()));
7339     }
7340 
7341     if (NumDefs == 0)
7342       return DAG.getUNDEF(VT);
7343 
7344     if (NumDefs == 1) {
7345       assert(V.getNode() && "The single defined operand is empty!");
7346       SmallVector<SDValue, 8> Opnds;
7347       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7348         if (i != Idx) {
7349           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7350           continue;
7351         }
7352         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7353         AddToWorklist(NV.getNode());
7354         Opnds.push_back(NV);
7355       }
7356       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7357     }
7358   }
7359 
7360   // Fold truncate of a bitcast of a vector to an extract of the low vector
7361   // element.
7362   //
7363   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7364   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7365     SDValue VecSrc = N0.getOperand(0);
7366     EVT SrcVT = VecSrc.getValueType();
7367     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7368         (!LegalOperations ||
7369          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7370       SDLoc SL(N);
7371 
7372       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7373       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7374                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7375     }
7376   }
7377 
7378   // Simplify the operands using demanded-bits information.
7379   if (!VT.isVector() &&
7380       SimplifyDemandedBits(SDValue(N, 0)))
7381     return SDValue(N, 0);
7382 
7383   return SDValue();
7384 }
7385 
7386 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7387   SDValue Elt = N->getOperand(i);
7388   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7389     return Elt.getNode();
7390   return Elt.getOperand(Elt.getResNo()).getNode();
7391 }
7392 
7393 /// build_pair (load, load) -> load
7394 /// if load locations are consecutive.
7395 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7396   assert(N->getOpcode() == ISD::BUILD_PAIR);
7397 
7398   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7399   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7400   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7401       LD1->getAddressSpace() != LD2->getAddressSpace())
7402     return SDValue();
7403   EVT LD1VT = LD1->getValueType(0);
7404   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7405   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7406       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7407     unsigned Align = LD1->getAlignment();
7408     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7409         VT.getTypeForEVT(*DAG.getContext()));
7410 
7411     if (NewAlign <= Align &&
7412         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7413       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
7414                          LD1->getPointerInfo(), Align);
7415   }
7416 
7417   return SDValue();
7418 }
7419 
7420 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7421   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7422   // and Lo parts; on big-endian machines it doesn't.
7423   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7424 }
7425 
7426 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7427                                     const TargetLowering &TLI) {
7428   // If this is not a bitcast to an FP type or if the target doesn't have
7429   // IEEE754-compliant FP logic, we're done.
7430   EVT VT = N->getValueType(0);
7431   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7432     return SDValue();
7433 
7434   // TODO: Use splat values for the constant-checking below and remove this
7435   // restriction.
7436   SDValue N0 = N->getOperand(0);
7437   EVT SourceVT = N0.getValueType();
7438   if (SourceVT.isVector())
7439     return SDValue();
7440 
7441   unsigned FPOpcode;
7442   APInt SignMask;
7443   switch (N0.getOpcode()) {
7444   case ISD::AND:
7445     FPOpcode = ISD::FABS;
7446     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7447     break;
7448   case ISD::XOR:
7449     FPOpcode = ISD::FNEG;
7450     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7451     break;
7452   // TODO: ISD::OR --> ISD::FNABS?
7453   default:
7454     return SDValue();
7455   }
7456 
7457   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7458   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7459   SDValue LogicOp0 = N0.getOperand(0);
7460   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7461   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7462       LogicOp0.getOpcode() == ISD::BITCAST &&
7463       LogicOp0->getOperand(0).getValueType() == VT)
7464     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7465 
7466   return SDValue();
7467 }
7468 
7469 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7470   SDValue N0 = N->getOperand(0);
7471   EVT VT = N->getValueType(0);
7472 
7473   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7474   // Only do this before legalize, since afterward the target may be depending
7475   // on the bitconvert.
7476   // First check to see if this is all constant.
7477   if (!LegalTypes &&
7478       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7479       VT.isVector()) {
7480     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7481 
7482     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7483     assert(!DestEltVT.isVector() &&
7484            "Element type of vector ValueType must not be vector!");
7485     if (isSimple)
7486       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7487   }
7488 
7489   // If the input is a constant, let getNode fold it.
7490   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7491     // If we can't allow illegal operations, we need to check that this is just
7492     // a fp -> int or int -> conversion and that the resulting operation will
7493     // be legal.
7494     if (!LegalOperations ||
7495         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7496          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7497         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7498          TLI.isOperationLegal(ISD::Constant, VT)))
7499       return DAG.getBitcast(VT, N0);
7500   }
7501 
7502   // (conv (conv x, t1), t2) -> (conv x, t2)
7503   if (N0.getOpcode() == ISD::BITCAST)
7504     return DAG.getBitcast(VT, N0.getOperand(0));
7505 
7506   // fold (conv (load x)) -> (load (conv*)x)
7507   // If the resultant load doesn't need a higher alignment than the original!
7508   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7509       // Do not change the width of a volatile load.
7510       !cast<LoadSDNode>(N0)->isVolatile() &&
7511       // Do not remove the cast if the types differ in endian layout.
7512       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7513           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7514       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7515       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7516     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7517     unsigned OrigAlign = LN0->getAlignment();
7518 
7519     bool Fast = false;
7520     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7521                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7522         Fast) {
7523       SDValue Load =
7524           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7525                       LN0->getPointerInfo(), OrigAlign,
7526                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7527       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7528       return Load;
7529     }
7530   }
7531 
7532   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7533     return V;
7534 
7535   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7536   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7537   //
7538   // For ppc_fp128:
7539   // fold (bitcast (fneg x)) ->
7540   //     flipbit = signbit
7541   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7542   //
7543   // fold (bitcast (fabs x)) ->
7544   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7545   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7546   // This often reduces constant pool loads.
7547   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7548        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7549       N0.getNode()->hasOneUse() && VT.isInteger() &&
7550       !VT.isVector() && !N0.getValueType().isVector()) {
7551     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7552     AddToWorklist(NewConv.getNode());
7553 
7554     SDLoc DL(N);
7555     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7556       assert(VT.getSizeInBits() == 128);
7557       SDValue SignBit = DAG.getConstant(
7558           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7559       SDValue FlipBit;
7560       if (N0.getOpcode() == ISD::FNEG) {
7561         FlipBit = SignBit;
7562         AddToWorklist(FlipBit.getNode());
7563       } else {
7564         assert(N0.getOpcode() == ISD::FABS);
7565         SDValue Hi =
7566             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7567                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7568                                               SDLoc(NewConv)));
7569         AddToWorklist(Hi.getNode());
7570         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7571         AddToWorklist(FlipBit.getNode());
7572       }
7573       SDValue FlipBits =
7574           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7575       AddToWorklist(FlipBits.getNode());
7576       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7577     }
7578     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7579     if (N0.getOpcode() == ISD::FNEG)
7580       return DAG.getNode(ISD::XOR, DL, VT,
7581                          NewConv, DAG.getConstant(SignBit, DL, VT));
7582     assert(N0.getOpcode() == ISD::FABS);
7583     return DAG.getNode(ISD::AND, DL, VT,
7584                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7585   }
7586 
7587   // fold (bitconvert (fcopysign cst, x)) ->
7588   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7589   // Note that we don't handle (copysign x, cst) because this can always be
7590   // folded to an fneg or fabs.
7591   //
7592   // For ppc_fp128:
7593   // fold (bitcast (fcopysign cst, x)) ->
7594   //     flipbit = (and (extract_element
7595   //                     (xor (bitcast cst), (bitcast x)), 0),
7596   //                    signbit)
7597   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7598   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7599       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7600       VT.isInteger() && !VT.isVector()) {
7601     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
7602     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7603     if (isTypeLegal(IntXVT)) {
7604       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7605       AddToWorklist(X.getNode());
7606 
7607       // If X has a different width than the result/lhs, sext it or truncate it.
7608       unsigned VTWidth = VT.getSizeInBits();
7609       if (OrigXWidth < VTWidth) {
7610         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7611         AddToWorklist(X.getNode());
7612       } else if (OrigXWidth > VTWidth) {
7613         // To get the sign bit in the right place, we have to shift it right
7614         // before truncating.
7615         SDLoc DL(X);
7616         X = DAG.getNode(ISD::SRL, DL,
7617                         X.getValueType(), X,
7618                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7619                                         X.getValueType()));
7620         AddToWorklist(X.getNode());
7621         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7622         AddToWorklist(X.getNode());
7623       }
7624 
7625       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7626         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7627         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7628         AddToWorklist(Cst.getNode());
7629         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7630         AddToWorklist(X.getNode());
7631         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7632         AddToWorklist(XorResult.getNode());
7633         SDValue XorResult64 = DAG.getNode(
7634             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7635             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7636                                   SDLoc(XorResult)));
7637         AddToWorklist(XorResult64.getNode());
7638         SDValue FlipBit =
7639             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7640                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7641         AddToWorklist(FlipBit.getNode());
7642         SDValue FlipBits =
7643             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7644         AddToWorklist(FlipBits.getNode());
7645         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7646       }
7647       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7648       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7649                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7650       AddToWorklist(X.getNode());
7651 
7652       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7653       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7654                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7655       AddToWorklist(Cst.getNode());
7656 
7657       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7658     }
7659   }
7660 
7661   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7662   if (N0.getOpcode() == ISD::BUILD_PAIR)
7663     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7664       return CombineLD;
7665 
7666   // Remove double bitcasts from shuffles - this is often a legacy of
7667   // XformToShuffleWithZero being used to combine bitmaskings (of
7668   // float vectors bitcast to integer vectors) into shuffles.
7669   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7670   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7671       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7672       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7673       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7674     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7675 
7676     // If operands are a bitcast, peek through if it casts the original VT.
7677     // If operands are a constant, just bitcast back to original VT.
7678     auto PeekThroughBitcast = [&](SDValue Op) {
7679       if (Op.getOpcode() == ISD::BITCAST &&
7680           Op.getOperand(0).getValueType() == VT)
7681         return SDValue(Op.getOperand(0));
7682       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7683           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7684         return DAG.getBitcast(VT, Op);
7685       return SDValue();
7686     };
7687 
7688     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7689     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7690     if (!(SV0 && SV1))
7691       return SDValue();
7692 
7693     int MaskScale =
7694         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7695     SmallVector<int, 8> NewMask;
7696     for (int M : SVN->getMask())
7697       for (int i = 0; i != MaskScale; ++i)
7698         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7699 
7700     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7701     if (!LegalMask) {
7702       std::swap(SV0, SV1);
7703       ShuffleVectorSDNode::commuteMask(NewMask);
7704       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7705     }
7706 
7707     if (LegalMask)
7708       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7709   }
7710 
7711   return SDValue();
7712 }
7713 
7714 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7715   EVT VT = N->getValueType(0);
7716   return CombineConsecutiveLoads(N, VT);
7717 }
7718 
7719 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7720 /// operands. DstEltVT indicates the destination element value type.
7721 SDValue DAGCombiner::
7722 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7723   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7724 
7725   // If this is already the right type, we're done.
7726   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7727 
7728   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7729   unsigned DstBitSize = DstEltVT.getSizeInBits();
7730 
7731   // If this is a conversion of N elements of one type to N elements of another
7732   // type, convert each element.  This handles FP<->INT cases.
7733   if (SrcBitSize == DstBitSize) {
7734     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7735                               BV->getValueType(0).getVectorNumElements());
7736 
7737     // Due to the FP element handling below calling this routine recursively,
7738     // we can end up with a scalar-to-vector node here.
7739     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7740       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7741                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7742 
7743     SmallVector<SDValue, 8> Ops;
7744     for (SDValue Op : BV->op_values()) {
7745       // If the vector element type is not legal, the BUILD_VECTOR operands
7746       // are promoted and implicitly truncated.  Make that explicit here.
7747       if (Op.getValueType() != SrcEltVT)
7748         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7749       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7750       AddToWorklist(Ops.back().getNode());
7751     }
7752     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7753   }
7754 
7755   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7756   // handle annoying details of growing/shrinking FP values, we convert them to
7757   // int first.
7758   if (SrcEltVT.isFloatingPoint()) {
7759     // Convert the input float vector to a int vector where the elements are the
7760     // same sizes.
7761     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7762     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7763     SrcEltVT = IntVT;
7764   }
7765 
7766   // Now we know the input is an integer vector.  If the output is a FP type,
7767   // convert to integer first, then to FP of the right size.
7768   if (DstEltVT.isFloatingPoint()) {
7769     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7770     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7771 
7772     // Next, convert to FP elements of the same size.
7773     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7774   }
7775 
7776   SDLoc DL(BV);
7777 
7778   // Okay, we know the src/dst types are both integers of differing types.
7779   // Handling growing first.
7780   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7781   if (SrcBitSize < DstBitSize) {
7782     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7783 
7784     SmallVector<SDValue, 8> Ops;
7785     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7786          i += NumInputsPerOutput) {
7787       bool isLE = DAG.getDataLayout().isLittleEndian();
7788       APInt NewBits = APInt(DstBitSize, 0);
7789       bool EltIsUndef = true;
7790       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7791         // Shift the previously computed bits over.
7792         NewBits <<= SrcBitSize;
7793         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7794         if (Op.isUndef()) continue;
7795         EltIsUndef = false;
7796 
7797         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7798                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7799       }
7800 
7801       if (EltIsUndef)
7802         Ops.push_back(DAG.getUNDEF(DstEltVT));
7803       else
7804         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7805     }
7806 
7807     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7808     return DAG.getBuildVector(VT, DL, Ops);
7809   }
7810 
7811   // Finally, this must be the case where we are shrinking elements: each input
7812   // turns into multiple outputs.
7813   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7814   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7815                             NumOutputsPerInput*BV->getNumOperands());
7816   SmallVector<SDValue, 8> Ops;
7817 
7818   for (const SDValue &Op : BV->op_values()) {
7819     if (Op.isUndef()) {
7820       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7821       continue;
7822     }
7823 
7824     APInt OpVal = cast<ConstantSDNode>(Op)->
7825                   getAPIntValue().zextOrTrunc(SrcBitSize);
7826 
7827     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7828       APInt ThisVal = OpVal.trunc(DstBitSize);
7829       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7830       OpVal = OpVal.lshr(DstBitSize);
7831     }
7832 
7833     // For big endian targets, swap the order of the pieces of each element.
7834     if (DAG.getDataLayout().isBigEndian())
7835       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7836   }
7837 
7838   return DAG.getBuildVector(VT, DL, Ops);
7839 }
7840 
7841 /// Try to perform FMA combining on a given FADD node.
7842 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7843   SDValue N0 = N->getOperand(0);
7844   SDValue N1 = N->getOperand(1);
7845   EVT VT = N->getValueType(0);
7846   SDLoc SL(N);
7847 
7848   const TargetOptions &Options = DAG.getTarget().Options;
7849   bool AllowFusion =
7850       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7851 
7852   // Floating-point multiply-add with intermediate rounding.
7853   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7854 
7855   // Floating-point multiply-add without intermediate rounding.
7856   bool HasFMA =
7857       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7858       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7859 
7860   // No valid opcode, do not combine.
7861   if (!HasFMAD && !HasFMA)
7862     return SDValue();
7863 
7864   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7865   ;
7866   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7867     return SDValue();
7868 
7869   // Always prefer FMAD to FMA for precision.
7870   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7871   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7872   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7873 
7874   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7875   // prefer to fold the multiply with fewer uses.
7876   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7877       N1.getOpcode() == ISD::FMUL) {
7878     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7879       std::swap(N0, N1);
7880   }
7881 
7882   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7883   if (N0.getOpcode() == ISD::FMUL &&
7884       (Aggressive || N0->hasOneUse())) {
7885     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7886                        N0.getOperand(0), N0.getOperand(1), N1);
7887   }
7888 
7889   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7890   // Note: Commutes FADD operands.
7891   if (N1.getOpcode() == ISD::FMUL &&
7892       (Aggressive || N1->hasOneUse())) {
7893     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7894                        N1.getOperand(0), N1.getOperand(1), N0);
7895   }
7896 
7897   // Look through FP_EXTEND nodes to do more combining.
7898   if (AllowFusion && LookThroughFPExt) {
7899     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7900     if (N0.getOpcode() == ISD::FP_EXTEND) {
7901       SDValue N00 = N0.getOperand(0);
7902       if (N00.getOpcode() == ISD::FMUL)
7903         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7904                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7905                                        N00.getOperand(0)),
7906                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7907                                        N00.getOperand(1)), N1);
7908     }
7909 
7910     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7911     // Note: Commutes FADD operands.
7912     if (N1.getOpcode() == ISD::FP_EXTEND) {
7913       SDValue N10 = N1.getOperand(0);
7914       if (N10.getOpcode() == ISD::FMUL)
7915         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7916                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7917                                        N10.getOperand(0)),
7918                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7919                                        N10.getOperand(1)), N0);
7920     }
7921   }
7922 
7923   // More folding opportunities when target permits.
7924   if ((AllowFusion || HasFMAD)  && Aggressive) {
7925     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7926     if (N0.getOpcode() == PreferredFusedOpcode &&
7927         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7928       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7929                          N0.getOperand(0), N0.getOperand(1),
7930                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7931                                      N0.getOperand(2).getOperand(0),
7932                                      N0.getOperand(2).getOperand(1),
7933                                      N1));
7934     }
7935 
7936     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7937     if (N1->getOpcode() == PreferredFusedOpcode &&
7938         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7939       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7940                          N1.getOperand(0), N1.getOperand(1),
7941                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7942                                      N1.getOperand(2).getOperand(0),
7943                                      N1.getOperand(2).getOperand(1),
7944                                      N0));
7945     }
7946 
7947     if (AllowFusion && LookThroughFPExt) {
7948       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7949       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7950       auto FoldFAddFMAFPExtFMul = [&] (
7951           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7952         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7953                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7954                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7955                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7956                                        Z));
7957       };
7958       if (N0.getOpcode() == PreferredFusedOpcode) {
7959         SDValue N02 = N0.getOperand(2);
7960         if (N02.getOpcode() == ISD::FP_EXTEND) {
7961           SDValue N020 = N02.getOperand(0);
7962           if (N020.getOpcode() == ISD::FMUL)
7963             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7964                                         N020.getOperand(0), N020.getOperand(1),
7965                                         N1);
7966         }
7967       }
7968 
7969       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7970       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7971       // FIXME: This turns two single-precision and one double-precision
7972       // operation into two double-precision operations, which might not be
7973       // interesting for all targets, especially GPUs.
7974       auto FoldFAddFPExtFMAFMul = [&] (
7975           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7976         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7977                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7978                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7979                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7980                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7981                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7982                                        Z));
7983       };
7984       if (N0.getOpcode() == ISD::FP_EXTEND) {
7985         SDValue N00 = N0.getOperand(0);
7986         if (N00.getOpcode() == PreferredFusedOpcode) {
7987           SDValue N002 = N00.getOperand(2);
7988           if (N002.getOpcode() == ISD::FMUL)
7989             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7990                                         N002.getOperand(0), N002.getOperand(1),
7991                                         N1);
7992         }
7993       }
7994 
7995       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7996       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7997       if (N1.getOpcode() == PreferredFusedOpcode) {
7998         SDValue N12 = N1.getOperand(2);
7999         if (N12.getOpcode() == ISD::FP_EXTEND) {
8000           SDValue N120 = N12.getOperand(0);
8001           if (N120.getOpcode() == ISD::FMUL)
8002             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8003                                         N120.getOperand(0), N120.getOperand(1),
8004                                         N0);
8005         }
8006       }
8007 
8008       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8009       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8010       // FIXME: This turns two single-precision and one double-precision
8011       // operation into two double-precision operations, which might not be
8012       // interesting for all targets, especially GPUs.
8013       if (N1.getOpcode() == ISD::FP_EXTEND) {
8014         SDValue N10 = N1.getOperand(0);
8015         if (N10.getOpcode() == PreferredFusedOpcode) {
8016           SDValue N102 = N10.getOperand(2);
8017           if (N102.getOpcode() == ISD::FMUL)
8018             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8019                                         N102.getOperand(0), N102.getOperand(1),
8020                                         N0);
8021         }
8022       }
8023     }
8024   }
8025 
8026   return SDValue();
8027 }
8028 
8029 /// Try to perform FMA combining on a given FSUB node.
8030 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8031   SDValue N0 = N->getOperand(0);
8032   SDValue N1 = N->getOperand(1);
8033   EVT VT = N->getValueType(0);
8034   SDLoc SL(N);
8035 
8036   const TargetOptions &Options = DAG.getTarget().Options;
8037   bool AllowFusion =
8038       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8039 
8040   // Floating-point multiply-add with intermediate rounding.
8041   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8042 
8043   // Floating-point multiply-add without intermediate rounding.
8044   bool HasFMA =
8045       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8046       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8047 
8048   // No valid opcode, do not combine.
8049   if (!HasFMAD && !HasFMA)
8050     return SDValue();
8051 
8052   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8053   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8054     return SDValue();
8055 
8056   // Always prefer FMAD to FMA for precision.
8057   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8058   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8059   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8060 
8061   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8062   if (N0.getOpcode() == ISD::FMUL &&
8063       (Aggressive || N0->hasOneUse())) {
8064     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8065                        N0.getOperand(0), N0.getOperand(1),
8066                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8067   }
8068 
8069   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8070   // Note: Commutes FSUB operands.
8071   if (N1.getOpcode() == ISD::FMUL &&
8072       (Aggressive || N1->hasOneUse()))
8073     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8074                        DAG.getNode(ISD::FNEG, SL, VT,
8075                                    N1.getOperand(0)),
8076                        N1.getOperand(1), N0);
8077 
8078   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8079   if (N0.getOpcode() == ISD::FNEG &&
8080       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8081       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8082     SDValue N00 = N0.getOperand(0).getOperand(0);
8083     SDValue N01 = N0.getOperand(0).getOperand(1);
8084     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8085                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8086                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8087   }
8088 
8089   // Look through FP_EXTEND nodes to do more combining.
8090   if (AllowFusion && LookThroughFPExt) {
8091     // fold (fsub (fpext (fmul x, y)), z)
8092     //   -> (fma (fpext x), (fpext y), (fneg z))
8093     if (N0.getOpcode() == ISD::FP_EXTEND) {
8094       SDValue N00 = N0.getOperand(0);
8095       if (N00.getOpcode() == ISD::FMUL)
8096         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8097                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8098                                        N00.getOperand(0)),
8099                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8100                                        N00.getOperand(1)),
8101                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8102     }
8103 
8104     // fold (fsub x, (fpext (fmul y, z)))
8105     //   -> (fma (fneg (fpext y)), (fpext z), x)
8106     // Note: Commutes FSUB operands.
8107     if (N1.getOpcode() == ISD::FP_EXTEND) {
8108       SDValue N10 = N1.getOperand(0);
8109       if (N10.getOpcode() == ISD::FMUL)
8110         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8111                            DAG.getNode(ISD::FNEG, SL, VT,
8112                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8113                                                    N10.getOperand(0))),
8114                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8115                                        N10.getOperand(1)),
8116                            N0);
8117     }
8118 
8119     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8120     //   -> (fneg (fma (fpext x), (fpext y), z))
8121     // Note: This could be removed with appropriate canonicalization of the
8122     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8123     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8124     // from implementing the canonicalization in visitFSUB.
8125     if (N0.getOpcode() == ISD::FP_EXTEND) {
8126       SDValue N00 = N0.getOperand(0);
8127       if (N00.getOpcode() == ISD::FNEG) {
8128         SDValue N000 = N00.getOperand(0);
8129         if (N000.getOpcode() == ISD::FMUL) {
8130           return DAG.getNode(ISD::FNEG, SL, VT,
8131                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8132                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8133                                                      N000.getOperand(0)),
8134                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8135                                                      N000.getOperand(1)),
8136                                          N1));
8137         }
8138       }
8139     }
8140 
8141     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8142     //   -> (fneg (fma (fpext x)), (fpext y), z)
8143     // Note: This could be removed with appropriate canonicalization of the
8144     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8145     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8146     // from implementing the canonicalization in visitFSUB.
8147     if (N0.getOpcode() == ISD::FNEG) {
8148       SDValue N00 = N0.getOperand(0);
8149       if (N00.getOpcode() == ISD::FP_EXTEND) {
8150         SDValue N000 = N00.getOperand(0);
8151         if (N000.getOpcode() == ISD::FMUL) {
8152           return DAG.getNode(ISD::FNEG, SL, VT,
8153                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8154                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8155                                                      N000.getOperand(0)),
8156                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8157                                                      N000.getOperand(1)),
8158                                          N1));
8159         }
8160       }
8161     }
8162 
8163   }
8164 
8165   // More folding opportunities when target permits.
8166   if ((AllowFusion || HasFMAD) && Aggressive) {
8167     // fold (fsub (fma x, y, (fmul u, v)), z)
8168     //   -> (fma x, y (fma u, v, (fneg z)))
8169     if (N0.getOpcode() == PreferredFusedOpcode &&
8170         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8171       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8172                          N0.getOperand(0), N0.getOperand(1),
8173                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8174                                      N0.getOperand(2).getOperand(0),
8175                                      N0.getOperand(2).getOperand(1),
8176                                      DAG.getNode(ISD::FNEG, SL, VT,
8177                                                  N1)));
8178     }
8179 
8180     // fold (fsub x, (fma y, z, (fmul u, v)))
8181     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8182     if (N1.getOpcode() == PreferredFusedOpcode &&
8183         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8184       SDValue N20 = N1.getOperand(2).getOperand(0);
8185       SDValue N21 = N1.getOperand(2).getOperand(1);
8186       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8187                          DAG.getNode(ISD::FNEG, SL, VT,
8188                                      N1.getOperand(0)),
8189                          N1.getOperand(1),
8190                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8191                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8192 
8193                                      N21, N0));
8194     }
8195 
8196     if (AllowFusion && LookThroughFPExt) {
8197       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8198       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8199       if (N0.getOpcode() == PreferredFusedOpcode) {
8200         SDValue N02 = N0.getOperand(2);
8201         if (N02.getOpcode() == ISD::FP_EXTEND) {
8202           SDValue N020 = N02.getOperand(0);
8203           if (N020.getOpcode() == ISD::FMUL)
8204             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8205                                N0.getOperand(0), N0.getOperand(1),
8206                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8207                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8208                                                        N020.getOperand(0)),
8209                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8210                                                        N020.getOperand(1)),
8211                                            DAG.getNode(ISD::FNEG, SL, VT,
8212                                                        N1)));
8213         }
8214       }
8215 
8216       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8217       //   -> (fma (fpext x), (fpext y),
8218       //           (fma (fpext u), (fpext v), (fneg z)))
8219       // FIXME: This turns two single-precision and one double-precision
8220       // operation into two double-precision operations, which might not be
8221       // interesting for all targets, especially GPUs.
8222       if (N0.getOpcode() == ISD::FP_EXTEND) {
8223         SDValue N00 = N0.getOperand(0);
8224         if (N00.getOpcode() == PreferredFusedOpcode) {
8225           SDValue N002 = N00.getOperand(2);
8226           if (N002.getOpcode() == ISD::FMUL)
8227             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8228                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8229                                            N00.getOperand(0)),
8230                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8231                                            N00.getOperand(1)),
8232                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8233                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8234                                                        N002.getOperand(0)),
8235                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8236                                                        N002.getOperand(1)),
8237                                            DAG.getNode(ISD::FNEG, SL, VT,
8238                                                        N1)));
8239         }
8240       }
8241 
8242       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8243       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8244       if (N1.getOpcode() == PreferredFusedOpcode &&
8245         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8246         SDValue N120 = N1.getOperand(2).getOperand(0);
8247         if (N120.getOpcode() == ISD::FMUL) {
8248           SDValue N1200 = N120.getOperand(0);
8249           SDValue N1201 = N120.getOperand(1);
8250           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8251                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8252                              N1.getOperand(1),
8253                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8254                                          DAG.getNode(ISD::FNEG, SL, VT,
8255                                              DAG.getNode(ISD::FP_EXTEND, SL,
8256                                                          VT, N1200)),
8257                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8258                                                      N1201),
8259                                          N0));
8260         }
8261       }
8262 
8263       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8264       //   -> (fma (fneg (fpext y)), (fpext z),
8265       //           (fma (fneg (fpext u)), (fpext v), x))
8266       // FIXME: This turns two single-precision and one double-precision
8267       // operation into two double-precision operations, which might not be
8268       // interesting for all targets, especially GPUs.
8269       if (N1.getOpcode() == ISD::FP_EXTEND &&
8270         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8271         SDValue N100 = N1.getOperand(0).getOperand(0);
8272         SDValue N101 = N1.getOperand(0).getOperand(1);
8273         SDValue N102 = N1.getOperand(0).getOperand(2);
8274         if (N102.getOpcode() == ISD::FMUL) {
8275           SDValue N1020 = N102.getOperand(0);
8276           SDValue N1021 = N102.getOperand(1);
8277           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8278                              DAG.getNode(ISD::FNEG, SL, VT,
8279                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8280                                                      N100)),
8281                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8282                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8283                                          DAG.getNode(ISD::FNEG, SL, VT,
8284                                              DAG.getNode(ISD::FP_EXTEND, SL,
8285                                                          VT, N1020)),
8286                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8287                                                      N1021),
8288                                          N0));
8289         }
8290       }
8291     }
8292   }
8293 
8294   return SDValue();
8295 }
8296 
8297 /// Try to perform FMA combining on a given FMUL node.
8298 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8299   SDValue N0 = N->getOperand(0);
8300   SDValue N1 = N->getOperand(1);
8301   EVT VT = N->getValueType(0);
8302   SDLoc SL(N);
8303 
8304   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8305 
8306   const TargetOptions &Options = DAG.getTarget().Options;
8307   bool AllowFusion =
8308       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8309 
8310   // Floating-point multiply-add with intermediate rounding.
8311   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8312 
8313   // Floating-point multiply-add without intermediate rounding.
8314   bool HasFMA =
8315       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8316       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8317 
8318   // No valid opcode, do not combine.
8319   if (!HasFMAD && !HasFMA)
8320     return SDValue();
8321 
8322   // Always prefer FMAD to FMA for precision.
8323   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8324   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8325 
8326   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8327   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8328   auto FuseFADD = [&](SDValue X, SDValue Y) {
8329     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8330       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8331       if (XC1 && XC1->isExactlyValue(+1.0))
8332         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8333       if (XC1 && XC1->isExactlyValue(-1.0))
8334         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8335                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8336     }
8337     return SDValue();
8338   };
8339 
8340   if (SDValue FMA = FuseFADD(N0, N1))
8341     return FMA;
8342   if (SDValue FMA = FuseFADD(N1, N0))
8343     return FMA;
8344 
8345   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8346   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8347   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8348   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8349   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8350     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8351       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8352       if (XC0 && XC0->isExactlyValue(+1.0))
8353         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8354                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8355                            Y);
8356       if (XC0 && XC0->isExactlyValue(-1.0))
8357         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8358                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8359                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8360 
8361       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8362       if (XC1 && XC1->isExactlyValue(+1.0))
8363         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8364                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8365       if (XC1 && XC1->isExactlyValue(-1.0))
8366         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8367     }
8368     return SDValue();
8369   };
8370 
8371   if (SDValue FMA = FuseFSUB(N0, N1))
8372     return FMA;
8373   if (SDValue FMA = FuseFSUB(N1, N0))
8374     return FMA;
8375 
8376   return SDValue();
8377 }
8378 
8379 SDValue DAGCombiner::visitFADD(SDNode *N) {
8380   SDValue N0 = N->getOperand(0);
8381   SDValue N1 = N->getOperand(1);
8382   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8383   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8384   EVT VT = N->getValueType(0);
8385   SDLoc DL(N);
8386   const TargetOptions &Options = DAG.getTarget().Options;
8387   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8388 
8389   // fold vector ops
8390   if (VT.isVector())
8391     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8392       return FoldedVOp;
8393 
8394   // fold (fadd c1, c2) -> c1 + c2
8395   if (N0CFP && N1CFP)
8396     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8397 
8398   // canonicalize constant to RHS
8399   if (N0CFP && !N1CFP)
8400     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8401 
8402   // fold (fadd A, (fneg B)) -> (fsub A, B)
8403   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8404       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8405     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8406                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8407 
8408   // fold (fadd (fneg A), B) -> (fsub B, A)
8409   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8410       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8411     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8412                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8413 
8414   // If 'unsafe math' is enabled, fold lots of things.
8415   if (Options.UnsafeFPMath) {
8416     // No FP constant should be created after legalization as Instruction
8417     // Selection pass has a hard time dealing with FP constants.
8418     bool AllowNewConst = (Level < AfterLegalizeDAG);
8419 
8420     // fold (fadd A, 0) -> A
8421     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8422       if (N1C->isZero())
8423         return N0;
8424 
8425     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8426     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8427         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8428       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8429                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8430                                      Flags),
8431                          Flags);
8432 
8433     // If allowed, fold (fadd (fneg x), x) -> 0.0
8434     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8435       return DAG.getConstantFP(0.0, DL, VT);
8436 
8437     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8438     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8439       return DAG.getConstantFP(0.0, DL, VT);
8440 
8441     // We can fold chains of FADD's of the same value into multiplications.
8442     // This transform is not safe in general because we are reducing the number
8443     // of rounding steps.
8444     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8445       if (N0.getOpcode() == ISD::FMUL) {
8446         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8447         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8448 
8449         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8450         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8451           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8452                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8453           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8454         }
8455 
8456         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8457         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8458             N1.getOperand(0) == N1.getOperand(1) &&
8459             N0.getOperand(0) == N1.getOperand(0)) {
8460           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8461                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8462           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8463         }
8464       }
8465 
8466       if (N1.getOpcode() == ISD::FMUL) {
8467         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8468         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8469 
8470         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8471         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8472           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8473                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8474           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8475         }
8476 
8477         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8478         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8479             N0.getOperand(0) == N0.getOperand(1) &&
8480             N1.getOperand(0) == N0.getOperand(0)) {
8481           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8482                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8483           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8484         }
8485       }
8486 
8487       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8488         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8489         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8490         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8491             (N0.getOperand(0) == N1)) {
8492           return DAG.getNode(ISD::FMUL, DL, VT,
8493                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8494         }
8495       }
8496 
8497       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8498         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8499         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8500         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8501             N1.getOperand(0) == N0) {
8502           return DAG.getNode(ISD::FMUL, DL, VT,
8503                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8504         }
8505       }
8506 
8507       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8508       if (AllowNewConst &&
8509           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8510           N0.getOperand(0) == N0.getOperand(1) &&
8511           N1.getOperand(0) == N1.getOperand(1) &&
8512           N0.getOperand(0) == N1.getOperand(0)) {
8513         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8514                            DAG.getConstantFP(4.0, DL, VT), Flags);
8515       }
8516     }
8517   } // enable-unsafe-fp-math
8518 
8519   // FADD -> FMA combines:
8520   if (SDValue Fused = visitFADDForFMACombine(N)) {
8521     AddToWorklist(Fused.getNode());
8522     return Fused;
8523   }
8524   return SDValue();
8525 }
8526 
8527 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8528   SDValue N0 = N->getOperand(0);
8529   SDValue N1 = N->getOperand(1);
8530   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8531   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8532   EVT VT = N->getValueType(0);
8533   SDLoc DL(N);
8534   const TargetOptions &Options = DAG.getTarget().Options;
8535   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8536 
8537   // fold vector ops
8538   if (VT.isVector())
8539     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8540       return FoldedVOp;
8541 
8542   // fold (fsub c1, c2) -> c1-c2
8543   if (N0CFP && N1CFP)
8544     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
8545 
8546   // fold (fsub A, (fneg B)) -> (fadd A, B)
8547   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8548     return DAG.getNode(ISD::FADD, DL, VT, N0,
8549                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8550 
8551   // If 'unsafe math' is enabled, fold lots of things.
8552   if (Options.UnsafeFPMath) {
8553     // (fsub A, 0) -> A
8554     if (N1CFP && N1CFP->isZero())
8555       return N0;
8556 
8557     // (fsub 0, B) -> -B
8558     if (N0CFP && N0CFP->isZero()) {
8559       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8560         return GetNegatedExpression(N1, DAG, LegalOperations);
8561       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8562         return DAG.getNode(ISD::FNEG, DL, VT, N1);
8563     }
8564 
8565     // (fsub x, x) -> 0.0
8566     if (N0 == N1)
8567       return DAG.getConstantFP(0.0f, DL, VT);
8568 
8569     // (fsub x, (fadd x, y)) -> (fneg y)
8570     // (fsub x, (fadd y, x)) -> (fneg y)
8571     if (N1.getOpcode() == ISD::FADD) {
8572       SDValue N10 = N1->getOperand(0);
8573       SDValue N11 = N1->getOperand(1);
8574 
8575       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8576         return GetNegatedExpression(N11, DAG, LegalOperations);
8577 
8578       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8579         return GetNegatedExpression(N10, DAG, LegalOperations);
8580     }
8581   }
8582 
8583   // FSUB -> FMA combines:
8584   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8585     AddToWorklist(Fused.getNode());
8586     return Fused;
8587   }
8588 
8589   return SDValue();
8590 }
8591 
8592 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8593   SDValue N0 = N->getOperand(0);
8594   SDValue N1 = N->getOperand(1);
8595   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8596   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8597   EVT VT = N->getValueType(0);
8598   SDLoc DL(N);
8599   const TargetOptions &Options = DAG.getTarget().Options;
8600   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8601 
8602   // fold vector ops
8603   if (VT.isVector()) {
8604     // This just handles C1 * C2 for vectors. Other vector folds are below.
8605     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8606       return FoldedVOp;
8607   }
8608 
8609   // fold (fmul c1, c2) -> c1*c2
8610   if (N0CFP && N1CFP)
8611     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8612 
8613   // canonicalize constant to RHS
8614   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8615      !isConstantFPBuildVectorOrConstantFP(N1))
8616     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8617 
8618   // fold (fmul A, 1.0) -> A
8619   if (N1CFP && N1CFP->isExactlyValue(1.0))
8620     return N0;
8621 
8622   if (Options.UnsafeFPMath) {
8623     // fold (fmul A, 0) -> 0
8624     if (N1CFP && N1CFP->isZero())
8625       return N1;
8626 
8627     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8628     if (N0.getOpcode() == ISD::FMUL) {
8629       // Fold scalars or any vector constants (not just splats).
8630       // This fold is done in general by InstCombine, but extra fmul insts
8631       // may have been generated during lowering.
8632       SDValue N00 = N0.getOperand(0);
8633       SDValue N01 = N0.getOperand(1);
8634       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8635       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8636       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8637 
8638       // Check 1: Make sure that the first operand of the inner multiply is NOT
8639       // a constant. Otherwise, we may induce infinite looping.
8640       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8641         // Check 2: Make sure that the second operand of the inner multiply and
8642         // the second operand of the outer multiply are constants.
8643         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8644             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8645           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8646           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8647         }
8648       }
8649     }
8650 
8651     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8652     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8653     // during an early run of DAGCombiner can prevent folding with fmuls
8654     // inserted during lowering.
8655     if (N0.getOpcode() == ISD::FADD &&
8656         (N0.getOperand(0) == N0.getOperand(1)) &&
8657         N0.hasOneUse()) {
8658       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8659       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8660       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8661     }
8662   }
8663 
8664   // fold (fmul X, 2.0) -> (fadd X, X)
8665   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8666     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8667 
8668   // fold (fmul X, -1.0) -> (fneg X)
8669   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8670     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8671       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8672 
8673   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8674   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8675     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8676       // Both can be negated for free, check to see if at least one is cheaper
8677       // negated.
8678       if (LHSNeg == 2 || RHSNeg == 2)
8679         return DAG.getNode(ISD::FMUL, DL, VT,
8680                            GetNegatedExpression(N0, DAG, LegalOperations),
8681                            GetNegatedExpression(N1, DAG, LegalOperations),
8682                            Flags);
8683     }
8684   }
8685 
8686   // FMUL -> FMA combines:
8687   if (SDValue Fused = visitFMULForFMACombine(N)) {
8688     AddToWorklist(Fused.getNode());
8689     return Fused;
8690   }
8691 
8692   return SDValue();
8693 }
8694 
8695 SDValue DAGCombiner::visitFMA(SDNode *N) {
8696   SDValue N0 = N->getOperand(0);
8697   SDValue N1 = N->getOperand(1);
8698   SDValue N2 = N->getOperand(2);
8699   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8700   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8701   EVT VT = N->getValueType(0);
8702   SDLoc DL(N);
8703   const TargetOptions &Options = DAG.getTarget().Options;
8704 
8705   // Constant fold FMA.
8706   if (isa<ConstantFPSDNode>(N0) &&
8707       isa<ConstantFPSDNode>(N1) &&
8708       isa<ConstantFPSDNode>(N2)) {
8709     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
8710   }
8711 
8712   if (Options.UnsafeFPMath) {
8713     if (N0CFP && N0CFP->isZero())
8714       return N2;
8715     if (N1CFP && N1CFP->isZero())
8716       return N2;
8717   }
8718   // TODO: The FMA node should have flags that propagate to these nodes.
8719   if (N0CFP && N0CFP->isExactlyValue(1.0))
8720     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8721   if (N1CFP && N1CFP->isExactlyValue(1.0))
8722     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8723 
8724   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8725   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8726      !isConstantFPBuildVectorOrConstantFP(N1))
8727     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8728 
8729   // TODO: FMA nodes should have flags that propagate to the created nodes.
8730   // For now, create a Flags object for use with all unsafe math transforms.
8731   SDNodeFlags Flags;
8732   Flags.setUnsafeAlgebra(true);
8733 
8734   if (Options.UnsafeFPMath) {
8735     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8736     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8737         isConstantFPBuildVectorOrConstantFP(N1) &&
8738         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8739       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8740                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
8741                                      &Flags), &Flags);
8742     }
8743 
8744     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8745     if (N0.getOpcode() == ISD::FMUL &&
8746         isConstantFPBuildVectorOrConstantFP(N1) &&
8747         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8748       return DAG.getNode(ISD::FMA, DL, VT,
8749                          N0.getOperand(0),
8750                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
8751                                      &Flags),
8752                          N2);
8753     }
8754   }
8755 
8756   // (fma x, 1, y) -> (fadd x, y)
8757   // (fma x, -1, y) -> (fadd (fneg x), y)
8758   if (N1CFP) {
8759     if (N1CFP->isExactlyValue(1.0))
8760       // TODO: The FMA node should have flags that propagate to this node.
8761       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
8762 
8763     if (N1CFP->isExactlyValue(-1.0) &&
8764         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8765       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
8766       AddToWorklist(RHSNeg.getNode());
8767       // TODO: The FMA node should have flags that propagate to this node.
8768       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
8769     }
8770   }
8771 
8772   if (Options.UnsafeFPMath) {
8773     // (fma x, c, x) -> (fmul x, (c+1))
8774     if (N1CFP && N0 == N2) {
8775       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8776                          DAG.getNode(ISD::FADD, DL, VT, N1,
8777                                      DAG.getConstantFP(1.0, DL, VT), &Flags),
8778                          &Flags);
8779     }
8780 
8781     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8782     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8783       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8784                          DAG.getNode(ISD::FADD, DL, VT, N1,
8785                                      DAG.getConstantFP(-1.0, DL, VT), &Flags),
8786                          &Flags);
8787     }
8788   }
8789 
8790   return SDValue();
8791 }
8792 
8793 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8794 // reciprocal.
8795 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8796 // Notice that this is not always beneficial. One reason is different target
8797 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8798 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8799 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8800 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8801   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8802   const SDNodeFlags *Flags = N->getFlags();
8803   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8804     return SDValue();
8805 
8806   // Skip if current node is a reciprocal.
8807   SDValue N0 = N->getOperand(0);
8808   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8809   if (N0CFP && N0CFP->isExactlyValue(1.0))
8810     return SDValue();
8811 
8812   // Exit early if the target does not want this transform or if there can't
8813   // possibly be enough uses of the divisor to make the transform worthwhile.
8814   SDValue N1 = N->getOperand(1);
8815   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8816   if (!MinUses || N1->use_size() < MinUses)
8817     return SDValue();
8818 
8819   // Find all FDIV users of the same divisor.
8820   // Use a set because duplicates may be present in the user list.
8821   SetVector<SDNode *> Users;
8822   for (auto *U : N1->uses()) {
8823     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8824       // This division is eligible for optimization only if global unsafe math
8825       // is enabled or if this division allows reciprocal formation.
8826       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8827         Users.insert(U);
8828     }
8829   }
8830 
8831   // Now that we have the actual number of divisor uses, make sure it meets
8832   // the minimum threshold specified by the target.
8833   if (Users.size() < MinUses)
8834     return SDValue();
8835 
8836   EVT VT = N->getValueType(0);
8837   SDLoc DL(N);
8838   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8839   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8840 
8841   // Dividend / Divisor -> Dividend * Reciprocal
8842   for (auto *U : Users) {
8843     SDValue Dividend = U->getOperand(0);
8844     if (Dividend != FPOne) {
8845       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8846                                     Reciprocal, Flags);
8847       CombineTo(U, NewNode);
8848     } else if (U != Reciprocal.getNode()) {
8849       // In the absence of fast-math-flags, this user node is always the
8850       // same node as Reciprocal, but with FMF they may be different nodes.
8851       CombineTo(U, Reciprocal);
8852     }
8853   }
8854   return SDValue(N, 0);  // N was replaced.
8855 }
8856 
8857 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8858   SDValue N0 = N->getOperand(0);
8859   SDValue N1 = N->getOperand(1);
8860   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8861   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8862   EVT VT = N->getValueType(0);
8863   SDLoc DL(N);
8864   const TargetOptions &Options = DAG.getTarget().Options;
8865   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8866 
8867   // fold vector ops
8868   if (VT.isVector())
8869     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8870       return FoldedVOp;
8871 
8872   // fold (fdiv c1, c2) -> c1/c2
8873   if (N0CFP && N1CFP)
8874     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8875 
8876   if (Options.UnsafeFPMath) {
8877     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8878     if (N1CFP) {
8879       // Compute the reciprocal 1.0 / c2.
8880       const APFloat &N1APF = N1CFP->getValueAPF();
8881       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8882       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8883       // Only do the transform if the reciprocal is a legal fp immediate that
8884       // isn't too nasty (eg NaN, denormal, ...).
8885       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8886           (!LegalOperations ||
8887            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8888            // backend)... we should handle this gracefully after Legalize.
8889            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8890            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8891            TLI.isFPImmLegal(Recip, VT)))
8892         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8893                            DAG.getConstantFP(Recip, DL, VT), Flags);
8894     }
8895 
8896     // If this FDIV is part of a reciprocal square root, it may be folded
8897     // into a target-specific square root estimate instruction.
8898     if (N1.getOpcode() == ISD::FSQRT) {
8899       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
8900         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8901       }
8902     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8903                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8904       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8905                                           Flags)) {
8906         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8907         AddToWorklist(RV.getNode());
8908         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8909       }
8910     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8911                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8912       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8913                                           Flags)) {
8914         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8915         AddToWorklist(RV.getNode());
8916         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8917       }
8918     } else if (N1.getOpcode() == ISD::FMUL) {
8919       // Look through an FMUL. Even though this won't remove the FDIV directly,
8920       // it's still worthwhile to get rid of the FSQRT if possible.
8921       SDValue SqrtOp;
8922       SDValue OtherOp;
8923       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8924         SqrtOp = N1.getOperand(0);
8925         OtherOp = N1.getOperand(1);
8926       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8927         SqrtOp = N1.getOperand(1);
8928         OtherOp = N1.getOperand(0);
8929       }
8930       if (SqrtOp.getNode()) {
8931         // We found a FSQRT, so try to make this fold:
8932         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8933         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8934           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8935           AddToWorklist(RV.getNode());
8936           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8937         }
8938       }
8939     }
8940 
8941     // Fold into a reciprocal estimate and multiply instead of a real divide.
8942     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8943       AddToWorklist(RV.getNode());
8944       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8945     }
8946   }
8947 
8948   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8949   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8950     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8951       // Both can be negated for free, check to see if at least one is cheaper
8952       // negated.
8953       if (LHSNeg == 2 || RHSNeg == 2)
8954         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8955                            GetNegatedExpression(N0, DAG, LegalOperations),
8956                            GetNegatedExpression(N1, DAG, LegalOperations),
8957                            Flags);
8958     }
8959   }
8960 
8961   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8962     return CombineRepeatedDivisors;
8963 
8964   return SDValue();
8965 }
8966 
8967 SDValue DAGCombiner::visitFREM(SDNode *N) {
8968   SDValue N0 = N->getOperand(0);
8969   SDValue N1 = N->getOperand(1);
8970   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8971   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8972   EVT VT = N->getValueType(0);
8973 
8974   // fold (frem c1, c2) -> fmod(c1,c2)
8975   if (N0CFP && N1CFP)
8976     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8977                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8978 
8979   return SDValue();
8980 }
8981 
8982 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8983   if (!DAG.getTarget().Options.UnsafeFPMath)
8984     return SDValue();
8985 
8986   SDValue N0 = N->getOperand(0);
8987   if (TLI.isFsqrtCheap(N0, DAG))
8988     return SDValue();
8989 
8990   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8991   // For now, create a Flags object for use with all unsafe math transforms.
8992   SDNodeFlags Flags;
8993   Flags.setUnsafeAlgebra(true);
8994   return buildSqrtEstimate(N0, &Flags);
8995 }
8996 
8997 /// copysign(x, fp_extend(y)) -> copysign(x, y)
8998 /// copysign(x, fp_round(y)) -> copysign(x, y)
8999 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9000   SDValue N1 = N->getOperand(1);
9001   if ((N1.getOpcode() == ISD::FP_EXTEND ||
9002        N1.getOpcode() == ISD::FP_ROUND)) {
9003     // Do not optimize out type conversion of f128 type yet.
9004     // For some targets like x86_64, configuration is changed to keep one f128
9005     // value in one SSE register, but instruction selection cannot handle
9006     // FCOPYSIGN on SSE registers yet.
9007     EVT N1VT = N1->getValueType(0);
9008     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9009     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9010   }
9011   return false;
9012 }
9013 
9014 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9015   SDValue N0 = N->getOperand(0);
9016   SDValue N1 = N->getOperand(1);
9017   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9018   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9019   EVT VT = N->getValueType(0);
9020 
9021   if (N0CFP && N1CFP) // Constant fold
9022     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9023 
9024   if (N1CFP) {
9025     const APFloat &V = N1CFP->getValueAPF();
9026     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
9027     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9028     if (!V.isNegative()) {
9029       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9030         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9031     } else {
9032       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9033         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9034                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9035     }
9036   }
9037 
9038   // copysign(fabs(x), y) -> copysign(x, y)
9039   // copysign(fneg(x), y) -> copysign(x, y)
9040   // copysign(copysign(x,z), y) -> copysign(x, y)
9041   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9042       N0.getOpcode() == ISD::FCOPYSIGN)
9043     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9044 
9045   // copysign(x, abs(y)) -> abs(x)
9046   if (N1.getOpcode() == ISD::FABS)
9047     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9048 
9049   // copysign(x, copysign(y,z)) -> copysign(x, z)
9050   if (N1.getOpcode() == ISD::FCOPYSIGN)
9051     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9052 
9053   // copysign(x, fp_extend(y)) -> copysign(x, y)
9054   // copysign(x, fp_round(y)) -> copysign(x, y)
9055   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9056     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9057 
9058   return SDValue();
9059 }
9060 
9061 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9062   SDValue N0 = N->getOperand(0);
9063   EVT VT = N->getValueType(0);
9064   EVT OpVT = N0.getValueType();
9065 
9066   // fold (sint_to_fp c1) -> c1fp
9067   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9068       // ...but only if the target supports immediate floating-point values
9069       (!LegalOperations ||
9070        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9071     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9072 
9073   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9074   // but UINT_TO_FP is legal on this target, try to convert.
9075   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9076       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9077     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9078     if (DAG.SignBitIsZero(N0))
9079       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9080   }
9081 
9082   // The next optimizations are desirable only if SELECT_CC can be lowered.
9083   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9084     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9085     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9086         !VT.isVector() &&
9087         (!LegalOperations ||
9088          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9089       SDLoc DL(N);
9090       SDValue Ops[] =
9091         { N0.getOperand(0), N0.getOperand(1),
9092           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9093           N0.getOperand(2) };
9094       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9095     }
9096 
9097     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9098     //      (select_cc x, y, 1.0, 0.0,, cc)
9099     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9100         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9101         (!LegalOperations ||
9102          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9103       SDLoc DL(N);
9104       SDValue Ops[] =
9105         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9106           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9107           N0.getOperand(0).getOperand(2) };
9108       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9109     }
9110   }
9111 
9112   return SDValue();
9113 }
9114 
9115 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9116   SDValue N0 = N->getOperand(0);
9117   EVT VT = N->getValueType(0);
9118   EVT OpVT = N0.getValueType();
9119 
9120   // fold (uint_to_fp c1) -> c1fp
9121   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9122       // ...but only if the target supports immediate floating-point values
9123       (!LegalOperations ||
9124        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9125     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9126 
9127   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9128   // but SINT_TO_FP is legal on this target, try to convert.
9129   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9130       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9131     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9132     if (DAG.SignBitIsZero(N0))
9133       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9134   }
9135 
9136   // The next optimizations are desirable only if SELECT_CC can be lowered.
9137   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9138     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9139 
9140     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9141         (!LegalOperations ||
9142          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9143       SDLoc DL(N);
9144       SDValue Ops[] =
9145         { N0.getOperand(0), N0.getOperand(1),
9146           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9147           N0.getOperand(2) };
9148       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9149     }
9150   }
9151 
9152   return SDValue();
9153 }
9154 
9155 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9156 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9157   SDValue N0 = N->getOperand(0);
9158   EVT VT = N->getValueType(0);
9159 
9160   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9161     return SDValue();
9162 
9163   SDValue Src = N0.getOperand(0);
9164   EVT SrcVT = Src.getValueType();
9165   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9166   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9167 
9168   // We can safely assume the conversion won't overflow the output range,
9169   // because (for example) (uint8_t)18293.f is undefined behavior.
9170 
9171   // Since we can assume the conversion won't overflow, our decision as to
9172   // whether the input will fit in the float should depend on the minimum
9173   // of the input range and output range.
9174 
9175   // This means this is also safe for a signed input and unsigned output, since
9176   // a negative input would lead to undefined behavior.
9177   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9178   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9179   unsigned ActualSize = std::min(InputSize, OutputSize);
9180   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9181 
9182   // We can only fold away the float conversion if the input range can be
9183   // represented exactly in the float range.
9184   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9185     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9186       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9187                                                        : ISD::ZERO_EXTEND;
9188       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9189     }
9190     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9191       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9192     return DAG.getBitcast(VT, Src);
9193   }
9194   return SDValue();
9195 }
9196 
9197 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9198   SDValue N0 = N->getOperand(0);
9199   EVT VT = N->getValueType(0);
9200 
9201   // fold (fp_to_sint c1fp) -> c1
9202   if (isConstantFPBuildVectorOrConstantFP(N0))
9203     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9204 
9205   return FoldIntToFPToInt(N, DAG);
9206 }
9207 
9208 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9209   SDValue N0 = N->getOperand(0);
9210   EVT VT = N->getValueType(0);
9211 
9212   // fold (fp_to_uint c1fp) -> c1
9213   if (isConstantFPBuildVectorOrConstantFP(N0))
9214     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9215 
9216   return FoldIntToFPToInt(N, DAG);
9217 }
9218 
9219 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9220   SDValue N0 = N->getOperand(0);
9221   SDValue N1 = N->getOperand(1);
9222   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9223   EVT VT = N->getValueType(0);
9224 
9225   // fold (fp_round c1fp) -> c1fp
9226   if (N0CFP)
9227     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9228 
9229   // fold (fp_round (fp_extend x)) -> x
9230   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9231     return N0.getOperand(0);
9232 
9233   // fold (fp_round (fp_round x)) -> (fp_round x)
9234   if (N0.getOpcode() == ISD::FP_ROUND) {
9235     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9236     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9237 
9238     // Skip this folding if it results in an fp_round from f80 to f16.
9239     //
9240     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9241     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9242     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9243     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9244     // x86.
9245     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9246       return SDValue();
9247 
9248     // If the first fp_round isn't a value preserving truncation, it might
9249     // introduce a tie in the second fp_round, that wouldn't occur in the
9250     // single-step fp_round we want to fold to.
9251     // In other words, double rounding isn't the same as rounding.
9252     // Also, this is a value preserving truncation iff both fp_round's are.
9253     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9254       SDLoc DL(N);
9255       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9256                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9257     }
9258   }
9259 
9260   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9261   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9262     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9263                               N0.getOperand(0), N1);
9264     AddToWorklist(Tmp.getNode());
9265     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9266                        Tmp, N0.getOperand(1));
9267   }
9268 
9269   return SDValue();
9270 }
9271 
9272 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9273   SDValue N0 = N->getOperand(0);
9274   EVT VT = N->getValueType(0);
9275   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9276   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9277 
9278   // fold (fp_round_inreg c1fp) -> c1fp
9279   if (N0CFP && isTypeLegal(EVT)) {
9280     SDLoc DL(N);
9281     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9282     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9283   }
9284 
9285   return SDValue();
9286 }
9287 
9288 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9289   SDValue N0 = N->getOperand(0);
9290   EVT VT = N->getValueType(0);
9291 
9292   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9293   if (N->hasOneUse() &&
9294       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9295     return SDValue();
9296 
9297   // fold (fp_extend c1fp) -> c1fp
9298   if (isConstantFPBuildVectorOrConstantFP(N0))
9299     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9300 
9301   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9302   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9303       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9304     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9305 
9306   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9307   // value of X.
9308   if (N0.getOpcode() == ISD::FP_ROUND
9309       && N0.getNode()->getConstantOperandVal(1) == 1) {
9310     SDValue In = N0.getOperand(0);
9311     if (In.getValueType() == VT) return In;
9312     if (VT.bitsLT(In.getValueType()))
9313       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9314                          In, N0.getOperand(1));
9315     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9316   }
9317 
9318   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9319   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9320        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9321     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9322     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9323                                      LN0->getChain(),
9324                                      LN0->getBasePtr(), N0.getValueType(),
9325                                      LN0->getMemOperand());
9326     CombineTo(N, ExtLoad);
9327     CombineTo(N0.getNode(),
9328               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9329                           N0.getValueType(), ExtLoad,
9330                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9331               ExtLoad.getValue(1));
9332     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9333   }
9334 
9335   return SDValue();
9336 }
9337 
9338 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9339   SDValue N0 = N->getOperand(0);
9340   EVT VT = N->getValueType(0);
9341 
9342   // fold (fceil c1) -> fceil(c1)
9343   if (isConstantFPBuildVectorOrConstantFP(N0))
9344     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9345 
9346   return SDValue();
9347 }
9348 
9349 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9350   SDValue N0 = N->getOperand(0);
9351   EVT VT = N->getValueType(0);
9352 
9353   // fold (ftrunc c1) -> ftrunc(c1)
9354   if (isConstantFPBuildVectorOrConstantFP(N0))
9355     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9356 
9357   return SDValue();
9358 }
9359 
9360 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9361   SDValue N0 = N->getOperand(0);
9362   EVT VT = N->getValueType(0);
9363 
9364   // fold (ffloor c1) -> ffloor(c1)
9365   if (isConstantFPBuildVectorOrConstantFP(N0))
9366     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9367 
9368   return SDValue();
9369 }
9370 
9371 // FIXME: FNEG and FABS have a lot in common; refactor.
9372 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9373   SDValue N0 = N->getOperand(0);
9374   EVT VT = N->getValueType(0);
9375 
9376   // Constant fold FNEG.
9377   if (isConstantFPBuildVectorOrConstantFP(N0))
9378     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9379 
9380   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9381                          &DAG.getTarget().Options))
9382     return GetNegatedExpression(N0, DAG, LegalOperations);
9383 
9384   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9385   // constant pool values.
9386   if (!TLI.isFNegFree(VT) &&
9387       N0.getOpcode() == ISD::BITCAST &&
9388       N0.getNode()->hasOneUse()) {
9389     SDValue Int = N0.getOperand(0);
9390     EVT IntVT = Int.getValueType();
9391     if (IntVT.isInteger() && !IntVT.isVector()) {
9392       APInt SignMask;
9393       if (N0.getValueType().isVector()) {
9394         // For a vector, get a mask such as 0x80... per scalar element
9395         // and splat it.
9396         SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits());
9397         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9398       } else {
9399         // For a scalar, just generate 0x80...
9400         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9401       }
9402       SDLoc DL0(N0);
9403       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9404                         DAG.getConstant(SignMask, DL0, IntVT));
9405       AddToWorklist(Int.getNode());
9406       return DAG.getBitcast(VT, Int);
9407     }
9408   }
9409 
9410   // (fneg (fmul c, x)) -> (fmul -c, x)
9411   if (N0.getOpcode() == ISD::FMUL &&
9412       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9413     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9414     if (CFP1) {
9415       APFloat CVal = CFP1->getValueAPF();
9416       CVal.changeSign();
9417       if (Level >= AfterLegalizeDAG &&
9418           (TLI.isFPImmLegal(CVal, VT) ||
9419            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9420         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9421                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9422                                        N0.getOperand(1)),
9423                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9424     }
9425   }
9426 
9427   return SDValue();
9428 }
9429 
9430 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9431   SDValue N0 = N->getOperand(0);
9432   SDValue N1 = N->getOperand(1);
9433   EVT VT = N->getValueType(0);
9434   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9435   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9436 
9437   if (N0CFP && N1CFP) {
9438     const APFloat &C0 = N0CFP->getValueAPF();
9439     const APFloat &C1 = N1CFP->getValueAPF();
9440     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9441   }
9442 
9443   // Canonicalize to constant on RHS.
9444   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9445      !isConstantFPBuildVectorOrConstantFP(N1))
9446     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9447 
9448   return SDValue();
9449 }
9450 
9451 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9452   SDValue N0 = N->getOperand(0);
9453   SDValue N1 = N->getOperand(1);
9454   EVT VT = N->getValueType(0);
9455   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9456   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9457 
9458   if (N0CFP && N1CFP) {
9459     const APFloat &C0 = N0CFP->getValueAPF();
9460     const APFloat &C1 = N1CFP->getValueAPF();
9461     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9462   }
9463 
9464   // Canonicalize to constant on RHS.
9465   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9466      !isConstantFPBuildVectorOrConstantFP(N1))
9467     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9468 
9469   return SDValue();
9470 }
9471 
9472 SDValue DAGCombiner::visitFABS(SDNode *N) {
9473   SDValue N0 = N->getOperand(0);
9474   EVT VT = N->getValueType(0);
9475 
9476   // fold (fabs c1) -> fabs(c1)
9477   if (isConstantFPBuildVectorOrConstantFP(N0))
9478     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9479 
9480   // fold (fabs (fabs x)) -> (fabs x)
9481   if (N0.getOpcode() == ISD::FABS)
9482     return N->getOperand(0);
9483 
9484   // fold (fabs (fneg x)) -> (fabs x)
9485   // fold (fabs (fcopysign x, y)) -> (fabs x)
9486   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9487     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9488 
9489   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9490   // constant pool values.
9491   if (!TLI.isFAbsFree(VT) &&
9492       N0.getOpcode() == ISD::BITCAST &&
9493       N0.getNode()->hasOneUse()) {
9494     SDValue Int = N0.getOperand(0);
9495     EVT IntVT = Int.getValueType();
9496     if (IntVT.isInteger() && !IntVT.isVector()) {
9497       APInt SignMask;
9498       if (N0.getValueType().isVector()) {
9499         // For a vector, get a mask such as 0x7f... per scalar element
9500         // and splat it.
9501         SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits());
9502         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9503       } else {
9504         // For a scalar, just generate 0x7f...
9505         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9506       }
9507       SDLoc DL(N0);
9508       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9509                         DAG.getConstant(SignMask, DL, IntVT));
9510       AddToWorklist(Int.getNode());
9511       return DAG.getBitcast(N->getValueType(0), Int);
9512     }
9513   }
9514 
9515   return SDValue();
9516 }
9517 
9518 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9519   SDValue Chain = N->getOperand(0);
9520   SDValue N1 = N->getOperand(1);
9521   SDValue N2 = N->getOperand(2);
9522 
9523   // If N is a constant we could fold this into a fallthrough or unconditional
9524   // branch. However that doesn't happen very often in normal code, because
9525   // Instcombine/SimplifyCFG should have handled the available opportunities.
9526   // If we did this folding here, it would be necessary to update the
9527   // MachineBasicBlock CFG, which is awkward.
9528 
9529   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9530   // on the target.
9531   if (N1.getOpcode() == ISD::SETCC &&
9532       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9533                                    N1.getOperand(0).getValueType())) {
9534     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9535                        Chain, N1.getOperand(2),
9536                        N1.getOperand(0), N1.getOperand(1), N2);
9537   }
9538 
9539   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9540       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9541        (N1.getOperand(0).hasOneUse() &&
9542         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9543     SDNode *Trunc = nullptr;
9544     if (N1.getOpcode() == ISD::TRUNCATE) {
9545       // Look pass the truncate.
9546       Trunc = N1.getNode();
9547       N1 = N1.getOperand(0);
9548     }
9549 
9550     // Match this pattern so that we can generate simpler code:
9551     //
9552     //   %a = ...
9553     //   %b = and i32 %a, 2
9554     //   %c = srl i32 %b, 1
9555     //   brcond i32 %c ...
9556     //
9557     // into
9558     //
9559     //   %a = ...
9560     //   %b = and i32 %a, 2
9561     //   %c = setcc eq %b, 0
9562     //   brcond %c ...
9563     //
9564     // This applies only when the AND constant value has one bit set and the
9565     // SRL constant is equal to the log2 of the AND constant. The back-end is
9566     // smart enough to convert the result into a TEST/JMP sequence.
9567     SDValue Op0 = N1.getOperand(0);
9568     SDValue Op1 = N1.getOperand(1);
9569 
9570     if (Op0.getOpcode() == ISD::AND &&
9571         Op1.getOpcode() == ISD::Constant) {
9572       SDValue AndOp1 = Op0.getOperand(1);
9573 
9574       if (AndOp1.getOpcode() == ISD::Constant) {
9575         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9576 
9577         if (AndConst.isPowerOf2() &&
9578             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9579           SDLoc DL(N);
9580           SDValue SetCC =
9581             DAG.getSetCC(DL,
9582                          getSetCCResultType(Op0.getValueType()),
9583                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9584                          ISD::SETNE);
9585 
9586           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9587                                           MVT::Other, Chain, SetCC, N2);
9588           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9589           // will convert it back to (X & C1) >> C2.
9590           CombineTo(N, NewBRCond, false);
9591           // Truncate is dead.
9592           if (Trunc)
9593             deleteAndRecombine(Trunc);
9594           // Replace the uses of SRL with SETCC
9595           WorklistRemover DeadNodes(*this);
9596           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9597           deleteAndRecombine(N1.getNode());
9598           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9599         }
9600       }
9601     }
9602 
9603     if (Trunc)
9604       // Restore N1 if the above transformation doesn't match.
9605       N1 = N->getOperand(1);
9606   }
9607 
9608   // Transform br(xor(x, y)) -> br(x != y)
9609   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9610   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9611     SDNode *TheXor = N1.getNode();
9612     SDValue Op0 = TheXor->getOperand(0);
9613     SDValue Op1 = TheXor->getOperand(1);
9614     if (Op0.getOpcode() == Op1.getOpcode()) {
9615       // Avoid missing important xor optimizations.
9616       if (SDValue Tmp = visitXOR(TheXor)) {
9617         if (Tmp.getNode() != TheXor) {
9618           DEBUG(dbgs() << "\nReplacing.8 ";
9619                 TheXor->dump(&DAG);
9620                 dbgs() << "\nWith: ";
9621                 Tmp.getNode()->dump(&DAG);
9622                 dbgs() << '\n');
9623           WorklistRemover DeadNodes(*this);
9624           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9625           deleteAndRecombine(TheXor);
9626           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9627                              MVT::Other, Chain, Tmp, N2);
9628         }
9629 
9630         // visitXOR has changed XOR's operands or replaced the XOR completely,
9631         // bail out.
9632         return SDValue(N, 0);
9633       }
9634     }
9635 
9636     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9637       bool Equal = false;
9638       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9639           Op0.getOpcode() == ISD::XOR) {
9640         TheXor = Op0.getNode();
9641         Equal = true;
9642       }
9643 
9644       EVT SetCCVT = N1.getValueType();
9645       if (LegalTypes)
9646         SetCCVT = getSetCCResultType(SetCCVT);
9647       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9648                                    SetCCVT,
9649                                    Op0, Op1,
9650                                    Equal ? ISD::SETEQ : ISD::SETNE);
9651       // Replace the uses of XOR with SETCC
9652       WorklistRemover DeadNodes(*this);
9653       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9654       deleteAndRecombine(N1.getNode());
9655       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9656                          MVT::Other, Chain, SetCC, N2);
9657     }
9658   }
9659 
9660   return SDValue();
9661 }
9662 
9663 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9664 //
9665 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9666   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9667   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9668 
9669   // If N is a constant we could fold this into a fallthrough or unconditional
9670   // branch. However that doesn't happen very often in normal code, because
9671   // Instcombine/SimplifyCFG should have handled the available opportunities.
9672   // If we did this folding here, it would be necessary to update the
9673   // MachineBasicBlock CFG, which is awkward.
9674 
9675   // Use SimplifySetCC to simplify SETCC's.
9676   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9677                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9678                                false);
9679   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9680 
9681   // fold to a simpler setcc
9682   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9683     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9684                        N->getOperand(0), Simp.getOperand(2),
9685                        Simp.getOperand(0), Simp.getOperand(1),
9686                        N->getOperand(4));
9687 
9688   return SDValue();
9689 }
9690 
9691 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9692 /// and that N may be folded in the load / store addressing mode.
9693 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9694                                     SelectionDAG &DAG,
9695                                     const TargetLowering &TLI) {
9696   EVT VT;
9697   unsigned AS;
9698 
9699   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9700     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9701       return false;
9702     VT = LD->getMemoryVT();
9703     AS = LD->getAddressSpace();
9704   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9705     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9706       return false;
9707     VT = ST->getMemoryVT();
9708     AS = ST->getAddressSpace();
9709   } else
9710     return false;
9711 
9712   TargetLowering::AddrMode AM;
9713   if (N->getOpcode() == ISD::ADD) {
9714     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9715     if (Offset)
9716       // [reg +/- imm]
9717       AM.BaseOffs = Offset->getSExtValue();
9718     else
9719       // [reg +/- reg]
9720       AM.Scale = 1;
9721   } else if (N->getOpcode() == ISD::SUB) {
9722     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9723     if (Offset)
9724       // [reg +/- imm]
9725       AM.BaseOffs = -Offset->getSExtValue();
9726     else
9727       // [reg +/- reg]
9728       AM.Scale = 1;
9729   } else
9730     return false;
9731 
9732   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9733                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9734 }
9735 
9736 /// Try turning a load/store into a pre-indexed load/store when the base
9737 /// pointer is an add or subtract and it has other uses besides the load/store.
9738 /// After the transformation, the new indexed load/store has effectively folded
9739 /// the add/subtract in and all of its other uses are redirected to the
9740 /// new load/store.
9741 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9742   if (Level < AfterLegalizeDAG)
9743     return false;
9744 
9745   bool isLoad = true;
9746   SDValue Ptr;
9747   EVT VT;
9748   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9749     if (LD->isIndexed())
9750       return false;
9751     VT = LD->getMemoryVT();
9752     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9753         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9754       return false;
9755     Ptr = LD->getBasePtr();
9756   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9757     if (ST->isIndexed())
9758       return false;
9759     VT = ST->getMemoryVT();
9760     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9761         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9762       return false;
9763     Ptr = ST->getBasePtr();
9764     isLoad = false;
9765   } else {
9766     return false;
9767   }
9768 
9769   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9770   // out.  There is no reason to make this a preinc/predec.
9771   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9772       Ptr.getNode()->hasOneUse())
9773     return false;
9774 
9775   // Ask the target to do addressing mode selection.
9776   SDValue BasePtr;
9777   SDValue Offset;
9778   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9779   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9780     return false;
9781 
9782   // Backends without true r+i pre-indexed forms may need to pass a
9783   // constant base with a variable offset so that constant coercion
9784   // will work with the patterns in canonical form.
9785   bool Swapped = false;
9786   if (isa<ConstantSDNode>(BasePtr)) {
9787     std::swap(BasePtr, Offset);
9788     Swapped = true;
9789   }
9790 
9791   // Don't create a indexed load / store with zero offset.
9792   if (isNullConstant(Offset))
9793     return false;
9794 
9795   // Try turning it into a pre-indexed load / store except when:
9796   // 1) The new base ptr is a frame index.
9797   // 2) If N is a store and the new base ptr is either the same as or is a
9798   //    predecessor of the value being stored.
9799   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9800   //    that would create a cycle.
9801   // 4) All uses are load / store ops that use it as old base ptr.
9802 
9803   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9804   // (plus the implicit offset) to a register to preinc anyway.
9805   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9806     return false;
9807 
9808   // Check #2.
9809   if (!isLoad) {
9810     SDValue Val = cast<StoreSDNode>(N)->getValue();
9811     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9812       return false;
9813   }
9814 
9815   // Caches for hasPredecessorHelper.
9816   SmallPtrSet<const SDNode *, 32> Visited;
9817   SmallVector<const SDNode *, 16> Worklist;
9818   Worklist.push_back(N);
9819 
9820   // If the offset is a constant, there may be other adds of constants that
9821   // can be folded with this one. We should do this to avoid having to keep
9822   // a copy of the original base pointer.
9823   SmallVector<SDNode *, 16> OtherUses;
9824   if (isa<ConstantSDNode>(Offset))
9825     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9826                               UE = BasePtr.getNode()->use_end();
9827          UI != UE; ++UI) {
9828       SDUse &Use = UI.getUse();
9829       // Skip the use that is Ptr and uses of other results from BasePtr's
9830       // node (important for nodes that return multiple results).
9831       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9832         continue;
9833 
9834       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9835         continue;
9836 
9837       if (Use.getUser()->getOpcode() != ISD::ADD &&
9838           Use.getUser()->getOpcode() != ISD::SUB) {
9839         OtherUses.clear();
9840         break;
9841       }
9842 
9843       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9844       if (!isa<ConstantSDNode>(Op1)) {
9845         OtherUses.clear();
9846         break;
9847       }
9848 
9849       // FIXME: In some cases, we can be smarter about this.
9850       if (Op1.getValueType() != Offset.getValueType()) {
9851         OtherUses.clear();
9852         break;
9853       }
9854 
9855       OtherUses.push_back(Use.getUser());
9856     }
9857 
9858   if (Swapped)
9859     std::swap(BasePtr, Offset);
9860 
9861   // Now check for #3 and #4.
9862   bool RealUse = false;
9863 
9864   for (SDNode *Use : Ptr.getNode()->uses()) {
9865     if (Use == N)
9866       continue;
9867     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9868       return false;
9869 
9870     // If Ptr may be folded in addressing mode of other use, then it's
9871     // not profitable to do this transformation.
9872     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9873       RealUse = true;
9874   }
9875 
9876   if (!RealUse)
9877     return false;
9878 
9879   SDValue Result;
9880   if (isLoad)
9881     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9882                                 BasePtr, Offset, AM);
9883   else
9884     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9885                                  BasePtr, Offset, AM);
9886   ++PreIndexedNodes;
9887   ++NodesCombined;
9888   DEBUG(dbgs() << "\nReplacing.4 ";
9889         N->dump(&DAG);
9890         dbgs() << "\nWith: ";
9891         Result.getNode()->dump(&DAG);
9892         dbgs() << '\n');
9893   WorklistRemover DeadNodes(*this);
9894   if (isLoad) {
9895     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9896     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9897   } else {
9898     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9899   }
9900 
9901   // Finally, since the node is now dead, remove it from the graph.
9902   deleteAndRecombine(N);
9903 
9904   if (Swapped)
9905     std::swap(BasePtr, Offset);
9906 
9907   // Replace other uses of BasePtr that can be updated to use Ptr
9908   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9909     unsigned OffsetIdx = 1;
9910     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9911       OffsetIdx = 0;
9912     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9913            BasePtr.getNode() && "Expected BasePtr operand");
9914 
9915     // We need to replace ptr0 in the following expression:
9916     //   x0 * offset0 + y0 * ptr0 = t0
9917     // knowing that
9918     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9919     //
9920     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9921     // indexed load/store and the expresion that needs to be re-written.
9922     //
9923     // Therefore, we have:
9924     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9925 
9926     ConstantSDNode *CN =
9927       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9928     int X0, X1, Y0, Y1;
9929     const APInt &Offset0 = CN->getAPIntValue();
9930     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9931 
9932     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9933     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9934     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9935     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9936 
9937     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9938 
9939     APInt CNV = Offset0;
9940     if (X0 < 0) CNV = -CNV;
9941     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9942     else CNV = CNV - Offset1;
9943 
9944     SDLoc DL(OtherUses[i]);
9945 
9946     // We can now generate the new expression.
9947     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9948     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9949 
9950     SDValue NewUse = DAG.getNode(Opcode,
9951                                  DL,
9952                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9953     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9954     deleteAndRecombine(OtherUses[i]);
9955   }
9956 
9957   // Replace the uses of Ptr with uses of the updated base value.
9958   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9959   deleteAndRecombine(Ptr.getNode());
9960 
9961   return true;
9962 }
9963 
9964 /// Try to combine a load/store with a add/sub of the base pointer node into a
9965 /// post-indexed load/store. The transformation folded the add/subtract into the
9966 /// new indexed load/store effectively and all of its uses are redirected to the
9967 /// new load/store.
9968 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9969   if (Level < AfterLegalizeDAG)
9970     return false;
9971 
9972   bool isLoad = true;
9973   SDValue Ptr;
9974   EVT VT;
9975   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9976     if (LD->isIndexed())
9977       return false;
9978     VT = LD->getMemoryVT();
9979     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9980         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9981       return false;
9982     Ptr = LD->getBasePtr();
9983   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9984     if (ST->isIndexed())
9985       return false;
9986     VT = ST->getMemoryVT();
9987     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9988         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9989       return false;
9990     Ptr = ST->getBasePtr();
9991     isLoad = false;
9992   } else {
9993     return false;
9994   }
9995 
9996   if (Ptr.getNode()->hasOneUse())
9997     return false;
9998 
9999   for (SDNode *Op : Ptr.getNode()->uses()) {
10000     if (Op == N ||
10001         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10002       continue;
10003 
10004     SDValue BasePtr;
10005     SDValue Offset;
10006     ISD::MemIndexedMode AM = ISD::UNINDEXED;
10007     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10008       // Don't create a indexed load / store with zero offset.
10009       if (isNullConstant(Offset))
10010         continue;
10011 
10012       // Try turning it into a post-indexed load / store except when
10013       // 1) All uses are load / store ops that use it as base ptr (and
10014       //    it may be folded as addressing mmode).
10015       // 2) Op must be independent of N, i.e. Op is neither a predecessor
10016       //    nor a successor of N. Otherwise, if Op is folded that would
10017       //    create a cycle.
10018 
10019       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10020         continue;
10021 
10022       // Check for #1.
10023       bool TryNext = false;
10024       for (SDNode *Use : BasePtr.getNode()->uses()) {
10025         if (Use == Ptr.getNode())
10026           continue;
10027 
10028         // If all the uses are load / store addresses, then don't do the
10029         // transformation.
10030         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10031           bool RealUse = false;
10032           for (SDNode *UseUse : Use->uses()) {
10033             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10034               RealUse = true;
10035           }
10036 
10037           if (!RealUse) {
10038             TryNext = true;
10039             break;
10040           }
10041         }
10042       }
10043 
10044       if (TryNext)
10045         continue;
10046 
10047       // Check for #2
10048       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10049         SDValue Result = isLoad
10050           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10051                                BasePtr, Offset, AM)
10052           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10053                                 BasePtr, Offset, AM);
10054         ++PostIndexedNodes;
10055         ++NodesCombined;
10056         DEBUG(dbgs() << "\nReplacing.5 ";
10057               N->dump(&DAG);
10058               dbgs() << "\nWith: ";
10059               Result.getNode()->dump(&DAG);
10060               dbgs() << '\n');
10061         WorklistRemover DeadNodes(*this);
10062         if (isLoad) {
10063           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10064           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10065         } else {
10066           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10067         }
10068 
10069         // Finally, since the node is now dead, remove it from the graph.
10070         deleteAndRecombine(N);
10071 
10072         // Replace the uses of Use with uses of the updated base value.
10073         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10074                                       Result.getValue(isLoad ? 1 : 0));
10075         deleteAndRecombine(Op);
10076         return true;
10077       }
10078     }
10079   }
10080 
10081   return false;
10082 }
10083 
10084 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10085 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10086   ISD::MemIndexedMode AM = LD->getAddressingMode();
10087   assert(AM != ISD::UNINDEXED);
10088   SDValue BP = LD->getOperand(1);
10089   SDValue Inc = LD->getOperand(2);
10090 
10091   // Some backends use TargetConstants for load offsets, but don't expect
10092   // TargetConstants in general ADD nodes. We can convert these constants into
10093   // regular Constants (if the constant is not opaque).
10094   assert((Inc.getOpcode() != ISD::TargetConstant ||
10095           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10096          "Cannot split out indexing using opaque target constants");
10097   if (Inc.getOpcode() == ISD::TargetConstant) {
10098     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10099     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10100                           ConstInc->getValueType(0));
10101   }
10102 
10103   unsigned Opc =
10104       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10105   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10106 }
10107 
10108 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10109   LoadSDNode *LD  = cast<LoadSDNode>(N);
10110   SDValue Chain = LD->getChain();
10111   SDValue Ptr   = LD->getBasePtr();
10112 
10113   // If load is not volatile and there are no uses of the loaded value (and
10114   // the updated indexed value in case of indexed loads), change uses of the
10115   // chain value into uses of the chain input (i.e. delete the dead load).
10116   if (!LD->isVolatile()) {
10117     if (N->getValueType(1) == MVT::Other) {
10118       // Unindexed loads.
10119       if (!N->hasAnyUseOfValue(0)) {
10120         // It's not safe to use the two value CombineTo variant here. e.g.
10121         // v1, chain2 = load chain1, loc
10122         // v2, chain3 = load chain2, loc
10123         // v3         = add v2, c
10124         // Now we replace use of chain2 with chain1.  This makes the second load
10125         // isomorphic to the one we are deleting, and thus makes this load live.
10126         DEBUG(dbgs() << "\nReplacing.6 ";
10127               N->dump(&DAG);
10128               dbgs() << "\nWith chain: ";
10129               Chain.getNode()->dump(&DAG);
10130               dbgs() << "\n");
10131         WorklistRemover DeadNodes(*this);
10132         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10133 
10134         if (N->use_empty())
10135           deleteAndRecombine(N);
10136 
10137         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10138       }
10139     } else {
10140       // Indexed loads.
10141       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10142 
10143       // If this load has an opaque TargetConstant offset, then we cannot split
10144       // the indexing into an add/sub directly (that TargetConstant may not be
10145       // valid for a different type of node, and we cannot convert an opaque
10146       // target constant into a regular constant).
10147       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10148                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10149 
10150       if (!N->hasAnyUseOfValue(0) &&
10151           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10152         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10153         SDValue Index;
10154         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10155           Index = SplitIndexingFromLoad(LD);
10156           // Try to fold the base pointer arithmetic into subsequent loads and
10157           // stores.
10158           AddUsersToWorklist(N);
10159         } else
10160           Index = DAG.getUNDEF(N->getValueType(1));
10161         DEBUG(dbgs() << "\nReplacing.7 ";
10162               N->dump(&DAG);
10163               dbgs() << "\nWith: ";
10164               Undef.getNode()->dump(&DAG);
10165               dbgs() << " and 2 other values\n");
10166         WorklistRemover DeadNodes(*this);
10167         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10168         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10169         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10170         deleteAndRecombine(N);
10171         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10172       }
10173     }
10174   }
10175 
10176   // If this load is directly stored, replace the load value with the stored
10177   // value.
10178   // TODO: Handle store large -> read small portion.
10179   // TODO: Handle TRUNCSTORE/LOADEXT
10180   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
10181     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10182       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10183       if (PrevST->getBasePtr() == Ptr &&
10184           PrevST->getValue().getValueType() == N->getValueType(0))
10185       return CombineTo(N, Chain.getOperand(1), Chain);
10186     }
10187   }
10188 
10189   // Try to infer better alignment information than the load already has.
10190   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10191     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10192       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10193         SDValue NewLoad = DAG.getExtLoad(
10194             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
10195             LD->getPointerInfo(), LD->getMemoryVT(), Align,
10196             LD->getMemOperand()->getFlags(), LD->getAAInfo());
10197         if (NewLoad.getNode() != N)
10198           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10199       }
10200     }
10201   }
10202 
10203   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10204                                                   : DAG.getSubtarget().useAA();
10205 #ifndef NDEBUG
10206   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10207       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10208     UseAA = false;
10209 #endif
10210   if (UseAA && LD->isUnindexed()) {
10211     // Walk up chain skipping non-aliasing memory nodes.
10212     SDValue BetterChain = FindBetterChain(N, Chain);
10213 
10214     // If there is a better chain.
10215     if (Chain != BetterChain) {
10216       SDValue ReplLoad;
10217 
10218       // Replace the chain to void dependency.
10219       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10220         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10221                                BetterChain, Ptr, LD->getMemOperand());
10222       } else {
10223         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10224                                   LD->getValueType(0),
10225                                   BetterChain, Ptr, LD->getMemoryVT(),
10226                                   LD->getMemOperand());
10227       }
10228 
10229       // Create token factor to keep old chain connected.
10230       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10231                                   MVT::Other, Chain, ReplLoad.getValue(1));
10232 
10233       // Make sure the new and old chains are cleaned up.
10234       AddToWorklist(Token.getNode());
10235 
10236       // Replace uses with load result and token factor. Don't add users
10237       // to work list.
10238       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10239     }
10240   }
10241 
10242   // Try transforming N to an indexed load.
10243   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10244     return SDValue(N, 0);
10245 
10246   // Try to slice up N to more direct loads if the slices are mapped to
10247   // different register banks or pairing can take place.
10248   if (SliceUpLoad(N))
10249     return SDValue(N, 0);
10250 
10251   return SDValue();
10252 }
10253 
10254 namespace {
10255 /// \brief Helper structure used to slice a load in smaller loads.
10256 /// Basically a slice is obtained from the following sequence:
10257 /// Origin = load Ty1, Base
10258 /// Shift = srl Ty1 Origin, CstTy Amount
10259 /// Inst = trunc Shift to Ty2
10260 ///
10261 /// Then, it will be rewriten into:
10262 /// Slice = load SliceTy, Base + SliceOffset
10263 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10264 ///
10265 /// SliceTy is deduced from the number of bits that are actually used to
10266 /// build Inst.
10267 struct LoadedSlice {
10268   /// \brief Helper structure used to compute the cost of a slice.
10269   struct Cost {
10270     /// Are we optimizing for code size.
10271     bool ForCodeSize;
10272     /// Various cost.
10273     unsigned Loads;
10274     unsigned Truncates;
10275     unsigned CrossRegisterBanksCopies;
10276     unsigned ZExts;
10277     unsigned Shift;
10278 
10279     Cost(bool ForCodeSize = false)
10280         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10281           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10282 
10283     /// \brief Get the cost of one isolated slice.
10284     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10285         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10286           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10287       EVT TruncType = LS.Inst->getValueType(0);
10288       EVT LoadedType = LS.getLoadedType();
10289       if (TruncType != LoadedType &&
10290           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10291         ZExts = 1;
10292     }
10293 
10294     /// \brief Account for slicing gain in the current cost.
10295     /// Slicing provide a few gains like removing a shift or a
10296     /// truncate. This method allows to grow the cost of the original
10297     /// load with the gain from this slice.
10298     void addSliceGain(const LoadedSlice &LS) {
10299       // Each slice saves a truncate.
10300       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10301       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10302                               LS.Inst->getValueType(0)))
10303         ++Truncates;
10304       // If there is a shift amount, this slice gets rid of it.
10305       if (LS.Shift)
10306         ++Shift;
10307       // If this slice can merge a cross register bank copy, account for it.
10308       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10309         ++CrossRegisterBanksCopies;
10310     }
10311 
10312     Cost &operator+=(const Cost &RHS) {
10313       Loads += RHS.Loads;
10314       Truncates += RHS.Truncates;
10315       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10316       ZExts += RHS.ZExts;
10317       Shift += RHS.Shift;
10318       return *this;
10319     }
10320 
10321     bool operator==(const Cost &RHS) const {
10322       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10323              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10324              ZExts == RHS.ZExts && Shift == RHS.Shift;
10325     }
10326 
10327     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10328 
10329     bool operator<(const Cost &RHS) const {
10330       // Assume cross register banks copies are as expensive as loads.
10331       // FIXME: Do we want some more target hooks?
10332       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10333       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10334       // Unless we are optimizing for code size, consider the
10335       // expensive operation first.
10336       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10337         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10338       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10339              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10340     }
10341 
10342     bool operator>(const Cost &RHS) const { return RHS < *this; }
10343 
10344     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10345 
10346     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10347   };
10348   // The last instruction that represent the slice. This should be a
10349   // truncate instruction.
10350   SDNode *Inst;
10351   // The original load instruction.
10352   LoadSDNode *Origin;
10353   // The right shift amount in bits from the original load.
10354   unsigned Shift;
10355   // The DAG from which Origin came from.
10356   // This is used to get some contextual information about legal types, etc.
10357   SelectionDAG *DAG;
10358 
10359   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10360               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10361       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10362 
10363   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10364   /// \return Result is \p BitWidth and has used bits set to 1 and
10365   ///         not used bits set to 0.
10366   APInt getUsedBits() const {
10367     // Reproduce the trunc(lshr) sequence:
10368     // - Start from the truncated value.
10369     // - Zero extend to the desired bit width.
10370     // - Shift left.
10371     assert(Origin && "No original load to compare against.");
10372     unsigned BitWidth = Origin->getValueSizeInBits(0);
10373     assert(Inst && "This slice is not bound to an instruction");
10374     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10375            "Extracted slice is bigger than the whole type!");
10376     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10377     UsedBits.setAllBits();
10378     UsedBits = UsedBits.zext(BitWidth);
10379     UsedBits <<= Shift;
10380     return UsedBits;
10381   }
10382 
10383   /// \brief Get the size of the slice to be loaded in bytes.
10384   unsigned getLoadedSize() const {
10385     unsigned SliceSize = getUsedBits().countPopulation();
10386     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10387     return SliceSize / 8;
10388   }
10389 
10390   /// \brief Get the type that will be loaded for this slice.
10391   /// Note: This may not be the final type for the slice.
10392   EVT getLoadedType() const {
10393     assert(DAG && "Missing context");
10394     LLVMContext &Ctxt = *DAG->getContext();
10395     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10396   }
10397 
10398   /// \brief Get the alignment of the load used for this slice.
10399   unsigned getAlignment() const {
10400     unsigned Alignment = Origin->getAlignment();
10401     unsigned Offset = getOffsetFromBase();
10402     if (Offset != 0)
10403       Alignment = MinAlign(Alignment, Alignment + Offset);
10404     return Alignment;
10405   }
10406 
10407   /// \brief Check if this slice can be rewritten with legal operations.
10408   bool isLegal() const {
10409     // An invalid slice is not legal.
10410     if (!Origin || !Inst || !DAG)
10411       return false;
10412 
10413     // Offsets are for indexed load only, we do not handle that.
10414     if (!Origin->getOffset().isUndef())
10415       return false;
10416 
10417     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10418 
10419     // Check that the type is legal.
10420     EVT SliceType = getLoadedType();
10421     if (!TLI.isTypeLegal(SliceType))
10422       return false;
10423 
10424     // Check that the load is legal for this type.
10425     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10426       return false;
10427 
10428     // Check that the offset can be computed.
10429     // 1. Check its type.
10430     EVT PtrType = Origin->getBasePtr().getValueType();
10431     if (PtrType == MVT::Untyped || PtrType.isExtended())
10432       return false;
10433 
10434     // 2. Check that it fits in the immediate.
10435     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10436       return false;
10437 
10438     // 3. Check that the computation is legal.
10439     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10440       return false;
10441 
10442     // Check that the zext is legal if it needs one.
10443     EVT TruncateType = Inst->getValueType(0);
10444     if (TruncateType != SliceType &&
10445         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10446       return false;
10447 
10448     return true;
10449   }
10450 
10451   /// \brief Get the offset in bytes of this slice in the original chunk of
10452   /// bits.
10453   /// \pre DAG != nullptr.
10454   uint64_t getOffsetFromBase() const {
10455     assert(DAG && "Missing context.");
10456     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10457     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10458     uint64_t Offset = Shift / 8;
10459     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10460     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10461            "The size of the original loaded type is not a multiple of a"
10462            " byte.");
10463     // If Offset is bigger than TySizeInBytes, it means we are loading all
10464     // zeros. This should have been optimized before in the process.
10465     assert(TySizeInBytes > Offset &&
10466            "Invalid shift amount for given loaded size");
10467     if (IsBigEndian)
10468       Offset = TySizeInBytes - Offset - getLoadedSize();
10469     return Offset;
10470   }
10471 
10472   /// \brief Generate the sequence of instructions to load the slice
10473   /// represented by this object and redirect the uses of this slice to
10474   /// this new sequence of instructions.
10475   /// \pre this->Inst && this->Origin are valid Instructions and this
10476   /// object passed the legal check: LoadedSlice::isLegal returned true.
10477   /// \return The last instruction of the sequence used to load the slice.
10478   SDValue loadSlice() const {
10479     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10480     const SDValue &OldBaseAddr = Origin->getBasePtr();
10481     SDValue BaseAddr = OldBaseAddr;
10482     // Get the offset in that chunk of bytes w.r.t. the endianess.
10483     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10484     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10485     if (Offset) {
10486       // BaseAddr = BaseAddr + Offset.
10487       EVT ArithType = BaseAddr.getValueType();
10488       SDLoc DL(Origin);
10489       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10490                               DAG->getConstant(Offset, DL, ArithType));
10491     }
10492 
10493     // Create the type of the loaded slice according to its size.
10494     EVT SliceType = getLoadedType();
10495 
10496     // Create the load for the slice.
10497     SDValue LastInst =
10498         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10499                      Origin->getPointerInfo().getWithOffset(Offset),
10500                      getAlignment(), Origin->getMemOperand()->getFlags());
10501     // If the final type is not the same as the loaded type, this means that
10502     // we have to pad with zero. Create a zero extend for that.
10503     EVT FinalType = Inst->getValueType(0);
10504     if (SliceType != FinalType)
10505       LastInst =
10506           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10507     return LastInst;
10508   }
10509 
10510   /// \brief Check if this slice can be merged with an expensive cross register
10511   /// bank copy. E.g.,
10512   /// i = load i32
10513   /// f = bitcast i32 i to float
10514   bool canMergeExpensiveCrossRegisterBankCopy() const {
10515     if (!Inst || !Inst->hasOneUse())
10516       return false;
10517     SDNode *Use = *Inst->use_begin();
10518     if (Use->getOpcode() != ISD::BITCAST)
10519       return false;
10520     assert(DAG && "Missing context");
10521     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10522     EVT ResVT = Use->getValueType(0);
10523     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10524     const TargetRegisterClass *ArgRC =
10525         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10526     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10527       return false;
10528 
10529     // At this point, we know that we perform a cross-register-bank copy.
10530     // Check if it is expensive.
10531     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10532     // Assume bitcasts are cheap, unless both register classes do not
10533     // explicitly share a common sub class.
10534     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10535       return false;
10536 
10537     // Check if it will be merged with the load.
10538     // 1. Check the alignment constraint.
10539     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10540         ResVT.getTypeForEVT(*DAG->getContext()));
10541 
10542     if (RequiredAlignment > getAlignment())
10543       return false;
10544 
10545     // 2. Check that the load is a legal operation for that type.
10546     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10547       return false;
10548 
10549     // 3. Check that we do not have a zext in the way.
10550     if (Inst->getValueType(0) != getLoadedType())
10551       return false;
10552 
10553     return true;
10554   }
10555 };
10556 }
10557 
10558 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10559 /// \p UsedBits looks like 0..0 1..1 0..0.
10560 static bool areUsedBitsDense(const APInt &UsedBits) {
10561   // If all the bits are one, this is dense!
10562   if (UsedBits.isAllOnesValue())
10563     return true;
10564 
10565   // Get rid of the unused bits on the right.
10566   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10567   // Get rid of the unused bits on the left.
10568   if (NarrowedUsedBits.countLeadingZeros())
10569     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10570   // Check that the chunk of bits is completely used.
10571   return NarrowedUsedBits.isAllOnesValue();
10572 }
10573 
10574 /// \brief Check whether or not \p First and \p Second are next to each other
10575 /// in memory. This means that there is no hole between the bits loaded
10576 /// by \p First and the bits loaded by \p Second.
10577 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10578                                      const LoadedSlice &Second) {
10579   assert(First.Origin == Second.Origin && First.Origin &&
10580          "Unable to match different memory origins.");
10581   APInt UsedBits = First.getUsedBits();
10582   assert((UsedBits & Second.getUsedBits()) == 0 &&
10583          "Slices are not supposed to overlap.");
10584   UsedBits |= Second.getUsedBits();
10585   return areUsedBitsDense(UsedBits);
10586 }
10587 
10588 /// \brief Adjust the \p GlobalLSCost according to the target
10589 /// paring capabilities and the layout of the slices.
10590 /// \pre \p GlobalLSCost should account for at least as many loads as
10591 /// there is in the slices in \p LoadedSlices.
10592 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10593                                  LoadedSlice::Cost &GlobalLSCost) {
10594   unsigned NumberOfSlices = LoadedSlices.size();
10595   // If there is less than 2 elements, no pairing is possible.
10596   if (NumberOfSlices < 2)
10597     return;
10598 
10599   // Sort the slices so that elements that are likely to be next to each
10600   // other in memory are next to each other in the list.
10601   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10602             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10603     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10604     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10605   });
10606   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10607   // First (resp. Second) is the first (resp. Second) potentially candidate
10608   // to be placed in a paired load.
10609   const LoadedSlice *First = nullptr;
10610   const LoadedSlice *Second = nullptr;
10611   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10612                 // Set the beginning of the pair.
10613                                                            First = Second) {
10614 
10615     Second = &LoadedSlices[CurrSlice];
10616 
10617     // If First is NULL, it means we start a new pair.
10618     // Get to the next slice.
10619     if (!First)
10620       continue;
10621 
10622     EVT LoadedType = First->getLoadedType();
10623 
10624     // If the types of the slices are different, we cannot pair them.
10625     if (LoadedType != Second->getLoadedType())
10626       continue;
10627 
10628     // Check if the target supplies paired loads for this type.
10629     unsigned RequiredAlignment = 0;
10630     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10631       // move to the next pair, this type is hopeless.
10632       Second = nullptr;
10633       continue;
10634     }
10635     // Check if we meet the alignment requirement.
10636     if (RequiredAlignment > First->getAlignment())
10637       continue;
10638 
10639     // Check that both loads are next to each other in memory.
10640     if (!areSlicesNextToEachOther(*First, *Second))
10641       continue;
10642 
10643     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10644     --GlobalLSCost.Loads;
10645     // Move to the next pair.
10646     Second = nullptr;
10647   }
10648 }
10649 
10650 /// \brief Check the profitability of all involved LoadedSlice.
10651 /// Currently, it is considered profitable if there is exactly two
10652 /// involved slices (1) which are (2) next to each other in memory, and
10653 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10654 ///
10655 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10656 /// the elements themselves.
10657 ///
10658 /// FIXME: When the cost model will be mature enough, we can relax
10659 /// constraints (1) and (2).
10660 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10661                                 const APInt &UsedBits, bool ForCodeSize) {
10662   unsigned NumberOfSlices = LoadedSlices.size();
10663   if (StressLoadSlicing)
10664     return NumberOfSlices > 1;
10665 
10666   // Check (1).
10667   if (NumberOfSlices != 2)
10668     return false;
10669 
10670   // Check (2).
10671   if (!areUsedBitsDense(UsedBits))
10672     return false;
10673 
10674   // Check (3).
10675   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10676   // The original code has one big load.
10677   OrigCost.Loads = 1;
10678   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10679     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10680     // Accumulate the cost of all the slices.
10681     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10682     GlobalSlicingCost += SliceCost;
10683 
10684     // Account as cost in the original configuration the gain obtained
10685     // with the current slices.
10686     OrigCost.addSliceGain(LS);
10687   }
10688 
10689   // If the target supports paired load, adjust the cost accordingly.
10690   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10691   return OrigCost > GlobalSlicingCost;
10692 }
10693 
10694 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10695 /// operations, split it in the various pieces being extracted.
10696 ///
10697 /// This sort of thing is introduced by SROA.
10698 /// This slicing takes care not to insert overlapping loads.
10699 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10700 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10701   if (Level < AfterLegalizeDAG)
10702     return false;
10703 
10704   LoadSDNode *LD = cast<LoadSDNode>(N);
10705   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10706       !LD->getValueType(0).isInteger())
10707     return false;
10708 
10709   // Keep track of already used bits to detect overlapping values.
10710   // In that case, we will just abort the transformation.
10711   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10712 
10713   SmallVector<LoadedSlice, 4> LoadedSlices;
10714 
10715   // Check if this load is used as several smaller chunks of bits.
10716   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10717   // of computation for each trunc.
10718   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10719        UI != UIEnd; ++UI) {
10720     // Skip the uses of the chain.
10721     if (UI.getUse().getResNo() != 0)
10722       continue;
10723 
10724     SDNode *User = *UI;
10725     unsigned Shift = 0;
10726 
10727     // Check if this is a trunc(lshr).
10728     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10729         isa<ConstantSDNode>(User->getOperand(1))) {
10730       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10731       User = *User->use_begin();
10732     }
10733 
10734     // At this point, User is a Truncate, iff we encountered, trunc or
10735     // trunc(lshr).
10736     if (User->getOpcode() != ISD::TRUNCATE)
10737       return false;
10738 
10739     // The width of the type must be a power of 2 and greater than 8-bits.
10740     // Otherwise the load cannot be represented in LLVM IR.
10741     // Moreover, if we shifted with a non-8-bits multiple, the slice
10742     // will be across several bytes. We do not support that.
10743     unsigned Width = User->getValueSizeInBits(0);
10744     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10745       return 0;
10746 
10747     // Build the slice for this chain of computations.
10748     LoadedSlice LS(User, LD, Shift, &DAG);
10749     APInt CurrentUsedBits = LS.getUsedBits();
10750 
10751     // Check if this slice overlaps with another.
10752     if ((CurrentUsedBits & UsedBits) != 0)
10753       return false;
10754     // Update the bits used globally.
10755     UsedBits |= CurrentUsedBits;
10756 
10757     // Check if the new slice would be legal.
10758     if (!LS.isLegal())
10759       return false;
10760 
10761     // Record the slice.
10762     LoadedSlices.push_back(LS);
10763   }
10764 
10765   // Abort slicing if it does not seem to be profitable.
10766   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10767     return false;
10768 
10769   ++SlicedLoads;
10770 
10771   // Rewrite each chain to use an independent load.
10772   // By construction, each chain can be represented by a unique load.
10773 
10774   // Prepare the argument for the new token factor for all the slices.
10775   SmallVector<SDValue, 8> ArgChains;
10776   for (SmallVectorImpl<LoadedSlice>::const_iterator
10777            LSIt = LoadedSlices.begin(),
10778            LSItEnd = LoadedSlices.end();
10779        LSIt != LSItEnd; ++LSIt) {
10780     SDValue SliceInst = LSIt->loadSlice();
10781     CombineTo(LSIt->Inst, SliceInst, true);
10782     if (SliceInst.getOpcode() != ISD::LOAD)
10783       SliceInst = SliceInst.getOperand(0);
10784     assert(SliceInst->getOpcode() == ISD::LOAD &&
10785            "It takes more than a zext to get to the loaded slice!!");
10786     ArgChains.push_back(SliceInst.getValue(1));
10787   }
10788 
10789   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10790                               ArgChains);
10791   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10792   return true;
10793 }
10794 
10795 /// Check to see if V is (and load (ptr), imm), where the load is having
10796 /// specific bytes cleared out.  If so, return the byte size being masked out
10797 /// and the shift amount.
10798 static std::pair<unsigned, unsigned>
10799 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10800   std::pair<unsigned, unsigned> Result(0, 0);
10801 
10802   // Check for the structure we're looking for.
10803   if (V->getOpcode() != ISD::AND ||
10804       !isa<ConstantSDNode>(V->getOperand(1)) ||
10805       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10806     return Result;
10807 
10808   // Check the chain and pointer.
10809   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10810   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10811 
10812   // The store should be chained directly to the load or be an operand of a
10813   // tokenfactor.
10814   if (LD == Chain.getNode())
10815     ; // ok.
10816   else if (Chain->getOpcode() != ISD::TokenFactor)
10817     return Result; // Fail.
10818   else {
10819     bool isOk = false;
10820     for (const SDValue &ChainOp : Chain->op_values())
10821       if (ChainOp.getNode() == LD) {
10822         isOk = true;
10823         break;
10824       }
10825     if (!isOk) return Result;
10826   }
10827 
10828   // This only handles simple types.
10829   if (V.getValueType() != MVT::i16 &&
10830       V.getValueType() != MVT::i32 &&
10831       V.getValueType() != MVT::i64)
10832     return Result;
10833 
10834   // Check the constant mask.  Invert it so that the bits being masked out are
10835   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10836   // follow the sign bit for uniformity.
10837   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10838   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10839   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10840   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10841   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10842   if (NotMaskLZ == 64) return Result;  // All zero mask.
10843 
10844   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10845   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10846     return Result;
10847 
10848   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10849   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10850     NotMaskLZ -= 64-V.getValueSizeInBits();
10851 
10852   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10853   switch (MaskedBytes) {
10854   case 1:
10855   case 2:
10856   case 4: break;
10857   default: return Result; // All one mask, or 5-byte mask.
10858   }
10859 
10860   // Verify that the first bit starts at a multiple of mask so that the access
10861   // is aligned the same as the access width.
10862   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10863 
10864   Result.first = MaskedBytes;
10865   Result.second = NotMaskTZ/8;
10866   return Result;
10867 }
10868 
10869 
10870 /// Check to see if IVal is something that provides a value as specified by
10871 /// MaskInfo. If so, replace the specified store with a narrower store of
10872 /// truncated IVal.
10873 static SDNode *
10874 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10875                                 SDValue IVal, StoreSDNode *St,
10876                                 DAGCombiner *DC) {
10877   unsigned NumBytes = MaskInfo.first;
10878   unsigned ByteShift = MaskInfo.second;
10879   SelectionDAG &DAG = DC->getDAG();
10880 
10881   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10882   // that uses this.  If not, this is not a replacement.
10883   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10884                                   ByteShift*8, (ByteShift+NumBytes)*8);
10885   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10886 
10887   // Check that it is legal on the target to do this.  It is legal if the new
10888   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10889   // legalization.
10890   MVT VT = MVT::getIntegerVT(NumBytes*8);
10891   if (!DC->isTypeLegal(VT))
10892     return nullptr;
10893 
10894   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10895   // shifted by ByteShift and truncated down to NumBytes.
10896   if (ByteShift) {
10897     SDLoc DL(IVal);
10898     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10899                        DAG.getConstant(ByteShift*8, DL,
10900                                     DC->getShiftAmountTy(IVal.getValueType())));
10901   }
10902 
10903   // Figure out the offset for the store and the alignment of the access.
10904   unsigned StOffset;
10905   unsigned NewAlign = St->getAlignment();
10906 
10907   if (DAG.getDataLayout().isLittleEndian())
10908     StOffset = ByteShift;
10909   else
10910     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10911 
10912   SDValue Ptr = St->getBasePtr();
10913   if (StOffset) {
10914     SDLoc DL(IVal);
10915     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10916                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10917     NewAlign = MinAlign(NewAlign, StOffset);
10918   }
10919 
10920   // Truncate down to the new size.
10921   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10922 
10923   ++OpsNarrowed;
10924   return DAG
10925       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10926                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
10927       .getNode();
10928 }
10929 
10930 
10931 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10932 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10933 /// narrowing the load and store if it would end up being a win for performance
10934 /// or code size.
10935 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10936   StoreSDNode *ST  = cast<StoreSDNode>(N);
10937   if (ST->isVolatile())
10938     return SDValue();
10939 
10940   SDValue Chain = ST->getChain();
10941   SDValue Value = ST->getValue();
10942   SDValue Ptr   = ST->getBasePtr();
10943   EVT VT = Value.getValueType();
10944 
10945   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10946     return SDValue();
10947 
10948   unsigned Opc = Value.getOpcode();
10949 
10950   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10951   // is a byte mask indicating a consecutive number of bytes, check to see if
10952   // Y is known to provide just those bytes.  If so, we try to replace the
10953   // load + replace + store sequence with a single (narrower) store, which makes
10954   // the load dead.
10955   if (Opc == ISD::OR) {
10956     std::pair<unsigned, unsigned> MaskedLoad;
10957     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10958     if (MaskedLoad.first)
10959       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10960                                                   Value.getOperand(1), ST,this))
10961         return SDValue(NewST, 0);
10962 
10963     // Or is commutative, so try swapping X and Y.
10964     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10965     if (MaskedLoad.first)
10966       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10967                                                   Value.getOperand(0), ST,this))
10968         return SDValue(NewST, 0);
10969   }
10970 
10971   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10972       Value.getOperand(1).getOpcode() != ISD::Constant)
10973     return SDValue();
10974 
10975   SDValue N0 = Value.getOperand(0);
10976   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10977       Chain == SDValue(N0.getNode(), 1)) {
10978     LoadSDNode *LD = cast<LoadSDNode>(N0);
10979     if (LD->getBasePtr() != Ptr ||
10980         LD->getPointerInfo().getAddrSpace() !=
10981         ST->getPointerInfo().getAddrSpace())
10982       return SDValue();
10983 
10984     // Find the type to narrow it the load / op / store to.
10985     SDValue N1 = Value.getOperand(1);
10986     unsigned BitWidth = N1.getValueSizeInBits();
10987     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10988     if (Opc == ISD::AND)
10989       Imm ^= APInt::getAllOnesValue(BitWidth);
10990     if (Imm == 0 || Imm.isAllOnesValue())
10991       return SDValue();
10992     unsigned ShAmt = Imm.countTrailingZeros();
10993     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10994     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10995     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10996     // The narrowing should be profitable, the load/store operation should be
10997     // legal (or custom) and the store size should be equal to the NewVT width.
10998     while (NewBW < BitWidth &&
10999            (NewVT.getStoreSizeInBits() != NewBW ||
11000             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11001             !TLI.isNarrowingProfitable(VT, NewVT))) {
11002       NewBW = NextPowerOf2(NewBW);
11003       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11004     }
11005     if (NewBW >= BitWidth)
11006       return SDValue();
11007 
11008     // If the lsb changed does not start at the type bitwidth boundary,
11009     // start at the previous one.
11010     if (ShAmt % NewBW)
11011       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11012     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11013                                    std::min(BitWidth, ShAmt + NewBW));
11014     if ((Imm & Mask) == Imm) {
11015       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11016       if (Opc == ISD::AND)
11017         NewImm ^= APInt::getAllOnesValue(NewBW);
11018       uint64_t PtrOff = ShAmt / 8;
11019       // For big endian targets, we need to adjust the offset to the pointer to
11020       // load the correct bytes.
11021       if (DAG.getDataLayout().isBigEndian())
11022         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11023 
11024       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11025       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11026       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11027         return SDValue();
11028 
11029       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11030                                    Ptr.getValueType(), Ptr,
11031                                    DAG.getConstant(PtrOff, SDLoc(LD),
11032                                                    Ptr.getValueType()));
11033       SDValue NewLD =
11034           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11035                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11036                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
11037       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11038                                    DAG.getConstant(NewImm, SDLoc(Value),
11039                                                    NewVT));
11040       SDValue NewST =
11041           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11042                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11043 
11044       AddToWorklist(NewPtr.getNode());
11045       AddToWorklist(NewLD.getNode());
11046       AddToWorklist(NewVal.getNode());
11047       WorklistRemover DeadNodes(*this);
11048       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11049       ++OpsNarrowed;
11050       return NewST;
11051     }
11052   }
11053 
11054   return SDValue();
11055 }
11056 
11057 /// For a given floating point load / store pair, if the load value isn't used
11058 /// by any other operations, then consider transforming the pair to integer
11059 /// load / store operations if the target deems the transformation profitable.
11060 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11061   StoreSDNode *ST  = cast<StoreSDNode>(N);
11062   SDValue Chain = ST->getChain();
11063   SDValue Value = ST->getValue();
11064   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11065       Value.hasOneUse() &&
11066       Chain == SDValue(Value.getNode(), 1)) {
11067     LoadSDNode *LD = cast<LoadSDNode>(Value);
11068     EVT VT = LD->getMemoryVT();
11069     if (!VT.isFloatingPoint() ||
11070         VT != ST->getMemoryVT() ||
11071         LD->isNonTemporal() ||
11072         ST->isNonTemporal() ||
11073         LD->getPointerInfo().getAddrSpace() != 0 ||
11074         ST->getPointerInfo().getAddrSpace() != 0)
11075       return SDValue();
11076 
11077     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11078     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11079         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11080         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11081         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11082       return SDValue();
11083 
11084     unsigned LDAlign = LD->getAlignment();
11085     unsigned STAlign = ST->getAlignment();
11086     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11087     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11088     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11089       return SDValue();
11090 
11091     SDValue NewLD =
11092         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
11093                     LD->getPointerInfo(), LDAlign);
11094 
11095     SDValue NewST =
11096         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
11097                      ST->getPointerInfo(), STAlign);
11098 
11099     AddToWorklist(NewLD.getNode());
11100     AddToWorklist(NewST.getNode());
11101     WorklistRemover DeadNodes(*this);
11102     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11103     ++LdStFP2Int;
11104     return NewST;
11105   }
11106 
11107   return SDValue();
11108 }
11109 
11110 namespace {
11111 /// Helper struct to parse and store a memory address as base + index + offset.
11112 /// We ignore sign extensions when it is safe to do so.
11113 /// The following two expressions are not equivalent. To differentiate we need
11114 /// to store whether there was a sign extension involved in the index
11115 /// computation.
11116 ///  (load (i64 add (i64 copyfromreg %c)
11117 ///                 (i64 signextend (add (i8 load %index)
11118 ///                                      (i8 1))))
11119 /// vs
11120 ///
11121 /// (load (i64 add (i64 copyfromreg %c)
11122 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11123 ///                                         (i32 1)))))
11124 struct BaseIndexOffset {
11125   SDValue Base;
11126   SDValue Index;
11127   int64_t Offset;
11128   bool IsIndexSignExt;
11129 
11130   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11131 
11132   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11133                   bool IsIndexSignExt) :
11134     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11135 
11136   bool equalBaseIndex(const BaseIndexOffset &Other) {
11137     return Other.Base == Base && Other.Index == Index &&
11138       Other.IsIndexSignExt == IsIndexSignExt;
11139   }
11140 
11141   /// Parses tree in Ptr for base, index, offset addresses.
11142   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11143     bool IsIndexSignExt = false;
11144 
11145     // Split up a folded GlobalAddress+Offset into its component parts.
11146     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11147       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11148         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11149                                                     SDLoc(GA),
11150                                                     GA->getValueType(0),
11151                                                     /*Offset=*/0,
11152                                                     /*isTargetGA=*/false,
11153                                                     GA->getTargetFlags()),
11154                                SDValue(),
11155                                GA->getOffset(),
11156                                IsIndexSignExt);
11157       }
11158 
11159     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11160     // instruction, then it could be just the BASE or everything else we don't
11161     // know how to handle. Just use Ptr as BASE and give up.
11162     if (Ptr->getOpcode() != ISD::ADD)
11163       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11164 
11165     // We know that we have at least an ADD instruction. Try to pattern match
11166     // the simple case of BASE + OFFSET.
11167     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11168       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11169       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11170                               IsIndexSignExt);
11171     }
11172 
11173     // Inside a loop the current BASE pointer is calculated using an ADD and a
11174     // MUL instruction. In this case Ptr is the actual BASE pointer.
11175     // (i64 add (i64 %array_ptr)
11176     //          (i64 mul (i64 %induction_var)
11177     //                   (i64 %element_size)))
11178     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11179       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11180 
11181     // Look at Base + Index + Offset cases.
11182     SDValue Base = Ptr->getOperand(0);
11183     SDValue IndexOffset = Ptr->getOperand(1);
11184 
11185     // Skip signextends.
11186     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11187       IndexOffset = IndexOffset->getOperand(0);
11188       IsIndexSignExt = true;
11189     }
11190 
11191     // Either the case of Base + Index (no offset) or something else.
11192     if (IndexOffset->getOpcode() != ISD::ADD)
11193       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11194 
11195     // Now we have the case of Base + Index + offset.
11196     SDValue Index = IndexOffset->getOperand(0);
11197     SDValue Offset = IndexOffset->getOperand(1);
11198 
11199     if (!isa<ConstantSDNode>(Offset))
11200       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11201 
11202     // Ignore signextends.
11203     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11204       Index = Index->getOperand(0);
11205       IsIndexSignExt = true;
11206     } else IsIndexSignExt = false;
11207 
11208     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11209     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11210   }
11211 };
11212 } // namespace
11213 
11214 // This is a helper function for visitMUL to check the profitability
11215 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11216 // MulNode is the original multiply, AddNode is (add x, c1),
11217 // and ConstNode is c2.
11218 //
11219 // If the (add x, c1) has multiple uses, we could increase
11220 // the number of adds if we make this transformation.
11221 // It would only be worth doing this if we can remove a
11222 // multiply in the process. Check for that here.
11223 // To illustrate:
11224 //     (A + c1) * c3
11225 //     (A + c2) * c3
11226 // We're checking for cases where we have common "c3 * A" expressions.
11227 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11228                                               SDValue &AddNode,
11229                                               SDValue &ConstNode) {
11230   APInt Val;
11231 
11232   // If the add only has one use, this would be OK to do.
11233   if (AddNode.getNode()->hasOneUse())
11234     return true;
11235 
11236   // Walk all the users of the constant with which we're multiplying.
11237   for (SDNode *Use : ConstNode->uses()) {
11238 
11239     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11240       continue;
11241 
11242     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11243       SDNode *OtherOp;
11244       SDNode *MulVar = AddNode.getOperand(0).getNode();
11245 
11246       // OtherOp is what we're multiplying against the constant.
11247       if (Use->getOperand(0) == ConstNode)
11248         OtherOp = Use->getOperand(1).getNode();
11249       else
11250         OtherOp = Use->getOperand(0).getNode();
11251 
11252       // Check to see if multiply is with the same operand of our "add".
11253       //
11254       //     ConstNode  = CONST
11255       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11256       //     ...
11257       //     AddNode  = (A + c1)  <-- MulVar is A.
11258       //         = AddNode * ConstNode   <-- current visiting instruction.
11259       //
11260       // If we make this transformation, we will have a common
11261       // multiply (ConstNode * A) that we can save.
11262       if (OtherOp == MulVar)
11263         return true;
11264 
11265       // Now check to see if a future expansion will give us a common
11266       // multiply.
11267       //
11268       //     ConstNode  = CONST
11269       //     AddNode    = (A + c1)
11270       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11271       //     ...
11272       //     OtherOp = (A + c2)
11273       //     Use     = OtherOp * ConstNode <-- visiting Use.
11274       //
11275       // If we make this transformation, we will have a common
11276       // multiply (CONST * A) after we also do the same transformation
11277       // to the "t2" instruction.
11278       if (OtherOp->getOpcode() == ISD::ADD &&
11279           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11280           OtherOp->getOperand(0).getNode() == MulVar)
11281         return true;
11282     }
11283   }
11284 
11285   // Didn't find a case where this would be profitable.
11286   return false;
11287 }
11288 
11289 SDValue DAGCombiner::getMergedConstantVectorStore(
11290     SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11291     SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11292   SmallVector<SDValue, 8> BuildVector;
11293 
11294   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11295     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11296     Chains.push_back(St->getChain());
11297     BuildVector.push_back(St->getValue());
11298   }
11299 
11300   return DAG.getBuildVector(Ty, SL, BuildVector);
11301 }
11302 
11303 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11304                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11305                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11306   // Make sure we have something to merge.
11307   if (NumStores < 2)
11308     return false;
11309 
11310   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11311   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11312   unsigned LatestNodeUsed = 0;
11313 
11314   for (unsigned i=0; i < NumStores; ++i) {
11315     // Find a chain for the new wide-store operand. Notice that some
11316     // of the store nodes that we found may not be selected for inclusion
11317     // in the wide store. The chain we use needs to be the chain of the
11318     // latest store node which is *used* and replaced by the wide store.
11319     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11320       LatestNodeUsed = i;
11321   }
11322 
11323   SmallVector<SDValue, 8> Chains;
11324 
11325   // The latest Node in the DAG.
11326   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11327   SDLoc DL(StoreNodes[0].MemNode);
11328 
11329   SDValue StoredVal;
11330   if (UseVector) {
11331     bool IsVec = MemVT.isVector();
11332     unsigned Elts = NumStores;
11333     if (IsVec) {
11334       // When merging vector stores, get the total number of elements.
11335       Elts *= MemVT.getVectorNumElements();
11336     }
11337     // Get the type for the merged vector store.
11338     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11339     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11340 
11341     if (IsConstantSrc) {
11342       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11343     } else {
11344       SmallVector<SDValue, 8> Ops;
11345       for (unsigned i = 0; i < NumStores; ++i) {
11346         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11347         SDValue Val = St->getValue();
11348         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11349         if (Val.getValueType() != MemVT)
11350           return false;
11351         Ops.push_back(Val);
11352         Chains.push_back(St->getChain());
11353       }
11354 
11355       // Build the extracted vector elements back into a vector.
11356       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11357                               DL, Ty, Ops);    }
11358   } else {
11359     // We should always use a vector store when merging extracted vector
11360     // elements, so this path implies a store of constants.
11361     assert(IsConstantSrc && "Merged vector elements should use vector store");
11362 
11363     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11364     APInt StoreInt(SizeInBits, 0);
11365 
11366     // Construct a single integer constant which is made of the smaller
11367     // constant inputs.
11368     bool IsLE = DAG.getDataLayout().isLittleEndian();
11369     for (unsigned i = 0; i < NumStores; ++i) {
11370       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11371       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11372       Chains.push_back(St->getChain());
11373 
11374       SDValue Val = St->getValue();
11375       StoreInt <<= ElementSizeBytes * 8;
11376       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11377         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11378       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11379         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11380       } else {
11381         llvm_unreachable("Invalid constant element type");
11382       }
11383     }
11384 
11385     // Create the new Load and Store operations.
11386     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11387     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11388   }
11389 
11390   assert(!Chains.empty());
11391 
11392   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11393   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11394                                   FirstInChain->getBasePtr(),
11395                                   FirstInChain->getPointerInfo(),
11396                                   FirstInChain->getAlignment());
11397 
11398   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11399                                                   : DAG.getSubtarget().useAA();
11400   if (UseAA) {
11401     // Replace all merged stores with the new store.
11402     for (unsigned i = 0; i < NumStores; ++i)
11403       CombineTo(StoreNodes[i].MemNode, NewStore);
11404   } else {
11405     // Replace the last store with the new store.
11406     CombineTo(LatestOp, NewStore);
11407     // Erase all other stores.
11408     for (unsigned i = 0; i < NumStores; ++i) {
11409       if (StoreNodes[i].MemNode == LatestOp)
11410         continue;
11411       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11412       // ReplaceAllUsesWith will replace all uses that existed when it was
11413       // called, but graph optimizations may cause new ones to appear. For
11414       // example, the case in pr14333 looks like
11415       //
11416       //  St's chain -> St -> another store -> X
11417       //
11418       // And the only difference from St to the other store is the chain.
11419       // When we change it's chain to be St's chain they become identical,
11420       // get CSEed and the net result is that X is now a use of St.
11421       // Since we know that St is redundant, just iterate.
11422       while (!St->use_empty())
11423         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11424       deleteAndRecombine(St);
11425     }
11426   }
11427 
11428   return true;
11429 }
11430 
11431 void DAGCombiner::getStoreMergeAndAliasCandidates(
11432     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11433     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11434   // This holds the base pointer, index, and the offset in bytes from the base
11435   // pointer.
11436   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11437 
11438   // We must have a base and an offset.
11439   if (!BasePtr.Base.getNode())
11440     return;
11441 
11442   // Do not handle stores to undef base pointers.
11443   if (BasePtr.Base.isUndef())
11444     return;
11445 
11446   // Walk up the chain and look for nodes with offsets from the same
11447   // base pointer. Stop when reaching an instruction with a different kind
11448   // or instruction which has a different base pointer.
11449   EVT MemVT = St->getMemoryVT();
11450   unsigned Seq = 0;
11451   StoreSDNode *Index = St;
11452 
11453 
11454   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11455                                                   : DAG.getSubtarget().useAA();
11456 
11457   if (UseAA) {
11458     // Look at other users of the same chain. Stores on the same chain do not
11459     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11460     // to be on the same chain, so don't bother looking at adjacent chains.
11461 
11462     SDValue Chain = St->getChain();
11463     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11464       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11465         if (I.getOperandNo() != 0)
11466           continue;
11467 
11468         if (OtherST->isVolatile() || OtherST->isIndexed())
11469           continue;
11470 
11471         if (OtherST->getMemoryVT() != MemVT)
11472           continue;
11473 
11474         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11475 
11476         if (Ptr.equalBaseIndex(BasePtr))
11477           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11478       }
11479     }
11480 
11481     return;
11482   }
11483 
11484   while (Index) {
11485     // If the chain has more than one use, then we can't reorder the mem ops.
11486     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11487       break;
11488 
11489     // Find the base pointer and offset for this memory node.
11490     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11491 
11492     // Check that the base pointer is the same as the original one.
11493     if (!Ptr.equalBaseIndex(BasePtr))
11494       break;
11495 
11496     // The memory operands must not be volatile.
11497     if (Index->isVolatile() || Index->isIndexed())
11498       break;
11499 
11500     // No truncation.
11501     if (Index->isTruncatingStore())
11502       break;
11503 
11504     // The stored memory type must be the same.
11505     if (Index->getMemoryVT() != MemVT)
11506       break;
11507 
11508     // We do not allow under-aligned stores in order to prevent
11509     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11510     // be irrelevant here; what MATTERS is that we not move memory
11511     // operations that potentially overlap past each-other.
11512     if (Index->getAlignment() < MemVT.getStoreSize())
11513       break;
11514 
11515     // We found a potential memory operand to merge.
11516     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11517 
11518     // Find the next memory operand in the chain. If the next operand in the
11519     // chain is a store then move up and continue the scan with the next
11520     // memory operand. If the next operand is a load save it and use alias
11521     // information to check if it interferes with anything.
11522     SDNode *NextInChain = Index->getChain().getNode();
11523     while (1) {
11524       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11525         // We found a store node. Use it for the next iteration.
11526         Index = STn;
11527         break;
11528       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11529         if (Ldn->isVolatile()) {
11530           Index = nullptr;
11531           break;
11532         }
11533 
11534         // Save the load node for later. Continue the scan.
11535         AliasLoadNodes.push_back(Ldn);
11536         NextInChain = Ldn->getChain().getNode();
11537         continue;
11538       } else {
11539         Index = nullptr;
11540         break;
11541       }
11542     }
11543   }
11544 }
11545 
11546 // We need to check that merging these stores does not cause a loop
11547 // in the DAG. Any store candidate may depend on another candidate
11548 // indirectly through its operand (we already consider dependencies
11549 // through the chain). Check in parallel by searching up from
11550 // non-chain operands of candidates.
11551 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11552     SmallVectorImpl<MemOpLink> &StoreNodes) {
11553   SmallPtrSet<const SDNode *, 16> Visited;
11554   SmallVector<const SDNode *, 8> Worklist;
11555   // search ops of store candidates
11556   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11557     SDNode *n = StoreNodes[i].MemNode;
11558     // Potential loops may happen only through non-chain operands
11559     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11560       Worklist.push_back(n->getOperand(j).getNode());
11561   }
11562   // search through DAG. We can stop early if we find a storenode
11563   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11564     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11565       return false;
11566   }
11567   return true;
11568 }
11569 
11570 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11571   if (OptLevel == CodeGenOpt::None)
11572     return false;
11573 
11574   EVT MemVT = St->getMemoryVT();
11575   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11576   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11577       Attribute::NoImplicitFloat);
11578 
11579   // This function cannot currently deal with non-byte-sized memory sizes.
11580   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11581     return false;
11582 
11583   if (!MemVT.isSimple())
11584     return false;
11585 
11586   // Perform an early exit check. Do not bother looking at stored values that
11587   // are not constants, loads, or extracted vector elements.
11588   SDValue StoredVal = St->getValue();
11589   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11590   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11591                        isa<ConstantFPSDNode>(StoredVal);
11592   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11593                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11594 
11595   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11596     return false;
11597 
11598   // Don't merge vectors into wider vectors if the source data comes from loads.
11599   // TODO: This restriction can be lifted by using logic similar to the
11600   // ExtractVecSrc case.
11601   if (MemVT.isVector() && IsLoadSrc)
11602     return false;
11603 
11604   // Only look at ends of store sequences.
11605   SDValue Chain = SDValue(St, 0);
11606   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11607     return false;
11608 
11609   // Save the LoadSDNodes that we find in the chain.
11610   // We need to make sure that these nodes do not interfere with
11611   // any of the store nodes.
11612   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11613 
11614   // Save the StoreSDNodes that we find in the chain.
11615   SmallVector<MemOpLink, 8> StoreNodes;
11616 
11617   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11618 
11619   // Check if there is anything to merge.
11620   if (StoreNodes.size() < 2)
11621     return false;
11622 
11623   // only do dependence check in AA case
11624   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11625                                                   : DAG.getSubtarget().useAA();
11626   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11627     return false;
11628 
11629   // Sort the memory operands according to their distance from the
11630   // base pointer.  As a secondary criteria: make sure stores coming
11631   // later in the code come first in the list. This is important for
11632   // the non-UseAA case, because we're merging stores into the FINAL
11633   // store along a chain which potentially contains aliasing stores.
11634   // Thus, if there are multiple stores to the same address, the last
11635   // one can be considered for merging but not the others.
11636   std::sort(StoreNodes.begin(), StoreNodes.end(),
11637             [](MemOpLink LHS, MemOpLink RHS) {
11638     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11639            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11640             LHS.SequenceNum < RHS.SequenceNum);
11641   });
11642 
11643   // Scan the memory operations on the chain and find the first non-consecutive
11644   // store memory address.
11645   unsigned LastConsecutiveStore = 0;
11646   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11647   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11648 
11649     // Check that the addresses are consecutive starting from the second
11650     // element in the list of stores.
11651     if (i > 0) {
11652       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11653       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11654         break;
11655     }
11656 
11657     // Check if this store interferes with any of the loads that we found.
11658     // If we find a load that alias with this store. Stop the sequence.
11659     if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) {
11660           return isAlias(Ldn, StoreNodes[i].MemNode);
11661         }))
11662       break;
11663 
11664     // Mark this node as useful.
11665     LastConsecutiveStore = i;
11666   }
11667 
11668   // The node with the lowest store address.
11669   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11670   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11671   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11672   LLVMContext &Context = *DAG.getContext();
11673   const DataLayout &DL = DAG.getDataLayout();
11674 
11675   // Store the constants into memory as one consecutive store.
11676   if (IsConstantSrc) {
11677     unsigned LastLegalType = 0;
11678     unsigned LastLegalVectorType = 0;
11679     bool NonZero = false;
11680     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11681       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11682       SDValue StoredVal = St->getValue();
11683 
11684       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11685         NonZero |= !C->isNullValue();
11686       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11687         NonZero |= !C->getConstantFPValue()->isNullValue();
11688       } else {
11689         // Non-constant.
11690         break;
11691       }
11692 
11693       // Find a legal type for the constant store.
11694       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11695       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11696       bool IsFast;
11697       if (TLI.isTypeLegal(StoreTy) &&
11698           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11699                                  FirstStoreAlign, &IsFast) && IsFast) {
11700         LastLegalType = i+1;
11701       // Or check whether a truncstore is legal.
11702       } else if (TLI.getTypeAction(Context, StoreTy) ==
11703                  TargetLowering::TypePromoteInteger) {
11704         EVT LegalizedStoredValueTy =
11705           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11706         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11707             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11708                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11709             IsFast) {
11710           LastLegalType = i + 1;
11711         }
11712       }
11713 
11714       // We only use vectors if the constant is known to be zero or the target
11715       // allows it and the function is not marked with the noimplicitfloat
11716       // attribute.
11717       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11718                                                         FirstStoreAS)) &&
11719           !NoVectors) {
11720         // Find a legal type for the vector store.
11721         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11722         if (TLI.isTypeLegal(Ty) &&
11723             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11724                                    FirstStoreAlign, &IsFast) && IsFast)
11725           LastLegalVectorType = i + 1;
11726       }
11727     }
11728 
11729     // Check if we found a legal integer type to store.
11730     if (LastLegalType == 0 && LastLegalVectorType == 0)
11731       return false;
11732 
11733     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11734     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11735 
11736     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11737                                            true, UseVector);
11738   }
11739 
11740   // When extracting multiple vector elements, try to store them
11741   // in one vector store rather than a sequence of scalar stores.
11742   if (IsExtractVecSrc) {
11743     unsigned NumStoresToMerge = 0;
11744     bool IsVec = MemVT.isVector();
11745     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11746       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11747       unsigned StoreValOpcode = St->getValue().getOpcode();
11748       // This restriction could be loosened.
11749       // Bail out if any stored values are not elements extracted from a vector.
11750       // It should be possible to handle mixed sources, but load sources need
11751       // more careful handling (see the block of code below that handles
11752       // consecutive loads).
11753       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11754           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11755         return false;
11756 
11757       // Find a legal type for the vector store.
11758       unsigned Elts = i + 1;
11759       if (IsVec) {
11760         // When merging vector stores, get the total number of elements.
11761         Elts *= MemVT.getVectorNumElements();
11762       }
11763       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11764       bool IsFast;
11765       if (TLI.isTypeLegal(Ty) &&
11766           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11767                                  FirstStoreAlign, &IsFast) && IsFast)
11768         NumStoresToMerge = i + 1;
11769     }
11770 
11771     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11772                                            false, true);
11773   }
11774 
11775   // Below we handle the case of multiple consecutive stores that
11776   // come from multiple consecutive loads. We merge them into a single
11777   // wide load and a single wide store.
11778 
11779   // Look for load nodes which are used by the stored values.
11780   SmallVector<MemOpLink, 8> LoadNodes;
11781 
11782   // Find acceptable loads. Loads need to have the same chain (token factor),
11783   // must not be zext, volatile, indexed, and they must be consecutive.
11784   BaseIndexOffset LdBasePtr;
11785   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11786     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11787     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11788     if (!Ld) break;
11789 
11790     // Loads must only have one use.
11791     if (!Ld->hasNUsesOfValue(1, 0))
11792       break;
11793 
11794     // The memory operands must not be volatile.
11795     if (Ld->isVolatile() || Ld->isIndexed())
11796       break;
11797 
11798     // We do not accept ext loads.
11799     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11800       break;
11801 
11802     // The stored memory type must be the same.
11803     if (Ld->getMemoryVT() != MemVT)
11804       break;
11805 
11806     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11807     // If this is not the first ptr that we check.
11808     if (LdBasePtr.Base.getNode()) {
11809       // The base ptr must be the same.
11810       if (!LdPtr.equalBaseIndex(LdBasePtr))
11811         break;
11812     } else {
11813       // Check that all other base pointers are the same as this one.
11814       LdBasePtr = LdPtr;
11815     }
11816 
11817     // We found a potential memory operand to merge.
11818     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11819   }
11820 
11821   if (LoadNodes.size() < 2)
11822     return false;
11823 
11824   // If we have load/store pair instructions and we only have two values,
11825   // don't bother.
11826   unsigned RequiredAlignment;
11827   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11828       St->getAlignment() >= RequiredAlignment)
11829     return false;
11830 
11831   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11832   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11833   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11834 
11835   // Scan the memory operations on the chain and find the first non-consecutive
11836   // load memory address. These variables hold the index in the store node
11837   // array.
11838   unsigned LastConsecutiveLoad = 0;
11839   // This variable refers to the size and not index in the array.
11840   unsigned LastLegalVectorType = 0;
11841   unsigned LastLegalIntegerType = 0;
11842   StartAddress = LoadNodes[0].OffsetFromBase;
11843   SDValue FirstChain = FirstLoad->getChain();
11844   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11845     // All loads must share the same chain.
11846     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11847       break;
11848 
11849     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11850     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11851       break;
11852     LastConsecutiveLoad = i;
11853     // Find a legal type for the vector store.
11854     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11855     bool IsFastSt, IsFastLd;
11856     if (TLI.isTypeLegal(StoreTy) &&
11857         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11858                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11859         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11860                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11861       LastLegalVectorType = i + 1;
11862     }
11863 
11864     // Find a legal type for the integer store.
11865     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11866     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11867     if (TLI.isTypeLegal(StoreTy) &&
11868         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11869                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11870         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11871                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11872       LastLegalIntegerType = i + 1;
11873     // Or check whether a truncstore and extload is legal.
11874     else if (TLI.getTypeAction(Context, StoreTy) ==
11875              TargetLowering::TypePromoteInteger) {
11876       EVT LegalizedStoredValueTy =
11877         TLI.getTypeToTransformTo(Context, StoreTy);
11878       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11879           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11880           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11881           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11882           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11883                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11884           IsFastSt &&
11885           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11886                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11887           IsFastLd)
11888         LastLegalIntegerType = i+1;
11889     }
11890   }
11891 
11892   // Only use vector types if the vector type is larger than the integer type.
11893   // If they are the same, use integers.
11894   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11895   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11896 
11897   // We add +1 here because the LastXXX variables refer to location while
11898   // the NumElem refers to array/index size.
11899   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11900   NumElem = std::min(LastLegalType, NumElem);
11901 
11902   if (NumElem < 2)
11903     return false;
11904 
11905   // Collect the chains from all merged stores.
11906   SmallVector<SDValue, 8> MergeStoreChains;
11907   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11908 
11909   // The latest Node in the DAG.
11910   unsigned LatestNodeUsed = 0;
11911   for (unsigned i=1; i<NumElem; ++i) {
11912     // Find a chain for the new wide-store operand. Notice that some
11913     // of the store nodes that we found may not be selected for inclusion
11914     // in the wide store. The chain we use needs to be the chain of the
11915     // latest store node which is *used* and replaced by the wide store.
11916     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11917       LatestNodeUsed = i;
11918 
11919     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11920   }
11921 
11922   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11923 
11924   // Find if it is better to use vectors or integers to load and store
11925   // to memory.
11926   EVT JointMemOpVT;
11927   if (UseVectorTy) {
11928     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11929   } else {
11930     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11931     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11932   }
11933 
11934   SDLoc LoadDL(LoadNodes[0].MemNode);
11935   SDLoc StoreDL(StoreNodes[0].MemNode);
11936 
11937   // The merged loads are required to have the same incoming chain, so
11938   // using the first's chain is acceptable.
11939   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
11940                                 FirstLoad->getBasePtr(),
11941                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
11942 
11943   SDValue NewStoreChain =
11944     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11945 
11946   SDValue NewStore =
11947       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11948                    FirstInChain->getPointerInfo(), FirstStoreAlign);
11949 
11950   // Transfer chain users from old loads to the new load.
11951   for (unsigned i = 0; i < NumElem; ++i) {
11952     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11953     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11954                                   SDValue(NewLoad.getNode(), 1));
11955   }
11956 
11957   if (UseAA) {
11958     // Replace the all stores with the new store.
11959     for (unsigned i = 0; i < NumElem; ++i)
11960       CombineTo(StoreNodes[i].MemNode, NewStore);
11961   } else {
11962     // Replace the last store with the new store.
11963     CombineTo(LatestOp, NewStore);
11964     // Erase all other stores.
11965     for (unsigned i = 0; i < NumElem; ++i) {
11966       // Remove all Store nodes.
11967       if (StoreNodes[i].MemNode == LatestOp)
11968         continue;
11969       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11970       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11971       deleteAndRecombine(St);
11972     }
11973   }
11974 
11975   return true;
11976 }
11977 
11978 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11979   SDLoc SL(ST);
11980   SDValue ReplStore;
11981 
11982   // Replace the chain to avoid dependency.
11983   if (ST->isTruncatingStore()) {
11984     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11985                                   ST->getBasePtr(), ST->getMemoryVT(),
11986                                   ST->getMemOperand());
11987   } else {
11988     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11989                              ST->getMemOperand());
11990   }
11991 
11992   // Create token to keep both nodes around.
11993   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11994                               MVT::Other, ST->getChain(), ReplStore);
11995 
11996   // Make sure the new and old chains are cleaned up.
11997   AddToWorklist(Token.getNode());
11998 
11999   // Don't add users to work list.
12000   return CombineTo(ST, Token, false);
12001 }
12002 
12003 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12004   SDValue Value = ST->getValue();
12005   if (Value.getOpcode() == ISD::TargetConstantFP)
12006     return SDValue();
12007 
12008   SDLoc DL(ST);
12009 
12010   SDValue Chain = ST->getChain();
12011   SDValue Ptr = ST->getBasePtr();
12012 
12013   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12014 
12015   // NOTE: If the original store is volatile, this transform must not increase
12016   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12017   // processor operation but an i64 (which is not legal) requires two.  So the
12018   // transform should not be done in this case.
12019 
12020   SDValue Tmp;
12021   switch (CFP->getSimpleValueType(0).SimpleTy) {
12022   default:
12023     llvm_unreachable("Unknown FP type");
12024   case MVT::f16:    // We don't do this for these yet.
12025   case MVT::f80:
12026   case MVT::f128:
12027   case MVT::ppcf128:
12028     return SDValue();
12029   case MVT::f32:
12030     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12031         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12032       ;
12033       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12034                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12035                             MVT::i32);
12036       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12037     }
12038 
12039     return SDValue();
12040   case MVT::f64:
12041     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12042          !ST->isVolatile()) ||
12043         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12044       ;
12045       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12046                             getZExtValue(), SDLoc(CFP), MVT::i64);
12047       return DAG.getStore(Chain, DL, Tmp,
12048                           Ptr, ST->getMemOperand());
12049     }
12050 
12051     if (!ST->isVolatile() &&
12052         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12053       // Many FP stores are not made apparent until after legalize, e.g. for
12054       // argument passing.  Since this is so common, custom legalize the
12055       // 64-bit integer store into two 32-bit stores.
12056       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12057       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12058       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12059       if (DAG.getDataLayout().isBigEndian())
12060         std::swap(Lo, Hi);
12061 
12062       unsigned Alignment = ST->getAlignment();
12063       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12064       AAMDNodes AAInfo = ST->getAAInfo();
12065 
12066       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12067                                  ST->getAlignment(), MMOFlags, AAInfo);
12068       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12069                         DAG.getConstant(4, DL, Ptr.getValueType()));
12070       Alignment = MinAlign(Alignment, 4U);
12071       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12072                                  ST->getPointerInfo().getWithOffset(4),
12073                                  Alignment, MMOFlags, AAInfo);
12074       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12075                          St0, St1);
12076     }
12077 
12078     return SDValue();
12079   }
12080 }
12081 
12082 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12083   StoreSDNode *ST  = cast<StoreSDNode>(N);
12084   SDValue Chain = ST->getChain();
12085   SDValue Value = ST->getValue();
12086   SDValue Ptr   = ST->getBasePtr();
12087 
12088   // If this is a store of a bit convert, store the input value if the
12089   // resultant store does not need a higher alignment than the original.
12090   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12091       ST->isUnindexed()) {
12092     EVT SVT = Value.getOperand(0).getValueType();
12093     if (((!LegalOperations && !ST->isVolatile()) ||
12094          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12095         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12096       unsigned OrigAlign = ST->getAlignment();
12097       bool Fast = false;
12098       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12099                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12100           Fast) {
12101         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12102                             ST->getPointerInfo(), OrigAlign,
12103                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
12104       }
12105     }
12106   }
12107 
12108   // Turn 'store undef, Ptr' -> nothing.
12109   if (Value.isUndef() && ST->isUnindexed())
12110     return Chain;
12111 
12112   // Try to infer better alignment information than the store already has.
12113   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12114     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12115       if (Align > ST->getAlignment()) {
12116         SDValue NewStore =
12117             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12118                               ST->getMemoryVT(), Align,
12119                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
12120         if (NewStore.getNode() != N)
12121           return CombineTo(ST, NewStore, true);
12122       }
12123     }
12124   }
12125 
12126   // Try transforming a pair floating point load / store ops to integer
12127   // load / store ops.
12128   if (SDValue NewST = TransformFPLoadStorePair(N))
12129     return NewST;
12130 
12131   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12132                                                   : DAG.getSubtarget().useAA();
12133 #ifndef NDEBUG
12134   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12135       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12136     UseAA = false;
12137 #endif
12138   if (UseAA && ST->isUnindexed()) {
12139     // FIXME: We should do this even without AA enabled. AA will just allow
12140     // FindBetterChain to work in more situations. The problem with this is that
12141     // any combine that expects memory operations to be on consecutive chains
12142     // first needs to be updated to look for users of the same chain.
12143 
12144     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12145     // adjacent stores.
12146     if (findBetterNeighborChains(ST)) {
12147       // replaceStoreChain uses CombineTo, which handled all of the worklist
12148       // manipulation. Return the original node to not do anything else.
12149       return SDValue(ST, 0);
12150     }
12151     Chain = ST->getChain();
12152   }
12153 
12154   // Try transforming N to an indexed store.
12155   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12156     return SDValue(N, 0);
12157 
12158   // FIXME: is there such a thing as a truncating indexed store?
12159   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12160       Value.getValueType().isInteger()) {
12161     // See if we can simplify the input to this truncstore with knowledge that
12162     // only the low bits are being used.  For example:
12163     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12164     SDValue Shorter = GetDemandedBits(
12165         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12166                                     ST->getMemoryVT().getScalarSizeInBits()));
12167     AddToWorklist(Value.getNode());
12168     if (Shorter.getNode())
12169       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12170                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12171 
12172     // Otherwise, see if we can simplify the operation with
12173     // SimplifyDemandedBits, which only works if the value has a single use.
12174     if (SimplifyDemandedBits(
12175             Value,
12176             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12177                                  ST->getMemoryVT().getScalarSizeInBits())))
12178       return SDValue(N, 0);
12179   }
12180 
12181   // If this is a load followed by a store to the same location, then the store
12182   // is dead/noop.
12183   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12184     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12185         ST->isUnindexed() && !ST->isVolatile() &&
12186         // There can't be any side effects between the load and store, such as
12187         // a call or store.
12188         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12189       // The store is dead, remove it.
12190       return Chain;
12191     }
12192   }
12193 
12194   // If this is a store followed by a store with the same value to the same
12195   // location, then the store is dead/noop.
12196   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12197     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12198         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12199         ST1->isUnindexed() && !ST1->isVolatile()) {
12200       // The store is dead, remove it.
12201       return Chain;
12202     }
12203   }
12204 
12205   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12206   // truncating store.  We can do this even if this is already a truncstore.
12207   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12208       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12209       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12210                             ST->getMemoryVT())) {
12211     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12212                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12213   }
12214 
12215   // Only perform this optimization before the types are legal, because we
12216   // don't want to perform this optimization on every DAGCombine invocation.
12217   if (!LegalTypes) {
12218     bool EverChanged = false;
12219 
12220     do {
12221       // There can be multiple store sequences on the same chain.
12222       // Keep trying to merge store sequences until we are unable to do so
12223       // or until we merge the last store on the chain.
12224       bool Changed = MergeConsecutiveStores(ST);
12225       EverChanged |= Changed;
12226       if (!Changed) break;
12227     } while (ST->getOpcode() != ISD::DELETED_NODE);
12228 
12229     if (EverChanged)
12230       return SDValue(N, 0);
12231   }
12232 
12233   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12234   //
12235   // Make sure to do this only after attempting to merge stores in order to
12236   //  avoid changing the types of some subset of stores due to visit order,
12237   //  preventing their merging.
12238   if (isa<ConstantFPSDNode>(Value)) {
12239     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12240       return NewSt;
12241   }
12242 
12243   if (SDValue NewSt = splitMergedValStore(ST))
12244     return NewSt;
12245 
12246   return ReduceLoadOpStoreWidth(N);
12247 }
12248 
12249 /// For the instruction sequence of store below, F and I values
12250 /// are bundled together as an i64 value before being stored into memory.
12251 /// Sometimes it is more efficent to generate separate stores for F and I,
12252 /// which can remove the bitwise instructions or sink them to colder places.
12253 ///
12254 ///   (store (or (zext (bitcast F to i32) to i64),
12255 ///              (shl (zext I to i64), 32)), addr)  -->
12256 ///   (store F, addr) and (store I, addr+4)
12257 ///
12258 /// Similarly, splitting for other merged store can also be beneficial, like:
12259 /// For pair of {i32, i32}, i64 store --> two i32 stores.
12260 /// For pair of {i32, i16}, i64 store --> two i32 stores.
12261 /// For pair of {i16, i16}, i32 store --> two i16 stores.
12262 /// For pair of {i16, i8},  i32 store --> two i16 stores.
12263 /// For pair of {i8, i8},   i16 store --> two i8 stores.
12264 ///
12265 /// We allow each target to determine specifically which kind of splitting is
12266 /// supported.
12267 ///
12268 /// The store patterns are commonly seen from the simple code snippet below
12269 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
12270 ///   void goo(const std::pair<int, float> &);
12271 ///   hoo() {
12272 ///     ...
12273 ///     goo(std::make_pair(tmp, ftmp));
12274 ///     ...
12275 ///   }
12276 ///
12277 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
12278   if (OptLevel == CodeGenOpt::None)
12279     return SDValue();
12280 
12281   SDValue Val = ST->getValue();
12282   SDLoc DL(ST);
12283 
12284   // Match OR operand.
12285   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
12286     return SDValue();
12287 
12288   // Match SHL operand and get Lower and Higher parts of Val.
12289   SDValue Op1 = Val.getOperand(0);
12290   SDValue Op2 = Val.getOperand(1);
12291   SDValue Lo, Hi;
12292   if (Op1.getOpcode() != ISD::SHL) {
12293     std::swap(Op1, Op2);
12294     if (Op1.getOpcode() != ISD::SHL)
12295       return SDValue();
12296   }
12297   Lo = Op2;
12298   Hi = Op1.getOperand(0);
12299   if (!Op1.hasOneUse())
12300     return SDValue();
12301 
12302   // Match shift amount to HalfValBitSize.
12303   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
12304   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
12305   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
12306     return SDValue();
12307 
12308   // Lo and Hi are zero-extended from int with size less equal than 32
12309   // to i64.
12310   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
12311       !Lo.getOperand(0).getValueType().isScalarInteger() ||
12312       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
12313       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
12314       !Hi.getOperand(0).getValueType().isScalarInteger() ||
12315       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
12316     return SDValue();
12317 
12318   if (!TLI.isMultiStoresCheaperThanBitsMerge(Lo.getOperand(0),
12319                                              Hi.getOperand(0)))
12320     return SDValue();
12321 
12322   // Start to split store.
12323   unsigned Alignment = ST->getAlignment();
12324   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12325   AAMDNodes AAInfo = ST->getAAInfo();
12326 
12327   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
12328   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
12329   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
12330   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
12331 
12332   SDValue Chain = ST->getChain();
12333   SDValue Ptr = ST->getBasePtr();
12334   // Lower value store.
12335   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12336                              ST->getAlignment(), MMOFlags, AAInfo);
12337   Ptr =
12338       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12339                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
12340   // Higher value store.
12341   SDValue St1 =
12342       DAG.getStore(St0, DL, Hi, Ptr,
12343                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
12344                    Alignment / 2, MMOFlags, AAInfo);
12345   return St1;
12346 }
12347 
12348 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12349   SDValue InVec = N->getOperand(0);
12350   SDValue InVal = N->getOperand(1);
12351   SDValue EltNo = N->getOperand(2);
12352   SDLoc DL(N);
12353 
12354   // If the inserted element is an UNDEF, just use the input vector.
12355   if (InVal.isUndef())
12356     return InVec;
12357 
12358   EVT VT = InVec.getValueType();
12359 
12360   // If we can't generate a legal BUILD_VECTOR, exit
12361   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12362     return SDValue();
12363 
12364   // Check that we know which element is being inserted
12365   if (!isa<ConstantSDNode>(EltNo))
12366     return SDValue();
12367   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12368 
12369   // Canonicalize insert_vector_elt dag nodes.
12370   // Example:
12371   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12372   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12373   //
12374   // Do this only if the child insert_vector node has one use; also
12375   // do this only if indices are both constants and Idx1 < Idx0.
12376   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12377       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12378     unsigned OtherElt =
12379       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12380     if (Elt < OtherElt) {
12381       // Swap nodes.
12382       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
12383                                   InVec.getOperand(0), InVal, EltNo);
12384       AddToWorklist(NewOp.getNode());
12385       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12386                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12387     }
12388   }
12389 
12390   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12391   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12392   // vector elements.
12393   SmallVector<SDValue, 8> Ops;
12394   // Do not combine these two vectors if the output vector will not replace
12395   // the input vector.
12396   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12397     Ops.append(InVec.getNode()->op_begin(),
12398                InVec.getNode()->op_end());
12399   } else if (InVec.isUndef()) {
12400     unsigned NElts = VT.getVectorNumElements();
12401     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12402   } else {
12403     return SDValue();
12404   }
12405 
12406   // Insert the element
12407   if (Elt < Ops.size()) {
12408     // All the operands of BUILD_VECTOR must have the same type;
12409     // we enforce that here.
12410     EVT OpVT = Ops[0].getValueType();
12411     if (InVal.getValueType() != OpVT)
12412       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12413                 DAG.getNode(ISD::ANY_EXTEND, DL, OpVT, InVal) :
12414                 DAG.getNode(ISD::TRUNCATE, DL, OpVT, InVal);
12415     Ops[Elt] = InVal;
12416   }
12417 
12418   // Return the new vector
12419   return DAG.getBuildVector(VT, DL, Ops);
12420 }
12421 
12422 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12423     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12424   assert(!OriginalLoad->isVolatile());
12425 
12426   EVT ResultVT = EVE->getValueType(0);
12427   EVT VecEltVT = InVecVT.getVectorElementType();
12428   unsigned Align = OriginalLoad->getAlignment();
12429   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12430       VecEltVT.getTypeForEVT(*DAG.getContext()));
12431 
12432   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12433     return SDValue();
12434 
12435   Align = NewAlign;
12436 
12437   SDValue NewPtr = OriginalLoad->getBasePtr();
12438   SDValue Offset;
12439   EVT PtrType = NewPtr.getValueType();
12440   MachinePointerInfo MPI;
12441   SDLoc DL(EVE);
12442   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12443     int Elt = ConstEltNo->getZExtValue();
12444     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12445     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12446     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12447   } else {
12448     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12449     Offset = DAG.getNode(
12450         ISD::MUL, DL, PtrType, Offset,
12451         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12452     MPI = OriginalLoad->getPointerInfo();
12453   }
12454   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12455 
12456   // The replacement we need to do here is a little tricky: we need to
12457   // replace an extractelement of a load with a load.
12458   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12459   // Note that this replacement assumes that the extractvalue is the only
12460   // use of the load; that's okay because we don't want to perform this
12461   // transformation in other cases anyway.
12462   SDValue Load;
12463   SDValue Chain;
12464   if (ResultVT.bitsGT(VecEltVT)) {
12465     // If the result type of vextract is wider than the load, then issue an
12466     // extending load instead.
12467     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12468                                                   VecEltVT)
12469                                    ? ISD::ZEXTLOAD
12470                                    : ISD::EXTLOAD;
12471     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
12472                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
12473                           Align, OriginalLoad->getMemOperand()->getFlags(),
12474                           OriginalLoad->getAAInfo());
12475     Chain = Load.getValue(1);
12476   } else {
12477     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
12478                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
12479                        OriginalLoad->getAAInfo());
12480     Chain = Load.getValue(1);
12481     if (ResultVT.bitsLT(VecEltVT))
12482       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12483     else
12484       Load = DAG.getBitcast(ResultVT, Load);
12485   }
12486   WorklistRemover DeadNodes(*this);
12487   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12488   SDValue To[] = { Load, Chain };
12489   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12490   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12491   // worklist explicitly as well.
12492   AddToWorklist(Load.getNode());
12493   AddUsersToWorklist(Load.getNode()); // Add users too
12494   // Make sure to revisit this node to clean it up; it will usually be dead.
12495   AddToWorklist(EVE);
12496   ++OpsNarrowed;
12497   return SDValue(EVE, 0);
12498 }
12499 
12500 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12501   // (vextract (scalar_to_vector val, 0) -> val
12502   SDValue InVec = N->getOperand(0);
12503   EVT VT = InVec.getValueType();
12504   EVT NVT = N->getValueType(0);
12505 
12506   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12507     // Check if the result type doesn't match the inserted element type. A
12508     // SCALAR_TO_VECTOR may truncate the inserted element and the
12509     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12510     SDValue InOp = InVec.getOperand(0);
12511     if (InOp.getValueType() != NVT) {
12512       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12513       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12514     }
12515     return InOp;
12516   }
12517 
12518   SDValue EltNo = N->getOperand(1);
12519   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12520 
12521   // extract_vector_elt (build_vector x, y), 1 -> y
12522   if (ConstEltNo &&
12523       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12524       TLI.isTypeLegal(VT) &&
12525       (InVec.hasOneUse() ||
12526        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12527     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12528     EVT InEltVT = Elt.getValueType();
12529 
12530     // Sometimes build_vector's scalar input types do not match result type.
12531     if (NVT == InEltVT)
12532       return Elt;
12533 
12534     // TODO: It may be useful to truncate if free if the build_vector implicitly
12535     // converts.
12536   }
12537 
12538   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12539   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12540       ConstEltNo->isNullValue() && VT.isInteger()) {
12541     SDValue BCSrc = InVec.getOperand(0);
12542     if (BCSrc.getValueType().isScalarInteger())
12543       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12544   }
12545 
12546   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
12547   //
12548   // This only really matters if the index is non-constant since other combines
12549   // on the constant elements already work.
12550   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12551       EltNo == InVec.getOperand(2)) {
12552     SDValue Elt = InVec.getOperand(1);
12553     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
12554   }
12555 
12556   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12557   // We only perform this optimization before the op legalization phase because
12558   // we may introduce new vector instructions which are not backed by TD
12559   // patterns. For example on AVX, extracting elements from a wide vector
12560   // without using extract_subvector. However, if we can find an underlying
12561   // scalar value, then we can always use that.
12562   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12563     int NumElem = VT.getVectorNumElements();
12564     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12565     // Find the new index to extract from.
12566     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12567 
12568     // Extracting an undef index is undef.
12569     if (OrigElt == -1)
12570       return DAG.getUNDEF(NVT);
12571 
12572     // Select the right vector half to extract from.
12573     SDValue SVInVec;
12574     if (OrigElt < NumElem) {
12575       SVInVec = InVec->getOperand(0);
12576     } else {
12577       SVInVec = InVec->getOperand(1);
12578       OrigElt -= NumElem;
12579     }
12580 
12581     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12582       SDValue InOp = SVInVec.getOperand(OrigElt);
12583       if (InOp.getValueType() != NVT) {
12584         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12585         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12586       }
12587 
12588       return InOp;
12589     }
12590 
12591     // FIXME: We should handle recursing on other vector shuffles and
12592     // scalar_to_vector here as well.
12593 
12594     if (!LegalOperations) {
12595       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12596       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12597                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12598     }
12599   }
12600 
12601   bool BCNumEltsChanged = false;
12602   EVT ExtVT = VT.getVectorElementType();
12603   EVT LVT = ExtVT;
12604 
12605   // If the result of load has to be truncated, then it's not necessarily
12606   // profitable.
12607   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12608     return SDValue();
12609 
12610   if (InVec.getOpcode() == ISD::BITCAST) {
12611     // Don't duplicate a load with other uses.
12612     if (!InVec.hasOneUse())
12613       return SDValue();
12614 
12615     EVT BCVT = InVec.getOperand(0).getValueType();
12616     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12617       return SDValue();
12618     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12619       BCNumEltsChanged = true;
12620     InVec = InVec.getOperand(0);
12621     ExtVT = BCVT.getVectorElementType();
12622   }
12623 
12624   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12625   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12626       ISD::isNormalLoad(InVec.getNode()) &&
12627       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12628     SDValue Index = N->getOperand(1);
12629     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
12630       if (!OrigLoad->isVolatile()) {
12631         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12632                                                              OrigLoad);
12633       }
12634     }
12635   }
12636 
12637   // Perform only after legalization to ensure build_vector / vector_shuffle
12638   // optimizations have already been done.
12639   if (!LegalOperations) return SDValue();
12640 
12641   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12642   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12643   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12644 
12645   if (ConstEltNo) {
12646     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12647 
12648     LoadSDNode *LN0 = nullptr;
12649     const ShuffleVectorSDNode *SVN = nullptr;
12650     if (ISD::isNormalLoad(InVec.getNode())) {
12651       LN0 = cast<LoadSDNode>(InVec);
12652     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12653                InVec.getOperand(0).getValueType() == ExtVT &&
12654                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12655       // Don't duplicate a load with other uses.
12656       if (!InVec.hasOneUse())
12657         return SDValue();
12658 
12659       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12660     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12661       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12662       // =>
12663       // (load $addr+1*size)
12664 
12665       // Don't duplicate a load with other uses.
12666       if (!InVec.hasOneUse())
12667         return SDValue();
12668 
12669       // If the bit convert changed the number of elements, it is unsafe
12670       // to examine the mask.
12671       if (BCNumEltsChanged)
12672         return SDValue();
12673 
12674       // Select the input vector, guarding against out of range extract vector.
12675       unsigned NumElems = VT.getVectorNumElements();
12676       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12677       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12678 
12679       if (InVec.getOpcode() == ISD::BITCAST) {
12680         // Don't duplicate a load with other uses.
12681         if (!InVec.hasOneUse())
12682           return SDValue();
12683 
12684         InVec = InVec.getOperand(0);
12685       }
12686       if (ISD::isNormalLoad(InVec.getNode())) {
12687         LN0 = cast<LoadSDNode>(InVec);
12688         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12689         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12690       }
12691     }
12692 
12693     // Make sure we found a non-volatile load and the extractelement is
12694     // the only use.
12695     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12696       return SDValue();
12697 
12698     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12699     if (Elt == -1)
12700       return DAG.getUNDEF(LVT);
12701 
12702     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12703   }
12704 
12705   return SDValue();
12706 }
12707 
12708 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12709 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12710   // We perform this optimization post type-legalization because
12711   // the type-legalizer often scalarizes integer-promoted vectors.
12712   // Performing this optimization before may create bit-casts which
12713   // will be type-legalized to complex code sequences.
12714   // We perform this optimization only before the operation legalizer because we
12715   // may introduce illegal operations.
12716   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12717     return SDValue();
12718 
12719   unsigned NumInScalars = N->getNumOperands();
12720   SDLoc DL(N);
12721   EVT VT = N->getValueType(0);
12722 
12723   // Check to see if this is a BUILD_VECTOR of a bunch of values
12724   // which come from any_extend or zero_extend nodes. If so, we can create
12725   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12726   // optimizations. We do not handle sign-extend because we can't fill the sign
12727   // using shuffles.
12728   EVT SourceType = MVT::Other;
12729   bool AllAnyExt = true;
12730 
12731   for (unsigned i = 0; i != NumInScalars; ++i) {
12732     SDValue In = N->getOperand(i);
12733     // Ignore undef inputs.
12734     if (In.isUndef()) continue;
12735 
12736     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12737     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12738 
12739     // Abort if the element is not an extension.
12740     if (!ZeroExt && !AnyExt) {
12741       SourceType = MVT::Other;
12742       break;
12743     }
12744 
12745     // The input is a ZeroExt or AnyExt. Check the original type.
12746     EVT InTy = In.getOperand(0).getValueType();
12747 
12748     // Check that all of the widened source types are the same.
12749     if (SourceType == MVT::Other)
12750       // First time.
12751       SourceType = InTy;
12752     else if (InTy != SourceType) {
12753       // Multiple income types. Abort.
12754       SourceType = MVT::Other;
12755       break;
12756     }
12757 
12758     // Check if all of the extends are ANY_EXTENDs.
12759     AllAnyExt &= AnyExt;
12760   }
12761 
12762   // In order to have valid types, all of the inputs must be extended from the
12763   // same source type and all of the inputs must be any or zero extend.
12764   // Scalar sizes must be a power of two.
12765   EVT OutScalarTy = VT.getScalarType();
12766   bool ValidTypes = SourceType != MVT::Other &&
12767                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12768                  isPowerOf2_32(SourceType.getSizeInBits());
12769 
12770   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12771   // turn into a single shuffle instruction.
12772   if (!ValidTypes)
12773     return SDValue();
12774 
12775   bool isLE = DAG.getDataLayout().isLittleEndian();
12776   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12777   assert(ElemRatio > 1 && "Invalid element size ratio");
12778   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12779                                DAG.getConstant(0, DL, SourceType);
12780 
12781   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12782   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12783 
12784   // Populate the new build_vector
12785   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12786     SDValue Cast = N->getOperand(i);
12787     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12788             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12789             Cast.isUndef()) && "Invalid cast opcode");
12790     SDValue In;
12791     if (Cast.isUndef())
12792       In = DAG.getUNDEF(SourceType);
12793     else
12794       In = Cast->getOperand(0);
12795     unsigned Index = isLE ? (i * ElemRatio) :
12796                             (i * ElemRatio + (ElemRatio - 1));
12797 
12798     assert(Index < Ops.size() && "Invalid index");
12799     Ops[Index] = In;
12800   }
12801 
12802   // The type of the new BUILD_VECTOR node.
12803   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12804   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12805          "Invalid vector size");
12806   // Check if the new vector type is legal.
12807   if (!isTypeLegal(VecVT)) return SDValue();
12808 
12809   // Make the new BUILD_VECTOR.
12810   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
12811 
12812   // The new BUILD_VECTOR node has the potential to be further optimized.
12813   AddToWorklist(BV.getNode());
12814   // Bitcast to the desired type.
12815   return DAG.getBitcast(VT, BV);
12816 }
12817 
12818 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12819   EVT VT = N->getValueType(0);
12820 
12821   unsigned NumInScalars = N->getNumOperands();
12822   SDLoc DL(N);
12823 
12824   EVT SrcVT = MVT::Other;
12825   unsigned Opcode = ISD::DELETED_NODE;
12826   unsigned NumDefs = 0;
12827 
12828   for (unsigned i = 0; i != NumInScalars; ++i) {
12829     SDValue In = N->getOperand(i);
12830     unsigned Opc = In.getOpcode();
12831 
12832     if (Opc == ISD::UNDEF)
12833       continue;
12834 
12835     // If all scalar values are floats and converted from integers.
12836     if (Opcode == ISD::DELETED_NODE &&
12837         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12838       Opcode = Opc;
12839     }
12840 
12841     if (Opc != Opcode)
12842       return SDValue();
12843 
12844     EVT InVT = In.getOperand(0).getValueType();
12845 
12846     // If all scalar values are typed differently, bail out. It's chosen to
12847     // simplify BUILD_VECTOR of integer types.
12848     if (SrcVT == MVT::Other)
12849       SrcVT = InVT;
12850     if (SrcVT != InVT)
12851       return SDValue();
12852     NumDefs++;
12853   }
12854 
12855   // If the vector has just one element defined, it's not worth to fold it into
12856   // a vectorized one.
12857   if (NumDefs < 2)
12858     return SDValue();
12859 
12860   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12861          && "Should only handle conversion from integer to float.");
12862   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12863 
12864   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12865 
12866   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12867     return SDValue();
12868 
12869   // Just because the floating-point vector type is legal does not necessarily
12870   // mean that the corresponding integer vector type is.
12871   if (!isTypeLegal(NVT))
12872     return SDValue();
12873 
12874   SmallVector<SDValue, 8> Opnds;
12875   for (unsigned i = 0; i != NumInScalars; ++i) {
12876     SDValue In = N->getOperand(i);
12877 
12878     if (In.isUndef())
12879       Opnds.push_back(DAG.getUNDEF(SrcVT));
12880     else
12881       Opnds.push_back(In.getOperand(0));
12882   }
12883   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
12884   AddToWorklist(BV.getNode());
12885 
12886   return DAG.getNode(Opcode, DL, VT, BV);
12887 }
12888 
12889 SDValue DAGCombiner::createBuildVecShuffle(SDLoc DL, SDNode *N,
12890                                            ArrayRef<int> VectorMask,
12891                                            SDValue VecIn1, SDValue VecIn2,
12892                                            unsigned LeftIdx) {
12893   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12894   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
12895 
12896   EVT VT = N->getValueType(0);
12897   EVT InVT1 = VecIn1.getValueType();
12898   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
12899 
12900   unsigned Vec2Offset = InVT1.getVectorNumElements();
12901   unsigned NumElems = VT.getVectorNumElements();
12902   unsigned ShuffleNumElems = NumElems;
12903 
12904   // We can't generate a shuffle node with mismatched input and output types.
12905   // Try to make the types match the type of the output.
12906   if (InVT1 != VT || InVT2 != VT) {
12907     if (InVT1.getSizeInBits() * 2 == VT.getSizeInBits() && InVT1 == InVT2) {
12908       // If both input vectors are exactly half the size of the output, concat
12909       // them. If we have only one (non-zero) input, concat it with undef.
12910       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, VecIn1,
12911                            VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1));
12912       VecIn2 = SDValue();
12913     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
12914       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
12915         return SDValue();
12916 
12917       if (!VecIn2.getNode()) {
12918         // If we only have one input vector, and it's twice the size of the
12919         // output, split it in two.
12920         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
12921                              DAG.getConstant(NumElems, DL, IdxTy));
12922         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
12923         // Since we now have shorter input vectors, adjust the offset of the
12924         // second vector's start.
12925         Vec2Offset = NumElems;
12926       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
12927         // VecIn1 is wider than the output, and we have another, possibly
12928         // smaller input. Pad the smaller input with undefs, shuffle at the
12929         // input vector width, and extract the output.
12930         // The shuffle type is different than VT, so check legality again.
12931         if (LegalOperations &&
12932             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
12933           return SDValue();
12934 
12935         if (InVT1 != InVT2)
12936           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
12937                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
12938         ShuffleNumElems = NumElems * 2;
12939       }
12940     } else {
12941       // TODO: Support cases where the length mismatch isn't exactly by a
12942       // factor of 2.
12943       // TODO: Move this check upwards, so that if we have bad type
12944       // mismatches, we don't create any DAG nodes.
12945       return SDValue();
12946     }
12947   }
12948 
12949   // Initialize mask to undef.
12950   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
12951 
12952   // Only need to run up to the number of elements actually used, not the
12953   // total number of elements in the shuffle - if we are shuffling a wider
12954   // vector, the high lanes should be set to undef.
12955   for (unsigned i = 0; i != NumElems; ++i) {
12956     if (VectorMask[i] <= 0)
12957       continue;
12958 
12959     SDValue Extract = N->getOperand(i);
12960     unsigned ExtIndex =
12961         cast<ConstantSDNode>(Extract.getOperand(1))->getZExtValue();
12962 
12963     if (VectorMask[i] == (int)LeftIdx) {
12964       Mask[i] = ExtIndex;
12965     } else if (VectorMask[i] == (int)LeftIdx + 1) {
12966       Mask[i] = Vec2Offset + ExtIndex;
12967     }
12968   }
12969 
12970   // The type the input vectors may have changed above.
12971   InVT1 = VecIn1.getValueType();
12972 
12973   // If we already have a VecIn2, it should have the same type as VecIn1.
12974   // If we don't, get an undef/zero vector of the appropriate type.
12975   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
12976   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
12977 
12978   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
12979   if (ShuffleNumElems > NumElems)
12980     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
12981 
12982   return Shuffle;
12983 }
12984 
12985 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12986 // operations. If the types of the vectors we're extracting from allow it,
12987 // turn this into a vector_shuffle node.
12988 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
12989   SDLoc DL(N);
12990   EVT VT = N->getValueType(0);
12991 
12992   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12993   if (!isTypeLegal(VT))
12994     return SDValue();
12995 
12996   // May only combine to shuffle after legalize if shuffle is legal.
12997   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12998     return SDValue();
12999 
13000   bool UsesZeroVector = false;
13001   unsigned NumElems = N->getNumOperands();
13002 
13003   // Record, for each element of the newly built vector, which input vector
13004   // that element comes from. -1 stands for undef, 0 for the zero vector,
13005   // and positive values for the input vectors.
13006   // VectorMask maps each element to its vector number, and VecIn maps vector
13007   // numbers to their initial SDValues.
13008 
13009   SmallVector<int, 8> VectorMask(NumElems, -1);
13010   SmallVector<SDValue, 8> VecIn;
13011   VecIn.push_back(SDValue());
13012 
13013   for (unsigned i = 0; i != NumElems; ++i) {
13014     SDValue Op = N->getOperand(i);
13015 
13016     if (Op.isUndef())
13017       continue;
13018 
13019     // See if we can use a blend with a zero vector.
13020     // TODO: Should we generalize this to a blend with an arbitrary constant
13021     // vector?
13022     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13023       UsesZeroVector = true;
13024       VectorMask[i] = 0;
13025       continue;
13026     }
13027 
13028     // Not an undef or zero. If the input is something other than an
13029     // EXTRACT_VECTOR_ELT with a constant index, bail out.
13030     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13031         !isa<ConstantSDNode>(Op.getOperand(1)))
13032       return SDValue();
13033 
13034     SDValue ExtractedFromVec = Op.getOperand(0);
13035 
13036     // All inputs must have the same element type as the output.
13037     if (VT.getVectorElementType() !=
13038         ExtractedFromVec.getValueType().getVectorElementType())
13039       return SDValue();
13040 
13041     // Have we seen this input vector before?
13042     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13043     // a map back from SDValues to numbers isn't worth it.
13044     unsigned Idx = std::distance(
13045         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13046     if (Idx == VecIn.size())
13047       VecIn.push_back(ExtractedFromVec);
13048 
13049     VectorMask[i] = Idx;
13050   }
13051 
13052   // If we didn't find at least one input vector, bail out.
13053   if (VecIn.size() < 2)
13054     return SDValue();
13055 
13056   // TODO: We want to sort the vectors by descending length, so that adjacent
13057   // pairs have similar length, and the longer vector is always first in the
13058   // pair.
13059 
13060   // TODO: Should this fire if some of the input vectors has illegal type (like
13061   // it does now), or should we let legalization run its course first?
13062 
13063   // Shuffle phase:
13064   // Take pairs of vectors, and shuffle them so that the result has elements
13065   // from these vectors in the correct places.
13066   // For example, given:
13067   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13068   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13069   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13070   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13071   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13072   // We will generate:
13073   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13074   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13075   SmallVector<SDValue, 4> Shuffles;
13076   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13077     unsigned LeftIdx = 2 * In + 1;
13078     SDValue VecLeft = VecIn[LeftIdx];
13079     SDValue VecRight =
13080         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13081 
13082     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13083                                                 VecRight, LeftIdx))
13084       Shuffles.push_back(Shuffle);
13085     else
13086       return SDValue();
13087   }
13088 
13089   // If we need the zero vector as an "ingredient" in the blend tree, add it
13090   // to the list of shuffles.
13091   if (UsesZeroVector)
13092     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13093                                       : DAG.getConstantFP(0.0, DL, VT));
13094 
13095   // If we only have one shuffle, we're done.
13096   if (Shuffles.size() == 1)
13097     return Shuffles[0];
13098 
13099   // Update the vector mask to point to the post-shuffle vectors.
13100   for (int &Vec : VectorMask)
13101     if (Vec == 0)
13102       Vec = Shuffles.size() - 1;
13103     else
13104       Vec = (Vec - 1) / 2;
13105 
13106   // More than one shuffle. Generate a binary tree of blends, e.g. if from
13107   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13108   // generate:
13109   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13110   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13111   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13112   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13113   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13114   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13115   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13116 
13117   // Make sure the initial size of the shuffle list is even.
13118   if (Shuffles.size() % 2)
13119     Shuffles.push_back(DAG.getUNDEF(VT));
13120 
13121   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13122     if (CurSize % 2) {
13123       Shuffles[CurSize] = DAG.getUNDEF(VT);
13124       CurSize++;
13125     }
13126     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13127       int Left = 2 * In;
13128       int Right = 2 * In + 1;
13129       SmallVector<int, 8> Mask(NumElems, -1);
13130       for (unsigned i = 0; i != NumElems; ++i) {
13131         if (VectorMask[i] == Left) {
13132           Mask[i] = i;
13133           VectorMask[i] = In;
13134         } else if (VectorMask[i] == Right) {
13135           Mask[i] = i + NumElems;
13136           VectorMask[i] = In;
13137         }
13138       }
13139 
13140       Shuffles[In] =
13141           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13142     }
13143   }
13144 
13145   return Shuffles[0];
13146 }
13147 
13148 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13149   EVT VT = N->getValueType(0);
13150 
13151   // A vector built entirely of undefs is undef.
13152   if (ISD::allOperandsUndef(N))
13153     return DAG.getUNDEF(VT);
13154 
13155   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13156     return V;
13157 
13158   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13159     return V;
13160 
13161   if (SDValue V = reduceBuildVecToShuffle(N))
13162     return V;
13163 
13164   return SDValue();
13165 }
13166 
13167 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13169   EVT OpVT = N->getOperand(0).getValueType();
13170 
13171   // If the operands are legal vectors, leave them alone.
13172   if (TLI.isTypeLegal(OpVT))
13173     return SDValue();
13174 
13175   SDLoc DL(N);
13176   EVT VT = N->getValueType(0);
13177   SmallVector<SDValue, 8> Ops;
13178 
13179   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13180   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13181 
13182   // Keep track of what we encounter.
13183   bool AnyInteger = false;
13184   bool AnyFP = false;
13185   for (const SDValue &Op : N->ops()) {
13186     if (ISD::BITCAST == Op.getOpcode() &&
13187         !Op.getOperand(0).getValueType().isVector())
13188       Ops.push_back(Op.getOperand(0));
13189     else if (ISD::UNDEF == Op.getOpcode())
13190       Ops.push_back(ScalarUndef);
13191     else
13192       return SDValue();
13193 
13194     // Note whether we encounter an integer or floating point scalar.
13195     // If it's neither, bail out, it could be something weird like x86mmx.
13196     EVT LastOpVT = Ops.back().getValueType();
13197     if (LastOpVT.isFloatingPoint())
13198       AnyFP = true;
13199     else if (LastOpVT.isInteger())
13200       AnyInteger = true;
13201     else
13202       return SDValue();
13203   }
13204 
13205   // If any of the operands is a floating point scalar bitcast to a vector,
13206   // use floating point types throughout, and bitcast everything.
13207   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
13208   if (AnyFP) {
13209     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
13210     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13211     if (AnyInteger) {
13212       for (SDValue &Op : Ops) {
13213         if (Op.getValueType() == SVT)
13214           continue;
13215         if (Op.isUndef())
13216           Op = ScalarUndef;
13217         else
13218           Op = DAG.getBitcast(SVT, Op);
13219       }
13220     }
13221   }
13222 
13223   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
13224                                VT.getSizeInBits() / SVT.getSizeInBits());
13225   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
13226 }
13227 
13228 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
13229 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
13230 // most two distinct vectors the same size as the result, attempt to turn this
13231 // into a legal shuffle.
13232 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
13233   EVT VT = N->getValueType(0);
13234   EVT OpVT = N->getOperand(0).getValueType();
13235   int NumElts = VT.getVectorNumElements();
13236   int NumOpElts = OpVT.getVectorNumElements();
13237 
13238   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
13239   SmallVector<int, 8> Mask;
13240 
13241   for (SDValue Op : N->ops()) {
13242     // Peek through any bitcast.
13243     while (Op.getOpcode() == ISD::BITCAST)
13244       Op = Op.getOperand(0);
13245 
13246     // UNDEF nodes convert to UNDEF shuffle mask values.
13247     if (Op.isUndef()) {
13248       Mask.append((unsigned)NumOpElts, -1);
13249       continue;
13250     }
13251 
13252     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13253       return SDValue();
13254 
13255     // What vector are we extracting the subvector from and at what index?
13256     SDValue ExtVec = Op.getOperand(0);
13257 
13258     // We want the EVT of the original extraction to correctly scale the
13259     // extraction index.
13260     EVT ExtVT = ExtVec.getValueType();
13261 
13262     // Peek through any bitcast.
13263     while (ExtVec.getOpcode() == ISD::BITCAST)
13264       ExtVec = ExtVec.getOperand(0);
13265 
13266     // UNDEF nodes convert to UNDEF shuffle mask values.
13267     if (ExtVec.isUndef()) {
13268       Mask.append((unsigned)NumOpElts, -1);
13269       continue;
13270     }
13271 
13272     if (!isa<ConstantSDNode>(Op.getOperand(1)))
13273       return SDValue();
13274     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13275 
13276     // Ensure that we are extracting a subvector from a vector the same
13277     // size as the result.
13278     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13279       return SDValue();
13280 
13281     // Scale the subvector index to account for any bitcast.
13282     int NumExtElts = ExtVT.getVectorNumElements();
13283     if (0 == (NumExtElts % NumElts))
13284       ExtIdx /= (NumExtElts / NumElts);
13285     else if (0 == (NumElts % NumExtElts))
13286       ExtIdx *= (NumElts / NumExtElts);
13287     else
13288       return SDValue();
13289 
13290     // At most we can reference 2 inputs in the final shuffle.
13291     if (SV0.isUndef() || SV0 == ExtVec) {
13292       SV0 = ExtVec;
13293       for (int i = 0; i != NumOpElts; ++i)
13294         Mask.push_back(i + ExtIdx);
13295     } else if (SV1.isUndef() || SV1 == ExtVec) {
13296       SV1 = ExtVec;
13297       for (int i = 0; i != NumOpElts; ++i)
13298         Mask.push_back(i + ExtIdx + NumElts);
13299     } else {
13300       return SDValue();
13301     }
13302   }
13303 
13304   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13305     return SDValue();
13306 
13307   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13308                               DAG.getBitcast(VT, SV1), Mask);
13309 }
13310 
13311 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13312   // If we only have one input vector, we don't need to do any concatenation.
13313   if (N->getNumOperands() == 1)
13314     return N->getOperand(0);
13315 
13316   // Check if all of the operands are undefs.
13317   EVT VT = N->getValueType(0);
13318   if (ISD::allOperandsUndef(N))
13319     return DAG.getUNDEF(VT);
13320 
13321   // Optimize concat_vectors where all but the first of the vectors are undef.
13322   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13323         return Op.isUndef();
13324       })) {
13325     SDValue In = N->getOperand(0);
13326     assert(In.getValueType().isVector() && "Must concat vectors");
13327 
13328     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13329     if (In->getOpcode() == ISD::BITCAST &&
13330         !In->getOperand(0)->getValueType(0).isVector()) {
13331       SDValue Scalar = In->getOperand(0);
13332 
13333       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13334       // look through the trunc so we can still do the transform:
13335       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13336       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13337           !TLI.isTypeLegal(Scalar.getValueType()) &&
13338           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13339         Scalar = Scalar->getOperand(0);
13340 
13341       EVT SclTy = Scalar->getValueType(0);
13342 
13343       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13344         return SDValue();
13345 
13346       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13347                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13348       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13349         return SDValue();
13350 
13351       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
13352       return DAG.getBitcast(VT, Res);
13353     }
13354   }
13355 
13356   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13357   // We have already tested above for an UNDEF only concatenation.
13358   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13359   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13360   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13361     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13362   };
13363   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13364     SmallVector<SDValue, 8> Opnds;
13365     EVT SVT = VT.getScalarType();
13366 
13367     EVT MinVT = SVT;
13368     if (!SVT.isFloatingPoint()) {
13369       // If BUILD_VECTOR are from built from integer, they may have different
13370       // operand types. Get the smallest type and truncate all operands to it.
13371       bool FoundMinVT = false;
13372       for (const SDValue &Op : N->ops())
13373         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13374           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13375           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13376           FoundMinVT = true;
13377         }
13378       assert(FoundMinVT && "Concat vector type mismatch");
13379     }
13380 
13381     for (const SDValue &Op : N->ops()) {
13382       EVT OpVT = Op.getValueType();
13383       unsigned NumElts = OpVT.getVectorNumElements();
13384 
13385       if (ISD::UNDEF == Op.getOpcode())
13386         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13387 
13388       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13389         if (SVT.isFloatingPoint()) {
13390           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13391           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13392         } else {
13393           for (unsigned i = 0; i != NumElts; ++i)
13394             Opnds.push_back(
13395                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13396         }
13397       }
13398     }
13399 
13400     assert(VT.getVectorNumElements() == Opnds.size() &&
13401            "Concat vector type mismatch");
13402     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13403   }
13404 
13405   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13406   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13407     return V;
13408 
13409   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13410   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13411     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13412       return V;
13413 
13414   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13415   // nodes often generate nop CONCAT_VECTOR nodes.
13416   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13417   // place the incoming vectors at the exact same location.
13418   SDValue SingleSource = SDValue();
13419   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13420 
13421   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13422     SDValue Op = N->getOperand(i);
13423 
13424     if (Op.isUndef())
13425       continue;
13426 
13427     // Check if this is the identity extract:
13428     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13429       return SDValue();
13430 
13431     // Find the single incoming vector for the extract_subvector.
13432     if (SingleSource.getNode()) {
13433       if (Op.getOperand(0) != SingleSource)
13434         return SDValue();
13435     } else {
13436       SingleSource = Op.getOperand(0);
13437 
13438       // Check the source type is the same as the type of the result.
13439       // If not, this concat may extend the vector, so we can not
13440       // optimize it away.
13441       if (SingleSource.getValueType() != N->getValueType(0))
13442         return SDValue();
13443     }
13444 
13445     unsigned IdentityIndex = i * PartNumElem;
13446     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13447     // The extract index must be constant.
13448     if (!CS)
13449       return SDValue();
13450 
13451     // Check that we are reading from the identity index.
13452     if (CS->getZExtValue() != IdentityIndex)
13453       return SDValue();
13454   }
13455 
13456   if (SingleSource.getNode())
13457     return SingleSource;
13458 
13459   return SDValue();
13460 }
13461 
13462 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13463   EVT NVT = N->getValueType(0);
13464   SDValue V = N->getOperand(0);
13465 
13466   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13467     // Combine:
13468     //    (extract_subvec (concat V1, V2, ...), i)
13469     // Into:
13470     //    Vi if possible
13471     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13472     // type.
13473     if (V->getOperand(0).getValueType() != NVT)
13474       return SDValue();
13475     unsigned Idx = N->getConstantOperandVal(1);
13476     unsigned NumElems = NVT.getVectorNumElements();
13477     assert((Idx % NumElems) == 0 &&
13478            "IDX in concat is not a multiple of the result vector length.");
13479     return V->getOperand(Idx / NumElems);
13480   }
13481 
13482   // Skip bitcasting
13483   if (V->getOpcode() == ISD::BITCAST)
13484     V = V.getOperand(0);
13485 
13486   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13487     // Handle only simple case where vector being inserted and vector
13488     // being extracted are of same type, and are half size of larger vectors.
13489     EVT BigVT = V->getOperand(0).getValueType();
13490     EVT SmallVT = V->getOperand(1).getValueType();
13491     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13492       return SDValue();
13493 
13494     // Only handle cases where both indexes are constants with the same type.
13495     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13496     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13497 
13498     if (InsIdx && ExtIdx &&
13499         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13500         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13501       // Combine:
13502       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13503       // Into:
13504       //    indices are equal or bit offsets are equal => V1
13505       //    otherwise => (extract_subvec V1, ExtIdx)
13506       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
13507           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
13508         return DAG.getBitcast(NVT, V->getOperand(1));
13509       return DAG.getNode(
13510           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
13511           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13512           N->getOperand(1));
13513     }
13514   }
13515 
13516   return SDValue();
13517 }
13518 
13519 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13520                                                  SDValue V, SelectionDAG &DAG) {
13521   SDLoc DL(V);
13522   EVT VT = V.getValueType();
13523 
13524   switch (V.getOpcode()) {
13525   default:
13526     return V;
13527 
13528   case ISD::CONCAT_VECTORS: {
13529     EVT OpVT = V->getOperand(0).getValueType();
13530     int OpSize = OpVT.getVectorNumElements();
13531     SmallBitVector OpUsedElements(OpSize, false);
13532     bool FoundSimplification = false;
13533     SmallVector<SDValue, 4> NewOps;
13534     NewOps.reserve(V->getNumOperands());
13535     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13536       SDValue Op = V->getOperand(i);
13537       bool OpUsed = false;
13538       for (int j = 0; j < OpSize; ++j)
13539         if (UsedElements[i * OpSize + j]) {
13540           OpUsedElements[j] = true;
13541           OpUsed = true;
13542         }
13543       NewOps.push_back(
13544           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13545                  : DAG.getUNDEF(OpVT));
13546       FoundSimplification |= Op == NewOps.back();
13547       OpUsedElements.reset();
13548     }
13549     if (FoundSimplification)
13550       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13551     return V;
13552   }
13553 
13554   case ISD::INSERT_SUBVECTOR: {
13555     SDValue BaseV = V->getOperand(0);
13556     SDValue SubV = V->getOperand(1);
13557     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13558     if (!IdxN)
13559       return V;
13560 
13561     int SubSize = SubV.getValueType().getVectorNumElements();
13562     int Idx = IdxN->getZExtValue();
13563     bool SubVectorUsed = false;
13564     SmallBitVector SubUsedElements(SubSize, false);
13565     for (int i = 0; i < SubSize; ++i)
13566       if (UsedElements[i + Idx]) {
13567         SubVectorUsed = true;
13568         SubUsedElements[i] = true;
13569         UsedElements[i + Idx] = false;
13570       }
13571 
13572     // Now recurse on both the base and sub vectors.
13573     SDValue SimplifiedSubV =
13574         SubVectorUsed
13575             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13576             : DAG.getUNDEF(SubV.getValueType());
13577     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13578     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13579       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13580                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13581     return V;
13582   }
13583   }
13584 }
13585 
13586 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13587                                        SDValue N1, SelectionDAG &DAG) {
13588   EVT VT = SVN->getValueType(0);
13589   int NumElts = VT.getVectorNumElements();
13590   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13591   for (int M : SVN->getMask())
13592     if (M >= 0 && M < NumElts)
13593       N0UsedElements[M] = true;
13594     else if (M >= NumElts)
13595       N1UsedElements[M - NumElts] = true;
13596 
13597   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13598   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13599   if (S0 == N0 && S1 == N1)
13600     return SDValue();
13601 
13602   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13603 }
13604 
13605 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13606 // or turn a shuffle of a single concat into simpler shuffle then concat.
13607 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13608   EVT VT = N->getValueType(0);
13609   unsigned NumElts = VT.getVectorNumElements();
13610 
13611   SDValue N0 = N->getOperand(0);
13612   SDValue N1 = N->getOperand(1);
13613   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13614 
13615   SmallVector<SDValue, 4> Ops;
13616   EVT ConcatVT = N0.getOperand(0).getValueType();
13617   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13618   unsigned NumConcats = NumElts / NumElemsPerConcat;
13619 
13620   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13621   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13622   // half vector elements.
13623   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13624       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13625                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13626     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13627                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13628     N1 = DAG.getUNDEF(ConcatVT);
13629     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13630   }
13631 
13632   // Look at every vector that's inserted. We're looking for exact
13633   // subvector-sized copies from a concatenated vector
13634   for (unsigned I = 0; I != NumConcats; ++I) {
13635     // Make sure we're dealing with a copy.
13636     unsigned Begin = I * NumElemsPerConcat;
13637     bool AllUndef = true, NoUndef = true;
13638     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13639       if (SVN->getMaskElt(J) >= 0)
13640         AllUndef = false;
13641       else
13642         NoUndef = false;
13643     }
13644 
13645     if (NoUndef) {
13646       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13647         return SDValue();
13648 
13649       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13650         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13651           return SDValue();
13652 
13653       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13654       if (FirstElt < N0.getNumOperands())
13655         Ops.push_back(N0.getOperand(FirstElt));
13656       else
13657         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13658 
13659     } else if (AllUndef) {
13660       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13661     } else { // Mixed with general masks and undefs, can't do optimization.
13662       return SDValue();
13663     }
13664   }
13665 
13666   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13667 }
13668 
13669 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13670   EVT VT = N->getValueType(0);
13671   unsigned NumElts = VT.getVectorNumElements();
13672 
13673   SDValue N0 = N->getOperand(0);
13674   SDValue N1 = N->getOperand(1);
13675 
13676   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13677 
13678   // Canonicalize shuffle undef, undef -> undef
13679   if (N0.isUndef() && N1.isUndef())
13680     return DAG.getUNDEF(VT);
13681 
13682   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13683 
13684   // Canonicalize shuffle v, v -> v, undef
13685   if (N0 == N1) {
13686     SmallVector<int, 8> NewMask;
13687     for (unsigned i = 0; i != NumElts; ++i) {
13688       int Idx = SVN->getMaskElt(i);
13689       if (Idx >= (int)NumElts) Idx -= NumElts;
13690       NewMask.push_back(Idx);
13691     }
13692     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
13693   }
13694 
13695   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13696   if (N0.isUndef())
13697     return DAG.getCommutedVectorShuffle(*SVN);
13698 
13699   // Remove references to rhs if it is undef
13700   if (N1.isUndef()) {
13701     bool Changed = false;
13702     SmallVector<int, 8> NewMask;
13703     for (unsigned i = 0; i != NumElts; ++i) {
13704       int Idx = SVN->getMaskElt(i);
13705       if (Idx >= (int)NumElts) {
13706         Idx = -1;
13707         Changed = true;
13708       }
13709       NewMask.push_back(Idx);
13710     }
13711     if (Changed)
13712       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
13713   }
13714 
13715   // If it is a splat, check if the argument vector is another splat or a
13716   // build_vector.
13717   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13718     SDNode *V = N0.getNode();
13719 
13720     // If this is a bit convert that changes the element type of the vector but
13721     // not the number of vector elements, look through it.  Be careful not to
13722     // look though conversions that change things like v4f32 to v2f64.
13723     if (V->getOpcode() == ISD::BITCAST) {
13724       SDValue ConvInput = V->getOperand(0);
13725       if (ConvInput.getValueType().isVector() &&
13726           ConvInput.getValueType().getVectorNumElements() == NumElts)
13727         V = ConvInput.getNode();
13728     }
13729 
13730     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13731       assert(V->getNumOperands() == NumElts &&
13732              "BUILD_VECTOR has wrong number of operands");
13733       SDValue Base;
13734       bool AllSame = true;
13735       for (unsigned i = 0; i != NumElts; ++i) {
13736         if (!V->getOperand(i).isUndef()) {
13737           Base = V->getOperand(i);
13738           break;
13739         }
13740       }
13741       // Splat of <u, u, u, u>, return <u, u, u, u>
13742       if (!Base.getNode())
13743         return N0;
13744       for (unsigned i = 0; i != NumElts; ++i) {
13745         if (V->getOperand(i) != Base) {
13746           AllSame = false;
13747           break;
13748         }
13749       }
13750       // Splat of <x, x, x, x>, return <x, x, x, x>
13751       if (AllSame)
13752         return N0;
13753 
13754       // Canonicalize any other splat as a build_vector.
13755       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13756       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13757       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13758 
13759       // We may have jumped through bitcasts, so the type of the
13760       // BUILD_VECTOR may not match the type of the shuffle.
13761       if (V->getValueType(0) != VT)
13762         NewBV = DAG.getBitcast(VT, NewBV);
13763       return NewBV;
13764     }
13765   }
13766 
13767   // There are various patterns used to build up a vector from smaller vectors,
13768   // subvectors, or elements. Scan chains of these and replace unused insertions
13769   // or components with undef.
13770   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13771     return S;
13772 
13773   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13774       Level < AfterLegalizeVectorOps &&
13775       (N1.isUndef() ||
13776       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13777        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13778     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13779       return V;
13780   }
13781 
13782   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13783   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13784   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13785     SmallVector<SDValue, 8> Ops;
13786     for (int M : SVN->getMask()) {
13787       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13788       if (M >= 0) {
13789         int Idx = M % NumElts;
13790         SDValue &S = (M < (int)NumElts ? N0 : N1);
13791         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13792           Op = S.getOperand(Idx);
13793         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13794           if (Idx == 0)
13795             Op = S.getOperand(0);
13796         } else {
13797           // Operand can't be combined - bail out.
13798           break;
13799         }
13800       }
13801       Ops.push_back(Op);
13802     }
13803     if (Ops.size() == VT.getVectorNumElements()) {
13804       // BUILD_VECTOR requires all inputs to be of the same type, find the
13805       // maximum type and extend them all.
13806       EVT SVT = VT.getScalarType();
13807       if (SVT.isInteger())
13808         for (SDValue &Op : Ops)
13809           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13810       if (SVT != VT.getScalarType())
13811         for (SDValue &Op : Ops)
13812           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13813                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13814                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13815       return DAG.getBuildVector(VT, SDLoc(N), Ops);
13816     }
13817   }
13818 
13819   // If this shuffle only has a single input that is a bitcasted shuffle,
13820   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13821   // back to their original types.
13822   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13823       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13824       TLI.isTypeLegal(VT)) {
13825 
13826     // Peek through the bitcast only if there is one user.
13827     SDValue BC0 = N0;
13828     while (BC0.getOpcode() == ISD::BITCAST) {
13829       if (!BC0.hasOneUse())
13830         break;
13831       BC0 = BC0.getOperand(0);
13832     }
13833 
13834     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13835       if (Scale == 1)
13836         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13837 
13838       SmallVector<int, 8> NewMask;
13839       for (int M : Mask)
13840         for (int s = 0; s != Scale; ++s)
13841           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13842       return NewMask;
13843     };
13844 
13845     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13846       EVT SVT = VT.getScalarType();
13847       EVT InnerVT = BC0->getValueType(0);
13848       EVT InnerSVT = InnerVT.getScalarType();
13849 
13850       // Determine which shuffle works with the smaller scalar type.
13851       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13852       EVT ScaleSVT = ScaleVT.getScalarType();
13853 
13854       if (TLI.isTypeLegal(ScaleVT) &&
13855           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13856           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13857 
13858         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13859         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13860 
13861         // Scale the shuffle masks to the smaller scalar type.
13862         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13863         SmallVector<int, 8> InnerMask =
13864             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13865         SmallVector<int, 8> OuterMask =
13866             ScaleShuffleMask(SVN->getMask(), OuterScale);
13867 
13868         // Merge the shuffle masks.
13869         SmallVector<int, 8> NewMask;
13870         for (int M : OuterMask)
13871           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13872 
13873         // Test for shuffle mask legality over both commutations.
13874         SDValue SV0 = BC0->getOperand(0);
13875         SDValue SV1 = BC0->getOperand(1);
13876         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13877         if (!LegalMask) {
13878           std::swap(SV0, SV1);
13879           ShuffleVectorSDNode::commuteMask(NewMask);
13880           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13881         }
13882 
13883         if (LegalMask) {
13884           SV0 = DAG.getBitcast(ScaleVT, SV0);
13885           SV1 = DAG.getBitcast(ScaleVT, SV1);
13886           return DAG.getBitcast(
13887               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13888         }
13889       }
13890     }
13891   }
13892 
13893   // Canonicalize shuffles according to rules:
13894   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13895   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13896   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13897   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13898       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13899       TLI.isTypeLegal(VT)) {
13900     // The incoming shuffle must be of the same type as the result of the
13901     // current shuffle.
13902     assert(N1->getOperand(0).getValueType() == VT &&
13903            "Shuffle types don't match");
13904 
13905     SDValue SV0 = N1->getOperand(0);
13906     SDValue SV1 = N1->getOperand(1);
13907     bool HasSameOp0 = N0 == SV0;
13908     bool IsSV1Undef = SV1.isUndef();
13909     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13910       // Commute the operands of this shuffle so that next rule
13911       // will trigger.
13912       return DAG.getCommutedVectorShuffle(*SVN);
13913   }
13914 
13915   // Try to fold according to rules:
13916   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13917   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13918   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13919   // Don't try to fold shuffles with illegal type.
13920   // Only fold if this shuffle is the only user of the other shuffle.
13921   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13922       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13923     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13924 
13925     // The incoming shuffle must be of the same type as the result of the
13926     // current shuffle.
13927     assert(OtherSV->getOperand(0).getValueType() == VT &&
13928            "Shuffle types don't match");
13929 
13930     SDValue SV0, SV1;
13931     SmallVector<int, 4> Mask;
13932     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13933     // operand, and SV1 as the second operand.
13934     for (unsigned i = 0; i != NumElts; ++i) {
13935       int Idx = SVN->getMaskElt(i);
13936       if (Idx < 0) {
13937         // Propagate Undef.
13938         Mask.push_back(Idx);
13939         continue;
13940       }
13941 
13942       SDValue CurrentVec;
13943       if (Idx < (int)NumElts) {
13944         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13945         // shuffle mask to identify which vector is actually referenced.
13946         Idx = OtherSV->getMaskElt(Idx);
13947         if (Idx < 0) {
13948           // Propagate Undef.
13949           Mask.push_back(Idx);
13950           continue;
13951         }
13952 
13953         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13954                                            : OtherSV->getOperand(1);
13955       } else {
13956         // This shuffle index references an element within N1.
13957         CurrentVec = N1;
13958       }
13959 
13960       // Simple case where 'CurrentVec' is UNDEF.
13961       if (CurrentVec.isUndef()) {
13962         Mask.push_back(-1);
13963         continue;
13964       }
13965 
13966       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13967       // will be the first or second operand of the combined shuffle.
13968       Idx = Idx % NumElts;
13969       if (!SV0.getNode() || SV0 == CurrentVec) {
13970         // Ok. CurrentVec is the left hand side.
13971         // Update the mask accordingly.
13972         SV0 = CurrentVec;
13973         Mask.push_back(Idx);
13974         continue;
13975       }
13976 
13977       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13978       if (SV1.getNode() && SV1 != CurrentVec)
13979         return SDValue();
13980 
13981       // Ok. CurrentVec is the right hand side.
13982       // Update the mask accordingly.
13983       SV1 = CurrentVec;
13984       Mask.push_back(Idx + NumElts);
13985     }
13986 
13987     // Check if all indices in Mask are Undef. In case, propagate Undef.
13988     bool isUndefMask = true;
13989     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13990       isUndefMask &= Mask[i] < 0;
13991 
13992     if (isUndefMask)
13993       return DAG.getUNDEF(VT);
13994 
13995     if (!SV0.getNode())
13996       SV0 = DAG.getUNDEF(VT);
13997     if (!SV1.getNode())
13998       SV1 = DAG.getUNDEF(VT);
13999 
14000     // Avoid introducing shuffles with illegal mask.
14001     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14002       ShuffleVectorSDNode::commuteMask(Mask);
14003 
14004       if (!TLI.isShuffleMaskLegal(Mask, VT))
14005         return SDValue();
14006 
14007       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14008       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14009       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14010       std::swap(SV0, SV1);
14011     }
14012 
14013     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14014     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14015     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14016     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14017   }
14018 
14019   return SDValue();
14020 }
14021 
14022 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14023   SDValue InVal = N->getOperand(0);
14024   EVT VT = N->getValueType(0);
14025 
14026   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14027   // with a VECTOR_SHUFFLE.
14028   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14029     SDValue InVec = InVal->getOperand(0);
14030     SDValue EltNo = InVal->getOperand(1);
14031 
14032     // FIXME: We could support implicit truncation if the shuffle can be
14033     // scaled to a smaller vector scalar type.
14034     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
14035     if (C0 && VT == InVec.getValueType() &&
14036         VT.getScalarType() == InVal.getValueType()) {
14037       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
14038       int Elt = C0->getZExtValue();
14039       NewMask[0] = Elt;
14040 
14041       if (TLI.isShuffleMaskLegal(NewMask, VT))
14042         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
14043                                     NewMask);
14044     }
14045   }
14046 
14047   return SDValue();
14048 }
14049 
14050 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
14051   EVT VT = N->getValueType(0);
14052   SDValue N0 = N->getOperand(0);
14053   SDValue N1 = N->getOperand(1);
14054   SDValue N2 = N->getOperand(2);
14055 
14056   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
14057   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
14058   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
14059   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
14060       N0.getOperand(1).getValueType() == N1.getValueType() &&
14061       N0.getOperand(2) == N2)
14062     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
14063                        N1, N2);
14064 
14065   if (N0.getValueType() != N1.getValueType())
14066     return SDValue();
14067 
14068   // If the input vector is a concatenation, and the insert replaces
14069   // one of the halves, we can optimize into a single concat_vectors.
14070   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
14071       N2.getOpcode() == ISD::Constant) {
14072     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
14073 
14074     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14075     // (concat_vectors Z, Y)
14076     if (InsIdx == 0)
14077       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
14078                          N0.getOperand(1));
14079 
14080     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14081     // (concat_vectors X, Z)
14082     if (InsIdx == VT.getVectorNumElements() / 2)
14083       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
14084                          N1);
14085   }
14086 
14087   return SDValue();
14088 }
14089 
14090 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
14091   SDValue N0 = N->getOperand(0);
14092 
14093   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
14094   if (N0->getOpcode() == ISD::FP16_TO_FP)
14095     return N0->getOperand(0);
14096 
14097   return SDValue();
14098 }
14099 
14100 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
14101   SDValue N0 = N->getOperand(0);
14102 
14103   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
14104   if (N0->getOpcode() == ISD::AND) {
14105     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
14106     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
14107       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
14108                          N0.getOperand(0));
14109     }
14110   }
14111 
14112   return SDValue();
14113 }
14114 
14115 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
14116 /// with the destination vector and a zero vector.
14117 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
14118 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
14119 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
14120   EVT VT = N->getValueType(0);
14121   SDValue LHS = N->getOperand(0);
14122   SDValue RHS = N->getOperand(1);
14123   SDLoc DL(N);
14124 
14125   // Make sure we're not running after operation legalization where it
14126   // may have custom lowered the vector shuffles.
14127   if (LegalOperations)
14128     return SDValue();
14129 
14130   if (N->getOpcode() != ISD::AND)
14131     return SDValue();
14132 
14133   if (RHS.getOpcode() == ISD::BITCAST)
14134     RHS = RHS.getOperand(0);
14135 
14136   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
14137     return SDValue();
14138 
14139   EVT RVT = RHS.getValueType();
14140   unsigned NumElts = RHS.getNumOperands();
14141 
14142   // Attempt to create a valid clear mask, splitting the mask into
14143   // sub elements and checking to see if each is
14144   // all zeros or all ones - suitable for shuffle masking.
14145   auto BuildClearMask = [&](int Split) {
14146     int NumSubElts = NumElts * Split;
14147     int NumSubBits = RVT.getScalarSizeInBits() / Split;
14148 
14149     SmallVector<int, 8> Indices;
14150     for (int i = 0; i != NumSubElts; ++i) {
14151       int EltIdx = i / Split;
14152       int SubIdx = i % Split;
14153       SDValue Elt = RHS.getOperand(EltIdx);
14154       if (Elt.isUndef()) {
14155         Indices.push_back(-1);
14156         continue;
14157       }
14158 
14159       APInt Bits;
14160       if (isa<ConstantSDNode>(Elt))
14161         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
14162       else if (isa<ConstantFPSDNode>(Elt))
14163         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
14164       else
14165         return SDValue();
14166 
14167       // Extract the sub element from the constant bit mask.
14168       if (DAG.getDataLayout().isBigEndian()) {
14169         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
14170       } else {
14171         Bits = Bits.lshr(SubIdx * NumSubBits);
14172       }
14173 
14174       if (Split > 1)
14175         Bits = Bits.trunc(NumSubBits);
14176 
14177       if (Bits.isAllOnesValue())
14178         Indices.push_back(i);
14179       else if (Bits == 0)
14180         Indices.push_back(i + NumSubElts);
14181       else
14182         return SDValue();
14183     }
14184 
14185     // Let's see if the target supports this vector_shuffle.
14186     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
14187     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
14188     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
14189       return SDValue();
14190 
14191     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
14192     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
14193                                                    DAG.getBitcast(ClearVT, LHS),
14194                                                    Zero, Indices));
14195   };
14196 
14197   // Determine maximum split level (byte level masking).
14198   int MaxSplit = 1;
14199   if (RVT.getScalarSizeInBits() % 8 == 0)
14200     MaxSplit = RVT.getScalarSizeInBits() / 8;
14201 
14202   for (int Split = 1; Split <= MaxSplit; ++Split)
14203     if (RVT.getScalarSizeInBits() % Split == 0)
14204       if (SDValue S = BuildClearMask(Split))
14205         return S;
14206 
14207   return SDValue();
14208 }
14209 
14210 /// Visit a binary vector operation, like ADD.
14211 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
14212   assert(N->getValueType(0).isVector() &&
14213          "SimplifyVBinOp only works on vectors!");
14214 
14215   SDValue LHS = N->getOperand(0);
14216   SDValue RHS = N->getOperand(1);
14217   SDValue Ops[] = {LHS, RHS};
14218 
14219   // See if we can constant fold the vector operation.
14220   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
14221           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
14222     return Fold;
14223 
14224   // Try to convert a constant mask AND into a shuffle clear mask.
14225   if (SDValue Shuffle = XformToShuffleWithZero(N))
14226     return Shuffle;
14227 
14228   // Type legalization might introduce new shuffles in the DAG.
14229   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
14230   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
14231   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
14232       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
14233       LHS.getOperand(1).isUndef() &&
14234       RHS.getOperand(1).isUndef()) {
14235     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
14236     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
14237 
14238     if (SVN0->getMask().equals(SVN1->getMask())) {
14239       EVT VT = N->getValueType(0);
14240       SDValue UndefVector = LHS.getOperand(1);
14241       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
14242                                      LHS.getOperand(0), RHS.getOperand(0),
14243                                      N->getFlags());
14244       AddUsersToWorklist(N);
14245       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
14246                                   SVN0->getMask());
14247     }
14248   }
14249 
14250   return SDValue();
14251 }
14252 
14253 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
14254                                     SDValue N2) {
14255   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
14256 
14257   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
14258                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
14259 
14260   // If we got a simplified select_cc node back from SimplifySelectCC, then
14261   // break it down into a new SETCC node, and a new SELECT node, and then return
14262   // the SELECT node, since we were called with a SELECT node.
14263   if (SCC.getNode()) {
14264     // Check to see if we got a select_cc back (to turn into setcc/select).
14265     // Otherwise, just return whatever node we got back, like fabs.
14266     if (SCC.getOpcode() == ISD::SELECT_CC) {
14267       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
14268                                   N0.getValueType(),
14269                                   SCC.getOperand(0), SCC.getOperand(1),
14270                                   SCC.getOperand(4));
14271       AddToWorklist(SETCC.getNode());
14272       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14273                            SCC.getOperand(2), SCC.getOperand(3));
14274     }
14275 
14276     return SCC;
14277   }
14278   return SDValue();
14279 }
14280 
14281 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14282 /// being selected between, see if we can simplify the select.  Callers of this
14283 /// should assume that TheSelect is deleted if this returns true.  As such, they
14284 /// should return the appropriate thing (e.g. the node) back to the top-level of
14285 /// the DAG combiner loop to avoid it being looked at.
14286 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14287                                     SDValue RHS) {
14288 
14289   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14290   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14291   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14292     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14293       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14294       SDValue Sqrt = RHS;
14295       ISD::CondCode CC;
14296       SDValue CmpLHS;
14297       const ConstantFPSDNode *Zero = nullptr;
14298 
14299       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14300         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14301         CmpLHS = TheSelect->getOperand(0);
14302         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14303       } else {
14304         // SELECT or VSELECT
14305         SDValue Cmp = TheSelect->getOperand(0);
14306         if (Cmp.getOpcode() == ISD::SETCC) {
14307           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14308           CmpLHS = Cmp.getOperand(0);
14309           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14310         }
14311       }
14312       if (Zero && Zero->isZero() &&
14313           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14314           CC == ISD::SETULT || CC == ISD::SETLT)) {
14315         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14316         CombineTo(TheSelect, Sqrt);
14317         return true;
14318       }
14319     }
14320   }
14321   // Cannot simplify select with vector condition
14322   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14323 
14324   // If this is a select from two identical things, try to pull the operation
14325   // through the select.
14326   if (LHS.getOpcode() != RHS.getOpcode() ||
14327       !LHS.hasOneUse() || !RHS.hasOneUse())
14328     return false;
14329 
14330   // If this is a load and the token chain is identical, replace the select
14331   // of two loads with a load through a select of the address to load from.
14332   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14333   // constants have been dropped into the constant pool.
14334   if (LHS.getOpcode() == ISD::LOAD) {
14335     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14336     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14337 
14338     // Token chains must be identical.
14339     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14340         // Do not let this transformation reduce the number of volatile loads.
14341         LLD->isVolatile() || RLD->isVolatile() ||
14342         // FIXME: If either is a pre/post inc/dec load,
14343         // we'd need to split out the address adjustment.
14344         LLD->isIndexed() || RLD->isIndexed() ||
14345         // If this is an EXTLOAD, the VT's must match.
14346         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14347         // If this is an EXTLOAD, the kind of extension must match.
14348         (LLD->getExtensionType() != RLD->getExtensionType() &&
14349          // The only exception is if one of the extensions is anyext.
14350          LLD->getExtensionType() != ISD::EXTLOAD &&
14351          RLD->getExtensionType() != ISD::EXTLOAD) ||
14352         // FIXME: this discards src value information.  This is
14353         // over-conservative. It would be beneficial to be able to remember
14354         // both potential memory locations.  Since we are discarding
14355         // src value info, don't do the transformation if the memory
14356         // locations are not in the default address space.
14357         LLD->getPointerInfo().getAddrSpace() != 0 ||
14358         RLD->getPointerInfo().getAddrSpace() != 0 ||
14359         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14360                                       LLD->getBasePtr().getValueType()))
14361       return false;
14362 
14363     // Check that the select condition doesn't reach either load.  If so,
14364     // folding this will induce a cycle into the DAG.  If not, this is safe to
14365     // xform, so create a select of the addresses.
14366     SDValue Addr;
14367     if (TheSelect->getOpcode() == ISD::SELECT) {
14368       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14369       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14370           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14371         return false;
14372       // The loads must not depend on one another.
14373       if (LLD->isPredecessorOf(RLD) ||
14374           RLD->isPredecessorOf(LLD))
14375         return false;
14376       Addr = DAG.getSelect(SDLoc(TheSelect),
14377                            LLD->getBasePtr().getValueType(),
14378                            TheSelect->getOperand(0), LLD->getBasePtr(),
14379                            RLD->getBasePtr());
14380     } else {  // Otherwise SELECT_CC
14381       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14382       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14383 
14384       if ((LLD->hasAnyUseOfValue(1) &&
14385            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14386           (RLD->hasAnyUseOfValue(1) &&
14387            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14388         return false;
14389 
14390       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14391                          LLD->getBasePtr().getValueType(),
14392                          TheSelect->getOperand(0),
14393                          TheSelect->getOperand(1),
14394                          LLD->getBasePtr(), RLD->getBasePtr(),
14395                          TheSelect->getOperand(4));
14396     }
14397 
14398     SDValue Load;
14399     // It is safe to replace the two loads if they have different alignments,
14400     // but the new load must be the minimum (most restrictive) alignment of the
14401     // inputs.
14402     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14403     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
14404     if (!RLD->isInvariant())
14405       MMOFlags &= ~MachineMemOperand::MOInvariant;
14406     if (!RLD->isDereferenceable())
14407       MMOFlags &= ~MachineMemOperand::MODereferenceable;
14408     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14409       // FIXME: Discards pointer and AA info.
14410       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
14411                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
14412                          MMOFlags);
14413     } else {
14414       // FIXME: Discards pointer and AA info.
14415       Load = DAG.getExtLoad(
14416           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
14417                                                   : LLD->getExtensionType(),
14418           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
14419           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
14420     }
14421 
14422     // Users of the select now use the result of the load.
14423     CombineTo(TheSelect, Load);
14424 
14425     // Users of the old loads now use the new load's chain.  We know the
14426     // old-load value is dead now.
14427     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14428     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14429     return true;
14430   }
14431 
14432   return false;
14433 }
14434 
14435 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14436 /// where 'cond' is the comparison specified by CC.
14437 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
14438                                       SDValue N2, SDValue N3, ISD::CondCode CC,
14439                                       bool NotExtCompare) {
14440   // (x ? y : y) -> y.
14441   if (N2 == N3) return N2;
14442 
14443   EVT VT = N2.getValueType();
14444   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14445   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14446 
14447   // Determine if the condition we're dealing with is constant
14448   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14449                               N0, N1, CC, DL, false);
14450   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14451 
14452   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14453     // fold select_cc true, x, y -> x
14454     // fold select_cc false, x, y -> y
14455     return !SCCC->isNullValue() ? N2 : N3;
14456   }
14457 
14458   // Check to see if we can simplify the select into an fabs node
14459   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14460     // Allow either -0.0 or 0.0
14461     if (CFP->isZero()) {
14462       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14463       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14464           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14465           N2 == N3.getOperand(0))
14466         return DAG.getNode(ISD::FABS, DL, VT, N0);
14467 
14468       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14469       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14470           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14471           N2.getOperand(0) == N3)
14472         return DAG.getNode(ISD::FABS, DL, VT, N3);
14473     }
14474   }
14475 
14476   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14477   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14478   // in it.  This is a win when the constant is not otherwise available because
14479   // it replaces two constant pool loads with one.  We only do this if the FP
14480   // type is known to be legal, because if it isn't, then we are before legalize
14481   // types an we want the other legalization to happen first (e.g. to avoid
14482   // messing with soft float) and if the ConstantFP is not legal, because if
14483   // it is legal, we may not need to store the FP constant in a constant pool.
14484   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14485     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14486       if (TLI.isTypeLegal(N2.getValueType()) &&
14487           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14488                TargetLowering::Legal &&
14489            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14490            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14491           // If both constants have multiple uses, then we won't need to do an
14492           // extra load, they are likely around in registers for other users.
14493           (TV->hasOneUse() || FV->hasOneUse())) {
14494         Constant *Elts[] = {
14495           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14496           const_cast<ConstantFP*>(TV->getConstantFPValue())
14497         };
14498         Type *FPTy = Elts[0]->getType();
14499         const DataLayout &TD = DAG.getDataLayout();
14500 
14501         // Create a ConstantArray of the two constants.
14502         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14503         SDValue CPIdx =
14504             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14505                                 TD.getPrefTypeAlignment(FPTy));
14506         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14507 
14508         // Get the offsets to the 0 and 1 element of the array so that we can
14509         // select between them.
14510         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14511         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14512         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14513 
14514         SDValue Cond = DAG.getSetCC(DL,
14515                                     getSetCCResultType(N0.getValueType()),
14516                                     N0, N1, CC);
14517         AddToWorklist(Cond.getNode());
14518         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14519                                           Cond, One, Zero);
14520         AddToWorklist(CstOffset.getNode());
14521         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14522                             CstOffset);
14523         AddToWorklist(CPIdx.getNode());
14524         return DAG.getLoad(
14525             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14526             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14527             Alignment);
14528       }
14529     }
14530 
14531   // Check to see if we can perform the "gzip trick", transforming
14532   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14533   if (isNullConstant(N3) && CC == ISD::SETLT &&
14534       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14535        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14536     EVT XType = N0.getValueType();
14537     EVT AType = N2.getValueType();
14538     if (XType.bitsGE(AType)) {
14539       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14540       // single-bit constant.
14541       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14542         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14543         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14544         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14545                                        getShiftAmountTy(N0.getValueType()));
14546         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14547                                     XType, N0, ShCt);
14548         AddToWorklist(Shift.getNode());
14549 
14550         if (XType.bitsGT(AType)) {
14551           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14552           AddToWorklist(Shift.getNode());
14553         }
14554 
14555         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14556       }
14557 
14558       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14559                                   XType, N0,
14560                                   DAG.getConstant(XType.getSizeInBits() - 1,
14561                                                   SDLoc(N0),
14562                                          getShiftAmountTy(N0.getValueType())));
14563       AddToWorklist(Shift.getNode());
14564 
14565       if (XType.bitsGT(AType)) {
14566         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14567         AddToWorklist(Shift.getNode());
14568       }
14569 
14570       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14571     }
14572   }
14573 
14574   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14575   // where y is has a single bit set.
14576   // A plaintext description would be, we can turn the SELECT_CC into an AND
14577   // when the condition can be materialized as an all-ones register.  Any
14578   // single bit-test can be materialized as an all-ones register with
14579   // shift-left and shift-right-arith.
14580   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14581       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14582     SDValue AndLHS = N0->getOperand(0);
14583     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14584     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14585       // Shift the tested bit over the sign bit.
14586       const APInt &AndMask = ConstAndRHS->getAPIntValue();
14587       SDValue ShlAmt =
14588         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14589                         getShiftAmountTy(AndLHS.getValueType()));
14590       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14591 
14592       // Now arithmetic right shift it all the way over, so the result is either
14593       // all-ones, or zero.
14594       SDValue ShrAmt =
14595         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14596                         getShiftAmountTy(Shl.getValueType()));
14597       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14598 
14599       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14600     }
14601   }
14602 
14603   // fold select C, 16, 0 -> shl C, 4
14604   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14605       TLI.getBooleanContents(N0.getValueType()) ==
14606           TargetLowering::ZeroOrOneBooleanContent) {
14607 
14608     // If the caller doesn't want us to simplify this into a zext of a compare,
14609     // don't do it.
14610     if (NotExtCompare && N2C->isOne())
14611       return SDValue();
14612 
14613     // Get a SetCC of the condition
14614     // NOTE: Don't create a SETCC if it's not legal on this target.
14615     if (!LegalOperations ||
14616         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14617       SDValue Temp, SCC;
14618       // cast from setcc result type to select result type
14619       if (LegalTypes) {
14620         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14621                             N0, N1, CC);
14622         if (N2.getValueType().bitsLT(SCC.getValueType()))
14623           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14624                                         N2.getValueType());
14625         else
14626           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14627                              N2.getValueType(), SCC);
14628       } else {
14629         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14630         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14631                            N2.getValueType(), SCC);
14632       }
14633 
14634       AddToWorklist(SCC.getNode());
14635       AddToWorklist(Temp.getNode());
14636 
14637       if (N2C->isOne())
14638         return Temp;
14639 
14640       // shl setcc result by log2 n2c
14641       return DAG.getNode(
14642           ISD::SHL, DL, N2.getValueType(), Temp,
14643           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14644                           getShiftAmountTy(Temp.getValueType())));
14645     }
14646   }
14647 
14648   // Check to see if this is an integer abs.
14649   // select_cc setg[te] X,  0,  X, -X ->
14650   // select_cc setgt    X, -1,  X, -X ->
14651   // select_cc setl[te] X,  0, -X,  X ->
14652   // select_cc setlt    X,  1, -X,  X ->
14653   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14654   if (N1C) {
14655     ConstantSDNode *SubC = nullptr;
14656     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14657          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14658         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14659       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14660     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14661               (N1C->isOne() && CC == ISD::SETLT)) &&
14662              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14663       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14664 
14665     EVT XType = N0.getValueType();
14666     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14667       SDLoc DL(N0);
14668       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14669                                   N0,
14670                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14671                                          getShiftAmountTy(N0.getValueType())));
14672       SDValue Add = DAG.getNode(ISD::ADD, DL,
14673                                 XType, N0, Shift);
14674       AddToWorklist(Shift.getNode());
14675       AddToWorklist(Add.getNode());
14676       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14677     }
14678   }
14679 
14680   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14681   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14682   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14683   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14684   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14685   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14686   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14687   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14688   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14689     SDValue ValueOnZero = N2;
14690     SDValue Count = N3;
14691     // If the condition is NE instead of E, swap the operands.
14692     if (CC == ISD::SETNE)
14693       std::swap(ValueOnZero, Count);
14694     // Check if the value on zero is a constant equal to the bits in the type.
14695     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14696       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14697         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14698         // legal, combine to just cttz.
14699         if ((Count.getOpcode() == ISD::CTTZ ||
14700              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14701             N0 == Count.getOperand(0) &&
14702             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14703           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14704         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14705         // legal, combine to just ctlz.
14706         if ((Count.getOpcode() == ISD::CTLZ ||
14707              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14708             N0 == Count.getOperand(0) &&
14709             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14710           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14711       }
14712     }
14713   }
14714 
14715   return SDValue();
14716 }
14717 
14718 /// This is a stub for TargetLowering::SimplifySetCC.
14719 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
14720                                    ISD::CondCode Cond, const SDLoc &DL,
14721                                    bool foldBooleans) {
14722   TargetLowering::DAGCombinerInfo
14723     DagCombineInfo(DAG, Level, false, this);
14724   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14725 }
14726 
14727 /// Given an ISD::SDIV node expressing a divide by constant, return
14728 /// a DAG expression to select that will generate the same value by multiplying
14729 /// by a magic number.
14730 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14731 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14732   // when optimising for minimum size, we don't want to expand a div to a mul
14733   // and a shift.
14734   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14735     return SDValue();
14736 
14737   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14738   if (!C)
14739     return SDValue();
14740 
14741   // Avoid division by zero.
14742   if (C->isNullValue())
14743     return SDValue();
14744 
14745   std::vector<SDNode*> Built;
14746   SDValue S =
14747       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14748 
14749   for (SDNode *N : Built)
14750     AddToWorklist(N);
14751   return S;
14752 }
14753 
14754 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14755 /// DAG expression that will generate the same value by right shifting.
14756 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14757   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14758   if (!C)
14759     return SDValue();
14760 
14761   // Avoid division by zero.
14762   if (C->isNullValue())
14763     return SDValue();
14764 
14765   std::vector<SDNode *> Built;
14766   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14767 
14768   for (SDNode *N : Built)
14769     AddToWorklist(N);
14770   return S;
14771 }
14772 
14773 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14774 /// expression that will generate the same value by multiplying by a magic
14775 /// number.
14776 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14777 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14778   // when optimising for minimum size, we don't want to expand a div to a mul
14779   // and a shift.
14780   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14781     return SDValue();
14782 
14783   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14784   if (!C)
14785     return SDValue();
14786 
14787   // Avoid division by zero.
14788   if (C->isNullValue())
14789     return SDValue();
14790 
14791   std::vector<SDNode*> Built;
14792   SDValue S =
14793       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14794 
14795   for (SDNode *N : Built)
14796     AddToWorklist(N);
14797   return S;
14798 }
14799 
14800 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14801   if (Level >= AfterLegalizeDAG)
14802     return SDValue();
14803 
14804   // Expose the DAG combiner to the target combiner implementations.
14805   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14806 
14807   unsigned Iterations = 0;
14808   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14809     if (Iterations) {
14810       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14811       // For the reciprocal, we need to find the zero of the function:
14812       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14813       //     =>
14814       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14815       //     does not require additional intermediate precision]
14816       EVT VT = Op.getValueType();
14817       SDLoc DL(Op);
14818       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14819 
14820       AddToWorklist(Est.getNode());
14821 
14822       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14823       for (unsigned i = 0; i < Iterations; ++i) {
14824         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14825         AddToWorklist(NewEst.getNode());
14826 
14827         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14828         AddToWorklist(NewEst.getNode());
14829 
14830         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14831         AddToWorklist(NewEst.getNode());
14832 
14833         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14834         AddToWorklist(Est.getNode());
14835       }
14836     }
14837     return Est;
14838   }
14839 
14840   return SDValue();
14841 }
14842 
14843 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14844 /// For the reciprocal sqrt, we need to find the zero of the function:
14845 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14846 ///     =>
14847 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14848 /// As a result, we precompute A/2 prior to the iteration loop.
14849 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
14850                                          unsigned Iterations,
14851                                          SDNodeFlags *Flags, bool Reciprocal) {
14852   EVT VT = Arg.getValueType();
14853   SDLoc DL(Arg);
14854   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14855 
14856   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14857   // this entire sequence requires only one FP constant.
14858   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14859   AddToWorklist(HalfArg.getNode());
14860 
14861   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14862   AddToWorklist(HalfArg.getNode());
14863 
14864   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14865   for (unsigned i = 0; i < Iterations; ++i) {
14866     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14867     AddToWorklist(NewEst.getNode());
14868 
14869     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14870     AddToWorklist(NewEst.getNode());
14871 
14872     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14873     AddToWorklist(NewEst.getNode());
14874 
14875     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14876     AddToWorklist(Est.getNode());
14877   }
14878 
14879   // If non-reciprocal square root is requested, multiply the result by Arg.
14880   if (!Reciprocal) {
14881     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14882     AddToWorklist(Est.getNode());
14883   }
14884 
14885   return Est;
14886 }
14887 
14888 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14889 /// For the reciprocal sqrt, we need to find the zero of the function:
14890 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14891 ///     =>
14892 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14893 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
14894                                          unsigned Iterations,
14895                                          SDNodeFlags *Flags, bool Reciprocal) {
14896   EVT VT = Arg.getValueType();
14897   SDLoc DL(Arg);
14898   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14899   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14900 
14901   // This routine must enter the loop below to work correctly
14902   // when (Reciprocal == false).
14903   assert(Iterations > 0);
14904 
14905   // Newton iterations for reciprocal square root:
14906   // E = (E * -0.5) * ((A * E) * E + -3.0)
14907   for (unsigned i = 0; i < Iterations; ++i) {
14908     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
14909     AddToWorklist(AE.getNode());
14910 
14911     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
14912     AddToWorklist(AEE.getNode());
14913 
14914     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
14915     AddToWorklist(RHS.getNode());
14916 
14917     // When calculating a square root at the last iteration build:
14918     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
14919     // (notice a common subexpression)
14920     SDValue LHS;
14921     if (Reciprocal || (i + 1) < Iterations) {
14922       // RSQRT: LHS = (E * -0.5)
14923       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14924     } else {
14925       // SQRT: LHS = (A * E) * -0.5
14926       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
14927     }
14928     AddToWorklist(LHS.getNode());
14929 
14930     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
14931     AddToWorklist(Est.getNode());
14932   }
14933 
14934   return Est;
14935 }
14936 
14937 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
14938 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
14939 /// Op can be zero.
14940 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
14941                                            bool Reciprocal) {
14942   if (Level >= AfterLegalizeDAG)
14943     return SDValue();
14944 
14945   // Expose the DAG combiner to the target combiner implementations.
14946   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14947   unsigned Iterations = 0;
14948   bool UseOneConstNR = false;
14949   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14950     AddToWorklist(Est.getNode());
14951     if (Iterations) {
14952       Est = UseOneConstNR
14953                 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
14954                 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
14955     }
14956     return Est;
14957   }
14958 
14959   return SDValue();
14960 }
14961 
14962 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14963   return buildSqrtEstimateImpl(Op, Flags, true);
14964 }
14965 
14966 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14967   SDValue Est = buildSqrtEstimateImpl(Op, Flags, false);
14968   if (!Est)
14969     return SDValue();
14970 
14971   // Unfortunately, Est is now NaN if the input was exactly 0.
14972   // Select out this case and force the answer to 0.
14973   EVT VT = Est.getValueType();
14974   SDLoc DL(Op);
14975   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
14976   EVT CCVT = getSetCCResultType(VT);
14977   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, Zero, ISD::SETEQ);
14978   AddToWorklist(ZeroCmp.getNode());
14979 
14980   Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, ZeroCmp,
14981                     Zero, Est);
14982   AddToWorklist(Est.getNode());
14983   return Est;
14984 }
14985 
14986 /// Return true if base is a frame index, which is known not to alias with
14987 /// anything but itself.  Provides base object and offset as results.
14988 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14989                            const GlobalValue *&GV, const void *&CV) {
14990   // Assume it is a primitive operation.
14991   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14992 
14993   // If it's an adding a simple constant then integrate the offset.
14994   if (Base.getOpcode() == ISD::ADD) {
14995     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14996       Base = Base.getOperand(0);
14997       Offset += C->getZExtValue();
14998     }
14999   }
15000 
15001   // Return the underlying GlobalValue, and update the Offset.  Return false
15002   // for GlobalAddressSDNode since the same GlobalAddress may be represented
15003   // by multiple nodes with different offsets.
15004   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
15005     GV = G->getGlobal();
15006     Offset += G->getOffset();
15007     return false;
15008   }
15009 
15010   // Return the underlying Constant value, and update the Offset.  Return false
15011   // for ConstantSDNodes since the same constant pool entry may be represented
15012   // by multiple nodes with different offsets.
15013   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
15014     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
15015                                          : (const void *)C->getConstVal();
15016     Offset += C->getOffset();
15017     return false;
15018   }
15019   // If it's any of the following then it can't alias with anything but itself.
15020   return isa<FrameIndexSDNode>(Base);
15021 }
15022 
15023 /// Return true if there is any possibility that the two addresses overlap.
15024 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
15025   // If they are the same then they must be aliases.
15026   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
15027 
15028   // If they are both volatile then they cannot be reordered.
15029   if (Op0->isVolatile() && Op1->isVolatile()) return true;
15030 
15031   // If one operation reads from invariant memory, and the other may store, they
15032   // cannot alias. These should really be checking the equivalent of mayWrite,
15033   // but it only matters for memory nodes other than load /store.
15034   if (Op0->isInvariant() && Op1->writeMem())
15035     return false;
15036 
15037   if (Op1->isInvariant() && Op0->writeMem())
15038     return false;
15039 
15040   // Gather base node and offset information.
15041   SDValue Base1, Base2;
15042   int64_t Offset1, Offset2;
15043   const GlobalValue *GV1, *GV2;
15044   const void *CV1, *CV2;
15045   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
15046                                       Base1, Offset1, GV1, CV1);
15047   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
15048                                       Base2, Offset2, GV2, CV2);
15049 
15050   // If they have a same base address then check to see if they overlap.
15051   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
15052     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15053              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15054 
15055   // It is possible for different frame indices to alias each other, mostly
15056   // when tail call optimization reuses return address slots for arguments.
15057   // To catch this case, look up the actual index of frame indices to compute
15058   // the real alias relationship.
15059   if (isFrameIndex1 && isFrameIndex2) {
15060     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
15061     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
15062     Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
15063     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15064              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15065   }
15066 
15067   // Otherwise, if we know what the bases are, and they aren't identical, then
15068   // we know they cannot alias.
15069   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
15070     return false;
15071 
15072   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
15073   // compared to the size and offset of the access, we may be able to prove they
15074   // do not alias.  This check is conservative for now to catch cases created by
15075   // splitting vector types.
15076   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
15077       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
15078       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
15079        Op1->getMemoryVT().getSizeInBits() >> 3) &&
15080       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
15081     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
15082     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
15083 
15084     // There is no overlap between these relatively aligned accesses of similar
15085     // size, return no alias.
15086     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
15087         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
15088       return false;
15089   }
15090 
15091   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
15092                    ? CombinerGlobalAA
15093                    : DAG.getSubtarget().useAA();
15094 #ifndef NDEBUG
15095   if (CombinerAAOnlyFunc.getNumOccurrences() &&
15096       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
15097     UseAA = false;
15098 #endif
15099   if (UseAA &&
15100       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
15101     // Use alias analysis information.
15102     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
15103                                  Op1->getSrcValueOffset());
15104     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
15105         Op0->getSrcValueOffset() - MinOffset;
15106     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
15107         Op1->getSrcValueOffset() - MinOffset;
15108     AliasResult AAResult =
15109         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
15110                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
15111                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
15112                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
15113     if (AAResult == NoAlias)
15114       return false;
15115   }
15116 
15117   // Otherwise we have to assume they alias.
15118   return true;
15119 }
15120 
15121 /// Walk up chain skipping non-aliasing memory nodes,
15122 /// looking for aliasing nodes and adding them to the Aliases vector.
15123 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
15124                                    SmallVectorImpl<SDValue> &Aliases) {
15125   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
15126   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
15127 
15128   // Get alias information for node.
15129   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
15130 
15131   // Starting off.
15132   Chains.push_back(OriginalChain);
15133   unsigned Depth = 0;
15134 
15135   // Look at each chain and determine if it is an alias.  If so, add it to the
15136   // aliases list.  If not, then continue up the chain looking for the next
15137   // candidate.
15138   while (!Chains.empty()) {
15139     SDValue Chain = Chains.pop_back_val();
15140 
15141     // For TokenFactor nodes, look at each operand and only continue up the
15142     // chain until we reach the depth limit.
15143     //
15144     // FIXME: The depth check could be made to return the last non-aliasing
15145     // chain we found before we hit a tokenfactor rather than the original
15146     // chain.
15147     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
15148       Aliases.clear();
15149       Aliases.push_back(OriginalChain);
15150       return;
15151     }
15152 
15153     // Don't bother if we've been before.
15154     if (!Visited.insert(Chain.getNode()).second)
15155       continue;
15156 
15157     switch (Chain.getOpcode()) {
15158     case ISD::EntryToken:
15159       // Entry token is ideal chain operand, but handled in FindBetterChain.
15160       break;
15161 
15162     case ISD::LOAD:
15163     case ISD::STORE: {
15164       // Get alias information for Chain.
15165       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
15166           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
15167 
15168       // If chain is alias then stop here.
15169       if (!(IsLoad && IsOpLoad) &&
15170           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
15171         Aliases.push_back(Chain);
15172       } else {
15173         // Look further up the chain.
15174         Chains.push_back(Chain.getOperand(0));
15175         ++Depth;
15176       }
15177       break;
15178     }
15179 
15180     case ISD::TokenFactor:
15181       // We have to check each of the operands of the token factor for "small"
15182       // token factors, so we queue them up.  Adding the operands to the queue
15183       // (stack) in reverse order maintains the original order and increases the
15184       // likelihood that getNode will find a matching token factor (CSE.)
15185       if (Chain.getNumOperands() > 16) {
15186         Aliases.push_back(Chain);
15187         break;
15188       }
15189       for (unsigned n = Chain.getNumOperands(); n;)
15190         Chains.push_back(Chain.getOperand(--n));
15191       ++Depth;
15192       break;
15193 
15194     default:
15195       // For all other instructions we will just have to take what we can get.
15196       Aliases.push_back(Chain);
15197       break;
15198     }
15199   }
15200 }
15201 
15202 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
15203 /// (aliasing node.)
15204 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
15205   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
15206 
15207   // Accumulate all the aliases to this node.
15208   GatherAllAliases(N, OldChain, Aliases);
15209 
15210   // If no operands then chain to entry token.
15211   if (Aliases.size() == 0)
15212     return DAG.getEntryNode();
15213 
15214   // If a single operand then chain to it.  We don't need to revisit it.
15215   if (Aliases.size() == 1)
15216     return Aliases[0];
15217 
15218   // Construct a custom tailored token factor.
15219   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
15220 }
15221 
15222 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
15223   // This holds the base pointer, index, and the offset in bytes from the base
15224   // pointer.
15225   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
15226 
15227   // We must have a base and an offset.
15228   if (!BasePtr.Base.getNode())
15229     return false;
15230 
15231   // Do not handle stores to undef base pointers.
15232   if (BasePtr.Base.isUndef())
15233     return false;
15234 
15235   SmallVector<StoreSDNode *, 8> ChainedStores;
15236   ChainedStores.push_back(St);
15237 
15238   // Walk up the chain and look for nodes with offsets from the same
15239   // base pointer. Stop when reaching an instruction with a different kind
15240   // or instruction which has a different base pointer.
15241   StoreSDNode *Index = St;
15242   while (Index) {
15243     // If the chain has more than one use, then we can't reorder the mem ops.
15244     if (Index != St && !SDValue(Index, 0)->hasOneUse())
15245       break;
15246 
15247     if (Index->isVolatile() || Index->isIndexed())
15248       break;
15249 
15250     // Find the base pointer and offset for this memory node.
15251     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
15252 
15253     // Check that the base pointer is the same as the original one.
15254     if (!Ptr.equalBaseIndex(BasePtr))
15255       break;
15256 
15257     // Find the next memory operand in the chain. If the next operand in the
15258     // chain is a store then move up and continue the scan with the next
15259     // memory operand. If the next operand is a load save it and use alias
15260     // information to check if it interferes with anything.
15261     SDNode *NextInChain = Index->getChain().getNode();
15262     while (true) {
15263       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
15264         // We found a store node. Use it for the next iteration.
15265         if (STn->isVolatile() || STn->isIndexed()) {
15266           Index = nullptr;
15267           break;
15268         }
15269         ChainedStores.push_back(STn);
15270         Index = STn;
15271         break;
15272       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
15273         NextInChain = Ldn->getChain().getNode();
15274         continue;
15275       } else {
15276         Index = nullptr;
15277         break;
15278       }
15279     }
15280   }
15281 
15282   bool MadeChangeToSt = false;
15283   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
15284 
15285   for (StoreSDNode *ChainedStore : ChainedStores) {
15286     SDValue Chain = ChainedStore->getChain();
15287     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15288 
15289     if (Chain != BetterChain) {
15290       if (ChainedStore == St)
15291         MadeChangeToSt = true;
15292       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15293     }
15294   }
15295 
15296   // Do all replacements after finding the replacements to make to avoid making
15297   // the chains more complicated by introducing new TokenFactors.
15298   for (auto Replacement : BetterChains)
15299     replaceStoreChain(Replacement.first, Replacement.second);
15300 
15301   return MadeChangeToSt;
15302 }
15303 
15304 /// This is the entry point for the file.
15305 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15306                            CodeGenOpt::Level OptLevel) {
15307   /// This is the main entry point to this class.
15308   DAGCombiner(*this, AA, OptLevel).Run(Level);
15309 }
15310