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 // Determines if it is a constant integer or a build vector of constant
828 // integers (and undefs).
829 // Do not permit build vector implicit truncation.
830 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
831   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
832     return !(Const->isOpaque() && NoOpaques);
833   if (N.getOpcode() != ISD::BUILD_VECTOR)
834     return false;
835   unsigned BitWidth = N.getScalarValueSizeInBits();
836   for (const SDValue &Op : N->op_values()) {
837     if (Op.isUndef())
838       continue;
839     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
840     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
841         (Const->isOpaque() && NoOpaques))
842       return false;
843   }
844   return true;
845 }
846 
847 // Determines if it is a constant null integer or a splatted vector of a
848 // constant null integer (with no undefs).
849 // Build vector implicit truncation is not an issue for null values.
850 static bool isNullConstantOrNullSplatConstant(SDValue N) {
851   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
852     return Splat->isNullValue();
853   return false;
854 }
855 
856 // Determines if it is a constant integer of one or a splatted vector of a
857 // constant integer of one (with no undefs).
858 // Do not permit build vector implicit truncation.
859 static bool isOneConstantOrOneSplatConstant(SDValue N) {
860   unsigned BitWidth = N.getScalarValueSizeInBits();
861   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
862     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
863   return false;
864 }
865 
866 // Determines if it is a constant integer of all ones or a splatted vector of a
867 // constant integer of all ones (with no undefs).
868 // Do not permit build vector implicit truncation.
869 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
870   unsigned BitWidth = N.getScalarValueSizeInBits();
871   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
872     return Splat->isAllOnesValue() &&
873            Splat->getAPIntValue().getBitWidth() == BitWidth;
874   return false;
875 }
876 
877 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
878                                     SDValue N1) {
879   EVT VT = N0.getValueType();
880   if (N0.getOpcode() == Opc) {
881     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
882       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
883         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
884         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
885           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
886         return SDValue();
887       }
888       if (N0.hasOneUse()) {
889         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
890         // use
891         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
892         if (!OpNode.getNode())
893           return SDValue();
894         AddToWorklist(OpNode.getNode());
895         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
896       }
897     }
898   }
899 
900   if (N1.getOpcode() == Opc) {
901     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
902       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
903         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
904         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
905           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
906         return SDValue();
907       }
908       if (N1.hasOneUse()) {
909         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
910         // use
911         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
912         if (!OpNode.getNode())
913           return SDValue();
914         AddToWorklist(OpNode.getNode());
915         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
916       }
917     }
918   }
919 
920   return SDValue();
921 }
922 
923 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
924                                bool AddTo) {
925   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
926   ++NodesCombined;
927   DEBUG(dbgs() << "\nReplacing.1 ";
928         N->dump(&DAG);
929         dbgs() << "\nWith: ";
930         To[0].getNode()->dump(&DAG);
931         dbgs() << " and " << NumTo-1 << " other values\n");
932   for (unsigned i = 0, e = NumTo; i != e; ++i)
933     assert((!To[i].getNode() ||
934             N->getValueType(i) == To[i].getValueType()) &&
935            "Cannot combine value to value of different type!");
936 
937   WorklistRemover DeadNodes(*this);
938   DAG.ReplaceAllUsesWith(N, To);
939   if (AddTo) {
940     // Push the new nodes and any users onto the worklist
941     for (unsigned i = 0, e = NumTo; i != e; ++i) {
942       if (To[i].getNode()) {
943         AddToWorklist(To[i].getNode());
944         AddUsersToWorklist(To[i].getNode());
945       }
946     }
947   }
948 
949   // Finally, if the node is now dead, remove it from the graph.  The node
950   // may not be dead if the replacement process recursively simplified to
951   // something else needing this node.
952   if (N->use_empty())
953     deleteAndRecombine(N);
954   return SDValue(N, 0);
955 }
956 
957 void DAGCombiner::
958 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
959   // Replace all uses.  If any nodes become isomorphic to other nodes and
960   // are deleted, make sure to remove them from our worklist.
961   WorklistRemover DeadNodes(*this);
962   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
963 
964   // Push the new node and any (possibly new) users onto the worklist.
965   AddToWorklist(TLO.New.getNode());
966   AddUsersToWorklist(TLO.New.getNode());
967 
968   // Finally, if the node is now dead, remove it from the graph.  The node
969   // may not be dead if the replacement process recursively simplified to
970   // something else needing this node.
971   if (TLO.Old.getNode()->use_empty())
972     deleteAndRecombine(TLO.Old.getNode());
973 }
974 
975 /// Check the specified integer node value to see if it can be simplified or if
976 /// things it uses can be simplified by bit propagation. If so, return true.
977 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
978   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
979   APInt KnownZero, KnownOne;
980   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
981     return false;
982 
983   // Revisit the node.
984   AddToWorklist(Op.getNode());
985 
986   // Replace the old value with the new one.
987   ++NodesCombined;
988   DEBUG(dbgs() << "\nReplacing.2 ";
989         TLO.Old.getNode()->dump(&DAG);
990         dbgs() << "\nWith: ";
991         TLO.New.getNode()->dump(&DAG);
992         dbgs() << '\n');
993 
994   CommitTargetLoweringOpt(TLO);
995   return true;
996 }
997 
998 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
999   SDLoc DL(Load);
1000   EVT VT = Load->getValueType(0);
1001   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1002 
1003   DEBUG(dbgs() << "\nReplacing.9 ";
1004         Load->dump(&DAG);
1005         dbgs() << "\nWith: ";
1006         Trunc.getNode()->dump(&DAG);
1007         dbgs() << '\n');
1008   WorklistRemover DeadNodes(*this);
1009   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1010   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1011   deleteAndRecombine(Load);
1012   AddToWorklist(Trunc.getNode());
1013 }
1014 
1015 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1016   Replace = false;
1017   SDLoc DL(Op);
1018   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1019     LoadSDNode *LD = cast<LoadSDNode>(Op);
1020     EVT MemVT = LD->getMemoryVT();
1021     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1022       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1023                                                        : ISD::EXTLOAD)
1024       : LD->getExtensionType();
1025     Replace = true;
1026     return DAG.getExtLoad(ExtType, DL, PVT,
1027                           LD->getChain(), LD->getBasePtr(),
1028                           MemVT, LD->getMemOperand());
1029   }
1030 
1031   unsigned Opc = Op.getOpcode();
1032   switch (Opc) {
1033   default: break;
1034   case ISD::AssertSext:
1035     return DAG.getNode(ISD::AssertSext, DL, PVT,
1036                        SExtPromoteOperand(Op.getOperand(0), PVT),
1037                        Op.getOperand(1));
1038   case ISD::AssertZext:
1039     return DAG.getNode(ISD::AssertZext, DL, PVT,
1040                        ZExtPromoteOperand(Op.getOperand(0), PVT),
1041                        Op.getOperand(1));
1042   case ISD::Constant: {
1043     unsigned ExtOpc =
1044       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1045     return DAG.getNode(ExtOpc, DL, PVT, Op);
1046   }
1047   }
1048 
1049   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1050     return SDValue();
1051   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1052 }
1053 
1054 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1055   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1056     return SDValue();
1057   EVT OldVT = Op.getValueType();
1058   SDLoc DL(Op);
1059   bool Replace = false;
1060   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1061   if (!NewOp.getNode())
1062     return SDValue();
1063   AddToWorklist(NewOp.getNode());
1064 
1065   if (Replace)
1066     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1067   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1068                      DAG.getValueType(OldVT));
1069 }
1070 
1071 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1072   EVT OldVT = Op.getValueType();
1073   SDLoc DL(Op);
1074   bool Replace = false;
1075   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1076   if (!NewOp.getNode())
1077     return SDValue();
1078   AddToWorklist(NewOp.getNode());
1079 
1080   if (Replace)
1081     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1082   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1083 }
1084 
1085 /// Promote the specified integer binary operation if the target indicates it is
1086 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1087 /// i32 since i16 instructions are longer.
1088 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1089   if (!LegalOperations)
1090     return SDValue();
1091 
1092   EVT VT = Op.getValueType();
1093   if (VT.isVector() || !VT.isInteger())
1094     return SDValue();
1095 
1096   // If operation type is 'undesirable', e.g. i16 on x86, consider
1097   // promoting it.
1098   unsigned Opc = Op.getOpcode();
1099   if (TLI.isTypeDesirableForOp(Opc, VT))
1100     return SDValue();
1101 
1102   EVT PVT = VT;
1103   // Consult target whether it is a good idea to promote this operation and
1104   // what's the right type to promote it to.
1105   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1106     assert(PVT != VT && "Don't know what type to promote to!");
1107 
1108     bool Replace0 = false;
1109     SDValue N0 = Op.getOperand(0);
1110     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1111     if (!NN0.getNode())
1112       return SDValue();
1113 
1114     bool Replace1 = false;
1115     SDValue N1 = Op.getOperand(1);
1116     SDValue NN1;
1117     if (N0 == N1)
1118       NN1 = NN0;
1119     else {
1120       NN1 = PromoteOperand(N1, PVT, Replace1);
1121       if (!NN1.getNode())
1122         return SDValue();
1123     }
1124 
1125     AddToWorklist(NN0.getNode());
1126     if (NN1.getNode())
1127       AddToWorklist(NN1.getNode());
1128 
1129     if (Replace0)
1130       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1131     if (Replace1)
1132       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1133 
1134     DEBUG(dbgs() << "\nPromoting ";
1135           Op.getNode()->dump(&DAG));
1136     SDLoc DL(Op);
1137     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1138                        DAG.getNode(Opc, DL, PVT, NN0, NN1));
1139   }
1140   return SDValue();
1141 }
1142 
1143 /// Promote the specified integer shift operation if the target indicates it is
1144 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1145 /// i32 since i16 instructions are longer.
1146 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1147   if (!LegalOperations)
1148     return SDValue();
1149 
1150   EVT VT = Op.getValueType();
1151   if (VT.isVector() || !VT.isInteger())
1152     return SDValue();
1153 
1154   // If operation type is 'undesirable', e.g. i16 on x86, consider
1155   // promoting it.
1156   unsigned Opc = Op.getOpcode();
1157   if (TLI.isTypeDesirableForOp(Opc, VT))
1158     return SDValue();
1159 
1160   EVT PVT = VT;
1161   // Consult target whether it is a good idea to promote this operation and
1162   // what's the right type to promote it to.
1163   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1164     assert(PVT != VT && "Don't know what type to promote to!");
1165 
1166     bool Replace = false;
1167     SDValue N0 = Op.getOperand(0);
1168     if (Opc == ISD::SRA)
1169       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1170     else if (Opc == ISD::SRL)
1171       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1172     else
1173       N0 = PromoteOperand(N0, PVT, Replace);
1174     if (!N0.getNode())
1175       return SDValue();
1176 
1177     AddToWorklist(N0.getNode());
1178     if (Replace)
1179       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1180 
1181     DEBUG(dbgs() << "\nPromoting ";
1182           Op.getNode()->dump(&DAG));
1183     SDLoc DL(Op);
1184     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1185                        DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1)));
1186   }
1187   return SDValue();
1188 }
1189 
1190 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1191   if (!LegalOperations)
1192     return SDValue();
1193 
1194   EVT VT = Op.getValueType();
1195   if (VT.isVector() || !VT.isInteger())
1196     return SDValue();
1197 
1198   // If operation type is 'undesirable', e.g. i16 on x86, consider
1199   // promoting it.
1200   unsigned Opc = Op.getOpcode();
1201   if (TLI.isTypeDesirableForOp(Opc, VT))
1202     return SDValue();
1203 
1204   EVT PVT = VT;
1205   // Consult target whether it is a good idea to promote this operation and
1206   // what's the right type to promote it to.
1207   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1208     assert(PVT != VT && "Don't know what type to promote to!");
1209     // fold (aext (aext x)) -> (aext x)
1210     // fold (aext (zext x)) -> (zext x)
1211     // fold (aext (sext x)) -> (sext x)
1212     DEBUG(dbgs() << "\nPromoting ";
1213           Op.getNode()->dump(&DAG));
1214     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1215   }
1216   return SDValue();
1217 }
1218 
1219 bool DAGCombiner::PromoteLoad(SDValue Op) {
1220   if (!LegalOperations)
1221     return false;
1222 
1223   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1224     return false;
1225 
1226   EVT VT = Op.getValueType();
1227   if (VT.isVector() || !VT.isInteger())
1228     return false;
1229 
1230   // If operation type is 'undesirable', e.g. i16 on x86, consider
1231   // promoting it.
1232   unsigned Opc = Op.getOpcode();
1233   if (TLI.isTypeDesirableForOp(Opc, VT))
1234     return false;
1235 
1236   EVT PVT = VT;
1237   // Consult target whether it is a good idea to promote this operation and
1238   // what's the right type to promote it to.
1239   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1240     assert(PVT != VT && "Don't know what type to promote to!");
1241 
1242     SDLoc DL(Op);
1243     SDNode *N = Op.getNode();
1244     LoadSDNode *LD = cast<LoadSDNode>(N);
1245     EVT MemVT = LD->getMemoryVT();
1246     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1247       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1248                                                        : ISD::EXTLOAD)
1249       : LD->getExtensionType();
1250     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1251                                    LD->getChain(), LD->getBasePtr(),
1252                                    MemVT, LD->getMemOperand());
1253     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1254 
1255     DEBUG(dbgs() << "\nPromoting ";
1256           N->dump(&DAG);
1257           dbgs() << "\nTo: ";
1258           Result.getNode()->dump(&DAG);
1259           dbgs() << '\n');
1260     WorklistRemover DeadNodes(*this);
1261     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1262     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1263     deleteAndRecombine(N);
1264     AddToWorklist(Result.getNode());
1265     return true;
1266   }
1267   return false;
1268 }
1269 
1270 /// \brief Recursively delete a node which has no uses and any operands for
1271 /// which it is the only use.
1272 ///
1273 /// Note that this both deletes the nodes and removes them from the worklist.
1274 /// It also adds any nodes who have had a user deleted to the worklist as they
1275 /// may now have only one use and subject to other combines.
1276 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1277   if (!N->use_empty())
1278     return false;
1279 
1280   SmallSetVector<SDNode *, 16> Nodes;
1281   Nodes.insert(N);
1282   do {
1283     N = Nodes.pop_back_val();
1284     if (!N)
1285       continue;
1286 
1287     if (N->use_empty()) {
1288       for (const SDValue &ChildN : N->op_values())
1289         Nodes.insert(ChildN.getNode());
1290 
1291       removeFromWorklist(N);
1292       DAG.DeleteNode(N);
1293     } else {
1294       AddToWorklist(N);
1295     }
1296   } while (!Nodes.empty());
1297   return true;
1298 }
1299 
1300 //===----------------------------------------------------------------------===//
1301 //  Main DAG Combiner implementation
1302 //===----------------------------------------------------------------------===//
1303 
1304 void DAGCombiner::Run(CombineLevel AtLevel) {
1305   // set the instance variables, so that the various visit routines may use it.
1306   Level = AtLevel;
1307   LegalOperations = Level >= AfterLegalizeVectorOps;
1308   LegalTypes = Level >= AfterLegalizeTypes;
1309 
1310   // Add all the dag nodes to the worklist.
1311   for (SDNode &Node : DAG.allnodes())
1312     AddToWorklist(&Node);
1313 
1314   // Create a dummy node (which is not added to allnodes), that adds a reference
1315   // to the root node, preventing it from being deleted, and tracking any
1316   // changes of the root.
1317   HandleSDNode Dummy(DAG.getRoot());
1318 
1319   // While the worklist isn't empty, find a node and try to combine it.
1320   while (!WorklistMap.empty()) {
1321     SDNode *N;
1322     // The Worklist holds the SDNodes in order, but it may contain null entries.
1323     do {
1324       N = Worklist.pop_back_val();
1325     } while (!N);
1326 
1327     bool GoodWorklistEntry = WorklistMap.erase(N);
1328     (void)GoodWorklistEntry;
1329     assert(GoodWorklistEntry &&
1330            "Found a worklist entry without a corresponding map entry!");
1331 
1332     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1333     // N is deleted from the DAG, since they too may now be dead or may have a
1334     // reduced number of uses, allowing other xforms.
1335     if (recursivelyDeleteUnusedNodes(N))
1336       continue;
1337 
1338     WorklistRemover DeadNodes(*this);
1339 
1340     // If this combine is running after legalizing the DAG, re-legalize any
1341     // nodes pulled off the worklist.
1342     if (Level == AfterLegalizeDAG) {
1343       SmallSetVector<SDNode *, 16> UpdatedNodes;
1344       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1345 
1346       for (SDNode *LN : UpdatedNodes) {
1347         AddToWorklist(LN);
1348         AddUsersToWorklist(LN);
1349       }
1350       if (!NIsValid)
1351         continue;
1352     }
1353 
1354     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1355 
1356     // Add any operands of the new node which have not yet been combined to the
1357     // worklist as well. Because the worklist uniques things already, this
1358     // won't repeatedly process the same operand.
1359     CombinedNodes.insert(N);
1360     for (const SDValue &ChildN : N->op_values())
1361       if (!CombinedNodes.count(ChildN.getNode()))
1362         AddToWorklist(ChildN.getNode());
1363 
1364     SDValue RV = combine(N);
1365 
1366     if (!RV.getNode())
1367       continue;
1368 
1369     ++NodesCombined;
1370 
1371     // If we get back the same node we passed in, rather than a new node or
1372     // zero, we know that the node must have defined multiple values and
1373     // CombineTo was used.  Since CombineTo takes care of the worklist
1374     // mechanics for us, we have no work to do in this case.
1375     if (RV.getNode() == N)
1376       continue;
1377 
1378     assert(N->getOpcode() != ISD::DELETED_NODE &&
1379            RV.getOpcode() != ISD::DELETED_NODE &&
1380            "Node was deleted but visit returned new node!");
1381 
1382     DEBUG(dbgs() << " ... into: ";
1383           RV.getNode()->dump(&DAG));
1384 
1385     if (N->getNumValues() == RV.getNode()->getNumValues())
1386       DAG.ReplaceAllUsesWith(N, RV.getNode());
1387     else {
1388       assert(N->getValueType(0) == RV.getValueType() &&
1389              N->getNumValues() == 1 && "Type mismatch");
1390       SDValue OpV = RV;
1391       DAG.ReplaceAllUsesWith(N, &OpV);
1392     }
1393 
1394     // Push the new node and any users onto the worklist
1395     AddToWorklist(RV.getNode());
1396     AddUsersToWorklist(RV.getNode());
1397 
1398     // Finally, if the node is now dead, remove it from the graph.  The node
1399     // may not be dead if the replacement process recursively simplified to
1400     // something else needing this node. This will also take care of adding any
1401     // operands which have lost a user to the worklist.
1402     recursivelyDeleteUnusedNodes(N);
1403   }
1404 
1405   // If the root changed (e.g. it was a dead load, update the root).
1406   DAG.setRoot(Dummy.getValue());
1407   DAG.RemoveDeadNodes();
1408 }
1409 
1410 SDValue DAGCombiner::visit(SDNode *N) {
1411   switch (N->getOpcode()) {
1412   default: break;
1413   case ISD::TokenFactor:        return visitTokenFactor(N);
1414   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1415   case ISD::ADD:                return visitADD(N);
1416   case ISD::SUB:                return visitSUB(N);
1417   case ISD::ADDC:               return visitADDC(N);
1418   case ISD::SUBC:               return visitSUBC(N);
1419   case ISD::ADDE:               return visitADDE(N);
1420   case ISD::SUBE:               return visitSUBE(N);
1421   case ISD::MUL:                return visitMUL(N);
1422   case ISD::SDIV:               return visitSDIV(N);
1423   case ISD::UDIV:               return visitUDIV(N);
1424   case ISD::SREM:
1425   case ISD::UREM:               return visitREM(N);
1426   case ISD::MULHU:              return visitMULHU(N);
1427   case ISD::MULHS:              return visitMULHS(N);
1428   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1429   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1430   case ISD::SMULO:              return visitSMULO(N);
1431   case ISD::UMULO:              return visitUMULO(N);
1432   case ISD::SMIN:
1433   case ISD::SMAX:
1434   case ISD::UMIN:
1435   case ISD::UMAX:               return visitIMINMAX(N);
1436   case ISD::AND:                return visitAND(N);
1437   case ISD::OR:                 return visitOR(N);
1438   case ISD::XOR:                return visitXOR(N);
1439   case ISD::SHL:                return visitSHL(N);
1440   case ISD::SRA:                return visitSRA(N);
1441   case ISD::SRL:                return visitSRL(N);
1442   case ISD::ROTR:
1443   case ISD::ROTL:               return visitRotate(N);
1444   case ISD::BSWAP:              return visitBSWAP(N);
1445   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1446   case ISD::CTLZ:               return visitCTLZ(N);
1447   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1448   case ISD::CTTZ:               return visitCTTZ(N);
1449   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1450   case ISD::CTPOP:              return visitCTPOP(N);
1451   case ISD::SELECT:             return visitSELECT(N);
1452   case ISD::VSELECT:            return visitVSELECT(N);
1453   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1454   case ISD::SETCC:              return visitSETCC(N);
1455   case ISD::SETCCE:             return visitSETCCE(N);
1456   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1457   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1458   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1459   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1460   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1461   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1462   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1463   case ISD::BITCAST:            return visitBITCAST(N);
1464   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1465   case ISD::FADD:               return visitFADD(N);
1466   case ISD::FSUB:               return visitFSUB(N);
1467   case ISD::FMUL:               return visitFMUL(N);
1468   case ISD::FMA:                return visitFMA(N);
1469   case ISD::FDIV:               return visitFDIV(N);
1470   case ISD::FREM:               return visitFREM(N);
1471   case ISD::FSQRT:              return visitFSQRT(N);
1472   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1473   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1474   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1475   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1476   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1477   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1478   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1479   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1480   case ISD::FNEG:               return visitFNEG(N);
1481   case ISD::FABS:               return visitFABS(N);
1482   case ISD::FFLOOR:             return visitFFLOOR(N);
1483   case ISD::FMINNUM:            return visitFMINNUM(N);
1484   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1485   case ISD::FCEIL:              return visitFCEIL(N);
1486   case ISD::FTRUNC:             return visitFTRUNC(N);
1487   case ISD::BRCOND:             return visitBRCOND(N);
1488   case ISD::BR_CC:              return visitBR_CC(N);
1489   case ISD::LOAD:               return visitLOAD(N);
1490   case ISD::STORE:              return visitSTORE(N);
1491   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1492   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1493   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1494   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1495   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1496   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1497   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1498   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1499   case ISD::MGATHER:            return visitMGATHER(N);
1500   case ISD::MLOAD:              return visitMLOAD(N);
1501   case ISD::MSCATTER:           return visitMSCATTER(N);
1502   case ISD::MSTORE:             return visitMSTORE(N);
1503   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1504   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1505   }
1506   return SDValue();
1507 }
1508 
1509 SDValue DAGCombiner::combine(SDNode *N) {
1510   SDValue RV = visit(N);
1511 
1512   // If nothing happened, try a target-specific DAG combine.
1513   if (!RV.getNode()) {
1514     assert(N->getOpcode() != ISD::DELETED_NODE &&
1515            "Node was deleted but visit returned NULL!");
1516 
1517     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1518         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1519 
1520       // Expose the DAG combiner to the target combiner impls.
1521       TargetLowering::DAGCombinerInfo
1522         DagCombineInfo(DAG, Level, false, this);
1523 
1524       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1525     }
1526   }
1527 
1528   // If nothing happened still, try promoting the operation.
1529   if (!RV.getNode()) {
1530     switch (N->getOpcode()) {
1531     default: break;
1532     case ISD::ADD:
1533     case ISD::SUB:
1534     case ISD::MUL:
1535     case ISD::AND:
1536     case ISD::OR:
1537     case ISD::XOR:
1538       RV = PromoteIntBinOp(SDValue(N, 0));
1539       break;
1540     case ISD::SHL:
1541     case ISD::SRA:
1542     case ISD::SRL:
1543       RV = PromoteIntShiftOp(SDValue(N, 0));
1544       break;
1545     case ISD::SIGN_EXTEND:
1546     case ISD::ZERO_EXTEND:
1547     case ISD::ANY_EXTEND:
1548       RV = PromoteExtend(SDValue(N, 0));
1549       break;
1550     case ISD::LOAD:
1551       if (PromoteLoad(SDValue(N, 0)))
1552         RV = SDValue(N, 0);
1553       break;
1554     }
1555   }
1556 
1557   // If N is a commutative binary node, try commuting it to enable more
1558   // sdisel CSE.
1559   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1560       N->getNumValues() == 1) {
1561     SDValue N0 = N->getOperand(0);
1562     SDValue N1 = N->getOperand(1);
1563 
1564     // Constant operands are canonicalized to RHS.
1565     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1566       SDValue Ops[] = {N1, N0};
1567       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1568                                             N->getFlags());
1569       if (CSENode)
1570         return SDValue(CSENode, 0);
1571     }
1572   }
1573 
1574   return RV;
1575 }
1576 
1577 /// Given a node, return its input chain if it has one, otherwise return a null
1578 /// sd operand.
1579 static SDValue getInputChainForNode(SDNode *N) {
1580   if (unsigned NumOps = N->getNumOperands()) {
1581     if (N->getOperand(0).getValueType() == MVT::Other)
1582       return N->getOperand(0);
1583     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1584       return N->getOperand(NumOps-1);
1585     for (unsigned i = 1; i < NumOps-1; ++i)
1586       if (N->getOperand(i).getValueType() == MVT::Other)
1587         return N->getOperand(i);
1588   }
1589   return SDValue();
1590 }
1591 
1592 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1593   // If N has two operands, where one has an input chain equal to the other,
1594   // the 'other' chain is redundant.
1595   if (N->getNumOperands() == 2) {
1596     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1597       return N->getOperand(0);
1598     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1599       return N->getOperand(1);
1600   }
1601 
1602   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1603   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1604   SmallPtrSet<SDNode*, 16> SeenOps;
1605   bool Changed = false;             // If we should replace this token factor.
1606 
1607   // Start out with this token factor.
1608   TFs.push_back(N);
1609 
1610   // Iterate through token factors.  The TFs grows when new token factors are
1611   // encountered.
1612   for (unsigned i = 0; i < TFs.size(); ++i) {
1613     SDNode *TF = TFs[i];
1614 
1615     // Check each of the operands.
1616     for (const SDValue &Op : TF->op_values()) {
1617 
1618       switch (Op.getOpcode()) {
1619       case ISD::EntryToken:
1620         // Entry tokens don't need to be added to the list. They are
1621         // redundant.
1622         Changed = true;
1623         break;
1624 
1625       case ISD::TokenFactor:
1626         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1627           // Queue up for processing.
1628           TFs.push_back(Op.getNode());
1629           // Clean up in case the token factor is removed.
1630           AddToWorklist(Op.getNode());
1631           Changed = true;
1632           break;
1633         }
1634         LLVM_FALLTHROUGH;
1635 
1636       default:
1637         // Only add if it isn't already in the list.
1638         if (SeenOps.insert(Op.getNode()).second)
1639           Ops.push_back(Op);
1640         else
1641           Changed = true;
1642         break;
1643       }
1644     }
1645   }
1646 
1647   SDValue Result;
1648 
1649   // If we've changed things around then replace token factor.
1650   if (Changed) {
1651     if (Ops.empty()) {
1652       // The entry token is the only possible outcome.
1653       Result = DAG.getEntryNode();
1654     } else {
1655       // New and improved token factor.
1656       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1657     }
1658 
1659     // Add users to worklist if AA is enabled, since it may introduce
1660     // a lot of new chained token factors while removing memory deps.
1661     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1662       : DAG.getSubtarget().useAA();
1663     return CombineTo(N, Result, UseAA /*add to worklist*/);
1664   }
1665 
1666   return Result;
1667 }
1668 
1669 /// MERGE_VALUES can always be eliminated.
1670 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1671   WorklistRemover DeadNodes(*this);
1672   // Replacing results may cause a different MERGE_VALUES to suddenly
1673   // be CSE'd with N, and carry its uses with it. Iterate until no
1674   // uses remain, to ensure that the node can be safely deleted.
1675   // First add the users of this node to the work list so that they
1676   // can be tried again once they have new operands.
1677   AddUsersToWorklist(N);
1678   do {
1679     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1680       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1681   } while (!N->use_empty());
1682   deleteAndRecombine(N);
1683   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1684 }
1685 
1686 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1687 /// ConstantSDNode pointer else nullptr.
1688 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1689   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1690   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1691 }
1692 
1693 SDValue DAGCombiner::visitADD(SDNode *N) {
1694   SDValue N0 = N->getOperand(0);
1695   SDValue N1 = N->getOperand(1);
1696   EVT VT = N0.getValueType();
1697   SDLoc DL(N);
1698 
1699   // fold vector ops
1700   if (VT.isVector()) {
1701     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1702       return FoldedVOp;
1703 
1704     // fold (add x, 0) -> x, vector edition
1705     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1706       return N0;
1707     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1708       return N1;
1709   }
1710 
1711   // fold (add x, undef) -> undef
1712   if (N0.isUndef())
1713     return N0;
1714 
1715   if (N1.isUndef())
1716     return N1;
1717 
1718   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1719     // canonicalize constant to RHS
1720     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1721       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1722     // fold (add c1, c2) -> c1+c2
1723     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1724                                       N1.getNode());
1725   }
1726 
1727   // fold (add x, 0) -> x
1728   if (isNullConstant(N1))
1729     return N0;
1730 
1731   // fold ((c1-A)+c2) -> (c1+c2)-A
1732   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1733     if (N0.getOpcode() == ISD::SUB)
1734       if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1735         return DAG.getNode(ISD::SUB, DL, VT,
1736                            DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1737                            N0.getOperand(1));
1738       }
1739   }
1740 
1741   // reassociate add
1742   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1743     return RADD;
1744 
1745   // fold ((0-A) + B) -> B-A
1746   if (N0.getOpcode() == ISD::SUB &&
1747       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1748     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1749 
1750   // fold (A + (0-B)) -> A-B
1751   if (N1.getOpcode() == ISD::SUB &&
1752       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1753     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1754 
1755   // fold (A+(B-A)) -> B
1756   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1757     return N1.getOperand(0);
1758 
1759   // fold ((B-A)+A) -> B
1760   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1761     return N0.getOperand(0);
1762 
1763   // fold (A+(B-(A+C))) to (B-C)
1764   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1765       N0 == N1.getOperand(1).getOperand(0))
1766     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1767                        N1.getOperand(1).getOperand(1));
1768 
1769   // fold (A+(B-(C+A))) to (B-C)
1770   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1771       N0 == N1.getOperand(1).getOperand(1))
1772     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1773                        N1.getOperand(1).getOperand(0));
1774 
1775   // fold (A+((B-A)+or-C)) to (B+or-C)
1776   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1777       N1.getOperand(0).getOpcode() == ISD::SUB &&
1778       N0 == N1.getOperand(0).getOperand(1))
1779     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1780                        N1.getOperand(1));
1781 
1782   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1783   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1784     SDValue N00 = N0.getOperand(0);
1785     SDValue N01 = N0.getOperand(1);
1786     SDValue N10 = N1.getOperand(0);
1787     SDValue N11 = N1.getOperand(1);
1788 
1789     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1790       return DAG.getNode(ISD::SUB, DL, VT,
1791                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1792                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1793   }
1794 
1795   if (SimplifyDemandedBits(SDValue(N, 0)))
1796     return SDValue(N, 0);
1797 
1798   // fold (a+b) -> (a|b) iff a and b share no bits.
1799   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1800       VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1801     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1802 
1803   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1804   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1805       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1806     return DAG.getNode(ISD::SUB, DL, VT, N0,
1807                        DAG.getNode(ISD::SHL, DL, VT,
1808                                    N1.getOperand(0).getOperand(1),
1809                                    N1.getOperand(1)));
1810   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1811       isNullConstantOrNullSplatConstant(N0.getOperand(0).getOperand(0)))
1812     return DAG.getNode(ISD::SUB, DL, VT, N1,
1813                        DAG.getNode(ISD::SHL, DL, VT,
1814                                    N0.getOperand(0).getOperand(1),
1815                                    N0.getOperand(1)));
1816 
1817   if (N1.getOpcode() == ISD::AND) {
1818     SDValue AndOp0 = N1.getOperand(0);
1819     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1820     unsigned DestBits = VT.getScalarSizeInBits();
1821 
1822     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1823     // and similar xforms where the inner op is either ~0 or 0.
1824     if (NumSignBits == DestBits &&
1825         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1826       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1827   }
1828 
1829   // add (sext i1), X -> sub X, (zext i1)
1830   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1831       N0.getOperand(0).getValueType() == MVT::i1 &&
1832       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1833     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1834     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1835   }
1836 
1837   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1838   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1839     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1840     if (TN->getVT() == MVT::i1) {
1841       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1842                                  DAG.getConstant(1, DL, VT));
1843       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1844     }
1845   }
1846 
1847   return SDValue();
1848 }
1849 
1850 SDValue DAGCombiner::visitADDC(SDNode *N) {
1851   SDValue N0 = N->getOperand(0);
1852   SDValue N1 = N->getOperand(1);
1853   EVT VT = N0.getValueType();
1854 
1855   // If the flag result is dead, turn this into an ADD.
1856   if (!N->hasAnyUseOfValue(1))
1857     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1858                      DAG.getNode(ISD::CARRY_FALSE,
1859                                  SDLoc(N), MVT::Glue));
1860 
1861   // canonicalize constant to RHS.
1862   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1863   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1864   if (N0C && !N1C)
1865     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1866 
1867   // fold (addc x, 0) -> x + no carry out
1868   if (isNullConstant(N1))
1869     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1870                                         SDLoc(N), MVT::Glue));
1871 
1872   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1873   APInt LHSZero, LHSOne;
1874   APInt RHSZero, RHSOne;
1875   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1876 
1877   if (LHSZero.getBoolValue()) {
1878     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1879 
1880     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1881     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1882     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1883       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1884                        DAG.getNode(ISD::CARRY_FALSE,
1885                                    SDLoc(N), MVT::Glue));
1886   }
1887 
1888   return SDValue();
1889 }
1890 
1891 SDValue DAGCombiner::visitADDE(SDNode *N) {
1892   SDValue N0 = N->getOperand(0);
1893   SDValue N1 = N->getOperand(1);
1894   SDValue CarryIn = N->getOperand(2);
1895 
1896   // canonicalize constant to RHS
1897   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1898   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1899   if (N0C && !N1C)
1900     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1901                        N1, N0, CarryIn);
1902 
1903   // fold (adde x, y, false) -> (addc x, y)
1904   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1905     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1906 
1907   return SDValue();
1908 }
1909 
1910 // Since it may not be valid to emit a fold to zero for vector initializers
1911 // check if we can before folding.
1912 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
1913                              SelectionDAG &DAG, bool LegalOperations,
1914                              bool LegalTypes) {
1915   if (!VT.isVector())
1916     return DAG.getConstant(0, DL, VT);
1917   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1918     return DAG.getConstant(0, DL, VT);
1919   return SDValue();
1920 }
1921 
1922 SDValue DAGCombiner::visitSUB(SDNode *N) {
1923   SDValue N0 = N->getOperand(0);
1924   SDValue N1 = N->getOperand(1);
1925   EVT VT = N0.getValueType();
1926   SDLoc DL(N);
1927 
1928   // fold vector ops
1929   if (VT.isVector()) {
1930     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1931       return FoldedVOp;
1932 
1933     // fold (sub x, 0) -> x, vector edition
1934     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1935       return N0;
1936   }
1937 
1938   // fold (sub x, x) -> 0
1939   // FIXME: Refactor this and xor and other similar operations together.
1940   if (N0 == N1)
1941     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
1942   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1943       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1944     // fold (sub c1, c2) -> c1-c2
1945     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
1946                                       N1.getNode());
1947   }
1948 
1949   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1950 
1951   // fold (sub x, c) -> (add x, -c)
1952   if (N1C) {
1953     return DAG.getNode(ISD::ADD, DL, VT, N0,
1954                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1955   }
1956 
1957   // Right-shifting everything out but the sign bit followed by negation is the
1958   // same as flipping arithmetic/logical shift type without the negation:
1959   // -(X >>u 31) -> (X >>s 31)
1960   // -(X >>s 31) -> (X >>u 31)
1961   if (isNullConstantOrNullSplatConstant(N0) &&
1962       (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL)) {
1963     ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
1964     if (ShiftAmt && ShiftAmt->getZExtValue() == VT.getScalarSizeInBits() - 1) {
1965       auto NewOpcode = N1->getOpcode() == ISD::SRA ? ISD::SRL :ISD::SRA;
1966       return DAG.getNode(NewOpcode, DL, VT, N1.getOperand(0), N1.getOperand(1));
1967     }
1968   }
1969 
1970   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1971   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
1972     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
1973 
1974   // fold A-(A-B) -> B
1975   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1976     return N1.getOperand(1);
1977 
1978   // fold (A+B)-A -> B
1979   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1980     return N0.getOperand(1);
1981 
1982   // fold (A+B)-B -> A
1983   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1984     return N0.getOperand(0);
1985 
1986   // fold C2-(A+C1) -> (C2-C1)-A
1987   if (N1.getOpcode() == ISD::ADD) {
1988     SDValue N11 = N1.getOperand(1);
1989     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
1990         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
1991       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
1992       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
1993     }
1994   }
1995 
1996   // fold ((A+(B+or-C))-B) -> A+or-C
1997   if (N0.getOpcode() == ISD::ADD &&
1998       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1999        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2000       N0.getOperand(1).getOperand(0) == N1)
2001     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2002                        N0.getOperand(1).getOperand(1));
2003 
2004   // fold ((A+(C+B))-B) -> A+C
2005   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2006       N0.getOperand(1).getOperand(1) == N1)
2007     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2008                        N0.getOperand(1).getOperand(0));
2009 
2010   // fold ((A-(B-C))-C) -> A-B
2011   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2012       N0.getOperand(1).getOperand(1) == N1)
2013     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2014                        N0.getOperand(1).getOperand(0));
2015 
2016   // If either operand of a sub is undef, the result is undef
2017   if (N0.isUndef())
2018     return N0;
2019   if (N1.isUndef())
2020     return N1;
2021 
2022   // If the relocation model supports it, consider symbol offsets.
2023   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2024     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2025       // fold (sub Sym, c) -> Sym-c
2026       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2027         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2028                                     GA->getOffset() -
2029                                         (uint64_t)N1C->getSExtValue());
2030       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2031       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2032         if (GA->getGlobal() == GB->getGlobal())
2033           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2034                                  DL, VT);
2035     }
2036 
2037   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2038   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2039     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2040     if (TN->getVT() == MVT::i1) {
2041       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2042                                  DAG.getConstant(1, DL, VT));
2043       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2044     }
2045   }
2046 
2047   return SDValue();
2048 }
2049 
2050 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2051   SDValue N0 = N->getOperand(0);
2052   SDValue N1 = N->getOperand(1);
2053   EVT VT = N0.getValueType();
2054   SDLoc DL(N);
2055 
2056   // If the flag result is dead, turn this into an SUB.
2057   if (!N->hasAnyUseOfValue(1))
2058     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2059                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2060 
2061   // fold (subc x, x) -> 0 + no borrow
2062   if (N0 == N1)
2063     return CombineTo(N, DAG.getConstant(0, DL, VT),
2064                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2065 
2066   // fold (subc x, 0) -> x + no borrow
2067   if (isNullConstant(N1))
2068     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2069 
2070   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2071   if (isAllOnesConstant(N0))
2072     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2073                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2074 
2075   return SDValue();
2076 }
2077 
2078 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2079   SDValue N0 = N->getOperand(0);
2080   SDValue N1 = N->getOperand(1);
2081   SDValue CarryIn = N->getOperand(2);
2082 
2083   // fold (sube x, y, false) -> (subc x, y)
2084   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2085     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2086 
2087   return SDValue();
2088 }
2089 
2090 SDValue DAGCombiner::visitMUL(SDNode *N) {
2091   SDValue N0 = N->getOperand(0);
2092   SDValue N1 = N->getOperand(1);
2093   EVT VT = N0.getValueType();
2094 
2095   // fold (mul x, undef) -> 0
2096   if (N0.isUndef() || N1.isUndef())
2097     return DAG.getConstant(0, SDLoc(N), VT);
2098 
2099   bool N0IsConst = false;
2100   bool N1IsConst = false;
2101   bool N1IsOpaqueConst = false;
2102   bool N0IsOpaqueConst = false;
2103   APInt ConstValue0, ConstValue1;
2104   // fold vector ops
2105   if (VT.isVector()) {
2106     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2107       return FoldedVOp;
2108 
2109     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2110     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2111   } else {
2112     N0IsConst = isa<ConstantSDNode>(N0);
2113     if (N0IsConst) {
2114       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2115       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2116     }
2117     N1IsConst = isa<ConstantSDNode>(N1);
2118     if (N1IsConst) {
2119       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2120       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2121     }
2122   }
2123 
2124   // fold (mul c1, c2) -> c1*c2
2125   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2126     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2127                                       N0.getNode(), N1.getNode());
2128 
2129   // canonicalize constant to RHS (vector doesn't have to splat)
2130   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2131      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2132     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2133   // fold (mul x, 0) -> 0
2134   if (N1IsConst && ConstValue1 == 0)
2135     return N1;
2136   // We require a splat of the entire scalar bit width for non-contiguous
2137   // bit patterns.
2138   bool IsFullSplat =
2139     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2140   // fold (mul x, 1) -> x
2141   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2142     return N0;
2143   // fold (mul x, -1) -> 0-x
2144   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2145     SDLoc DL(N);
2146     return DAG.getNode(ISD::SUB, DL, VT,
2147                        DAG.getConstant(0, DL, VT), N0);
2148   }
2149   // fold (mul x, (1 << c)) -> x << c
2150   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2151       IsFullSplat) {
2152     SDLoc DL(N);
2153     return DAG.getNode(ISD::SHL, DL, VT, N0,
2154                        DAG.getConstant(ConstValue1.logBase2(), DL,
2155                                        getShiftAmountTy(N0.getValueType())));
2156   }
2157   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2158   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2159       IsFullSplat) {
2160     unsigned Log2Val = (-ConstValue1).logBase2();
2161     SDLoc DL(N);
2162     // FIXME: If the input is something that is easily negated (e.g. a
2163     // single-use add), we should put the negate there.
2164     return DAG.getNode(ISD::SUB, DL, VT,
2165                        DAG.getConstant(0, DL, VT),
2166                        DAG.getNode(ISD::SHL, DL, VT, N0,
2167                             DAG.getConstant(Log2Val, DL,
2168                                       getShiftAmountTy(N0.getValueType()))));
2169   }
2170 
2171   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2172   if (N0.getOpcode() == ISD::SHL &&
2173       isConstantOrConstantVector(N1) &&
2174       isConstantOrConstantVector(N0.getOperand(1))) {
2175     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2176     AddToWorklist(C3.getNode());
2177     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2178   }
2179 
2180   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2181   // use.
2182   {
2183     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2184 
2185     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2186     if (N0.getOpcode() == ISD::SHL &&
2187         isConstantOrConstantVector(N0.getOperand(1)) &&
2188         N0.getNode()->hasOneUse()) {
2189       Sh = N0; Y = N1;
2190     } else if (N1.getOpcode() == ISD::SHL &&
2191                isConstantOrConstantVector(N1.getOperand(1)) &&
2192                N1.getNode()->hasOneUse()) {
2193       Sh = N1; Y = N0;
2194     }
2195 
2196     if (Sh.getNode()) {
2197       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2198       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2199     }
2200   }
2201 
2202   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2203   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2204       N0.getOpcode() == ISD::ADD &&
2205       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2206       isMulAddWithConstProfitable(N, N0, N1))
2207       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2208                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2209                                      N0.getOperand(0), N1),
2210                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2211                                      N0.getOperand(1), N1));
2212 
2213   // reassociate mul
2214   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2215     return RMUL;
2216 
2217   return SDValue();
2218 }
2219 
2220 /// Return true if divmod libcall is available.
2221 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2222                                      const TargetLowering &TLI) {
2223   RTLIB::Libcall LC;
2224   EVT NodeType = Node->getValueType(0);
2225   if (!NodeType.isSimple())
2226     return false;
2227   switch (NodeType.getSimpleVT().SimpleTy) {
2228   default: return false; // No libcall for vector types.
2229   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2230   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2231   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2232   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2233   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2234   }
2235 
2236   return TLI.getLibcallName(LC) != nullptr;
2237 }
2238 
2239 /// Issue divrem if both quotient and remainder are needed.
2240 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2241   if (Node->use_empty())
2242     return SDValue(); // This is a dead node, leave it alone.
2243 
2244   unsigned Opcode = Node->getOpcode();
2245   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2246   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2247 
2248   // DivMod lib calls can still work on non-legal types if using lib-calls.
2249   EVT VT = Node->getValueType(0);
2250   if (VT.isVector() || !VT.isInteger())
2251     return SDValue();
2252 
2253   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2254     return SDValue();
2255 
2256   // If DIVREM is going to get expanded into a libcall,
2257   // but there is no libcall available, then don't combine.
2258   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2259       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2260     return SDValue();
2261 
2262   // If div is legal, it's better to do the normal expansion
2263   unsigned OtherOpcode = 0;
2264   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2265     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2266     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2267       return SDValue();
2268   } else {
2269     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2270     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2271       return SDValue();
2272   }
2273 
2274   SDValue Op0 = Node->getOperand(0);
2275   SDValue Op1 = Node->getOperand(1);
2276   SDValue combined;
2277   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2278          UE = Op0.getNode()->use_end(); UI != UE;) {
2279     SDNode *User = *UI++;
2280     if (User == Node || User->use_empty())
2281       continue;
2282     // Convert the other matching node(s), too;
2283     // otherwise, the DIVREM may get target-legalized into something
2284     // target-specific that we won't be able to recognize.
2285     unsigned UserOpc = User->getOpcode();
2286     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2287         User->getOperand(0) == Op0 &&
2288         User->getOperand(1) == Op1) {
2289       if (!combined) {
2290         if (UserOpc == OtherOpcode) {
2291           SDVTList VTs = DAG.getVTList(VT, VT);
2292           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2293         } else if (UserOpc == DivRemOpc) {
2294           combined = SDValue(User, 0);
2295         } else {
2296           assert(UserOpc == Opcode);
2297           continue;
2298         }
2299       }
2300       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2301         CombineTo(User, combined);
2302       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2303         CombineTo(User, combined.getValue(1));
2304     }
2305   }
2306   return combined;
2307 }
2308 
2309 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2310   SDValue N0 = N->getOperand(0);
2311   SDValue N1 = N->getOperand(1);
2312   EVT VT = N->getValueType(0);
2313 
2314   // fold vector ops
2315   if (VT.isVector())
2316     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2317       return FoldedVOp;
2318 
2319   SDLoc DL(N);
2320 
2321   // fold (sdiv c1, c2) -> c1/c2
2322   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2323   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2324   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2325     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2326   // fold (sdiv X, 1) -> X
2327   if (N1C && N1C->isOne())
2328     return N0;
2329   // fold (sdiv X, -1) -> 0-X
2330   if (N1C && N1C->isAllOnesValue())
2331     return DAG.getNode(ISD::SUB, DL, VT,
2332                        DAG.getConstant(0, DL, VT), N0);
2333 
2334   // If we know the sign bits of both operands are zero, strength reduce to a
2335   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2336   if (!VT.isVector()) {
2337     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2338       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2339   }
2340 
2341   // fold (sdiv X, pow2) -> simple ops after legalize
2342   // FIXME: We check for the exact bit here because the generic lowering gives
2343   // better results in that case. The target-specific lowering should learn how
2344   // to handle exact sdivs efficiently.
2345   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2346       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2347       (N1C->getAPIntValue().isPowerOf2() ||
2348        (-N1C->getAPIntValue()).isPowerOf2())) {
2349     // Target-specific implementation of sdiv x, pow2.
2350     if (SDValue Res = BuildSDIVPow2(N))
2351       return Res;
2352 
2353     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2354 
2355     // Splat the sign bit into the register
2356     SDValue SGN =
2357         DAG.getNode(ISD::SRA, DL, VT, N0,
2358                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2359                                     getShiftAmountTy(N0.getValueType())));
2360     AddToWorklist(SGN.getNode());
2361 
2362     // Add (N0 < 0) ? abs2 - 1 : 0;
2363     SDValue SRL =
2364         DAG.getNode(ISD::SRL, DL, VT, SGN,
2365                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2366                                     getShiftAmountTy(SGN.getValueType())));
2367     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2368     AddToWorklist(SRL.getNode());
2369     AddToWorklist(ADD.getNode());    // Divide by pow2
2370     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2371                   DAG.getConstant(lg2, DL,
2372                                   getShiftAmountTy(ADD.getValueType())));
2373 
2374     // If we're dividing by a positive value, we're done.  Otherwise, we must
2375     // negate the result.
2376     if (N1C->getAPIntValue().isNonNegative())
2377       return SRA;
2378 
2379     AddToWorklist(SRA.getNode());
2380     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2381   }
2382 
2383   // If integer divide is expensive and we satisfy the requirements, emit an
2384   // alternate sequence.  Targets may check function attributes for size/speed
2385   // trade-offs.
2386   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2387   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2388     if (SDValue Op = BuildSDIV(N))
2389       return Op;
2390 
2391   // sdiv, srem -> sdivrem
2392   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2393   // Otherwise, we break the simplification logic in visitREM().
2394   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2395     if (SDValue DivRem = useDivRem(N))
2396         return DivRem;
2397 
2398   // undef / X -> 0
2399   if (N0.isUndef())
2400     return DAG.getConstant(0, DL, VT);
2401   // X / undef -> undef
2402   if (N1.isUndef())
2403     return N1;
2404 
2405   return SDValue();
2406 }
2407 
2408 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2409   SDValue N0 = N->getOperand(0);
2410   SDValue N1 = N->getOperand(1);
2411   EVT VT = N->getValueType(0);
2412 
2413   // fold vector ops
2414   if (VT.isVector())
2415     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2416       return FoldedVOp;
2417 
2418   SDLoc DL(N);
2419 
2420   // fold (udiv c1, c2) -> c1/c2
2421   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2422   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2423   if (N0C && N1C)
2424     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2425                                                     N0C, N1C))
2426       return Folded;
2427   // fold (udiv x, (1 << c)) -> x >>u c
2428   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2429     return DAG.getNode(ISD::SRL, DL, VT, N0,
2430                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2431                                        getShiftAmountTy(N0.getValueType())));
2432 
2433   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2434   if (N1.getOpcode() == ISD::SHL) {
2435     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2436       if (SHC->getAPIntValue().isPowerOf2()) {
2437         EVT ADDVT = N1.getOperand(1).getValueType();
2438         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2439                                   N1.getOperand(1),
2440                                   DAG.getConstant(SHC->getAPIntValue()
2441                                                                   .logBase2(),
2442                                                   DL, ADDVT));
2443         AddToWorklist(Add.getNode());
2444         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2445       }
2446     }
2447   }
2448 
2449   // fold (udiv x, c) -> alternate
2450   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2451   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2452     if (SDValue Op = BuildUDIV(N))
2453       return Op;
2454 
2455   // sdiv, srem -> sdivrem
2456   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2457   // Otherwise, we break the simplification logic in visitREM().
2458   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2459     if (SDValue DivRem = useDivRem(N))
2460         return DivRem;
2461 
2462   // undef / X -> 0
2463   if (N0.isUndef())
2464     return DAG.getConstant(0, DL, VT);
2465   // X / undef -> undef
2466   if (N1.isUndef())
2467     return N1;
2468 
2469   return SDValue();
2470 }
2471 
2472 // handles ISD::SREM and ISD::UREM
2473 SDValue DAGCombiner::visitREM(SDNode *N) {
2474   unsigned Opcode = N->getOpcode();
2475   SDValue N0 = N->getOperand(0);
2476   SDValue N1 = N->getOperand(1);
2477   EVT VT = N->getValueType(0);
2478   bool isSigned = (Opcode == ISD::SREM);
2479   SDLoc DL(N);
2480 
2481   // fold (rem c1, c2) -> c1%c2
2482   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2483   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2484   if (N0C && N1C)
2485     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2486       return Folded;
2487 
2488   if (isSigned) {
2489     // If we know the sign bits of both operands are zero, strength reduce to a
2490     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2491     if (!VT.isVector()) {
2492       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2493         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2494     }
2495   } else {
2496     // fold (urem x, pow2) -> (and x, pow2-1)
2497     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2498         N1C->getAPIntValue().isPowerOf2()) {
2499       return DAG.getNode(ISD::AND, DL, VT, N0,
2500                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2501     }
2502     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2503     if (N1.getOpcode() == ISD::SHL) {
2504       ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0));
2505       if (SHC && SHC->getAPIntValue().isPowerOf2()) {
2506         APInt NegOne = APInt::getAllOnesValue(VT.getSizeInBits());
2507         SDValue Add =
2508             DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2509         AddToWorklist(Add.getNode());
2510         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2511       }
2512     }
2513   }
2514 
2515   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2516 
2517   // If X/C can be simplified by the division-by-constant logic, lower
2518   // X%C to the equivalent of X-X/C*C.
2519   // To avoid mangling nodes, this simplification requires that the combine()
2520   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2521   // against this by skipping the simplification if isIntDivCheap().  When
2522   // div is not cheap, combine will not return a DIVREM.  Regardless,
2523   // checking cheapness here makes sense since the simplification results in
2524   // fatter code.
2525   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2526     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2527     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2528     AddToWorklist(Div.getNode());
2529     SDValue OptimizedDiv = combine(Div.getNode());
2530     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2531       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2532              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2533       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2534       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2535       AddToWorklist(Mul.getNode());
2536       return Sub;
2537     }
2538   }
2539 
2540   // sdiv, srem -> sdivrem
2541   if (SDValue DivRem = useDivRem(N))
2542     return DivRem.getValue(1);
2543 
2544   // undef % X -> 0
2545   if (N0.isUndef())
2546     return DAG.getConstant(0, DL, VT);
2547   // X % undef -> undef
2548   if (N1.isUndef())
2549     return N1;
2550 
2551   return SDValue();
2552 }
2553 
2554 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2555   SDValue N0 = N->getOperand(0);
2556   SDValue N1 = N->getOperand(1);
2557   EVT VT = N->getValueType(0);
2558   SDLoc DL(N);
2559 
2560   // fold (mulhs x, 0) -> 0
2561   if (isNullConstant(N1))
2562     return N1;
2563   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2564   if (isOneConstant(N1)) {
2565     SDLoc DL(N);
2566     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2567                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2568                                        getShiftAmountTy(N0.getValueType())));
2569   }
2570   // fold (mulhs x, undef) -> 0
2571   if (N0.isUndef() || N1.isUndef())
2572     return DAG.getConstant(0, SDLoc(N), VT);
2573 
2574   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2575   // plus a shift.
2576   if (VT.isSimple() && !VT.isVector()) {
2577     MVT Simple = VT.getSimpleVT();
2578     unsigned SimpleSize = Simple.getSizeInBits();
2579     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2580     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2581       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2582       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2583       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2584       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2585             DAG.getConstant(SimpleSize, DL,
2586                             getShiftAmountTy(N1.getValueType())));
2587       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2588     }
2589   }
2590 
2591   return SDValue();
2592 }
2593 
2594 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2595   SDValue N0 = N->getOperand(0);
2596   SDValue N1 = N->getOperand(1);
2597   EVT VT = N->getValueType(0);
2598   SDLoc DL(N);
2599 
2600   // fold (mulhu x, 0) -> 0
2601   if (isNullConstant(N1))
2602     return N1;
2603   // fold (mulhu x, 1) -> 0
2604   if (isOneConstant(N1))
2605     return DAG.getConstant(0, DL, N0.getValueType());
2606   // fold (mulhu x, undef) -> 0
2607   if (N0.isUndef() || N1.isUndef())
2608     return DAG.getConstant(0, DL, VT);
2609 
2610   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2611   // plus a shift.
2612   if (VT.isSimple() && !VT.isVector()) {
2613     MVT Simple = VT.getSimpleVT();
2614     unsigned SimpleSize = Simple.getSizeInBits();
2615     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2616     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2617       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2618       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2619       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2620       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2621             DAG.getConstant(SimpleSize, DL,
2622                             getShiftAmountTy(N1.getValueType())));
2623       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2624     }
2625   }
2626 
2627   return SDValue();
2628 }
2629 
2630 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2631 /// give the opcodes for the two computations that are being performed. Return
2632 /// true if a simplification was made.
2633 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2634                                                 unsigned HiOp) {
2635   // If the high half is not needed, just compute the low half.
2636   bool HiExists = N->hasAnyUseOfValue(1);
2637   if (!HiExists &&
2638       (!LegalOperations ||
2639        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2640     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2641     return CombineTo(N, Res, Res);
2642   }
2643 
2644   // If the low half is not needed, just compute the high half.
2645   bool LoExists = N->hasAnyUseOfValue(0);
2646   if (!LoExists &&
2647       (!LegalOperations ||
2648        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2649     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2650     return CombineTo(N, Res, Res);
2651   }
2652 
2653   // If both halves are used, return as it is.
2654   if (LoExists && HiExists)
2655     return SDValue();
2656 
2657   // If the two computed results can be simplified separately, separate them.
2658   if (LoExists) {
2659     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2660     AddToWorklist(Lo.getNode());
2661     SDValue LoOpt = combine(Lo.getNode());
2662     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2663         (!LegalOperations ||
2664          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2665       return CombineTo(N, LoOpt, LoOpt);
2666   }
2667 
2668   if (HiExists) {
2669     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2670     AddToWorklist(Hi.getNode());
2671     SDValue HiOpt = combine(Hi.getNode());
2672     if (HiOpt.getNode() && HiOpt != Hi &&
2673         (!LegalOperations ||
2674          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2675       return CombineTo(N, HiOpt, HiOpt);
2676   }
2677 
2678   return SDValue();
2679 }
2680 
2681 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2682   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2683     return Res;
2684 
2685   EVT VT = N->getValueType(0);
2686   SDLoc DL(N);
2687 
2688   // If the type is twice as wide is legal, transform the mulhu to a wider
2689   // multiply plus a shift.
2690   if (VT.isSimple() && !VT.isVector()) {
2691     MVT Simple = VT.getSimpleVT();
2692     unsigned SimpleSize = Simple.getSizeInBits();
2693     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2694     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2695       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2696       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2697       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2698       // Compute the high part as N1.
2699       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2700             DAG.getConstant(SimpleSize, DL,
2701                             getShiftAmountTy(Lo.getValueType())));
2702       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2703       // Compute the low part as N0.
2704       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2705       return CombineTo(N, Lo, Hi);
2706     }
2707   }
2708 
2709   return SDValue();
2710 }
2711 
2712 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2713   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2714     return Res;
2715 
2716   EVT VT = N->getValueType(0);
2717   SDLoc DL(N);
2718 
2719   // If the type is twice as wide is legal, transform the mulhu to a wider
2720   // multiply plus a shift.
2721   if (VT.isSimple() && !VT.isVector()) {
2722     MVT Simple = VT.getSimpleVT();
2723     unsigned SimpleSize = Simple.getSizeInBits();
2724     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2725     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2726       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2727       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2728       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2729       // Compute the high part as N1.
2730       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2731             DAG.getConstant(SimpleSize, DL,
2732                             getShiftAmountTy(Lo.getValueType())));
2733       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2734       // Compute the low part as N0.
2735       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2736       return CombineTo(N, Lo, Hi);
2737     }
2738   }
2739 
2740   return SDValue();
2741 }
2742 
2743 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2744   // (smulo x, 2) -> (saddo x, x)
2745   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2746     if (C2->getAPIntValue() == 2)
2747       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2748                          N->getOperand(0), N->getOperand(0));
2749 
2750   return SDValue();
2751 }
2752 
2753 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2754   // (umulo x, 2) -> (uaddo x, x)
2755   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2756     if (C2->getAPIntValue() == 2)
2757       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2758                          N->getOperand(0), N->getOperand(0));
2759 
2760   return SDValue();
2761 }
2762 
2763 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2764   SDValue N0 = N->getOperand(0);
2765   SDValue N1 = N->getOperand(1);
2766   EVT VT = N0.getValueType();
2767 
2768   // fold vector ops
2769   if (VT.isVector())
2770     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2771       return FoldedVOp;
2772 
2773   // fold (add c1, c2) -> c1+c2
2774   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2775   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2776   if (N0C && N1C)
2777     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2778 
2779   // canonicalize constant to RHS
2780   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2781      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2782     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2783 
2784   return SDValue();
2785 }
2786 
2787 /// If this is a binary operator with two operands of the same opcode, try to
2788 /// simplify it.
2789 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2790   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2791   EVT VT = N0.getValueType();
2792   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2793 
2794   // Bail early if none of these transforms apply.
2795   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2796 
2797   // For each of OP in AND/OR/XOR:
2798   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2799   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2800   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2801   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2802   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2803   //
2804   // do not sink logical op inside of a vector extend, since it may combine
2805   // into a vsetcc.
2806   EVT Op0VT = N0.getOperand(0).getValueType();
2807   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2808        N0.getOpcode() == ISD::SIGN_EXTEND ||
2809        N0.getOpcode() == ISD::BSWAP ||
2810        // Avoid infinite looping with PromoteIntBinOp.
2811        (N0.getOpcode() == ISD::ANY_EXTEND &&
2812         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2813        (N0.getOpcode() == ISD::TRUNCATE &&
2814         (!TLI.isZExtFree(VT, Op0VT) ||
2815          !TLI.isTruncateFree(Op0VT, VT)) &&
2816         TLI.isTypeLegal(Op0VT))) &&
2817       !VT.isVector() &&
2818       Op0VT == N1.getOperand(0).getValueType() &&
2819       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2820     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2821                                  N0.getOperand(0).getValueType(),
2822                                  N0.getOperand(0), N1.getOperand(0));
2823     AddToWorklist(ORNode.getNode());
2824     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2825   }
2826 
2827   // For each of OP in SHL/SRL/SRA/AND...
2828   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2829   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2830   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2831   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2832        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2833       N0.getOperand(1) == N1.getOperand(1)) {
2834     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2835                                  N0.getOperand(0).getValueType(),
2836                                  N0.getOperand(0), N1.getOperand(0));
2837     AddToWorklist(ORNode.getNode());
2838     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2839                        ORNode, N0.getOperand(1));
2840   }
2841 
2842   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2843   // Only perform this optimization up until type legalization, before
2844   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2845   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2846   // we don't want to undo this promotion.
2847   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2848   // on scalars.
2849   if ((N0.getOpcode() == ISD::BITCAST ||
2850        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2851        Level <= AfterLegalizeTypes) {
2852     SDValue In0 = N0.getOperand(0);
2853     SDValue In1 = N1.getOperand(0);
2854     EVT In0Ty = In0.getValueType();
2855     EVT In1Ty = In1.getValueType();
2856     SDLoc DL(N);
2857     // If both incoming values are integers, and the original types are the
2858     // same.
2859     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2860       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2861       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2862       AddToWorklist(Op.getNode());
2863       return BC;
2864     }
2865   }
2866 
2867   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2868   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2869   // If both shuffles use the same mask, and both shuffle within a single
2870   // vector, then it is worthwhile to move the swizzle after the operation.
2871   // The type-legalizer generates this pattern when loading illegal
2872   // vector types from memory. In many cases this allows additional shuffle
2873   // optimizations.
2874   // There are other cases where moving the shuffle after the xor/and/or
2875   // is profitable even if shuffles don't perform a swizzle.
2876   // If both shuffles use the same mask, and both shuffles have the same first
2877   // or second operand, then it might still be profitable to move the shuffle
2878   // after the xor/and/or operation.
2879   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2880     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2881     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2882 
2883     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2884            "Inputs to shuffles are not the same type");
2885 
2886     // Check that both shuffles use the same mask. The masks are known to be of
2887     // the same length because the result vector type is the same.
2888     // Check also that shuffles have only one use to avoid introducing extra
2889     // instructions.
2890     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2891         SVN0->getMask().equals(SVN1->getMask())) {
2892       SDValue ShOp = N0->getOperand(1);
2893 
2894       // Don't try to fold this node if it requires introducing a
2895       // build vector of all zeros that might be illegal at this stage.
2896       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2897         if (!LegalTypes)
2898           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2899         else
2900           ShOp = SDValue();
2901       }
2902 
2903       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2904       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2905       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2906       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2907         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2908                                       N0->getOperand(0), N1->getOperand(0));
2909         AddToWorklist(NewNode.getNode());
2910         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2911                                     SVN0->getMask());
2912       }
2913 
2914       // Don't try to fold this node if it requires introducing a
2915       // build vector of all zeros that might be illegal at this stage.
2916       ShOp = N0->getOperand(0);
2917       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2918         if (!LegalTypes)
2919           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2920         else
2921           ShOp = SDValue();
2922       }
2923 
2924       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2925       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2926       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2927       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2928         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2929                                       N0->getOperand(1), N1->getOperand(1));
2930         AddToWorklist(NewNode.getNode());
2931         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2932                                     SVN0->getMask());
2933       }
2934     }
2935   }
2936 
2937   return SDValue();
2938 }
2939 
2940 /// This contains all DAGCombine rules which reduce two values combined by
2941 /// an And operation to a single value. This makes them reusable in the context
2942 /// of visitSELECT(). Rules involving constants are not included as
2943 /// visitSELECT() already handles those cases.
2944 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2945                                   SDNode *LocReference) {
2946   EVT VT = N1.getValueType();
2947 
2948   // fold (and x, undef) -> 0
2949   if (N0.isUndef() || N1.isUndef())
2950     return DAG.getConstant(0, SDLoc(LocReference), VT);
2951   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2952   SDValue LL, LR, RL, RR, CC0, CC1;
2953   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2954     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2955     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2956 
2957     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2958         LL.getValueType().isInteger()) {
2959       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2960       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2961         EVT CCVT = getSetCCResultType(LR.getValueType());
2962         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2963           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2964                                        LR.getValueType(), LL, RL);
2965           AddToWorklist(ORNode.getNode());
2966           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2967         }
2968       }
2969       if (isAllOnesConstant(LR)) {
2970         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2971         if (Op1 == ISD::SETEQ) {
2972           EVT CCVT = getSetCCResultType(LR.getValueType());
2973           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2974             SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2975                                           LR.getValueType(), LL, RL);
2976             AddToWorklist(ANDNode.getNode());
2977             return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2978           }
2979         }
2980         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2981         if (Op1 == ISD::SETGT) {
2982           EVT CCVT = getSetCCResultType(LR.getValueType());
2983           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2984             SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2985                                          LR.getValueType(), LL, RL);
2986             AddToWorklist(ORNode.getNode());
2987             return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2988           }
2989         }
2990       }
2991     }
2992     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2993     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2994         Op0 == Op1 && LL.getValueType().isInteger() &&
2995       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2996                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2997       EVT CCVT = getSetCCResultType(LL.getValueType());
2998       if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2999         SDLoc DL(N0);
3000         SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
3001                                       LL, DAG.getConstant(1, DL,
3002                                                           LL.getValueType()));
3003         AddToWorklist(ADDNode.getNode());
3004         return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
3005                             DAG.getConstant(2, DL, LL.getValueType()),
3006                             ISD::SETUGE);
3007       }
3008     }
3009     // canonicalize equivalent to ll == rl
3010     if (LL == RR && LR == RL) {
3011       Op1 = ISD::getSetCCSwappedOperands(Op1);
3012       std::swap(RL, RR);
3013     }
3014     if (LL == RL && LR == RR) {
3015       bool isInteger = LL.getValueType().isInteger();
3016       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
3017       if (Result != ISD::SETCC_INVALID &&
3018           (!LegalOperations ||
3019            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3020             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3021         EVT CCVT = getSetCCResultType(LL.getValueType());
3022         if (N0.getValueType() == CCVT ||
3023             (!LegalOperations && N0.getValueType() == MVT::i1))
3024           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3025                               LL, LR, Result);
3026       }
3027     }
3028   }
3029 
3030   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3031       VT.getSizeInBits() <= 64) {
3032     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3033       APInt ADDC = ADDI->getAPIntValue();
3034       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3035         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3036         // immediate for an add, but it is legal if its top c2 bits are set,
3037         // transform the ADD so the immediate doesn't need to be materialized
3038         // in a register.
3039         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3040           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3041                                              SRLI->getZExtValue());
3042           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3043             ADDC |= Mask;
3044             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3045               SDLoc DL(N0);
3046               SDValue NewAdd =
3047                 DAG.getNode(ISD::ADD, DL, VT,
3048                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3049               CombineTo(N0.getNode(), NewAdd);
3050               // Return N so it doesn't get rechecked!
3051               return SDValue(LocReference, 0);
3052             }
3053           }
3054         }
3055       }
3056     }
3057   }
3058 
3059   // Reduce bit extract of low half of an integer to the narrower type.
3060   // (and (srl i64:x, K), KMask) ->
3061   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3062   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3063     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3064       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3065         unsigned Size = VT.getSizeInBits();
3066         const APInt &AndMask = CAnd->getAPIntValue();
3067         unsigned ShiftBits = CShift->getZExtValue();
3068         unsigned MaskBits = AndMask.countTrailingOnes();
3069         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3070 
3071         if (APIntOps::isMask(AndMask) &&
3072             // Required bits must not span the two halves of the integer and
3073             // must fit in the half size type.
3074             (ShiftBits + MaskBits <= Size / 2) &&
3075             TLI.isNarrowingProfitable(VT, HalfVT) &&
3076             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3077             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3078             TLI.isTruncateFree(VT, HalfVT) &&
3079             TLI.isZExtFree(HalfVT, VT)) {
3080           // The isNarrowingProfitable is to avoid regressions on PPC and
3081           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3082           // on downstream users of this. Those patterns could probably be
3083           // extended to handle extensions mixed in.
3084 
3085           SDValue SL(N0);
3086           assert(ShiftBits != 0 && MaskBits <= Size);
3087 
3088           // Extracting the highest bit of the low half.
3089           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3090           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3091                                       N0.getOperand(0));
3092 
3093           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3094           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3095           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3096           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3097           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3098         }
3099       }
3100     }
3101   }
3102 
3103   return SDValue();
3104 }
3105 
3106 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3107                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3108                                    bool &NarrowLoad) {
3109   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3110 
3111   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3112     return false;
3113 
3114   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3115   LoadedVT = LoadN->getMemoryVT();
3116 
3117   if (ExtVT == LoadedVT &&
3118       (!LegalOperations ||
3119        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3120     // ZEXTLOAD will match without needing to change the size of the value being
3121     // loaded.
3122     NarrowLoad = false;
3123     return true;
3124   }
3125 
3126   // Do not change the width of a volatile load.
3127   if (LoadN->isVolatile())
3128     return false;
3129 
3130   // Do not generate loads of non-round integer types since these can
3131   // be expensive (and would be wrong if the type is not byte sized).
3132   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3133     return false;
3134 
3135   if (LegalOperations &&
3136       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3137     return false;
3138 
3139   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3140     return false;
3141 
3142   NarrowLoad = true;
3143   return true;
3144 }
3145 
3146 SDValue DAGCombiner::visitAND(SDNode *N) {
3147   SDValue N0 = N->getOperand(0);
3148   SDValue N1 = N->getOperand(1);
3149   EVT VT = N1.getValueType();
3150 
3151   // fold vector ops
3152   if (VT.isVector()) {
3153     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3154       return FoldedVOp;
3155 
3156     // fold (and x, 0) -> 0, vector edition
3157     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3158       // do not return N0, because undef node may exist in N0
3159       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3160                              SDLoc(N), N0.getValueType());
3161     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3162       // do not return N1, because undef node may exist in N1
3163       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3164                              SDLoc(N), N1.getValueType());
3165 
3166     // fold (and x, -1) -> x, vector edition
3167     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3168       return N1;
3169     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3170       return N0;
3171   }
3172 
3173   // fold (and c1, c2) -> c1&c2
3174   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3175   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3176   if (N0C && N1C && !N1C->isOpaque())
3177     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3178   // canonicalize constant to RHS
3179   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3180      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3181     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3182   // fold (and x, -1) -> x
3183   if (isAllOnesConstant(N1))
3184     return N0;
3185   // if (and x, c) is known to be zero, return 0
3186   unsigned BitWidth = VT.getScalarSizeInBits();
3187   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3188                                    APInt::getAllOnesValue(BitWidth)))
3189     return DAG.getConstant(0, SDLoc(N), VT);
3190   // reassociate and
3191   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3192     return RAND;
3193   // fold (and (or x, C), D) -> D if (C & D) == D
3194   if (N1C && N0.getOpcode() == ISD::OR)
3195     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3196       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3197         return N1;
3198   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3199   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3200     SDValue N0Op0 = N0.getOperand(0);
3201     APInt Mask = ~N1C->getAPIntValue();
3202     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3203     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3204       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3205                                  N0.getValueType(), N0Op0);
3206 
3207       // Replace uses of the AND with uses of the Zero extend node.
3208       CombineTo(N, Zext);
3209 
3210       // We actually want to replace all uses of the any_extend with the
3211       // zero_extend, to avoid duplicating things.  This will later cause this
3212       // AND to be folded.
3213       CombineTo(N0.getNode(), Zext);
3214       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3215     }
3216   }
3217   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3218   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3219   // already be zero by virtue of the width of the base type of the load.
3220   //
3221   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3222   // more cases.
3223   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3224        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3225        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3226        N0.getOperand(0).getResNo() == 0) ||
3227       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3228     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3229                                          N0 : N0.getOperand(0) );
3230 
3231     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3232     // This can be a pure constant or a vector splat, in which case we treat the
3233     // vector as a scalar and use the splat value.
3234     APInt Constant = APInt::getNullValue(1);
3235     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3236       Constant = C->getAPIntValue();
3237     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3238       APInt SplatValue, SplatUndef;
3239       unsigned SplatBitSize;
3240       bool HasAnyUndefs;
3241       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3242                                              SplatBitSize, HasAnyUndefs);
3243       if (IsSplat) {
3244         // Undef bits can contribute to a possible optimisation if set, so
3245         // set them.
3246         SplatValue |= SplatUndef;
3247 
3248         // The splat value may be something like "0x00FFFFFF", which means 0 for
3249         // the first vector value and FF for the rest, repeating. We need a mask
3250         // that will apply equally to all members of the vector, so AND all the
3251         // lanes of the constant together.
3252         EVT VT = Vector->getValueType(0);
3253         unsigned BitWidth = VT.getScalarSizeInBits();
3254 
3255         // If the splat value has been compressed to a bitlength lower
3256         // than the size of the vector lane, we need to re-expand it to
3257         // the lane size.
3258         if (BitWidth > SplatBitSize)
3259           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3260                SplatBitSize < BitWidth;
3261                SplatBitSize = SplatBitSize * 2)
3262             SplatValue |= SplatValue.shl(SplatBitSize);
3263 
3264         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3265         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3266         if (SplatBitSize % BitWidth == 0) {
3267           Constant = APInt::getAllOnesValue(BitWidth);
3268           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3269             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3270         }
3271       }
3272     }
3273 
3274     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3275     // actually legal and isn't going to get expanded, else this is a false
3276     // optimisation.
3277     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3278                                                     Load->getValueType(0),
3279                                                     Load->getMemoryVT());
3280 
3281     // Resize the constant to the same size as the original memory access before
3282     // extension. If it is still the AllOnesValue then this AND is completely
3283     // unneeded.
3284     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3285 
3286     bool B;
3287     switch (Load->getExtensionType()) {
3288     default: B = false; break;
3289     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3290     case ISD::ZEXTLOAD:
3291     case ISD::NON_EXTLOAD: B = true; break;
3292     }
3293 
3294     if (B && Constant.isAllOnesValue()) {
3295       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3296       // preserve semantics once we get rid of the AND.
3297       SDValue NewLoad(Load, 0);
3298       if (Load->getExtensionType() == ISD::EXTLOAD) {
3299         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3300                               Load->getValueType(0), SDLoc(Load),
3301                               Load->getChain(), Load->getBasePtr(),
3302                               Load->getOffset(), Load->getMemoryVT(),
3303                               Load->getMemOperand());
3304         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3305         if (Load->getNumValues() == 3) {
3306           // PRE/POST_INC loads have 3 values.
3307           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3308                            NewLoad.getValue(2) };
3309           CombineTo(Load, To, 3, true);
3310         } else {
3311           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3312         }
3313       }
3314 
3315       // Fold the AND away, taking care not to fold to the old load node if we
3316       // replaced it.
3317       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3318 
3319       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3320     }
3321   }
3322 
3323   // fold (and (load x), 255) -> (zextload x, i8)
3324   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3325   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3326   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3327                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3328                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3329     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3330     LoadSDNode *LN0 = HasAnyExt
3331       ? cast<LoadSDNode>(N0.getOperand(0))
3332       : cast<LoadSDNode>(N0);
3333     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3334         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3335       auto NarrowLoad = false;
3336       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3337       EVT ExtVT, LoadedVT;
3338       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3339                            NarrowLoad)) {
3340         if (!NarrowLoad) {
3341           SDValue NewLoad =
3342             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3343                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3344                            LN0->getMemOperand());
3345           AddToWorklist(N);
3346           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3347           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3348         } else {
3349           EVT PtrType = LN0->getOperand(1).getValueType();
3350 
3351           unsigned Alignment = LN0->getAlignment();
3352           SDValue NewPtr = LN0->getBasePtr();
3353 
3354           // For big endian targets, we need to add an offset to the pointer
3355           // to load the correct bytes.  For little endian systems, we merely
3356           // need to read fewer bytes from the same pointer.
3357           if (DAG.getDataLayout().isBigEndian()) {
3358             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3359             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3360             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3361             SDLoc DL(LN0);
3362             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3363                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3364             Alignment = MinAlign(Alignment, PtrOff);
3365           }
3366 
3367           AddToWorklist(NewPtr.getNode());
3368 
3369           SDValue Load = DAG.getExtLoad(
3370               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3371               LN0->getPointerInfo(), ExtVT, Alignment,
3372               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3373           AddToWorklist(N);
3374           CombineTo(LN0, Load, Load.getValue(1));
3375           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3376         }
3377       }
3378     }
3379   }
3380 
3381   if (SDValue Combined = visitANDLike(N0, N1, N))
3382     return Combined;
3383 
3384   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3385   if (N0.getOpcode() == N1.getOpcode())
3386     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3387       return Tmp;
3388 
3389   // Masking the negated extension of a boolean is just the zero-extended
3390   // boolean:
3391   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3392   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3393   //
3394   // Note: the SimplifyDemandedBits fold below can make an information-losing
3395   // transform, and then we have no way to find this better fold.
3396   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3397     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3398     SDValue SubRHS = N0.getOperand(1);
3399     if (SubLHS && SubLHS->isNullValue()) {
3400       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3401           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3402         return SubRHS;
3403       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3404           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3405         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3406     }
3407   }
3408 
3409   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3410   // fold (and (sra)) -> (and (srl)) when possible.
3411   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
3412     return SDValue(N, 0);
3413 
3414   // fold (zext_inreg (extload x)) -> (zextload x)
3415   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3416     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3417     EVT MemVT = LN0->getMemoryVT();
3418     // If we zero all the possible extended bits, then we can turn this into
3419     // a zextload if we are running before legalize or the operation is legal.
3420     unsigned BitWidth = N1.getScalarValueSizeInBits();
3421     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3422                            BitWidth - MemVT.getScalarSizeInBits())) &&
3423         ((!LegalOperations && !LN0->isVolatile()) ||
3424          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3425       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3426                                        LN0->getChain(), LN0->getBasePtr(),
3427                                        MemVT, LN0->getMemOperand());
3428       AddToWorklist(N);
3429       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3430       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3431     }
3432   }
3433   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3434   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3435       N0.hasOneUse()) {
3436     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3437     EVT MemVT = LN0->getMemoryVT();
3438     // If we zero all the possible extended bits, then we can turn this into
3439     // a zextload if we are running before legalize or the operation is legal.
3440     unsigned BitWidth = N1.getScalarValueSizeInBits();
3441     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3442                            BitWidth - MemVT.getScalarSizeInBits())) &&
3443         ((!LegalOperations && !LN0->isVolatile()) ||
3444          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3445       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3446                                        LN0->getChain(), LN0->getBasePtr(),
3447                                        MemVT, LN0->getMemOperand());
3448       AddToWorklist(N);
3449       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3450       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3451     }
3452   }
3453   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3454   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3455     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3456                                            N0.getOperand(1), false))
3457       return BSwap;
3458   }
3459 
3460   return SDValue();
3461 }
3462 
3463 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3464 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3465                                         bool DemandHighBits) {
3466   if (!LegalOperations)
3467     return SDValue();
3468 
3469   EVT VT = N->getValueType(0);
3470   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3471     return SDValue();
3472   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3473     return SDValue();
3474 
3475   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3476   bool LookPassAnd0 = false;
3477   bool LookPassAnd1 = false;
3478   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3479       std::swap(N0, N1);
3480   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3481       std::swap(N0, N1);
3482   if (N0.getOpcode() == ISD::AND) {
3483     if (!N0.getNode()->hasOneUse())
3484       return SDValue();
3485     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3486     if (!N01C || N01C->getZExtValue() != 0xFF00)
3487       return SDValue();
3488     N0 = N0.getOperand(0);
3489     LookPassAnd0 = true;
3490   }
3491 
3492   if (N1.getOpcode() == ISD::AND) {
3493     if (!N1.getNode()->hasOneUse())
3494       return SDValue();
3495     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3496     if (!N11C || N11C->getZExtValue() != 0xFF)
3497       return SDValue();
3498     N1 = N1.getOperand(0);
3499     LookPassAnd1 = true;
3500   }
3501 
3502   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3503     std::swap(N0, N1);
3504   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3505     return SDValue();
3506   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3507     return SDValue();
3508 
3509   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3510   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3511   if (!N01C || !N11C)
3512     return SDValue();
3513   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3514     return SDValue();
3515 
3516   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3517   SDValue N00 = N0->getOperand(0);
3518   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3519     if (!N00.getNode()->hasOneUse())
3520       return SDValue();
3521     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3522     if (!N001C || N001C->getZExtValue() != 0xFF)
3523       return SDValue();
3524     N00 = N00.getOperand(0);
3525     LookPassAnd0 = true;
3526   }
3527 
3528   SDValue N10 = N1->getOperand(0);
3529   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3530     if (!N10.getNode()->hasOneUse())
3531       return SDValue();
3532     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3533     if (!N101C || N101C->getZExtValue() != 0xFF00)
3534       return SDValue();
3535     N10 = N10.getOperand(0);
3536     LookPassAnd1 = true;
3537   }
3538 
3539   if (N00 != N10)
3540     return SDValue();
3541 
3542   // Make sure everything beyond the low halfword gets set to zero since the SRL
3543   // 16 will clear the top bits.
3544   unsigned OpSizeInBits = VT.getSizeInBits();
3545   if (DemandHighBits && OpSizeInBits > 16) {
3546     // If the left-shift isn't masked out then the only way this is a bswap is
3547     // if all bits beyond the low 8 are 0. In that case the entire pattern
3548     // reduces to a left shift anyway: leave it for other parts of the combiner.
3549     if (!LookPassAnd0)
3550       return SDValue();
3551 
3552     // However, if the right shift isn't masked out then it might be because
3553     // it's not needed. See if we can spot that too.
3554     if (!LookPassAnd1 &&
3555         !DAG.MaskedValueIsZero(
3556             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3557       return SDValue();
3558   }
3559 
3560   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3561   if (OpSizeInBits > 16) {
3562     SDLoc DL(N);
3563     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3564                       DAG.getConstant(OpSizeInBits - 16, DL,
3565                                       getShiftAmountTy(VT)));
3566   }
3567   return Res;
3568 }
3569 
3570 /// Return true if the specified node is an element that makes up a 32-bit
3571 /// packed halfword byteswap.
3572 /// ((x & 0x000000ff) << 8) |
3573 /// ((x & 0x0000ff00) >> 8) |
3574 /// ((x & 0x00ff0000) << 8) |
3575 /// ((x & 0xff000000) >> 8)
3576 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3577   if (!N.getNode()->hasOneUse())
3578     return false;
3579 
3580   unsigned Opc = N.getOpcode();
3581   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3582     return false;
3583 
3584   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3585   if (!N1C)
3586     return false;
3587 
3588   unsigned Num;
3589   switch (N1C->getZExtValue()) {
3590   default:
3591     return false;
3592   case 0xFF:       Num = 0; break;
3593   case 0xFF00:     Num = 1; break;
3594   case 0xFF0000:   Num = 2; break;
3595   case 0xFF000000: Num = 3; break;
3596   }
3597 
3598   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3599   SDValue N0 = N.getOperand(0);
3600   if (Opc == ISD::AND) {
3601     if (Num == 0 || Num == 2) {
3602       // (x >> 8) & 0xff
3603       // (x >> 8) & 0xff0000
3604       if (N0.getOpcode() != ISD::SRL)
3605         return false;
3606       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3607       if (!C || C->getZExtValue() != 8)
3608         return false;
3609     } else {
3610       // (x << 8) & 0xff00
3611       // (x << 8) & 0xff000000
3612       if (N0.getOpcode() != ISD::SHL)
3613         return false;
3614       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3615       if (!C || C->getZExtValue() != 8)
3616         return false;
3617     }
3618   } else if (Opc == ISD::SHL) {
3619     // (x & 0xff) << 8
3620     // (x & 0xff0000) << 8
3621     if (Num != 0 && Num != 2)
3622       return false;
3623     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3624     if (!C || C->getZExtValue() != 8)
3625       return false;
3626   } else { // Opc == ISD::SRL
3627     // (x & 0xff00) >> 8
3628     // (x & 0xff000000) >> 8
3629     if (Num != 1 && Num != 3)
3630       return false;
3631     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3632     if (!C || C->getZExtValue() != 8)
3633       return false;
3634   }
3635 
3636   if (Parts[Num])
3637     return false;
3638 
3639   Parts[Num] = N0.getOperand(0).getNode();
3640   return true;
3641 }
3642 
3643 /// Match a 32-bit packed halfword bswap. That is
3644 /// ((x & 0x000000ff) << 8) |
3645 /// ((x & 0x0000ff00) >> 8) |
3646 /// ((x & 0x00ff0000) << 8) |
3647 /// ((x & 0xff000000) >> 8)
3648 /// => (rotl (bswap x), 16)
3649 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3650   if (!LegalOperations)
3651     return SDValue();
3652 
3653   EVT VT = N->getValueType(0);
3654   if (VT != MVT::i32)
3655     return SDValue();
3656   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3657     return SDValue();
3658 
3659   // Look for either
3660   // (or (or (and), (and)), (or (and), (and)))
3661   // (or (or (or (and), (and)), (and)), (and))
3662   if (N0.getOpcode() != ISD::OR)
3663     return SDValue();
3664   SDValue N00 = N0.getOperand(0);
3665   SDValue N01 = N0.getOperand(1);
3666   SDNode *Parts[4] = {};
3667 
3668   if (N1.getOpcode() == ISD::OR &&
3669       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3670     // (or (or (and), (and)), (or (and), (and)))
3671     SDValue N000 = N00.getOperand(0);
3672     if (!isBSwapHWordElement(N000, Parts))
3673       return SDValue();
3674 
3675     SDValue N001 = N00.getOperand(1);
3676     if (!isBSwapHWordElement(N001, Parts))
3677       return SDValue();
3678     SDValue N010 = N01.getOperand(0);
3679     if (!isBSwapHWordElement(N010, Parts))
3680       return SDValue();
3681     SDValue N011 = N01.getOperand(1);
3682     if (!isBSwapHWordElement(N011, Parts))
3683       return SDValue();
3684   } else {
3685     // (or (or (or (and), (and)), (and)), (and))
3686     if (!isBSwapHWordElement(N1, Parts))
3687       return SDValue();
3688     if (!isBSwapHWordElement(N01, Parts))
3689       return SDValue();
3690     if (N00.getOpcode() != ISD::OR)
3691       return SDValue();
3692     SDValue N000 = N00.getOperand(0);
3693     if (!isBSwapHWordElement(N000, Parts))
3694       return SDValue();
3695     SDValue N001 = N00.getOperand(1);
3696     if (!isBSwapHWordElement(N001, Parts))
3697       return SDValue();
3698   }
3699 
3700   // Make sure the parts are all coming from the same node.
3701   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3702     return SDValue();
3703 
3704   SDLoc DL(N);
3705   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3706                               SDValue(Parts[0], 0));
3707 
3708   // Result of the bswap should be rotated by 16. If it's not legal, then
3709   // do  (x << 16) | (x >> 16).
3710   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3711   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3712     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3713   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3714     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3715   return DAG.getNode(ISD::OR, DL, VT,
3716                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3717                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3718 }
3719 
3720 /// This contains all DAGCombine rules which reduce two values combined by
3721 /// an Or operation to a single value \see visitANDLike().
3722 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3723   EVT VT = N1.getValueType();
3724   // fold (or x, undef) -> -1
3725   if (!LegalOperations &&
3726       (N0.isUndef() || N1.isUndef())) {
3727     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3728     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3729                            SDLoc(LocReference), VT);
3730   }
3731   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3732   SDValue LL, LR, RL, RR, CC0, CC1;
3733   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3734     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3735     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3736 
3737     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3738       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3739       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3740       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3741         EVT CCVT = getSetCCResultType(LR.getValueType());
3742         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3743           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3744                                        LR.getValueType(), LL, RL);
3745           AddToWorklist(ORNode.getNode());
3746           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3747         }
3748       }
3749       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3750       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3751       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3752         EVT CCVT = getSetCCResultType(LR.getValueType());
3753         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3754           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3755                                         LR.getValueType(), LL, RL);
3756           AddToWorklist(ANDNode.getNode());
3757           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3758         }
3759       }
3760     }
3761     // canonicalize equivalent to ll == rl
3762     if (LL == RR && LR == RL) {
3763       Op1 = ISD::getSetCCSwappedOperands(Op1);
3764       std::swap(RL, RR);
3765     }
3766     if (LL == RL && LR == RR) {
3767       bool isInteger = LL.getValueType().isInteger();
3768       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3769       if (Result != ISD::SETCC_INVALID &&
3770           (!LegalOperations ||
3771            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3772             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3773         EVT CCVT = getSetCCResultType(LL.getValueType());
3774         if (N0.getValueType() == CCVT ||
3775             (!LegalOperations && N0.getValueType() == MVT::i1))
3776           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3777                               LL, LR, Result);
3778       }
3779     }
3780   }
3781 
3782   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3783   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3784       // Don't increase # computations.
3785       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3786     // We can only do this xform if we know that bits from X that are set in C2
3787     // but not in C1 are already zero.  Likewise for Y.
3788     if (const ConstantSDNode *N0O1C =
3789         getAsNonOpaqueConstant(N0.getOperand(1))) {
3790       if (const ConstantSDNode *N1O1C =
3791           getAsNonOpaqueConstant(N1.getOperand(1))) {
3792         // We can only do this xform if we know that bits from X that are set in
3793         // C2 but not in C1 are already zero.  Likewise for Y.
3794         const APInt &LHSMask = N0O1C->getAPIntValue();
3795         const APInt &RHSMask = N1O1C->getAPIntValue();
3796 
3797         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3798             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3799           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3800                                   N0.getOperand(0), N1.getOperand(0));
3801           SDLoc DL(LocReference);
3802           return DAG.getNode(ISD::AND, DL, VT, X,
3803                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3804         }
3805       }
3806     }
3807   }
3808 
3809   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3810   if (N0.getOpcode() == ISD::AND &&
3811       N1.getOpcode() == ISD::AND &&
3812       N0.getOperand(0) == N1.getOperand(0) &&
3813       // Don't increase # computations.
3814       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3815     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3816                             N0.getOperand(1), N1.getOperand(1));
3817     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3818   }
3819 
3820   return SDValue();
3821 }
3822 
3823 SDValue DAGCombiner::visitOR(SDNode *N) {
3824   SDValue N0 = N->getOperand(0);
3825   SDValue N1 = N->getOperand(1);
3826   EVT VT = N1.getValueType();
3827 
3828   // fold vector ops
3829   if (VT.isVector()) {
3830     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3831       return FoldedVOp;
3832 
3833     // fold (or x, 0) -> x, vector edition
3834     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3835       return N1;
3836     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3837       return N0;
3838 
3839     // fold (or x, -1) -> -1, vector edition
3840     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3841       // do not return N0, because undef node may exist in N0
3842       return DAG.getConstant(
3843           APInt::getAllOnesValue(N0.getScalarValueSizeInBits()), SDLoc(N),
3844           N0.getValueType());
3845     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3846       // do not return N1, because undef node may exist in N1
3847       return DAG.getConstant(
3848           APInt::getAllOnesValue(N1.getScalarValueSizeInBits()), SDLoc(N),
3849           N1.getValueType());
3850 
3851     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
3852     // Do this only if the resulting shuffle is legal.
3853     if (isa<ShuffleVectorSDNode>(N0) &&
3854         isa<ShuffleVectorSDNode>(N1) &&
3855         // Avoid folding a node with illegal type.
3856         TLI.isTypeLegal(VT)) {
3857       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
3858       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
3859       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
3860       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
3861       // Ensure both shuffles have a zero input.
3862       if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) {
3863         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
3864         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
3865         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3866         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3867         bool CanFold = true;
3868         int NumElts = VT.getVectorNumElements();
3869         SmallVector<int, 4> Mask(NumElts);
3870 
3871         for (int i = 0; i != NumElts; ++i) {
3872           int M0 = SV0->getMaskElt(i);
3873           int M1 = SV1->getMaskElt(i);
3874 
3875           // Determine if either index is pointing to a zero vector.
3876           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
3877           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
3878 
3879           // If one element is zero and the otherside is undef, keep undef.
3880           // This also handles the case that both are undef.
3881           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
3882             Mask[i] = -1;
3883             continue;
3884           }
3885 
3886           // Make sure only one of the elements is zero.
3887           if (M0Zero == M1Zero) {
3888             CanFold = false;
3889             break;
3890           }
3891 
3892           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
3893 
3894           // We have a zero and non-zero element. If the non-zero came from
3895           // SV0 make the index a LHS index. If it came from SV1, make it
3896           // a RHS index. We need to mod by NumElts because we don't care
3897           // which operand it came from in the original shuffles.
3898           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
3899         }
3900 
3901         if (CanFold) {
3902           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
3903           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
3904 
3905           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3906           if (!LegalMask) {
3907             std::swap(NewLHS, NewRHS);
3908             ShuffleVectorSDNode::commuteMask(Mask);
3909             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3910           }
3911 
3912           if (LegalMask)
3913             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
3914         }
3915       }
3916     }
3917   }
3918 
3919   // fold (or c1, c2) -> c1|c2
3920   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3921   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3922   if (N0C && N1C && !N1C->isOpaque())
3923     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3924   // canonicalize constant to RHS
3925   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3926      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3927     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3928   // fold (or x, 0) -> x
3929   if (isNullConstant(N1))
3930     return N0;
3931   // fold (or x, -1) -> -1
3932   if (isAllOnesConstant(N1))
3933     return N1;
3934   // fold (or x, c) -> c iff (x & ~c) == 0
3935   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3936     return N1;
3937 
3938   if (SDValue Combined = visitORLike(N0, N1, N))
3939     return Combined;
3940 
3941   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3942   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3943     return BSwap;
3944   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3945     return BSwap;
3946 
3947   // reassociate or
3948   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3949     return ROR;
3950   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3951   // iff (c1 & c2) == 0.
3952   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3953              isa<ConstantSDNode>(N0.getOperand(1))) {
3954     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3955     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3956       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3957                                                    N1C, C1))
3958         return DAG.getNode(
3959             ISD::AND, SDLoc(N), VT,
3960             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3961       return SDValue();
3962     }
3963   }
3964   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3965   if (N0.getOpcode() == N1.getOpcode())
3966     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3967       return Tmp;
3968 
3969   // See if this is some rotate idiom.
3970   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3971     return SDValue(Rot, 0);
3972 
3973   // Simplify the operands using demanded-bits information.
3974   if (!VT.isVector() &&
3975       SimplifyDemandedBits(SDValue(N, 0)))
3976     return SDValue(N, 0);
3977 
3978   return SDValue();
3979 }
3980 
3981 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3982 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3983   if (Op.getOpcode() == ISD::AND) {
3984     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3985       Mask = Op.getOperand(1);
3986       Op = Op.getOperand(0);
3987     } else {
3988       return false;
3989     }
3990   }
3991 
3992   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3993     Shift = Op;
3994     return true;
3995   }
3996 
3997   return false;
3998 }
3999 
4000 // Return true if we can prove that, whenever Neg and Pos are both in the
4001 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4002 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4003 //
4004 //     (or (shift1 X, Neg), (shift2 X, Pos))
4005 //
4006 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4007 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4008 // to consider shift amounts with defined behavior.
4009 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4010   // If EltSize is a power of 2 then:
4011   //
4012   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4013   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4014   //
4015   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4016   // for the stronger condition:
4017   //
4018   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4019   //
4020   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4021   // we can just replace Neg with Neg' for the rest of the function.
4022   //
4023   // In other cases we check for the even stronger condition:
4024   //
4025   //     Neg == EltSize - Pos                                    [B]
4026   //
4027   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4028   // behavior if Pos == 0 (and consequently Neg == EltSize).
4029   //
4030   // We could actually use [A] whenever EltSize is a power of 2, but the
4031   // only extra cases that it would match are those uninteresting ones
4032   // where Neg and Pos are never in range at the same time.  E.g. for
4033   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4034   // as well as (sub 32, Pos), but:
4035   //
4036   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4037   //
4038   // always invokes undefined behavior for 32-bit X.
4039   //
4040   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4041   unsigned MaskLoBits = 0;
4042   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4043     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4044       if (NegC->getAPIntValue() == EltSize - 1) {
4045         Neg = Neg.getOperand(0);
4046         MaskLoBits = Log2_64(EltSize);
4047       }
4048     }
4049   }
4050 
4051   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4052   if (Neg.getOpcode() != ISD::SUB)
4053     return false;
4054   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4055   if (!NegC)
4056     return false;
4057   SDValue NegOp1 = Neg.getOperand(1);
4058 
4059   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4060   // Pos'.  The truncation is redundant for the purpose of the equality.
4061   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4062     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4063       if (PosC->getAPIntValue() == EltSize - 1)
4064         Pos = Pos.getOperand(0);
4065 
4066   // The condition we need is now:
4067   //
4068   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4069   //
4070   // If NegOp1 == Pos then we need:
4071   //
4072   //              EltSize & Mask == NegC & Mask
4073   //
4074   // (because "x & Mask" is a truncation and distributes through subtraction).
4075   APInt Width;
4076   if (Pos == NegOp1)
4077     Width = NegC->getAPIntValue();
4078 
4079   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4080   // Then the condition we want to prove becomes:
4081   //
4082   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4083   //
4084   // which, again because "x & Mask" is a truncation, becomes:
4085   //
4086   //                NegC & Mask == (EltSize - PosC) & Mask
4087   //             EltSize & Mask == (NegC + PosC) & Mask
4088   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4089     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4090       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4091     else
4092       return false;
4093   } else
4094     return false;
4095 
4096   // Now we just need to check that EltSize & Mask == Width & Mask.
4097   if (MaskLoBits)
4098     // EltSize & Mask is 0 since Mask is EltSize - 1.
4099     return Width.getLoBits(MaskLoBits) == 0;
4100   return Width == EltSize;
4101 }
4102 
4103 // A subroutine of MatchRotate used once we have found an OR of two opposite
4104 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4105 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4106 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4107 // Neg with outer conversions stripped away.
4108 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4109                                        SDValue Neg, SDValue InnerPos,
4110                                        SDValue InnerNeg, unsigned PosOpcode,
4111                                        unsigned NegOpcode, const SDLoc &DL) {
4112   // fold (or (shl x, (*ext y)),
4113   //          (srl x, (*ext (sub 32, y)))) ->
4114   //   (rotl x, y) or (rotr x, (sub 32, y))
4115   //
4116   // fold (or (shl x, (*ext (sub 32, y))),
4117   //          (srl x, (*ext y))) ->
4118   //   (rotr x, y) or (rotl x, (sub 32, y))
4119   EVT VT = Shifted.getValueType();
4120   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4121     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4122     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4123                        HasPos ? Pos : Neg).getNode();
4124   }
4125 
4126   return nullptr;
4127 }
4128 
4129 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4130 // idioms for rotate, and if the target supports rotation instructions, generate
4131 // a rot[lr].
4132 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4133   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4134   EVT VT = LHS.getValueType();
4135   if (!TLI.isTypeLegal(VT)) return nullptr;
4136 
4137   // The target must have at least one rotate flavor.
4138   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4139   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4140   if (!HasROTL && !HasROTR) return nullptr;
4141 
4142   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4143   SDValue LHSShift;   // The shift.
4144   SDValue LHSMask;    // AND value if any.
4145   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4146     return nullptr; // Not part of a rotate.
4147 
4148   SDValue RHSShift;   // The shift.
4149   SDValue RHSMask;    // AND value if any.
4150   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4151     return nullptr; // Not part of a rotate.
4152 
4153   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4154     return nullptr;   // Not shifting the same value.
4155 
4156   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4157     return nullptr;   // Shifts must disagree.
4158 
4159   // Canonicalize shl to left side in a shl/srl pair.
4160   if (RHSShift.getOpcode() == ISD::SHL) {
4161     std::swap(LHS, RHS);
4162     std::swap(LHSShift, RHSShift);
4163     std::swap(LHSMask, RHSMask);
4164   }
4165 
4166   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4167   SDValue LHSShiftArg = LHSShift.getOperand(0);
4168   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4169   SDValue RHSShiftArg = RHSShift.getOperand(0);
4170   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4171 
4172   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4173   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4174   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4175     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4176     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4177     if ((LShVal + RShVal) != EltSizeInBits)
4178       return nullptr;
4179 
4180     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4181                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4182 
4183     // If there is an AND of either shifted operand, apply it to the result.
4184     if (LHSMask.getNode() || RHSMask.getNode()) {
4185       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4186       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4187 
4188       if (LHSMask.getNode()) {
4189         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4190         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4191                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4192                                        DAG.getConstant(RHSBits, DL, VT)));
4193       }
4194       if (RHSMask.getNode()) {
4195         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4196         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4197                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4198                                        DAG.getConstant(LHSBits, DL, VT)));
4199       }
4200 
4201       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4202     }
4203 
4204     return Rot.getNode();
4205   }
4206 
4207   // If there is a mask here, and we have a variable shift, we can't be sure
4208   // that we're masking out the right stuff.
4209   if (LHSMask.getNode() || RHSMask.getNode())
4210     return nullptr;
4211 
4212   // If the shift amount is sign/zext/any-extended just peel it off.
4213   SDValue LExtOp0 = LHSShiftAmt;
4214   SDValue RExtOp0 = RHSShiftAmt;
4215   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4216        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4217        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4218        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4219       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4220        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4221        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4222        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4223     LExtOp0 = LHSShiftAmt.getOperand(0);
4224     RExtOp0 = RHSShiftAmt.getOperand(0);
4225   }
4226 
4227   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4228                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4229   if (TryL)
4230     return TryL;
4231 
4232   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4233                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4234   if (TryR)
4235     return TryR;
4236 
4237   return nullptr;
4238 }
4239 
4240 SDValue DAGCombiner::visitXOR(SDNode *N) {
4241   SDValue N0 = N->getOperand(0);
4242   SDValue N1 = N->getOperand(1);
4243   EVT VT = N0.getValueType();
4244 
4245   // fold vector ops
4246   if (VT.isVector()) {
4247     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4248       return FoldedVOp;
4249 
4250     // fold (xor x, 0) -> x, vector edition
4251     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4252       return N1;
4253     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4254       return N0;
4255   }
4256 
4257   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4258   if (N0.isUndef() && N1.isUndef())
4259     return DAG.getConstant(0, SDLoc(N), VT);
4260   // fold (xor x, undef) -> undef
4261   if (N0.isUndef())
4262     return N0;
4263   if (N1.isUndef())
4264     return N1;
4265   // fold (xor c1, c2) -> c1^c2
4266   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4267   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4268   if (N0C && N1C)
4269     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4270   // canonicalize constant to RHS
4271   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4272      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4273     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4274   // fold (xor x, 0) -> x
4275   if (isNullConstant(N1))
4276     return N0;
4277   // reassociate xor
4278   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4279     return RXOR;
4280 
4281   // fold !(x cc y) -> (x !cc y)
4282   SDValue LHS, RHS, CC;
4283   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4284     bool isInt = LHS.getValueType().isInteger();
4285     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4286                                                isInt);
4287 
4288     if (!LegalOperations ||
4289         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4290       switch (N0.getOpcode()) {
4291       default:
4292         llvm_unreachable("Unhandled SetCC Equivalent!");
4293       case ISD::SETCC:
4294         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4295       case ISD::SELECT_CC:
4296         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4297                                N0.getOperand(3), NotCC);
4298       }
4299     }
4300   }
4301 
4302   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4303   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4304       N0.getNode()->hasOneUse() &&
4305       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4306     SDValue V = N0.getOperand(0);
4307     SDLoc DL(N0);
4308     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4309                     DAG.getConstant(1, DL, V.getValueType()));
4310     AddToWorklist(V.getNode());
4311     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4312   }
4313 
4314   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4315   if (isOneConstant(N1) && VT == MVT::i1 &&
4316       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4317     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4318     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4319       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4320       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4321       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4322       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4323       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4324     }
4325   }
4326   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4327   if (isAllOnesConstant(N1) &&
4328       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4329     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4330     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4331       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4332       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4333       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4334       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4335       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4336     }
4337   }
4338   // fold (xor (and x, y), y) -> (and (not x), y)
4339   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4340       N0->getOperand(1) == N1) {
4341     SDValue X = N0->getOperand(0);
4342     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4343     AddToWorklist(NotX.getNode());
4344     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4345   }
4346   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4347   if (N1C && N0.getOpcode() == ISD::XOR) {
4348     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4349       SDLoc DL(N);
4350       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4351                          DAG.getConstant(N1C->getAPIntValue() ^
4352                                          N00C->getAPIntValue(), DL, VT));
4353     }
4354     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4355       SDLoc DL(N);
4356       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4357                          DAG.getConstant(N1C->getAPIntValue() ^
4358                                          N01C->getAPIntValue(), DL, VT));
4359     }
4360   }
4361   // fold (xor x, x) -> 0
4362   if (N0 == N1)
4363     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4364 
4365   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4366   // Here is a concrete example of this equivalence:
4367   // i16   x ==  14
4368   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4369   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4370   //
4371   // =>
4372   //
4373   // i16     ~1      == 0b1111111111111110
4374   // i16 rol(~1, 14) == 0b1011111111111111
4375   //
4376   // Some additional tips to help conceptualize this transform:
4377   // - Try to see the operation as placing a single zero in a value of all ones.
4378   // - There exists no value for x which would allow the result to contain zero.
4379   // - Values of x larger than the bitwidth are undefined and do not require a
4380   //   consistent result.
4381   // - Pushing the zero left requires shifting one bits in from the right.
4382   // A rotate left of ~1 is a nice way of achieving the desired result.
4383   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4384       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4385     SDLoc DL(N);
4386     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4387                        N0.getOperand(1));
4388   }
4389 
4390   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4391   if (N0.getOpcode() == N1.getOpcode())
4392     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4393       return Tmp;
4394 
4395   // Simplify the expression using non-local knowledge.
4396   if (!VT.isVector() &&
4397       SimplifyDemandedBits(SDValue(N, 0)))
4398     return SDValue(N, 0);
4399 
4400   return SDValue();
4401 }
4402 
4403 /// Handle transforms common to the three shifts, when the shift amount is a
4404 /// constant.
4405 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4406   SDNode *LHS = N->getOperand(0).getNode();
4407   if (!LHS->hasOneUse()) return SDValue();
4408 
4409   // We want to pull some binops through shifts, so that we have (and (shift))
4410   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4411   // thing happens with address calculations, so it's important to canonicalize
4412   // it.
4413   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4414 
4415   switch (LHS->getOpcode()) {
4416   default: return SDValue();
4417   case ISD::OR:
4418   case ISD::XOR:
4419     HighBitSet = false; // We can only transform sra if the high bit is clear.
4420     break;
4421   case ISD::AND:
4422     HighBitSet = true;  // We can only transform sra if the high bit is set.
4423     break;
4424   case ISD::ADD:
4425     if (N->getOpcode() != ISD::SHL)
4426       return SDValue(); // only shl(add) not sr[al](add).
4427     HighBitSet = false; // We can only transform sra if the high bit is clear.
4428     break;
4429   }
4430 
4431   // We require the RHS of the binop to be a constant and not opaque as well.
4432   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4433   if (!BinOpCst) return SDValue();
4434 
4435   // FIXME: disable this unless the input to the binop is a shift by a constant.
4436   // If it is not a shift, it pessimizes some common cases like:
4437   //
4438   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4439   //    int bar(int *X, int i) { return X[i & 255]; }
4440   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4441   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4442        BinOpLHSVal->getOpcode() != ISD::SRA &&
4443        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4444       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4445     return SDValue();
4446 
4447   EVT VT = N->getValueType(0);
4448 
4449   // If this is a signed shift right, and the high bit is modified by the
4450   // logical operation, do not perform the transformation. The highBitSet
4451   // boolean indicates the value of the high bit of the constant which would
4452   // cause it to be modified for this operation.
4453   if (N->getOpcode() == ISD::SRA) {
4454     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4455     if (BinOpRHSSignSet != HighBitSet)
4456       return SDValue();
4457   }
4458 
4459   if (!TLI.isDesirableToCommuteWithShift(LHS))
4460     return SDValue();
4461 
4462   // Fold the constants, shifting the binop RHS by the shift amount.
4463   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4464                                N->getValueType(0),
4465                                LHS->getOperand(1), N->getOperand(1));
4466   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4467 
4468   // Create the new shift.
4469   SDValue NewShift = DAG.getNode(N->getOpcode(),
4470                                  SDLoc(LHS->getOperand(0)),
4471                                  VT, LHS->getOperand(0), N->getOperand(1));
4472 
4473   // Create the new binop.
4474   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4475 }
4476 
4477 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4478   assert(N->getOpcode() == ISD::TRUNCATE);
4479   assert(N->getOperand(0).getOpcode() == ISD::AND);
4480 
4481   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4482   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4483     SDValue N01 = N->getOperand(0).getOperand(1);
4484 
4485     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4486       if (!N01C->isOpaque()) {
4487         EVT TruncVT = N->getValueType(0);
4488         SDValue N00 = N->getOperand(0).getOperand(0);
4489         APInt TruncC = N01C->getAPIntValue();
4490         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4491         SDLoc DL(N);
4492 
4493         return DAG.getNode(ISD::AND, DL, TruncVT,
4494                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4495                            DAG.getConstant(TruncC, DL, TruncVT));
4496       }
4497     }
4498   }
4499 
4500   return SDValue();
4501 }
4502 
4503 SDValue DAGCombiner::visitRotate(SDNode *N) {
4504   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4505   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4506       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4507     if (SDValue NewOp1 =
4508             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4509       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4510                          N->getOperand(0), NewOp1);
4511   }
4512   return SDValue();
4513 }
4514 
4515 SDValue DAGCombiner::visitSHL(SDNode *N) {
4516   SDValue N0 = N->getOperand(0);
4517   SDValue N1 = N->getOperand(1);
4518   EVT VT = N0.getValueType();
4519   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4520 
4521   // fold vector ops
4522   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4523   if (VT.isVector()) {
4524     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4525       return FoldedVOp;
4526 
4527     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4528     // If setcc produces all-one true value then:
4529     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4530     if (N1CV && N1CV->isConstant()) {
4531       if (N0.getOpcode() == ISD::AND) {
4532         SDValue N00 = N0->getOperand(0);
4533         SDValue N01 = N0->getOperand(1);
4534         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4535 
4536         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4537             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4538                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4539           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4540                                                      N01CV, N1CV))
4541             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4542         }
4543       } else {
4544         N1C = isConstOrConstSplat(N1);
4545       }
4546     }
4547   }
4548 
4549   // fold (shl c1, c2) -> c1<<c2
4550   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4551   if (N0C && N1C && !N1C->isOpaque())
4552     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4553   // fold (shl 0, x) -> 0
4554   if (isNullConstant(N0))
4555     return N0;
4556   // fold (shl x, c >= size(x)) -> undef
4557   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4558     return DAG.getUNDEF(VT);
4559   // fold (shl x, 0) -> x
4560   if (N1C && N1C->isNullValue())
4561     return N0;
4562   // fold (shl undef, x) -> 0
4563   if (N0.isUndef())
4564     return DAG.getConstant(0, SDLoc(N), VT);
4565   // if (shl x, c) is known to be zero, return 0
4566   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4567                             APInt::getAllOnesValue(OpSizeInBits)))
4568     return DAG.getConstant(0, SDLoc(N), VT);
4569   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4570   if (N1.getOpcode() == ISD::TRUNCATE &&
4571       N1.getOperand(0).getOpcode() == ISD::AND) {
4572     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4573       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4574   }
4575 
4576   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4577     return SDValue(N, 0);
4578 
4579   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4580   if (N1C && N0.getOpcode() == ISD::SHL) {
4581     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4582       SDLoc DL(N);
4583       APInt c1 = N0C1->getAPIntValue();
4584       APInt c2 = N1C->getAPIntValue();
4585       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4586 
4587       APInt Sum = c1 + c2;
4588       if (Sum.uge(OpSizeInBits))
4589         return DAG.getConstant(0, DL, VT);
4590 
4591       return DAG.getNode(
4592           ISD::SHL, DL, VT, N0.getOperand(0),
4593           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4594     }
4595   }
4596 
4597   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4598   // For this to be valid, the second form must not preserve any of the bits
4599   // that are shifted out by the inner shift in the first form.  This means
4600   // the outer shift size must be >= the number of bits added by the ext.
4601   // As a corollary, we don't care what kind of ext it is.
4602   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4603               N0.getOpcode() == ISD::ANY_EXTEND ||
4604               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4605       N0.getOperand(0).getOpcode() == ISD::SHL) {
4606     SDValue N0Op0 = N0.getOperand(0);
4607     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4608       APInt c1 = N0Op0C1->getAPIntValue();
4609       APInt c2 = N1C->getAPIntValue();
4610       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4611 
4612       EVT InnerShiftVT = N0Op0.getValueType();
4613       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4614       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
4615         SDLoc DL(N0);
4616         APInt Sum = c1 + c2;
4617         if (Sum.uge(OpSizeInBits))
4618           return DAG.getConstant(0, DL, VT);
4619 
4620         return DAG.getNode(
4621             ISD::SHL, DL, VT,
4622             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
4623             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4624       }
4625     }
4626   }
4627 
4628   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4629   // Only fold this if the inner zext has no other uses to avoid increasing
4630   // the total number of instructions.
4631   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4632       N0.getOperand(0).getOpcode() == ISD::SRL) {
4633     SDValue N0Op0 = N0.getOperand(0);
4634     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4635       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
4636         uint64_t c1 = N0Op0C1->getZExtValue();
4637         uint64_t c2 = N1C->getZExtValue();
4638         if (c1 == c2) {
4639           SDValue NewOp0 = N0.getOperand(0);
4640           EVT CountVT = NewOp0.getOperand(1).getValueType();
4641           SDLoc DL(N);
4642           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4643                                        NewOp0,
4644                                        DAG.getConstant(c2, DL, CountVT));
4645           AddToWorklist(NewSHL.getNode());
4646           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4647         }
4648       }
4649     }
4650   }
4651 
4652   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4653   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4654   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4655       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4656     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4657       uint64_t C1 = N0C1->getZExtValue();
4658       uint64_t C2 = N1C->getZExtValue();
4659       SDLoc DL(N);
4660       if (C1 <= C2)
4661         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4662                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4663       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4664                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4665     }
4666   }
4667 
4668   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4669   //                               (and (srl x, (sub c1, c2), MASK)
4670   // Only fold this if the inner shift has no other uses -- if it does, folding
4671   // this will increase the total number of instructions.
4672   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4673     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4674       uint64_t c1 = N0C1->getZExtValue();
4675       if (c1 < OpSizeInBits) {
4676         uint64_t c2 = N1C->getZExtValue();
4677         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4678         SDValue Shift;
4679         if (c2 > c1) {
4680           Mask = Mask.shl(c2 - c1);
4681           SDLoc DL(N);
4682           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4683                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4684         } else {
4685           Mask = Mask.lshr(c1 - c2);
4686           SDLoc DL(N);
4687           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4688                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4689         }
4690         SDLoc DL(N0);
4691         return DAG.getNode(ISD::AND, DL, VT, Shift,
4692                            DAG.getConstant(Mask, DL, VT));
4693       }
4694     }
4695   }
4696   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4697   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4698     unsigned BitSize = VT.getScalarSizeInBits();
4699     SDLoc DL(N);
4700     SDValue HiBitsMask =
4701       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4702                                             BitSize - N1C->getZExtValue()),
4703                       DL, VT);
4704     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4705                        HiBitsMask);
4706   }
4707 
4708   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4709   // Variant of version done on multiply, except mul by a power of 2 is turned
4710   // into a shift.
4711   APInt Val;
4712   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4713       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4714        ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4715     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4716     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4717     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4718   }
4719 
4720   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4721   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4722     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4723       if (SDValue Folded =
4724               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4725         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4726     }
4727   }
4728 
4729   if (N1C && !N1C->isOpaque())
4730     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4731       return NewSHL;
4732 
4733   return SDValue();
4734 }
4735 
4736 SDValue DAGCombiner::visitSRA(SDNode *N) {
4737   SDValue N0 = N->getOperand(0);
4738   SDValue N1 = N->getOperand(1);
4739   EVT VT = N0.getValueType();
4740   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4741 
4742   // fold vector ops
4743   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4744   if (VT.isVector()) {
4745     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4746       return FoldedVOp;
4747 
4748     N1C = isConstOrConstSplat(N1);
4749   }
4750 
4751   // fold (sra c1, c2) -> (sra c1, c2)
4752   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4753   if (N0C && N1C && !N1C->isOpaque())
4754     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4755   // fold (sra 0, x) -> 0
4756   if (isNullConstant(N0))
4757     return N0;
4758   // fold (sra -1, x) -> -1
4759   if (isAllOnesConstant(N0))
4760     return N0;
4761   // fold (sra x, c >= size(x)) -> undef
4762   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4763     return DAG.getUNDEF(VT);
4764   // fold (sra x, 0) -> x
4765   if (N1C && N1C->isNullValue())
4766     return N0;
4767   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4768   // sext_inreg.
4769   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4770     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4771     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4772     if (VT.isVector())
4773       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4774                                ExtVT, VT.getVectorNumElements());
4775     if ((!LegalOperations ||
4776          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4777       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4778                          N0.getOperand(0), DAG.getValueType(ExtVT));
4779   }
4780 
4781   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4782   if (N1C && N0.getOpcode() == ISD::SRA) {
4783     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4784       SDLoc DL(N);
4785       APInt c1 = N0C1->getAPIntValue();
4786       APInt c2 = N1C->getAPIntValue();
4787       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4788 
4789       APInt Sum = c1 + c2;
4790       if (Sum.uge(OpSizeInBits))
4791         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
4792 
4793       return DAG.getNode(
4794           ISD::SRA, DL, VT, N0.getOperand(0),
4795           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4796     }
4797   }
4798 
4799   // fold (sra (shl X, m), (sub result_size, n))
4800   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4801   // result_size - n != m.
4802   // If truncate is free for the target sext(shl) is likely to result in better
4803   // code.
4804   if (N0.getOpcode() == ISD::SHL && N1C) {
4805     // Get the two constanst of the shifts, CN0 = m, CN = n.
4806     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4807     if (N01C) {
4808       LLVMContext &Ctx = *DAG.getContext();
4809       // Determine what the truncate's result bitsize and type would be.
4810       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4811 
4812       if (VT.isVector())
4813         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4814 
4815       // Determine the residual right-shift amount.
4816       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4817 
4818       // If the shift is not a no-op (in which case this should be just a sign
4819       // extend already), the truncated to type is legal, sign_extend is legal
4820       // on that type, and the truncate to that type is both legal and free,
4821       // perform the transform.
4822       if ((ShiftAmt > 0) &&
4823           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4824           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4825           TLI.isTruncateFree(VT, TruncVT)) {
4826 
4827         SDLoc DL(N);
4828         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4829             getShiftAmountTy(N0.getOperand(0).getValueType()));
4830         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4831                                     N0.getOperand(0), Amt);
4832         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4833                                     Shift);
4834         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4835                            N->getValueType(0), Trunc);
4836       }
4837     }
4838   }
4839 
4840   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4841   if (N1.getOpcode() == ISD::TRUNCATE &&
4842       N1.getOperand(0).getOpcode() == ISD::AND) {
4843     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4844       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4845   }
4846 
4847   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4848   //      if c1 is equal to the number of bits the trunc removes
4849   if (N0.getOpcode() == ISD::TRUNCATE &&
4850       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4851        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4852       N0.getOperand(0).hasOneUse() &&
4853       N0.getOperand(0).getOperand(1).hasOneUse() &&
4854       N1C) {
4855     SDValue N0Op0 = N0.getOperand(0);
4856     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4857       unsigned LargeShiftVal = LargeShift->getZExtValue();
4858       EVT LargeVT = N0Op0.getValueType();
4859 
4860       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4861         SDLoc DL(N);
4862         SDValue Amt =
4863           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4864                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4865         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4866                                   N0Op0.getOperand(0), Amt);
4867         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4868       }
4869     }
4870   }
4871 
4872   // Simplify, based on bits shifted out of the LHS.
4873   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4874     return SDValue(N, 0);
4875 
4876 
4877   // If the sign bit is known to be zero, switch this to a SRL.
4878   if (DAG.SignBitIsZero(N0))
4879     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4880 
4881   if (N1C && !N1C->isOpaque())
4882     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4883       return NewSRA;
4884 
4885   return SDValue();
4886 }
4887 
4888 SDValue DAGCombiner::visitSRL(SDNode *N) {
4889   SDValue N0 = N->getOperand(0);
4890   SDValue N1 = N->getOperand(1);
4891   EVT VT = N0.getValueType();
4892   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4893 
4894   // fold vector ops
4895   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4896   if (VT.isVector()) {
4897     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4898       return FoldedVOp;
4899 
4900     N1C = isConstOrConstSplat(N1);
4901   }
4902 
4903   // fold (srl c1, c2) -> c1 >>u c2
4904   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4905   if (N0C && N1C && !N1C->isOpaque())
4906     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4907   // fold (srl 0, x) -> 0
4908   if (isNullConstant(N0))
4909     return N0;
4910   // fold (srl x, c >= size(x)) -> undef
4911   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4912     return DAG.getUNDEF(VT);
4913   // fold (srl x, 0) -> x
4914   if (N1C && N1C->isNullValue())
4915     return N0;
4916   // if (srl x, c) is known to be zero, return 0
4917   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4918                                    APInt::getAllOnesValue(OpSizeInBits)))
4919     return DAG.getConstant(0, SDLoc(N), VT);
4920 
4921   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4922   if (N1C && N0.getOpcode() == ISD::SRL) {
4923     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4924       SDLoc DL(N);
4925       APInt c1 = N0C1->getAPIntValue();
4926       APInt c2 = N1C->getAPIntValue();
4927       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4928 
4929       APInt Sum = c1 + c2;
4930       if (Sum.uge(OpSizeInBits))
4931         return DAG.getConstant(0, DL, VT);
4932 
4933       return DAG.getNode(
4934           ISD::SRL, DL, VT, N0.getOperand(0),
4935           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4936     }
4937   }
4938 
4939   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4940   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4941       N0.getOperand(0).getOpcode() == ISD::SRL &&
4942       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4943     uint64_t c1 =
4944       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4945     uint64_t c2 = N1C->getZExtValue();
4946     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4947     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4948     uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4949     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4950     if (c1 + OpSizeInBits == InnerShiftSize) {
4951       SDLoc DL(N0);
4952       if (c1 + c2 >= InnerShiftSize)
4953         return DAG.getConstant(0, DL, VT);
4954       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4955                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4956                                      N0.getOperand(0)->getOperand(0),
4957                                      DAG.getConstant(c1 + c2, DL,
4958                                                      ShiftCountVT)));
4959     }
4960   }
4961 
4962   // fold (srl (shl x, c), c) -> (and x, cst2)
4963   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4964     unsigned BitSize = N0.getScalarValueSizeInBits();
4965     if (BitSize <= 64) {
4966       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4967       SDLoc DL(N);
4968       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4969                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4970     }
4971   }
4972 
4973   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4974   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4975     // Shifting in all undef bits?
4976     EVT SmallVT = N0.getOperand(0).getValueType();
4977     unsigned BitSize = SmallVT.getScalarSizeInBits();
4978     if (N1C->getZExtValue() >= BitSize)
4979       return DAG.getUNDEF(VT);
4980 
4981     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4982       uint64_t ShiftAmt = N1C->getZExtValue();
4983       SDLoc DL0(N0);
4984       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4985                                        N0.getOperand(0),
4986                           DAG.getConstant(ShiftAmt, DL0,
4987                                           getShiftAmountTy(SmallVT)));
4988       AddToWorklist(SmallShift.getNode());
4989       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4990       SDLoc DL(N);
4991       return DAG.getNode(ISD::AND, DL, VT,
4992                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4993                          DAG.getConstant(Mask, DL, VT));
4994     }
4995   }
4996 
4997   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4998   // bit, which is unmodified by sra.
4999   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5000     if (N0.getOpcode() == ISD::SRA)
5001       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5002   }
5003 
5004   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5005   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5006       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5007     APInt KnownZero, KnownOne;
5008     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
5009 
5010     // If any of the input bits are KnownOne, then the input couldn't be all
5011     // zeros, thus the result of the srl will always be zero.
5012     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5013 
5014     // If all of the bits input the to ctlz node are known to be zero, then
5015     // the result of the ctlz is "32" and the result of the shift is one.
5016     APInt UnknownBits = ~KnownZero;
5017     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5018 
5019     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5020     if ((UnknownBits & (UnknownBits - 1)) == 0) {
5021       // Okay, we know that only that the single bit specified by UnknownBits
5022       // could be set on input to the CTLZ node. If this bit is set, the SRL
5023       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5024       // to an SRL/XOR pair, which is likely to simplify more.
5025       unsigned ShAmt = UnknownBits.countTrailingZeros();
5026       SDValue Op = N0.getOperand(0);
5027 
5028       if (ShAmt) {
5029         SDLoc DL(N0);
5030         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5031                   DAG.getConstant(ShAmt, DL,
5032                                   getShiftAmountTy(Op.getValueType())));
5033         AddToWorklist(Op.getNode());
5034       }
5035 
5036       SDLoc DL(N);
5037       return DAG.getNode(ISD::XOR, DL, VT,
5038                          Op, DAG.getConstant(1, DL, VT));
5039     }
5040   }
5041 
5042   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5043   if (N1.getOpcode() == ISD::TRUNCATE &&
5044       N1.getOperand(0).getOpcode() == ISD::AND) {
5045     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5046       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5047   }
5048 
5049   // fold operands of srl based on knowledge that the low bits are not
5050   // demanded.
5051   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5052     return SDValue(N, 0);
5053 
5054   if (N1C && !N1C->isOpaque())
5055     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5056       return NewSRL;
5057 
5058   // Attempt to convert a srl of a load into a narrower zero-extending load.
5059   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5060     return NarrowLoad;
5061 
5062   // Here is a common situation. We want to optimize:
5063   //
5064   //   %a = ...
5065   //   %b = and i32 %a, 2
5066   //   %c = srl i32 %b, 1
5067   //   brcond i32 %c ...
5068   //
5069   // into
5070   //
5071   //   %a = ...
5072   //   %b = and %a, 2
5073   //   %c = setcc eq %b, 0
5074   //   brcond %c ...
5075   //
5076   // However when after the source operand of SRL is optimized into AND, the SRL
5077   // itself may not be optimized further. Look for it and add the BRCOND into
5078   // the worklist.
5079   if (N->hasOneUse()) {
5080     SDNode *Use = *N->use_begin();
5081     if (Use->getOpcode() == ISD::BRCOND)
5082       AddToWorklist(Use);
5083     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5084       // Also look pass the truncate.
5085       Use = *Use->use_begin();
5086       if (Use->getOpcode() == ISD::BRCOND)
5087         AddToWorklist(Use);
5088     }
5089   }
5090 
5091   return SDValue();
5092 }
5093 
5094 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5095   SDValue N0 = N->getOperand(0);
5096   EVT VT = N->getValueType(0);
5097 
5098   // fold (bswap c1) -> c2
5099   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5100     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5101   // fold (bswap (bswap x)) -> x
5102   if (N0.getOpcode() == ISD::BSWAP)
5103     return N0->getOperand(0);
5104   return SDValue();
5105 }
5106 
5107 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5108   SDValue N0 = N->getOperand(0);
5109 
5110   // fold (bitreverse (bitreverse x)) -> x
5111   if (N0.getOpcode() == ISD::BITREVERSE)
5112     return N0.getOperand(0);
5113   return SDValue();
5114 }
5115 
5116 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5117   SDValue N0 = N->getOperand(0);
5118   EVT VT = N->getValueType(0);
5119 
5120   // fold (ctlz c1) -> c2
5121   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5122     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5123   return SDValue();
5124 }
5125 
5126 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5127   SDValue N0 = N->getOperand(0);
5128   EVT VT = N->getValueType(0);
5129 
5130   // fold (ctlz_zero_undef c1) -> c2
5131   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5132     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5133   return SDValue();
5134 }
5135 
5136 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5137   SDValue N0 = N->getOperand(0);
5138   EVT VT = N->getValueType(0);
5139 
5140   // fold (cttz c1) -> c2
5141   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5142     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5143   return SDValue();
5144 }
5145 
5146 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5147   SDValue N0 = N->getOperand(0);
5148   EVT VT = N->getValueType(0);
5149 
5150   // fold (cttz_zero_undef c1) -> c2
5151   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5152     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5153   return SDValue();
5154 }
5155 
5156 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5157   SDValue N0 = N->getOperand(0);
5158   EVT VT = N->getValueType(0);
5159 
5160   // fold (ctpop c1) -> c2
5161   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5162     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5163   return SDValue();
5164 }
5165 
5166 
5167 /// \brief Generate Min/Max node
5168 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5169                                    SDValue RHS, SDValue True, SDValue False,
5170                                    ISD::CondCode CC, const TargetLowering &TLI,
5171                                    SelectionDAG &DAG) {
5172   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5173     return SDValue();
5174 
5175   switch (CC) {
5176   case ISD::SETOLT:
5177   case ISD::SETOLE:
5178   case ISD::SETLT:
5179   case ISD::SETLE:
5180   case ISD::SETULT:
5181   case ISD::SETULE: {
5182     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5183     if (TLI.isOperationLegal(Opcode, VT))
5184       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5185     return SDValue();
5186   }
5187   case ISD::SETOGT:
5188   case ISD::SETOGE:
5189   case ISD::SETGT:
5190   case ISD::SETGE:
5191   case ISD::SETUGT:
5192   case ISD::SETUGE: {
5193     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5194     if (TLI.isOperationLegal(Opcode, VT))
5195       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5196     return SDValue();
5197   }
5198   default:
5199     return SDValue();
5200   }
5201 }
5202 
5203 // TODO: We should handle other cases of selecting between {-1,0,1} here.
5204 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5205   SDValue Cond = N->getOperand(0);
5206   SDValue N1 = N->getOperand(1);
5207   SDValue N2 = N->getOperand(2);
5208   EVT VT = N->getValueType(0);
5209   EVT CondVT = Cond.getValueType();
5210   SDLoc DL(N);
5211 
5212   // fold (select Cond, 0, 1) -> (xor Cond, 1)
5213   // We can't do this reliably if integer based booleans have different contents
5214   // to floating point based booleans. This is because we can't tell whether we
5215   // have an integer-based boolean or a floating-point-based boolean unless we
5216   // can find the SETCC that produced it and inspect its operands. This is
5217   // fairly easy if C is the SETCC node, but it can potentially be
5218   // undiscoverable (or not reasonably discoverable). For example, it could be
5219   // in another basic block or it could require searching a complicated
5220   // expression.
5221   if (VT.isInteger() &&
5222       (CondVT == MVT::i1 || (CondVT.isInteger() &&
5223                              TLI.getBooleanContents(false, true) ==
5224                                  TargetLowering::ZeroOrOneBooleanContent &&
5225                              TLI.getBooleanContents(false, false) ==
5226                                  TargetLowering::ZeroOrOneBooleanContent)) &&
5227       isNullConstant(N1) && isOneConstant(N2)) {
5228     SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond,
5229                                   DAG.getConstant(1, DL, CondVT));
5230     if (VT.bitsEq(CondVT))
5231       return NotCond;
5232     return DAG.getZExtOrTrunc(NotCond, DL, VT);
5233   }
5234 
5235   return SDValue();
5236 }
5237 
5238 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5239   SDValue N0 = N->getOperand(0);
5240   SDValue N1 = N->getOperand(1);
5241   SDValue N2 = N->getOperand(2);
5242   EVT VT = N->getValueType(0);
5243   EVT VT0 = N0.getValueType();
5244 
5245   // fold (select C, X, X) -> X
5246   if (N1 == N2)
5247     return N1;
5248   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5249     // fold (select true, X, Y) -> X
5250     // fold (select false, X, Y) -> Y
5251     return !N0C->isNullValue() ? N1 : N2;
5252   }
5253   // fold (select C, 1, X) -> (or C, X)
5254   if (VT == MVT::i1 && isOneConstant(N1))
5255     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5256 
5257   if (SDValue V = foldSelectOfConstants(N))
5258     return V;
5259 
5260   // fold (select C, 0, X) -> (and (not C), X)
5261   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5262     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5263     AddToWorklist(NOTNode.getNode());
5264     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5265   }
5266   // fold (select C, X, 1) -> (or (not C), X)
5267   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5268     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5269     AddToWorklist(NOTNode.getNode());
5270     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5271   }
5272   // fold (select C, X, 0) -> (and C, X)
5273   if (VT == MVT::i1 && isNullConstant(N2))
5274     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5275   // fold (select X, X, Y) -> (or X, Y)
5276   // fold (select X, 1, Y) -> (or X, Y)
5277   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5278     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5279   // fold (select X, Y, X) -> (and X, Y)
5280   // fold (select X, Y, 0) -> (and X, Y)
5281   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5282     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5283 
5284   // If we can fold this based on the true/false value, do so.
5285   if (SimplifySelectOps(N, N1, N2))
5286     return SDValue(N, 0);  // Don't revisit N.
5287 
5288   if (VT0 == MVT::i1) {
5289     // The code in this block deals with the following 2 equivalences:
5290     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5291     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5292     // The target can specify its prefered form with the
5293     // shouldNormalizeToSelectSequence() callback. However we always transform
5294     // to the right anyway if we find the inner select exists in the DAG anyway
5295     // and we always transform to the left side if we know that we can further
5296     // optimize the combination of the conditions.
5297     bool normalizeToSequence
5298       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5299     // select (and Cond0, Cond1), X, Y
5300     //   -> select Cond0, (select Cond1, X, Y), Y
5301     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5302       SDValue Cond0 = N0->getOperand(0);
5303       SDValue Cond1 = N0->getOperand(1);
5304       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5305                                         N1.getValueType(), Cond1, N1, N2);
5306       if (normalizeToSequence || !InnerSelect.use_empty())
5307         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5308                            InnerSelect, N2);
5309     }
5310     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5311     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5312       SDValue Cond0 = N0->getOperand(0);
5313       SDValue Cond1 = N0->getOperand(1);
5314       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5315                                         N1.getValueType(), Cond1, N1, N2);
5316       if (normalizeToSequence || !InnerSelect.use_empty())
5317         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5318                            InnerSelect);
5319     }
5320 
5321     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5322     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5323       SDValue N1_0 = N1->getOperand(0);
5324       SDValue N1_1 = N1->getOperand(1);
5325       SDValue N1_2 = N1->getOperand(2);
5326       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5327         // Create the actual and node if we can generate good code for it.
5328         if (!normalizeToSequence) {
5329           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5330                                     N0, N1_0);
5331           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5332                              N1_1, N2);
5333         }
5334         // Otherwise see if we can optimize the "and" to a better pattern.
5335         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5336           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5337                              N1_1, N2);
5338       }
5339     }
5340     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5341     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5342       SDValue N2_0 = N2->getOperand(0);
5343       SDValue N2_1 = N2->getOperand(1);
5344       SDValue N2_2 = N2->getOperand(2);
5345       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5346         // Create the actual or node if we can generate good code for it.
5347         if (!normalizeToSequence) {
5348           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5349                                    N0, N2_0);
5350           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5351                              N1, N2_2);
5352         }
5353         // Otherwise see if we can optimize to a better pattern.
5354         if (SDValue Combined = visitORLike(N0, N2_0, N))
5355           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5356                              N1, N2_2);
5357       }
5358     }
5359   }
5360 
5361   // select (xor Cond, 1), X, Y -> select Cond, Y, X
5362   // select (xor Cond, 0), X, Y -> selext Cond, X, Y
5363   if (VT0 == MVT::i1) {
5364     if (N0->getOpcode() == ISD::XOR) {
5365       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
5366         SDValue Cond0 = N0->getOperand(0);
5367         if (C->isOne())
5368           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5369                              Cond0, N2, N1);
5370         else
5371           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5372                              Cond0, N1, N2);
5373       }
5374     }
5375   }
5376 
5377   // fold selects based on a setcc into other things, such as min/max/abs
5378   if (N0.getOpcode() == ISD::SETCC) {
5379     // select x, y (fcmp lt x, y) -> fminnum x, y
5380     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5381     //
5382     // This is OK if we don't care about what happens if either operand is a
5383     // NaN.
5384     //
5385 
5386     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5387     // no signed zeros as well as no nans.
5388     const TargetOptions &Options = DAG.getTarget().Options;
5389     if (Options.UnsafeFPMath &&
5390         VT.isFloatingPoint() && N0.hasOneUse() &&
5391         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5392       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5393 
5394       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5395                                                 N0.getOperand(1), N1, N2, CC,
5396                                                 TLI, DAG))
5397         return FMinMax;
5398     }
5399 
5400     if ((!LegalOperations &&
5401          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5402         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5403       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5404                          N0.getOperand(0), N0.getOperand(1),
5405                          N1, N2, N0.getOperand(2));
5406     return SimplifySelect(SDLoc(N), N0, N1, N2);
5407   }
5408 
5409   return SDValue();
5410 }
5411 
5412 static
5413 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5414   SDLoc DL(N);
5415   EVT LoVT, HiVT;
5416   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5417 
5418   // Split the inputs.
5419   SDValue Lo, Hi, LL, LH, RL, RH;
5420   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5421   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5422 
5423   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5424   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5425 
5426   return std::make_pair(Lo, Hi);
5427 }
5428 
5429 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5430 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5431 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5432   SDLoc DL(N);
5433   SDValue Cond = N->getOperand(0);
5434   SDValue LHS = N->getOperand(1);
5435   SDValue RHS = N->getOperand(2);
5436   EVT VT = N->getValueType(0);
5437   int NumElems = VT.getVectorNumElements();
5438   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5439          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5440          Cond.getOpcode() == ISD::BUILD_VECTOR);
5441 
5442   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5443   // binary ones here.
5444   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5445     return SDValue();
5446 
5447   // We're sure we have an even number of elements due to the
5448   // concat_vectors we have as arguments to vselect.
5449   // Skip BV elements until we find one that's not an UNDEF
5450   // After we find an UNDEF element, keep looping until we get to half the
5451   // length of the BV and see if all the non-undef nodes are the same.
5452   ConstantSDNode *BottomHalf = nullptr;
5453   for (int i = 0; i < NumElems / 2; ++i) {
5454     if (Cond->getOperand(i)->isUndef())
5455       continue;
5456 
5457     if (BottomHalf == nullptr)
5458       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5459     else if (Cond->getOperand(i).getNode() != BottomHalf)
5460       return SDValue();
5461   }
5462 
5463   // Do the same for the second half of the BuildVector
5464   ConstantSDNode *TopHalf = nullptr;
5465   for (int i = NumElems / 2; i < NumElems; ++i) {
5466     if (Cond->getOperand(i)->isUndef())
5467       continue;
5468 
5469     if (TopHalf == nullptr)
5470       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5471     else if (Cond->getOperand(i).getNode() != TopHalf)
5472       return SDValue();
5473   }
5474 
5475   assert(TopHalf && BottomHalf &&
5476          "One half of the selector was all UNDEFs and the other was all the "
5477          "same value. This should have been addressed before this function.");
5478   return DAG.getNode(
5479       ISD::CONCAT_VECTORS, DL, VT,
5480       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5481       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5482 }
5483 
5484 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5485 
5486   if (Level >= AfterLegalizeTypes)
5487     return SDValue();
5488 
5489   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5490   SDValue Mask = MSC->getMask();
5491   SDValue Data  = MSC->getValue();
5492   SDLoc DL(N);
5493 
5494   // If the MSCATTER data type requires splitting and the mask is provided by a
5495   // SETCC, then split both nodes and its operands before legalization. This
5496   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5497   // and enables future optimizations (e.g. min/max pattern matching on X86).
5498   if (Mask.getOpcode() != ISD::SETCC)
5499     return SDValue();
5500 
5501   // Check if any splitting is required.
5502   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5503       TargetLowering::TypeSplitVector)
5504     return SDValue();
5505   SDValue MaskLo, MaskHi, Lo, Hi;
5506   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5507 
5508   EVT LoVT, HiVT;
5509   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5510 
5511   SDValue Chain = MSC->getChain();
5512 
5513   EVT MemoryVT = MSC->getMemoryVT();
5514   unsigned Alignment = MSC->getOriginalAlignment();
5515 
5516   EVT LoMemVT, HiMemVT;
5517   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5518 
5519   SDValue DataLo, DataHi;
5520   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5521 
5522   SDValue BasePtr = MSC->getBasePtr();
5523   SDValue IndexLo, IndexHi;
5524   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5525 
5526   MachineMemOperand *MMO = DAG.getMachineFunction().
5527     getMachineMemOperand(MSC->getPointerInfo(),
5528                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5529                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5530 
5531   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5532   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5533                             DL, OpsLo, MMO);
5534 
5535   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5536   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5537                             DL, OpsHi, MMO);
5538 
5539   AddToWorklist(Lo.getNode());
5540   AddToWorklist(Hi.getNode());
5541 
5542   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5543 }
5544 
5545 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5546 
5547   if (Level >= AfterLegalizeTypes)
5548     return SDValue();
5549 
5550   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5551   SDValue Mask = MST->getMask();
5552   SDValue Data  = MST->getValue();
5553   SDLoc DL(N);
5554 
5555   // If the MSTORE data type requires splitting and the mask is provided by a
5556   // SETCC, then split both nodes and its operands before legalization. This
5557   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5558   // and enables future optimizations (e.g. min/max pattern matching on X86).
5559   if (Mask.getOpcode() == ISD::SETCC) {
5560 
5561     // Check if any splitting is required.
5562     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5563         TargetLowering::TypeSplitVector)
5564       return SDValue();
5565 
5566     SDValue MaskLo, MaskHi, Lo, Hi;
5567     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5568 
5569     EVT LoVT, HiVT;
5570     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5571 
5572     SDValue Chain = MST->getChain();
5573     SDValue Ptr   = MST->getBasePtr();
5574 
5575     EVT MemoryVT = MST->getMemoryVT();
5576     unsigned Alignment = MST->getOriginalAlignment();
5577 
5578     // if Alignment is equal to the vector size,
5579     // take the half of it for the second part
5580     unsigned SecondHalfAlignment =
5581       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5582          Alignment/2 : Alignment;
5583 
5584     EVT LoMemVT, HiMemVT;
5585     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5586 
5587     SDValue DataLo, DataHi;
5588     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5589 
5590     MachineMemOperand *MMO = DAG.getMachineFunction().
5591       getMachineMemOperand(MST->getPointerInfo(),
5592                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5593                            Alignment, MST->getAAInfo(), MST->getRanges());
5594 
5595     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5596                             MST->isTruncatingStore());
5597 
5598     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5599     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5600                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5601 
5602     MMO = DAG.getMachineFunction().
5603       getMachineMemOperand(MST->getPointerInfo(),
5604                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5605                            SecondHalfAlignment, MST->getAAInfo(),
5606                            MST->getRanges());
5607 
5608     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5609                             MST->isTruncatingStore());
5610 
5611     AddToWorklist(Lo.getNode());
5612     AddToWorklist(Hi.getNode());
5613 
5614     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5615   }
5616   return SDValue();
5617 }
5618 
5619 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5620 
5621   if (Level >= AfterLegalizeTypes)
5622     return SDValue();
5623 
5624   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5625   SDValue Mask = MGT->getMask();
5626   SDLoc DL(N);
5627 
5628   // If the MGATHER result requires splitting and the mask is provided by a
5629   // SETCC, then split both nodes and its operands before legalization. This
5630   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5631   // and enables future optimizations (e.g. min/max pattern matching on X86).
5632 
5633   if (Mask.getOpcode() != ISD::SETCC)
5634     return SDValue();
5635 
5636   EVT VT = N->getValueType(0);
5637 
5638   // Check if any splitting is required.
5639   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5640       TargetLowering::TypeSplitVector)
5641     return SDValue();
5642 
5643   SDValue MaskLo, MaskHi, Lo, Hi;
5644   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5645 
5646   SDValue Src0 = MGT->getValue();
5647   SDValue Src0Lo, Src0Hi;
5648   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5649 
5650   EVT LoVT, HiVT;
5651   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5652 
5653   SDValue Chain = MGT->getChain();
5654   EVT MemoryVT = MGT->getMemoryVT();
5655   unsigned Alignment = MGT->getOriginalAlignment();
5656 
5657   EVT LoMemVT, HiMemVT;
5658   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5659 
5660   SDValue BasePtr = MGT->getBasePtr();
5661   SDValue Index = MGT->getIndex();
5662   SDValue IndexLo, IndexHi;
5663   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5664 
5665   MachineMemOperand *MMO = DAG.getMachineFunction().
5666     getMachineMemOperand(MGT->getPointerInfo(),
5667                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5668                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5669 
5670   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5671   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5672                             MMO);
5673 
5674   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5675   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5676                             MMO);
5677 
5678   AddToWorklist(Lo.getNode());
5679   AddToWorklist(Hi.getNode());
5680 
5681   // Build a factor node to remember that this load is independent of the
5682   // other one.
5683   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5684                       Hi.getValue(1));
5685 
5686   // Legalized the chain result - switch anything that used the old chain to
5687   // use the new one.
5688   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5689 
5690   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5691 
5692   SDValue RetOps[] = { GatherRes, Chain };
5693   return DAG.getMergeValues(RetOps, DL);
5694 }
5695 
5696 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5697 
5698   if (Level >= AfterLegalizeTypes)
5699     return SDValue();
5700 
5701   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5702   SDValue Mask = MLD->getMask();
5703   SDLoc DL(N);
5704 
5705   // If the MLOAD result requires splitting and the mask is provided by a
5706   // SETCC, then split both nodes and its operands before legalization. This
5707   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5708   // and enables future optimizations (e.g. min/max pattern matching on X86).
5709 
5710   if (Mask.getOpcode() == ISD::SETCC) {
5711     EVT VT = N->getValueType(0);
5712 
5713     // Check if any splitting is required.
5714     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5715         TargetLowering::TypeSplitVector)
5716       return SDValue();
5717 
5718     SDValue MaskLo, MaskHi, Lo, Hi;
5719     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5720 
5721     SDValue Src0 = MLD->getSrc0();
5722     SDValue Src0Lo, Src0Hi;
5723     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5724 
5725     EVT LoVT, HiVT;
5726     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5727 
5728     SDValue Chain = MLD->getChain();
5729     SDValue Ptr   = MLD->getBasePtr();
5730     EVT MemoryVT = MLD->getMemoryVT();
5731     unsigned Alignment = MLD->getOriginalAlignment();
5732 
5733     // if Alignment is equal to the vector size,
5734     // take the half of it for the second part
5735     unsigned SecondHalfAlignment =
5736       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5737          Alignment/2 : Alignment;
5738 
5739     EVT LoMemVT, HiMemVT;
5740     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5741 
5742     MachineMemOperand *MMO = DAG.getMachineFunction().
5743     getMachineMemOperand(MLD->getPointerInfo(),
5744                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5745                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5746 
5747     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5748                            ISD::NON_EXTLOAD);
5749 
5750     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5751     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5752                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5753 
5754     MMO = DAG.getMachineFunction().
5755     getMachineMemOperand(MLD->getPointerInfo(),
5756                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5757                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5758 
5759     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5760                            ISD::NON_EXTLOAD);
5761 
5762     AddToWorklist(Lo.getNode());
5763     AddToWorklist(Hi.getNode());
5764 
5765     // Build a factor node to remember that this load is independent of the
5766     // other one.
5767     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5768                         Hi.getValue(1));
5769 
5770     // Legalized the chain result - switch anything that used the old chain to
5771     // use the new one.
5772     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5773 
5774     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5775 
5776     SDValue RetOps[] = { LoadRes, Chain };
5777     return DAG.getMergeValues(RetOps, DL);
5778   }
5779   return SDValue();
5780 }
5781 
5782 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5783   SDValue N0 = N->getOperand(0);
5784   SDValue N1 = N->getOperand(1);
5785   SDValue N2 = N->getOperand(2);
5786   SDLoc DL(N);
5787 
5788   // Canonicalize integer abs.
5789   // vselect (setg[te] X,  0),  X, -X ->
5790   // vselect (setgt    X, -1),  X, -X ->
5791   // vselect (setl[te] X,  0), -X,  X ->
5792   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5793   if (N0.getOpcode() == ISD::SETCC) {
5794     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5795     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5796     bool isAbs = false;
5797     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5798 
5799     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5800          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5801         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5802       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5803     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5804              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5805       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5806 
5807     if (isAbs) {
5808       EVT VT = LHS.getValueType();
5809       SDValue Shift = DAG.getNode(
5810           ISD::SRA, DL, VT, LHS,
5811           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
5812       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5813       AddToWorklist(Shift.getNode());
5814       AddToWorklist(Add.getNode());
5815       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5816     }
5817   }
5818 
5819   if (SimplifySelectOps(N, N1, N2))
5820     return SDValue(N, 0);  // Don't revisit N.
5821 
5822   // If the VSELECT result requires splitting and the mask is provided by a
5823   // SETCC, then split both nodes and its operands before legalization. This
5824   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5825   // and enables future optimizations (e.g. min/max pattern matching on X86).
5826   if (N0.getOpcode() == ISD::SETCC) {
5827     EVT VT = N->getValueType(0);
5828 
5829     // Check if any splitting is required.
5830     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5831         TargetLowering::TypeSplitVector)
5832       return SDValue();
5833 
5834     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5835     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5836     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5837     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5838 
5839     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5840     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5841 
5842     // Add the new VSELECT nodes to the work list in case they need to be split
5843     // again.
5844     AddToWorklist(Lo.getNode());
5845     AddToWorklist(Hi.getNode());
5846 
5847     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5848   }
5849 
5850   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5851   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5852     return N1;
5853   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5854   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5855     return N2;
5856 
5857   // The ConvertSelectToConcatVector function is assuming both the above
5858   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5859   // and addressed.
5860   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5861       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5862       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5863     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5864       return CV;
5865   }
5866 
5867   return SDValue();
5868 }
5869 
5870 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5871   SDValue N0 = N->getOperand(0);
5872   SDValue N1 = N->getOperand(1);
5873   SDValue N2 = N->getOperand(2);
5874   SDValue N3 = N->getOperand(3);
5875   SDValue N4 = N->getOperand(4);
5876   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5877 
5878   // fold select_cc lhs, rhs, x, x, cc -> x
5879   if (N2 == N3)
5880     return N2;
5881 
5882   // Determine if the condition we're dealing with is constant
5883   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5884                                   CC, SDLoc(N), false)) {
5885     AddToWorklist(SCC.getNode());
5886 
5887     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5888       if (!SCCC->isNullValue())
5889         return N2;    // cond always true -> true val
5890       else
5891         return N3;    // cond always false -> false val
5892     } else if (SCC->isUndef()) {
5893       // When the condition is UNDEF, just return the first operand. This is
5894       // coherent the DAG creation, no setcc node is created in this case
5895       return N2;
5896     } else if (SCC.getOpcode() == ISD::SETCC) {
5897       // Fold to a simpler select_cc
5898       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5899                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5900                          SCC.getOperand(2));
5901     }
5902   }
5903 
5904   // If we can fold this based on the true/false value, do so.
5905   if (SimplifySelectOps(N, N2, N3))
5906     return SDValue(N, 0);  // Don't revisit N.
5907 
5908   // fold select_cc into other things, such as min/max/abs
5909   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5910 }
5911 
5912 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5913   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5914                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5915                        SDLoc(N));
5916 }
5917 
5918 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5919   SDValue LHS = N->getOperand(0);
5920   SDValue RHS = N->getOperand(1);
5921   SDValue Carry = N->getOperand(2);
5922   SDValue Cond = N->getOperand(3);
5923 
5924   // If Carry is false, fold to a regular SETCC.
5925   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5926     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5927 
5928   return SDValue();
5929 }
5930 
5931 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5932 /// a build_vector of constants.
5933 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5934 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5935 /// Vector extends are not folded if operations are legal; this is to
5936 /// avoid introducing illegal build_vector dag nodes.
5937 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5938                                          SelectionDAG &DAG, bool LegalTypes,
5939                                          bool LegalOperations) {
5940   unsigned Opcode = N->getOpcode();
5941   SDValue N0 = N->getOperand(0);
5942   EVT VT = N->getValueType(0);
5943 
5944   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5945          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5946          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5947          && "Expected EXTEND dag node in input!");
5948 
5949   // fold (sext c1) -> c1
5950   // fold (zext c1) -> c1
5951   // fold (aext c1) -> c1
5952   if (isa<ConstantSDNode>(N0))
5953     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5954 
5955   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5956   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5957   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5958   EVT SVT = VT.getScalarType();
5959   if (!(VT.isVector() &&
5960       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5961       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5962     return nullptr;
5963 
5964   // We can fold this node into a build_vector.
5965   unsigned VTBits = SVT.getSizeInBits();
5966   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
5967   SmallVector<SDValue, 8> Elts;
5968   unsigned NumElts = VT.getVectorNumElements();
5969   SDLoc DL(N);
5970 
5971   for (unsigned i=0; i != NumElts; ++i) {
5972     SDValue Op = N0->getOperand(i);
5973     if (Op->isUndef()) {
5974       Elts.push_back(DAG.getUNDEF(SVT));
5975       continue;
5976     }
5977 
5978     SDLoc DL(Op);
5979     // Get the constant value and if needed trunc it to the size of the type.
5980     // Nodes like build_vector might have constants wider than the scalar type.
5981     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5982     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5983       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5984     else
5985       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5986   }
5987 
5988   return DAG.getBuildVector(VT, DL, Elts).getNode();
5989 }
5990 
5991 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5992 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5993 // transformation. Returns true if extension are possible and the above
5994 // mentioned transformation is profitable.
5995 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5996                                     unsigned ExtOpc,
5997                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5998                                     const TargetLowering &TLI) {
5999   bool HasCopyToRegUses = false;
6000   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6001   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6002                             UE = N0.getNode()->use_end();
6003        UI != UE; ++UI) {
6004     SDNode *User = *UI;
6005     if (User == N)
6006       continue;
6007     if (UI.getUse().getResNo() != N0.getResNo())
6008       continue;
6009     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6010     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6011       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6012       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6013         // Sign bits will be lost after a zext.
6014         return false;
6015       bool Add = false;
6016       for (unsigned i = 0; i != 2; ++i) {
6017         SDValue UseOp = User->getOperand(i);
6018         if (UseOp == N0)
6019           continue;
6020         if (!isa<ConstantSDNode>(UseOp))
6021           return false;
6022         Add = true;
6023       }
6024       if (Add)
6025         ExtendNodes.push_back(User);
6026       continue;
6027     }
6028     // If truncates aren't free and there are users we can't
6029     // extend, it isn't worthwhile.
6030     if (!isTruncFree)
6031       return false;
6032     // Remember if this value is live-out.
6033     if (User->getOpcode() == ISD::CopyToReg)
6034       HasCopyToRegUses = true;
6035   }
6036 
6037   if (HasCopyToRegUses) {
6038     bool BothLiveOut = false;
6039     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6040          UI != UE; ++UI) {
6041       SDUse &Use = UI.getUse();
6042       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6043         BothLiveOut = true;
6044         break;
6045       }
6046     }
6047     if (BothLiveOut)
6048       // Both unextended and extended values are live out. There had better be
6049       // a good reason for the transformation.
6050       return ExtendNodes.size();
6051   }
6052   return true;
6053 }
6054 
6055 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6056                                   SDValue Trunc, SDValue ExtLoad,
6057                                   const SDLoc &DL, ISD::NodeType ExtType) {
6058   // Extend SetCC uses if necessary.
6059   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6060     SDNode *SetCC = SetCCs[i];
6061     SmallVector<SDValue, 4> Ops;
6062 
6063     for (unsigned j = 0; j != 2; ++j) {
6064       SDValue SOp = SetCC->getOperand(j);
6065       if (SOp == Trunc)
6066         Ops.push_back(ExtLoad);
6067       else
6068         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6069     }
6070 
6071     Ops.push_back(SetCC->getOperand(2));
6072     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6073   }
6074 }
6075 
6076 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6077 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6078   SDValue N0 = N->getOperand(0);
6079   EVT DstVT = N->getValueType(0);
6080   EVT SrcVT = N0.getValueType();
6081 
6082   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6083           N->getOpcode() == ISD::ZERO_EXTEND) &&
6084          "Unexpected node type (not an extend)!");
6085 
6086   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6087   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6088   //   (v8i32 (sext (v8i16 (load x))))
6089   // into:
6090   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6091   //                          (v4i32 (sextload (x + 16)))))
6092   // Where uses of the original load, i.e.:
6093   //   (v8i16 (load x))
6094   // are replaced with:
6095   //   (v8i16 (truncate
6096   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6097   //                            (v4i32 (sextload (x + 16)))))))
6098   //
6099   // This combine is only applicable to illegal, but splittable, vectors.
6100   // All legal types, and illegal non-vector types, are handled elsewhere.
6101   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6102   //
6103   if (N0->getOpcode() != ISD::LOAD)
6104     return SDValue();
6105 
6106   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6107 
6108   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6109       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6110       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6111     return SDValue();
6112 
6113   SmallVector<SDNode *, 4> SetCCs;
6114   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6115     return SDValue();
6116 
6117   ISD::LoadExtType ExtType =
6118       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6119 
6120   // Try to split the vector types to get down to legal types.
6121   EVT SplitSrcVT = SrcVT;
6122   EVT SplitDstVT = DstVT;
6123   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6124          SplitSrcVT.getVectorNumElements() > 1) {
6125     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6126     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6127   }
6128 
6129   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6130     return SDValue();
6131 
6132   SDLoc DL(N);
6133   const unsigned NumSplits =
6134       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6135   const unsigned Stride = SplitSrcVT.getStoreSize();
6136   SmallVector<SDValue, 4> Loads;
6137   SmallVector<SDValue, 4> Chains;
6138 
6139   SDValue BasePtr = LN0->getBasePtr();
6140   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6141     const unsigned Offset = Idx * Stride;
6142     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6143 
6144     SDValue SplitLoad = DAG.getExtLoad(
6145         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6146         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6147         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6148 
6149     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6150                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6151 
6152     Loads.push_back(SplitLoad.getValue(0));
6153     Chains.push_back(SplitLoad.getValue(1));
6154   }
6155 
6156   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6157   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6158 
6159   CombineTo(N, NewValue);
6160 
6161   // Replace uses of the original load (before extension)
6162   // with a truncate of the concatenated sextloaded vectors.
6163   SDValue Trunc =
6164       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6165   CombineTo(N0.getNode(), Trunc, NewChain);
6166   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6167                   (ISD::NodeType)N->getOpcode());
6168   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6169 }
6170 
6171 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6172   SDValue N0 = N->getOperand(0);
6173   EVT VT = N->getValueType(0);
6174 
6175   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6176                                               LegalOperations))
6177     return SDValue(Res, 0);
6178 
6179   // fold (sext (sext x)) -> (sext x)
6180   // fold (sext (aext x)) -> (sext x)
6181   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6182     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6183                        N0.getOperand(0));
6184 
6185   if (N0.getOpcode() == ISD::TRUNCATE) {
6186     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6187     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6188     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6189       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6190       if (NarrowLoad.getNode() != N0.getNode()) {
6191         CombineTo(N0.getNode(), NarrowLoad);
6192         // CombineTo deleted the truncate, if needed, but not what's under it.
6193         AddToWorklist(oye);
6194       }
6195       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6196     }
6197 
6198     // See if the value being truncated is already sign extended.  If so, just
6199     // eliminate the trunc/sext pair.
6200     SDValue Op = N0.getOperand(0);
6201     unsigned OpBits   = Op.getScalarValueSizeInBits();
6202     unsigned MidBits  = N0.getScalarValueSizeInBits();
6203     unsigned DestBits = VT.getScalarSizeInBits();
6204     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6205 
6206     if (OpBits == DestBits) {
6207       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6208       // bits, it is already ready.
6209       if (NumSignBits > DestBits-MidBits)
6210         return Op;
6211     } else if (OpBits < DestBits) {
6212       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6213       // bits, just sext from i32.
6214       if (NumSignBits > OpBits-MidBits)
6215         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6216     } else {
6217       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6218       // bits, just truncate to i32.
6219       if (NumSignBits > OpBits-MidBits)
6220         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6221     }
6222 
6223     // fold (sext (truncate x)) -> (sextinreg x).
6224     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6225                                                  N0.getValueType())) {
6226       if (OpBits < DestBits)
6227         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6228       else if (OpBits > DestBits)
6229         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6230       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6231                          DAG.getValueType(N0.getValueType()));
6232     }
6233   }
6234 
6235   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6236   // Only generate vector extloads when 1) they're legal, and 2) they are
6237   // deemed desirable by the target.
6238   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6239       ((!LegalOperations && !VT.isVector() &&
6240         !cast<LoadSDNode>(N0)->isVolatile()) ||
6241        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6242     bool DoXform = true;
6243     SmallVector<SDNode*, 4> SetCCs;
6244     if (!N0.hasOneUse())
6245       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6246     if (VT.isVector())
6247       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6248     if (DoXform) {
6249       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6250       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6251                                        LN0->getChain(),
6252                                        LN0->getBasePtr(), N0.getValueType(),
6253                                        LN0->getMemOperand());
6254       CombineTo(N, ExtLoad);
6255       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6256                                   N0.getValueType(), ExtLoad);
6257       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6258       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6259                       ISD::SIGN_EXTEND);
6260       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6261     }
6262   }
6263 
6264   // fold (sext (load x)) to multiple smaller sextloads.
6265   // Only on illegal but splittable vectors.
6266   if (SDValue ExtLoad = CombineExtLoad(N))
6267     return ExtLoad;
6268 
6269   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6270   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6271   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6272       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6273     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6274     EVT MemVT = LN0->getMemoryVT();
6275     if ((!LegalOperations && !LN0->isVolatile()) ||
6276         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6277       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6278                                        LN0->getChain(),
6279                                        LN0->getBasePtr(), MemVT,
6280                                        LN0->getMemOperand());
6281       CombineTo(N, ExtLoad);
6282       CombineTo(N0.getNode(),
6283                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6284                             N0.getValueType(), ExtLoad),
6285                 ExtLoad.getValue(1));
6286       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6287     }
6288   }
6289 
6290   // fold (sext (and/or/xor (load x), cst)) ->
6291   //      (and/or/xor (sextload x), (sext cst))
6292   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6293        N0.getOpcode() == ISD::XOR) &&
6294       isa<LoadSDNode>(N0.getOperand(0)) &&
6295       N0.getOperand(1).getOpcode() == ISD::Constant &&
6296       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6297       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6298     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6299     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6300       bool DoXform = true;
6301       SmallVector<SDNode*, 4> SetCCs;
6302       if (!N0.hasOneUse())
6303         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6304                                           SetCCs, TLI);
6305       if (DoXform) {
6306         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6307                                          LN0->getChain(), LN0->getBasePtr(),
6308                                          LN0->getMemoryVT(),
6309                                          LN0->getMemOperand());
6310         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6311         Mask = Mask.sext(VT.getSizeInBits());
6312         SDLoc DL(N);
6313         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6314                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6315         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6316                                     SDLoc(N0.getOperand(0)),
6317                                     N0.getOperand(0).getValueType(), ExtLoad);
6318         CombineTo(N, And);
6319         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6320         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6321                         ISD::SIGN_EXTEND);
6322         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6323       }
6324     }
6325   }
6326 
6327   if (N0.getOpcode() == ISD::SETCC) {
6328     EVT N0VT = N0.getOperand(0).getValueType();
6329     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6330     // Only do this before legalize for now.
6331     if (VT.isVector() && !LegalOperations &&
6332         TLI.getBooleanContents(N0VT) ==
6333             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6334       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6335       // of the same size as the compared operands. Only optimize sext(setcc())
6336       // if this is the case.
6337       EVT SVT = getSetCCResultType(N0VT);
6338 
6339       // We know that the # elements of the results is the same as the
6340       // # elements of the compare (and the # elements of the compare result
6341       // for that matter).  Check to see that they are the same size.  If so,
6342       // we know that the element size of the sext'd result matches the
6343       // element size of the compare operands.
6344       if (VT.getSizeInBits() == SVT.getSizeInBits())
6345         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6346                              N0.getOperand(1),
6347                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6348 
6349       // If the desired elements are smaller or larger than the source
6350       // elements we can use a matching integer vector type and then
6351       // truncate/sign extend
6352       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6353       if (SVT == MatchingVectorType) {
6354         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6355                                N0.getOperand(0), N0.getOperand(1),
6356                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6357         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6358       }
6359     }
6360 
6361     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
6362     // Here, T can be 1 or -1, depending on the type of the setcc and
6363     // getBooleanContents().
6364     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
6365 
6366     SDLoc DL(N);
6367     // To determine the "true" side of the select, we need to know the high bit
6368     // of the value returned by the setcc if it evaluates to true.
6369     // If the type of the setcc is i1, then the true case of the select is just
6370     // sext(i1 1), that is, -1.
6371     // If the type of the setcc is larger (say, i8) then the value of the high
6372     // bit depends on getBooleanContents(). So, ask TLI for a real "true" value
6373     // of the appropriate width.
6374     SDValue ExtTrueVal =
6375         (SetCCWidth == 1)
6376             ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()),
6377                               DL, VT)
6378             : TLI.getConstTrueVal(DAG, VT, DL);
6379 
6380     if (SDValue SCC = SimplifySelectCC(
6381             DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal,
6382             DAG.getConstant(0, DL, VT),
6383             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6384       return SCC;
6385 
6386     if (!VT.isVector()) {
6387       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6388       if (!LegalOperations ||
6389           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6390         SDLoc DL(N);
6391         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6392         SDValue SetCC =
6393             DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC);
6394         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal,
6395                              DAG.getConstant(0, DL, VT));
6396       }
6397     }
6398   }
6399 
6400   // fold (sext x) -> (zext x) if the sign bit is known zero.
6401   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6402       DAG.SignBitIsZero(N0))
6403     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6404 
6405   return SDValue();
6406 }
6407 
6408 // isTruncateOf - If N is a truncate of some other value, return true, record
6409 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6410 // This function computes KnownZero to avoid a duplicated call to
6411 // computeKnownBits in the caller.
6412 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6413                          APInt &KnownZero) {
6414   APInt KnownOne;
6415   if (N->getOpcode() == ISD::TRUNCATE) {
6416     Op = N->getOperand(0);
6417     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6418     return true;
6419   }
6420 
6421   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6422       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6423     return false;
6424 
6425   SDValue Op0 = N->getOperand(0);
6426   SDValue Op1 = N->getOperand(1);
6427   assert(Op0.getValueType() == Op1.getValueType());
6428 
6429   if (isNullConstant(Op0))
6430     Op = Op1;
6431   else if (isNullConstant(Op1))
6432     Op = Op0;
6433   else
6434     return false;
6435 
6436   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6437 
6438   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6439     return false;
6440 
6441   return true;
6442 }
6443 
6444 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6445   SDValue N0 = N->getOperand(0);
6446   EVT VT = N->getValueType(0);
6447 
6448   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6449                                               LegalOperations))
6450     return SDValue(Res, 0);
6451 
6452   // fold (zext (zext x)) -> (zext x)
6453   // fold (zext (aext x)) -> (zext x)
6454   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6455     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6456                        N0.getOperand(0));
6457 
6458   // fold (zext (truncate x)) -> (zext x) or
6459   //      (zext (truncate x)) -> (truncate x)
6460   // This is valid when the truncated bits of x are already zero.
6461   // FIXME: We should extend this to work for vectors too.
6462   SDValue Op;
6463   APInt KnownZero;
6464   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6465     APInt TruncatedBits =
6466       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6467       APInt(Op.getValueSizeInBits(), 0) :
6468       APInt::getBitsSet(Op.getValueSizeInBits(),
6469                         N0.getValueSizeInBits(),
6470                         std::min(Op.getValueSizeInBits(),
6471                                  VT.getSizeInBits()));
6472     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6473       if (VT.bitsGT(Op.getValueType()))
6474         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6475       if (VT.bitsLT(Op.getValueType()))
6476         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6477 
6478       return Op;
6479     }
6480   }
6481 
6482   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6483   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6484   if (N0.getOpcode() == ISD::TRUNCATE) {
6485     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6486       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6487       if (NarrowLoad.getNode() != N0.getNode()) {
6488         CombineTo(N0.getNode(), NarrowLoad);
6489         // CombineTo deleted the truncate, if needed, but not what's under it.
6490         AddToWorklist(oye);
6491       }
6492       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6493     }
6494   }
6495 
6496   // fold (zext (truncate x)) -> (and x, mask)
6497   if (N0.getOpcode() == ISD::TRUNCATE) {
6498     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6499     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6500     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6501       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6502       if (NarrowLoad.getNode() != N0.getNode()) {
6503         CombineTo(N0.getNode(), NarrowLoad);
6504         // CombineTo deleted the truncate, if needed, but not what's under it.
6505         AddToWorklist(oye);
6506       }
6507       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6508     }
6509 
6510     EVT SrcVT = N0.getOperand(0).getValueType();
6511     EVT MinVT = N0.getValueType();
6512 
6513     // Try to mask before the extension to avoid having to generate a larger mask,
6514     // possibly over several sub-vectors.
6515     if (SrcVT.bitsLT(VT)) {
6516       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6517                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6518         SDValue Op = N0.getOperand(0);
6519         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6520         AddToWorklist(Op.getNode());
6521         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6522       }
6523     }
6524 
6525     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6526       SDValue Op = N0.getOperand(0);
6527       if (SrcVT.bitsLT(VT)) {
6528         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6529         AddToWorklist(Op.getNode());
6530       } else if (SrcVT.bitsGT(VT)) {
6531         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6532         AddToWorklist(Op.getNode());
6533       }
6534       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6535     }
6536   }
6537 
6538   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6539   // if either of the casts is not free.
6540   if (N0.getOpcode() == ISD::AND &&
6541       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6542       N0.getOperand(1).getOpcode() == ISD::Constant &&
6543       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6544                            N0.getValueType()) ||
6545        !TLI.isZExtFree(N0.getValueType(), VT))) {
6546     SDValue X = N0.getOperand(0).getOperand(0);
6547     if (X.getValueType().bitsLT(VT)) {
6548       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6549     } else if (X.getValueType().bitsGT(VT)) {
6550       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6551     }
6552     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6553     Mask = Mask.zext(VT.getSizeInBits());
6554     SDLoc DL(N);
6555     return DAG.getNode(ISD::AND, DL, VT,
6556                        X, DAG.getConstant(Mask, DL, VT));
6557   }
6558 
6559   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6560   // Only generate vector extloads when 1) they're legal, and 2) they are
6561   // deemed desirable by the target.
6562   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6563       ((!LegalOperations && !VT.isVector() &&
6564         !cast<LoadSDNode>(N0)->isVolatile()) ||
6565        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6566     bool DoXform = true;
6567     SmallVector<SDNode*, 4> SetCCs;
6568     if (!N0.hasOneUse())
6569       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6570     if (VT.isVector())
6571       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6572     if (DoXform) {
6573       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6574       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6575                                        LN0->getChain(),
6576                                        LN0->getBasePtr(), N0.getValueType(),
6577                                        LN0->getMemOperand());
6578       CombineTo(N, ExtLoad);
6579       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6580                                   N0.getValueType(), ExtLoad);
6581       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6582 
6583       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6584                       ISD::ZERO_EXTEND);
6585       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6586     }
6587   }
6588 
6589   // fold (zext (load x)) to multiple smaller zextloads.
6590   // Only on illegal but splittable vectors.
6591   if (SDValue ExtLoad = CombineExtLoad(N))
6592     return ExtLoad;
6593 
6594   // fold (zext (and/or/xor (load x), cst)) ->
6595   //      (and/or/xor (zextload x), (zext cst))
6596   // Unless (and (load x) cst) will match as a zextload already and has
6597   // additional users.
6598   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6599        N0.getOpcode() == ISD::XOR) &&
6600       isa<LoadSDNode>(N0.getOperand(0)) &&
6601       N0.getOperand(1).getOpcode() == ISD::Constant &&
6602       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6603       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6604     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6605     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6606       bool DoXform = true;
6607       SmallVector<SDNode*, 4> SetCCs;
6608       if (!N0.hasOneUse()) {
6609         if (N0.getOpcode() == ISD::AND) {
6610           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6611           auto NarrowLoad = false;
6612           EVT LoadResultTy = AndC->getValueType(0);
6613           EVT ExtVT, LoadedVT;
6614           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6615                                NarrowLoad))
6616             DoXform = false;
6617         }
6618         if (DoXform)
6619           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6620                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6621       }
6622       if (DoXform) {
6623         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6624                                          LN0->getChain(), LN0->getBasePtr(),
6625                                          LN0->getMemoryVT(),
6626                                          LN0->getMemOperand());
6627         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6628         Mask = Mask.zext(VT.getSizeInBits());
6629         SDLoc DL(N);
6630         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6631                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6632         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6633                                     SDLoc(N0.getOperand(0)),
6634                                     N0.getOperand(0).getValueType(), ExtLoad);
6635         CombineTo(N, And);
6636         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6637         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6638                         ISD::ZERO_EXTEND);
6639         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6640       }
6641     }
6642   }
6643 
6644   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6645   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6646   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6647       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6648     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6649     EVT MemVT = LN0->getMemoryVT();
6650     if ((!LegalOperations && !LN0->isVolatile()) ||
6651         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6652       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6653                                        LN0->getChain(),
6654                                        LN0->getBasePtr(), MemVT,
6655                                        LN0->getMemOperand());
6656       CombineTo(N, ExtLoad);
6657       CombineTo(N0.getNode(),
6658                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6659                             ExtLoad),
6660                 ExtLoad.getValue(1));
6661       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6662     }
6663   }
6664 
6665   if (N0.getOpcode() == ISD::SETCC) {
6666     // Only do this before legalize for now.
6667     if (!LegalOperations && VT.isVector() &&
6668         N0.getValueType().getVectorElementType() == MVT::i1) {
6669       EVT N00VT = N0.getOperand(0).getValueType();
6670       if (getSetCCResultType(N00VT) == N0.getValueType())
6671         return SDValue();
6672 
6673       // We know that the # elements of the results is the same as the #
6674       // elements of the compare (and the # elements of the compare result for
6675       // that matter). Check to see that they are the same size. If so, we know
6676       // that the element size of the sext'd result matches the element size of
6677       // the compare operands.
6678       SDLoc DL(N);
6679       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6680       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
6681         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6682         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
6683                                      N0.getOperand(1), N0.getOperand(2));
6684         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
6685       }
6686 
6687       // If the desired elements are smaller or larger than the source
6688       // elements we can use a matching integer vector type and then
6689       // truncate/sign extend.
6690       EVT MatchingElementType = EVT::getIntegerVT(
6691           *DAG.getContext(), N00VT.getScalarSizeInBits());
6692       EVT MatchingVectorType = EVT::getVectorVT(
6693           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
6694       SDValue VsetCC =
6695           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
6696                       N0.getOperand(1), N0.getOperand(2));
6697       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
6698                          VecOnes);
6699     }
6700 
6701     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6702     SDLoc DL(N);
6703     if (SDValue SCC = SimplifySelectCC(
6704             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6705             DAG.getConstant(0, DL, VT),
6706             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6707       return SCC;
6708   }
6709 
6710   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6711   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6712       isa<ConstantSDNode>(N0.getOperand(1)) &&
6713       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6714       N0.hasOneUse()) {
6715     SDValue ShAmt = N0.getOperand(1);
6716     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6717     if (N0.getOpcode() == ISD::SHL) {
6718       SDValue InnerZExt = N0.getOperand(0);
6719       // If the original shl may be shifting out bits, do not perform this
6720       // transformation.
6721       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
6722         InnerZExt.getOperand(0).getValueSizeInBits();
6723       if (ShAmtVal > KnownZeroBits)
6724         return SDValue();
6725     }
6726 
6727     SDLoc DL(N);
6728 
6729     // Ensure that the shift amount is wide enough for the shifted value.
6730     if (VT.getSizeInBits() >= 256)
6731       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6732 
6733     return DAG.getNode(N0.getOpcode(), DL, VT,
6734                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6735                        ShAmt);
6736   }
6737 
6738   return SDValue();
6739 }
6740 
6741 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6742   SDValue N0 = N->getOperand(0);
6743   EVT VT = N->getValueType(0);
6744 
6745   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6746                                               LegalOperations))
6747     return SDValue(Res, 0);
6748 
6749   // fold (aext (aext x)) -> (aext x)
6750   // fold (aext (zext x)) -> (zext x)
6751   // fold (aext (sext x)) -> (sext x)
6752   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6753       N0.getOpcode() == ISD::ZERO_EXTEND ||
6754       N0.getOpcode() == ISD::SIGN_EXTEND)
6755     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6756 
6757   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6758   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6759   if (N0.getOpcode() == ISD::TRUNCATE) {
6760     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6761       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6762       if (NarrowLoad.getNode() != N0.getNode()) {
6763         CombineTo(N0.getNode(), NarrowLoad);
6764         // CombineTo deleted the truncate, if needed, but not what's under it.
6765         AddToWorklist(oye);
6766       }
6767       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6768     }
6769   }
6770 
6771   // fold (aext (truncate x))
6772   if (N0.getOpcode() == ISD::TRUNCATE) {
6773     SDValue TruncOp = N0.getOperand(0);
6774     if (TruncOp.getValueType() == VT)
6775       return TruncOp; // x iff x size == zext size.
6776     if (TruncOp.getValueType().bitsGT(VT))
6777       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6778     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6779   }
6780 
6781   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6782   // if the trunc is not free.
6783   if (N0.getOpcode() == ISD::AND &&
6784       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6785       N0.getOperand(1).getOpcode() == ISD::Constant &&
6786       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6787                           N0.getValueType())) {
6788     SDValue X = N0.getOperand(0).getOperand(0);
6789     if (X.getValueType().bitsLT(VT)) {
6790       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6791     } else if (X.getValueType().bitsGT(VT)) {
6792       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6793     }
6794     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6795     Mask = Mask.zext(VT.getSizeInBits());
6796     SDLoc DL(N);
6797     return DAG.getNode(ISD::AND, DL, VT,
6798                        X, DAG.getConstant(Mask, DL, VT));
6799   }
6800 
6801   // fold (aext (load x)) -> (aext (truncate (extload x)))
6802   // None of the supported targets knows how to perform load and any_ext
6803   // on vectors in one instruction.  We only perform this transformation on
6804   // scalars.
6805   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6806       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6807       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6808     bool DoXform = true;
6809     SmallVector<SDNode*, 4> SetCCs;
6810     if (!N0.hasOneUse())
6811       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6812     if (DoXform) {
6813       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6814       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6815                                        LN0->getChain(),
6816                                        LN0->getBasePtr(), N0.getValueType(),
6817                                        LN0->getMemOperand());
6818       CombineTo(N, ExtLoad);
6819       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6820                                   N0.getValueType(), ExtLoad);
6821       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6822       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6823                       ISD::ANY_EXTEND);
6824       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6825     }
6826   }
6827 
6828   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6829   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6830   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6831   if (N0.getOpcode() == ISD::LOAD &&
6832       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6833       N0.hasOneUse()) {
6834     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6835     ISD::LoadExtType ExtType = LN0->getExtensionType();
6836     EVT MemVT = LN0->getMemoryVT();
6837     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6838       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6839                                        VT, LN0->getChain(), LN0->getBasePtr(),
6840                                        MemVT, LN0->getMemOperand());
6841       CombineTo(N, ExtLoad);
6842       CombineTo(N0.getNode(),
6843                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6844                             N0.getValueType(), ExtLoad),
6845                 ExtLoad.getValue(1));
6846       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6847     }
6848   }
6849 
6850   if (N0.getOpcode() == ISD::SETCC) {
6851     // For vectors:
6852     // aext(setcc) -> vsetcc
6853     // aext(setcc) -> truncate(vsetcc)
6854     // aext(setcc) -> aext(vsetcc)
6855     // Only do this before legalize for now.
6856     if (VT.isVector() && !LegalOperations) {
6857       EVT N0VT = N0.getOperand(0).getValueType();
6858         // We know that the # elements of the results is the same as the
6859         // # elements of the compare (and the # elements of the compare result
6860         // for that matter).  Check to see that they are the same size.  If so,
6861         // we know that the element size of the sext'd result matches the
6862         // element size of the compare operands.
6863       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6864         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6865                              N0.getOperand(1),
6866                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6867       // If the desired elements are smaller or larger than the source
6868       // elements we can use a matching integer vector type and then
6869       // truncate/any extend
6870       else {
6871         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6872         SDValue VsetCC =
6873           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6874                         N0.getOperand(1),
6875                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6876         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6877       }
6878     }
6879 
6880     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6881     SDLoc DL(N);
6882     if (SDValue SCC = SimplifySelectCC(
6883             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6884             DAG.getConstant(0, DL, VT),
6885             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6886       return SCC;
6887   }
6888 
6889   return SDValue();
6890 }
6891 
6892 /// See if the specified operand can be simplified with the knowledge that only
6893 /// the bits specified by Mask are used.  If so, return the simpler operand,
6894 /// otherwise return a null SDValue.
6895 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6896   switch (V.getOpcode()) {
6897   default: break;
6898   case ISD::Constant: {
6899     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6900     assert(CV && "Const value should be ConstSDNode.");
6901     const APInt &CVal = CV->getAPIntValue();
6902     APInt NewVal = CVal & Mask;
6903     if (NewVal != CVal)
6904       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6905     break;
6906   }
6907   case ISD::OR:
6908   case ISD::XOR:
6909     // If the LHS or RHS don't contribute bits to the or, drop them.
6910     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6911       return V.getOperand(1);
6912     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6913       return V.getOperand(0);
6914     break;
6915   case ISD::SRL:
6916     // Only look at single-use SRLs.
6917     if (!V.getNode()->hasOneUse())
6918       break;
6919     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6920       // See if we can recursively simplify the LHS.
6921       unsigned Amt = RHSC->getZExtValue();
6922 
6923       // Watch out for shift count overflow though.
6924       if (Amt >= Mask.getBitWidth()) break;
6925       APInt NewMask = Mask << Amt;
6926       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6927         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6928                            SimplifyLHS, V.getOperand(1));
6929     }
6930   }
6931   return SDValue();
6932 }
6933 
6934 /// If the result of a wider load is shifted to right of N  bits and then
6935 /// truncated to a narrower type and where N is a multiple of number of bits of
6936 /// the narrower type, transform it to a narrower load from address + N / num of
6937 /// bits of new type. If the result is to be extended, also fold the extension
6938 /// to form a extending load.
6939 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6940   unsigned Opc = N->getOpcode();
6941 
6942   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6943   SDValue N0 = N->getOperand(0);
6944   EVT VT = N->getValueType(0);
6945   EVT ExtVT = VT;
6946 
6947   // This transformation isn't valid for vector loads.
6948   if (VT.isVector())
6949     return SDValue();
6950 
6951   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6952   // extended to VT.
6953   if (Opc == ISD::SIGN_EXTEND_INREG) {
6954     ExtType = ISD::SEXTLOAD;
6955     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6956   } else if (Opc == ISD::SRL) {
6957     // Another special-case: SRL is basically zero-extending a narrower value.
6958     ExtType = ISD::ZEXTLOAD;
6959     N0 = SDValue(N, 0);
6960     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6961     if (!N01) return SDValue();
6962     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6963                               VT.getSizeInBits() - N01->getZExtValue());
6964   }
6965   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6966     return SDValue();
6967 
6968   unsigned EVTBits = ExtVT.getSizeInBits();
6969 
6970   // Do not generate loads of non-round integer types since these can
6971   // be expensive (and would be wrong if the type is not byte sized).
6972   if (!ExtVT.isRound())
6973     return SDValue();
6974 
6975   unsigned ShAmt = 0;
6976   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6977     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6978       ShAmt = N01->getZExtValue();
6979       // Is the shift amount a multiple of size of VT?
6980       if ((ShAmt & (EVTBits-1)) == 0) {
6981         N0 = N0.getOperand(0);
6982         // Is the load width a multiple of size of VT?
6983         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
6984           return SDValue();
6985       }
6986 
6987       // At this point, we must have a load or else we can't do the transform.
6988       if (!isa<LoadSDNode>(N0)) return SDValue();
6989 
6990       // Because a SRL must be assumed to *need* to zero-extend the high bits
6991       // (as opposed to anyext the high bits), we can't combine the zextload
6992       // lowering of SRL and an sextload.
6993       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6994         return SDValue();
6995 
6996       // If the shift amount is larger than the input type then we're not
6997       // accessing any of the loaded bytes.  If the load was a zextload/extload
6998       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6999       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7000         return SDValue();
7001     }
7002   }
7003 
7004   // If the load is shifted left (and the result isn't shifted back right),
7005   // we can fold the truncate through the shift.
7006   unsigned ShLeftAmt = 0;
7007   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7008       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7009     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7010       ShLeftAmt = N01->getZExtValue();
7011       N0 = N0.getOperand(0);
7012     }
7013   }
7014 
7015   // If we haven't found a load, we can't narrow it.  Don't transform one with
7016   // multiple uses, this would require adding a new load.
7017   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7018     return SDValue();
7019 
7020   // Don't change the width of a volatile load.
7021   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7022   if (LN0->isVolatile())
7023     return SDValue();
7024 
7025   // Verify that we are actually reducing a load width here.
7026   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7027     return SDValue();
7028 
7029   // For the transform to be legal, the load must produce only two values
7030   // (the value loaded and the chain).  Don't transform a pre-increment
7031   // load, for example, which produces an extra value.  Otherwise the
7032   // transformation is not equivalent, and the downstream logic to replace
7033   // uses gets things wrong.
7034   if (LN0->getNumValues() > 2)
7035     return SDValue();
7036 
7037   // If the load that we're shrinking is an extload and we're not just
7038   // discarding the extension we can't simply shrink the load. Bail.
7039   // TODO: It would be possible to merge the extensions in some cases.
7040   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7041       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7042     return SDValue();
7043 
7044   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7045     return SDValue();
7046 
7047   EVT PtrType = N0.getOperand(1).getValueType();
7048 
7049   if (PtrType == MVT::Untyped || PtrType.isExtended())
7050     // It's not possible to generate a constant of extended or untyped type.
7051     return SDValue();
7052 
7053   // For big endian targets, we need to adjust the offset to the pointer to
7054   // load the correct bytes.
7055   if (DAG.getDataLayout().isBigEndian()) {
7056     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7057     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7058     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7059   }
7060 
7061   uint64_t PtrOff = ShAmt / 8;
7062   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7063   SDLoc DL(LN0);
7064   // The original load itself didn't wrap, so an offset within it doesn't.
7065   SDNodeFlags Flags;
7066   Flags.setNoUnsignedWrap(true);
7067   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7068                                PtrType, LN0->getBasePtr(),
7069                                DAG.getConstant(PtrOff, DL, PtrType),
7070                                &Flags);
7071   AddToWorklist(NewPtr.getNode());
7072 
7073   SDValue Load;
7074   if (ExtType == ISD::NON_EXTLOAD)
7075     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7076                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7077                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7078   else
7079     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7080                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7081                           NewAlign, LN0->getMemOperand()->getFlags(),
7082                           LN0->getAAInfo());
7083 
7084   // Replace the old load's chain with the new load's chain.
7085   WorklistRemover DeadNodes(*this);
7086   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7087 
7088   // Shift the result left, if we've swallowed a left shift.
7089   SDValue Result = Load;
7090   if (ShLeftAmt != 0) {
7091     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7092     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7093       ShImmTy = VT;
7094     // If the shift amount is as large as the result size (but, presumably,
7095     // no larger than the source) then the useful bits of the result are
7096     // zero; we can't simply return the shortened shift, because the result
7097     // of that operation is undefined.
7098     SDLoc DL(N0);
7099     if (ShLeftAmt >= VT.getSizeInBits())
7100       Result = DAG.getConstant(0, DL, VT);
7101     else
7102       Result = DAG.getNode(ISD::SHL, DL, VT,
7103                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7104   }
7105 
7106   // Return the new loaded value.
7107   return Result;
7108 }
7109 
7110 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7111   SDValue N0 = N->getOperand(0);
7112   SDValue N1 = N->getOperand(1);
7113   EVT VT = N->getValueType(0);
7114   EVT EVT = cast<VTSDNode>(N1)->getVT();
7115   unsigned VTBits = VT.getScalarSizeInBits();
7116   unsigned EVTBits = EVT.getScalarSizeInBits();
7117 
7118   if (N0.isUndef())
7119     return DAG.getUNDEF(VT);
7120 
7121   // fold (sext_in_reg c1) -> c1
7122   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7123     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7124 
7125   // If the input is already sign extended, just drop the extension.
7126   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7127     return N0;
7128 
7129   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7130   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7131       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7132     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7133                        N0.getOperand(0), N1);
7134 
7135   // fold (sext_in_reg (sext x)) -> (sext x)
7136   // fold (sext_in_reg (aext x)) -> (sext x)
7137   // if x is small enough.
7138   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7139     SDValue N00 = N0.getOperand(0);
7140     if (N00.getScalarValueSizeInBits() <= EVTBits &&
7141         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7142       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7143   }
7144 
7145   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7146   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7147     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7148 
7149   // fold operands of sext_in_reg based on knowledge that the top bits are not
7150   // demanded.
7151   if (SimplifyDemandedBits(SDValue(N, 0)))
7152     return SDValue(N, 0);
7153 
7154   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7155   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7156   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7157     return NarrowLoad;
7158 
7159   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7160   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7161   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7162   if (N0.getOpcode() == ISD::SRL) {
7163     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7164       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7165         // We can turn this into an SRA iff the input to the SRL is already sign
7166         // extended enough.
7167         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7168         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7169           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7170                              N0.getOperand(0), N0.getOperand(1));
7171       }
7172   }
7173 
7174   // fold (sext_inreg (extload x)) -> (sextload x)
7175   if (ISD::isEXTLoad(N0.getNode()) &&
7176       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7177       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7178       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7179        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7180     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7181     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7182                                      LN0->getChain(),
7183                                      LN0->getBasePtr(), EVT,
7184                                      LN0->getMemOperand());
7185     CombineTo(N, ExtLoad);
7186     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7187     AddToWorklist(ExtLoad.getNode());
7188     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7189   }
7190   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7191   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7192       N0.hasOneUse() &&
7193       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7194       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7195        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7196     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7197     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7198                                      LN0->getChain(),
7199                                      LN0->getBasePtr(), EVT,
7200                                      LN0->getMemOperand());
7201     CombineTo(N, ExtLoad);
7202     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7203     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7204   }
7205 
7206   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7207   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7208     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7209                                            N0.getOperand(1), false))
7210       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7211                          BSwap, N1);
7212   }
7213 
7214   return SDValue();
7215 }
7216 
7217 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7218   SDValue N0 = N->getOperand(0);
7219   EVT VT = N->getValueType(0);
7220 
7221   if (N0.isUndef())
7222     return DAG.getUNDEF(VT);
7223 
7224   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7225                                               LegalOperations))
7226     return SDValue(Res, 0);
7227 
7228   return SDValue();
7229 }
7230 
7231 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7232   SDValue N0 = N->getOperand(0);
7233   EVT VT = N->getValueType(0);
7234 
7235   if (N0.isUndef())
7236     return DAG.getUNDEF(VT);
7237 
7238   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7239                                               LegalOperations))
7240     return SDValue(Res, 0);
7241 
7242   return SDValue();
7243 }
7244 
7245 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7246   SDValue N0 = N->getOperand(0);
7247   EVT VT = N->getValueType(0);
7248   bool isLE = DAG.getDataLayout().isLittleEndian();
7249 
7250   // noop truncate
7251   if (N0.getValueType() == N->getValueType(0))
7252     return N0;
7253   // fold (truncate c1) -> c1
7254   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7255     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7256   // fold (truncate (truncate x)) -> (truncate x)
7257   if (N0.getOpcode() == ISD::TRUNCATE)
7258     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7259   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7260   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7261       N0.getOpcode() == ISD::SIGN_EXTEND ||
7262       N0.getOpcode() == ISD::ANY_EXTEND) {
7263     // if the source is smaller than the dest, we still need an extend.
7264     if (N0.getOperand(0).getValueType().bitsLT(VT))
7265       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7266     // if the source is larger than the dest, than we just need the truncate.
7267     if (N0.getOperand(0).getValueType().bitsGT(VT))
7268       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7269     // if the source and dest are the same type, we can drop both the extend
7270     // and the truncate.
7271     return N0.getOperand(0);
7272   }
7273 
7274   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
7275   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
7276     return SDValue();
7277 
7278   // Fold extract-and-trunc into a narrow extract. For example:
7279   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7280   //   i32 y = TRUNCATE(i64 x)
7281   //        -- becomes --
7282   //   v16i8 b = BITCAST (v2i64 val)
7283   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7284   //
7285   // Note: We only run this optimization after type legalization (which often
7286   // creates this pattern) and before operation legalization after which
7287   // we need to be more careful about the vector instructions that we generate.
7288   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7289       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7290 
7291     EVT VecTy = N0.getOperand(0).getValueType();
7292     EVT ExTy = N0.getValueType();
7293     EVT TrTy = N->getValueType(0);
7294 
7295     unsigned NumElem = VecTy.getVectorNumElements();
7296     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7297 
7298     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7299     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7300 
7301     SDValue EltNo = N0->getOperand(1);
7302     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7303       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7304       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7305       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7306 
7307       SDLoc DL(N);
7308       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7309                          DAG.getBitcast(NVT, N0.getOperand(0)),
7310                          DAG.getConstant(Index, DL, IndexTy));
7311     }
7312   }
7313 
7314   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7315   if (N0.getOpcode() == ISD::SELECT) {
7316     EVT SrcVT = N0.getValueType();
7317     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7318         TLI.isTruncateFree(SrcVT, VT)) {
7319       SDLoc SL(N0);
7320       SDValue Cond = N0.getOperand(0);
7321       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7322       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7323       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7324     }
7325   }
7326 
7327   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
7328   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7329       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7330       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7331     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7332       uint64_t Amt = CAmt->getZExtValue();
7333       unsigned Size = VT.getScalarSizeInBits();
7334 
7335       if (Amt < Size) {
7336         SDLoc SL(N);
7337         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7338 
7339         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7340         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7341                            DAG.getConstant(Amt, SL, AmtVT));
7342       }
7343     }
7344   }
7345 
7346   // Fold a series of buildvector, bitcast, and truncate if possible.
7347   // For example fold
7348   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7349   //   (2xi32 (buildvector x, y)).
7350   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7351       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7352       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7353       N0.getOperand(0).hasOneUse()) {
7354 
7355     SDValue BuildVect = N0.getOperand(0);
7356     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7357     EVT TruncVecEltTy = VT.getVectorElementType();
7358 
7359     // Check that the element types match.
7360     if (BuildVectEltTy == TruncVecEltTy) {
7361       // Now we only need to compute the offset of the truncated elements.
7362       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7363       unsigned TruncVecNumElts = VT.getVectorNumElements();
7364       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7365 
7366       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7367              "Invalid number of elements");
7368 
7369       SmallVector<SDValue, 8> Opnds;
7370       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7371         Opnds.push_back(BuildVect.getOperand(i));
7372 
7373       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7374     }
7375   }
7376 
7377   // See if we can simplify the input to this truncate through knowledge that
7378   // only the low bits are being used.
7379   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7380   // Currently we only perform this optimization on scalars because vectors
7381   // may have different active low bits.
7382   if (!VT.isVector()) {
7383     if (SDValue Shorter =
7384             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7385                                                      VT.getSizeInBits())))
7386       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7387   }
7388   // fold (truncate (load x)) -> (smaller load x)
7389   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7390   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7391     if (SDValue Reduced = ReduceLoadWidth(N))
7392       return Reduced;
7393 
7394     // Handle the case where the load remains an extending load even
7395     // after truncation.
7396     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7397       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7398       if (!LN0->isVolatile() &&
7399           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7400         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7401                                          VT, LN0->getChain(), LN0->getBasePtr(),
7402                                          LN0->getMemoryVT(),
7403                                          LN0->getMemOperand());
7404         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7405         return NewLoad;
7406       }
7407     }
7408   }
7409   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7410   // where ... are all 'undef'.
7411   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7412     SmallVector<EVT, 8> VTs;
7413     SDValue V;
7414     unsigned Idx = 0;
7415     unsigned NumDefs = 0;
7416 
7417     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7418       SDValue X = N0.getOperand(i);
7419       if (!X.isUndef()) {
7420         V = X;
7421         Idx = i;
7422         NumDefs++;
7423       }
7424       // Stop if more than one members are non-undef.
7425       if (NumDefs > 1)
7426         break;
7427       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7428                                      VT.getVectorElementType(),
7429                                      X.getValueType().getVectorNumElements()));
7430     }
7431 
7432     if (NumDefs == 0)
7433       return DAG.getUNDEF(VT);
7434 
7435     if (NumDefs == 1) {
7436       assert(V.getNode() && "The single defined operand is empty!");
7437       SmallVector<SDValue, 8> Opnds;
7438       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7439         if (i != Idx) {
7440           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7441           continue;
7442         }
7443         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7444         AddToWorklist(NV.getNode());
7445         Opnds.push_back(NV);
7446       }
7447       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7448     }
7449   }
7450 
7451   // Fold truncate of a bitcast of a vector to an extract of the low vector
7452   // element.
7453   //
7454   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7455   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7456     SDValue VecSrc = N0.getOperand(0);
7457     EVT SrcVT = VecSrc.getValueType();
7458     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7459         (!LegalOperations ||
7460          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7461       SDLoc SL(N);
7462 
7463       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7464       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7465                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7466     }
7467   }
7468 
7469   // Simplify the operands using demanded-bits information.
7470   if (!VT.isVector() &&
7471       SimplifyDemandedBits(SDValue(N, 0)))
7472     return SDValue(N, 0);
7473 
7474   return SDValue();
7475 }
7476 
7477 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7478   SDValue Elt = N->getOperand(i);
7479   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7480     return Elt.getNode();
7481   return Elt.getOperand(Elt.getResNo()).getNode();
7482 }
7483 
7484 /// build_pair (load, load) -> load
7485 /// if load locations are consecutive.
7486 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7487   assert(N->getOpcode() == ISD::BUILD_PAIR);
7488 
7489   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7490   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7491   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7492       LD1->getAddressSpace() != LD2->getAddressSpace())
7493     return SDValue();
7494   EVT LD1VT = LD1->getValueType(0);
7495   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7496   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7497       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7498     unsigned Align = LD1->getAlignment();
7499     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7500         VT.getTypeForEVT(*DAG.getContext()));
7501 
7502     if (NewAlign <= Align &&
7503         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7504       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
7505                          LD1->getPointerInfo(), Align);
7506   }
7507 
7508   return SDValue();
7509 }
7510 
7511 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7512   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7513   // and Lo parts; on big-endian machines it doesn't.
7514   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7515 }
7516 
7517 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7518                                     const TargetLowering &TLI) {
7519   // If this is not a bitcast to an FP type or if the target doesn't have
7520   // IEEE754-compliant FP logic, we're done.
7521   EVT VT = N->getValueType(0);
7522   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7523     return SDValue();
7524 
7525   // TODO: Use splat values for the constant-checking below and remove this
7526   // restriction.
7527   SDValue N0 = N->getOperand(0);
7528   EVT SourceVT = N0.getValueType();
7529   if (SourceVT.isVector())
7530     return SDValue();
7531 
7532   unsigned FPOpcode;
7533   APInt SignMask;
7534   switch (N0.getOpcode()) {
7535   case ISD::AND:
7536     FPOpcode = ISD::FABS;
7537     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7538     break;
7539   case ISD::XOR:
7540     FPOpcode = ISD::FNEG;
7541     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7542     break;
7543   // TODO: ISD::OR --> ISD::FNABS?
7544   default:
7545     return SDValue();
7546   }
7547 
7548   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7549   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7550   SDValue LogicOp0 = N0.getOperand(0);
7551   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7552   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7553       LogicOp0.getOpcode() == ISD::BITCAST &&
7554       LogicOp0->getOperand(0).getValueType() == VT)
7555     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7556 
7557   return SDValue();
7558 }
7559 
7560 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7561   SDValue N0 = N->getOperand(0);
7562   EVT VT = N->getValueType(0);
7563 
7564   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7565   // Only do this before legalize, since afterward the target may be depending
7566   // on the bitconvert.
7567   // First check to see if this is all constant.
7568   if (!LegalTypes &&
7569       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7570       VT.isVector()) {
7571     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7572 
7573     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7574     assert(!DestEltVT.isVector() &&
7575            "Element type of vector ValueType must not be vector!");
7576     if (isSimple)
7577       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7578   }
7579 
7580   // If the input is a constant, let getNode fold it.
7581   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7582     // If we can't allow illegal operations, we need to check that this is just
7583     // a fp -> int or int -> conversion and that the resulting operation will
7584     // be legal.
7585     if (!LegalOperations ||
7586         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7587          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7588         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7589          TLI.isOperationLegal(ISD::Constant, VT)))
7590       return DAG.getBitcast(VT, N0);
7591   }
7592 
7593   // (conv (conv x, t1), t2) -> (conv x, t2)
7594   if (N0.getOpcode() == ISD::BITCAST)
7595     return DAG.getBitcast(VT, N0.getOperand(0));
7596 
7597   // fold (conv (load x)) -> (load (conv*)x)
7598   // If the resultant load doesn't need a higher alignment than the original!
7599   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7600       // Do not change the width of a volatile load.
7601       !cast<LoadSDNode>(N0)->isVolatile() &&
7602       // Do not remove the cast if the types differ in endian layout.
7603       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7604           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7605       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7606       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7607     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7608     unsigned OrigAlign = LN0->getAlignment();
7609 
7610     bool Fast = false;
7611     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7612                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7613         Fast) {
7614       SDValue Load =
7615           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7616                       LN0->getPointerInfo(), OrigAlign,
7617                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7618       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7619       return Load;
7620     }
7621   }
7622 
7623   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7624     return V;
7625 
7626   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7627   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7628   //
7629   // For ppc_fp128:
7630   // fold (bitcast (fneg x)) ->
7631   //     flipbit = signbit
7632   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7633   //
7634   // fold (bitcast (fabs x)) ->
7635   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7636   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7637   // This often reduces constant pool loads.
7638   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7639        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7640       N0.getNode()->hasOneUse() && VT.isInteger() &&
7641       !VT.isVector() && !N0.getValueType().isVector()) {
7642     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7643     AddToWorklist(NewConv.getNode());
7644 
7645     SDLoc DL(N);
7646     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7647       assert(VT.getSizeInBits() == 128);
7648       SDValue SignBit = DAG.getConstant(
7649           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7650       SDValue FlipBit;
7651       if (N0.getOpcode() == ISD::FNEG) {
7652         FlipBit = SignBit;
7653         AddToWorklist(FlipBit.getNode());
7654       } else {
7655         assert(N0.getOpcode() == ISD::FABS);
7656         SDValue Hi =
7657             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7658                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7659                                               SDLoc(NewConv)));
7660         AddToWorklist(Hi.getNode());
7661         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7662         AddToWorklist(FlipBit.getNode());
7663       }
7664       SDValue FlipBits =
7665           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7666       AddToWorklist(FlipBits.getNode());
7667       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7668     }
7669     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7670     if (N0.getOpcode() == ISD::FNEG)
7671       return DAG.getNode(ISD::XOR, DL, VT,
7672                          NewConv, DAG.getConstant(SignBit, DL, VT));
7673     assert(N0.getOpcode() == ISD::FABS);
7674     return DAG.getNode(ISD::AND, DL, VT,
7675                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7676   }
7677 
7678   // fold (bitconvert (fcopysign cst, x)) ->
7679   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7680   // Note that we don't handle (copysign x, cst) because this can always be
7681   // folded to an fneg or fabs.
7682   //
7683   // For ppc_fp128:
7684   // fold (bitcast (fcopysign cst, x)) ->
7685   //     flipbit = (and (extract_element
7686   //                     (xor (bitcast cst), (bitcast x)), 0),
7687   //                    signbit)
7688   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7689   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7690       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7691       VT.isInteger() && !VT.isVector()) {
7692     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
7693     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7694     if (isTypeLegal(IntXVT)) {
7695       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7696       AddToWorklist(X.getNode());
7697 
7698       // If X has a different width than the result/lhs, sext it or truncate it.
7699       unsigned VTWidth = VT.getSizeInBits();
7700       if (OrigXWidth < VTWidth) {
7701         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7702         AddToWorklist(X.getNode());
7703       } else if (OrigXWidth > VTWidth) {
7704         // To get the sign bit in the right place, we have to shift it right
7705         // before truncating.
7706         SDLoc DL(X);
7707         X = DAG.getNode(ISD::SRL, DL,
7708                         X.getValueType(), X,
7709                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7710                                         X.getValueType()));
7711         AddToWorklist(X.getNode());
7712         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7713         AddToWorklist(X.getNode());
7714       }
7715 
7716       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7717         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7718         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7719         AddToWorklist(Cst.getNode());
7720         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7721         AddToWorklist(X.getNode());
7722         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7723         AddToWorklist(XorResult.getNode());
7724         SDValue XorResult64 = DAG.getNode(
7725             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7726             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7727                                   SDLoc(XorResult)));
7728         AddToWorklist(XorResult64.getNode());
7729         SDValue FlipBit =
7730             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7731                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7732         AddToWorklist(FlipBit.getNode());
7733         SDValue FlipBits =
7734             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7735         AddToWorklist(FlipBits.getNode());
7736         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7737       }
7738       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7739       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7740                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7741       AddToWorklist(X.getNode());
7742 
7743       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7744       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7745                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7746       AddToWorklist(Cst.getNode());
7747 
7748       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7749     }
7750   }
7751 
7752   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7753   if (N0.getOpcode() == ISD::BUILD_PAIR)
7754     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7755       return CombineLD;
7756 
7757   // Remove double bitcasts from shuffles - this is often a legacy of
7758   // XformToShuffleWithZero being used to combine bitmaskings (of
7759   // float vectors bitcast to integer vectors) into shuffles.
7760   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7761   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7762       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7763       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7764       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7765     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7766 
7767     // If operands are a bitcast, peek through if it casts the original VT.
7768     // If operands are a constant, just bitcast back to original VT.
7769     auto PeekThroughBitcast = [&](SDValue Op) {
7770       if (Op.getOpcode() == ISD::BITCAST &&
7771           Op.getOperand(0).getValueType() == VT)
7772         return SDValue(Op.getOperand(0));
7773       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7774           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7775         return DAG.getBitcast(VT, Op);
7776       return SDValue();
7777     };
7778 
7779     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7780     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7781     if (!(SV0 && SV1))
7782       return SDValue();
7783 
7784     int MaskScale =
7785         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7786     SmallVector<int, 8> NewMask;
7787     for (int M : SVN->getMask())
7788       for (int i = 0; i != MaskScale; ++i)
7789         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7790 
7791     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7792     if (!LegalMask) {
7793       std::swap(SV0, SV1);
7794       ShuffleVectorSDNode::commuteMask(NewMask);
7795       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7796     }
7797 
7798     if (LegalMask)
7799       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7800   }
7801 
7802   return SDValue();
7803 }
7804 
7805 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7806   EVT VT = N->getValueType(0);
7807   return CombineConsecutiveLoads(N, VT);
7808 }
7809 
7810 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7811 /// operands. DstEltVT indicates the destination element value type.
7812 SDValue DAGCombiner::
7813 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7814   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7815 
7816   // If this is already the right type, we're done.
7817   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7818 
7819   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7820   unsigned DstBitSize = DstEltVT.getSizeInBits();
7821 
7822   // If this is a conversion of N elements of one type to N elements of another
7823   // type, convert each element.  This handles FP<->INT cases.
7824   if (SrcBitSize == DstBitSize) {
7825     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7826                               BV->getValueType(0).getVectorNumElements());
7827 
7828     // Due to the FP element handling below calling this routine recursively,
7829     // we can end up with a scalar-to-vector node here.
7830     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7831       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7832                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7833 
7834     SmallVector<SDValue, 8> Ops;
7835     for (SDValue Op : BV->op_values()) {
7836       // If the vector element type is not legal, the BUILD_VECTOR operands
7837       // are promoted and implicitly truncated.  Make that explicit here.
7838       if (Op.getValueType() != SrcEltVT)
7839         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7840       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7841       AddToWorklist(Ops.back().getNode());
7842     }
7843     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7844   }
7845 
7846   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7847   // handle annoying details of growing/shrinking FP values, we convert them to
7848   // int first.
7849   if (SrcEltVT.isFloatingPoint()) {
7850     // Convert the input float vector to a int vector where the elements are the
7851     // same sizes.
7852     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7853     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7854     SrcEltVT = IntVT;
7855   }
7856 
7857   // Now we know the input is an integer vector.  If the output is a FP type,
7858   // convert to integer first, then to FP of the right size.
7859   if (DstEltVT.isFloatingPoint()) {
7860     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7861     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7862 
7863     // Next, convert to FP elements of the same size.
7864     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7865   }
7866 
7867   SDLoc DL(BV);
7868 
7869   // Okay, we know the src/dst types are both integers of differing types.
7870   // Handling growing first.
7871   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7872   if (SrcBitSize < DstBitSize) {
7873     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7874 
7875     SmallVector<SDValue, 8> Ops;
7876     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7877          i += NumInputsPerOutput) {
7878       bool isLE = DAG.getDataLayout().isLittleEndian();
7879       APInt NewBits = APInt(DstBitSize, 0);
7880       bool EltIsUndef = true;
7881       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7882         // Shift the previously computed bits over.
7883         NewBits <<= SrcBitSize;
7884         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7885         if (Op.isUndef()) continue;
7886         EltIsUndef = false;
7887 
7888         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7889                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7890       }
7891 
7892       if (EltIsUndef)
7893         Ops.push_back(DAG.getUNDEF(DstEltVT));
7894       else
7895         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7896     }
7897 
7898     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7899     return DAG.getBuildVector(VT, DL, Ops);
7900   }
7901 
7902   // Finally, this must be the case where we are shrinking elements: each input
7903   // turns into multiple outputs.
7904   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7905   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7906                             NumOutputsPerInput*BV->getNumOperands());
7907   SmallVector<SDValue, 8> Ops;
7908 
7909   for (const SDValue &Op : BV->op_values()) {
7910     if (Op.isUndef()) {
7911       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7912       continue;
7913     }
7914 
7915     APInt OpVal = cast<ConstantSDNode>(Op)->
7916                   getAPIntValue().zextOrTrunc(SrcBitSize);
7917 
7918     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7919       APInt ThisVal = OpVal.trunc(DstBitSize);
7920       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7921       OpVal = OpVal.lshr(DstBitSize);
7922     }
7923 
7924     // For big endian targets, swap the order of the pieces of each element.
7925     if (DAG.getDataLayout().isBigEndian())
7926       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7927   }
7928 
7929   return DAG.getBuildVector(VT, DL, Ops);
7930 }
7931 
7932 /// Try to perform FMA combining on a given FADD node.
7933 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7934   SDValue N0 = N->getOperand(0);
7935   SDValue N1 = N->getOperand(1);
7936   EVT VT = N->getValueType(0);
7937   SDLoc SL(N);
7938 
7939   const TargetOptions &Options = DAG.getTarget().Options;
7940   bool AllowFusion =
7941       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7942 
7943   // Floating-point multiply-add with intermediate rounding.
7944   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7945 
7946   // Floating-point multiply-add without intermediate rounding.
7947   bool HasFMA =
7948       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7949       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7950 
7951   // No valid opcode, do not combine.
7952   if (!HasFMAD && !HasFMA)
7953     return SDValue();
7954 
7955   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7956   ;
7957   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7958     return SDValue();
7959 
7960   // Always prefer FMAD to FMA for precision.
7961   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7962   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7963   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7964 
7965   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7966   // prefer to fold the multiply with fewer uses.
7967   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7968       N1.getOpcode() == ISD::FMUL) {
7969     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7970       std::swap(N0, N1);
7971   }
7972 
7973   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7974   if (N0.getOpcode() == ISD::FMUL &&
7975       (Aggressive || N0->hasOneUse())) {
7976     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7977                        N0.getOperand(0), N0.getOperand(1), N1);
7978   }
7979 
7980   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7981   // Note: Commutes FADD operands.
7982   if (N1.getOpcode() == ISD::FMUL &&
7983       (Aggressive || N1->hasOneUse())) {
7984     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7985                        N1.getOperand(0), N1.getOperand(1), N0);
7986   }
7987 
7988   // Look through FP_EXTEND nodes to do more combining.
7989   if (AllowFusion && LookThroughFPExt) {
7990     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7991     if (N0.getOpcode() == ISD::FP_EXTEND) {
7992       SDValue N00 = N0.getOperand(0);
7993       if (N00.getOpcode() == ISD::FMUL)
7994         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7995                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7996                                        N00.getOperand(0)),
7997                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7998                                        N00.getOperand(1)), N1);
7999     }
8000 
8001     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8002     // Note: Commutes FADD operands.
8003     if (N1.getOpcode() == ISD::FP_EXTEND) {
8004       SDValue N10 = N1.getOperand(0);
8005       if (N10.getOpcode() == ISD::FMUL)
8006         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8007                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8008                                        N10.getOperand(0)),
8009                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8010                                        N10.getOperand(1)), N0);
8011     }
8012   }
8013 
8014   // More folding opportunities when target permits.
8015   if ((AllowFusion || HasFMAD)  && Aggressive) {
8016     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8017     if (N0.getOpcode() == PreferredFusedOpcode &&
8018         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8019       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8020                          N0.getOperand(0), N0.getOperand(1),
8021                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8022                                      N0.getOperand(2).getOperand(0),
8023                                      N0.getOperand(2).getOperand(1),
8024                                      N1));
8025     }
8026 
8027     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8028     if (N1->getOpcode() == PreferredFusedOpcode &&
8029         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8030       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8031                          N1.getOperand(0), N1.getOperand(1),
8032                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8033                                      N1.getOperand(2).getOperand(0),
8034                                      N1.getOperand(2).getOperand(1),
8035                                      N0));
8036     }
8037 
8038     if (AllowFusion && LookThroughFPExt) {
8039       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8040       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
8041       auto FoldFAddFMAFPExtFMul = [&] (
8042           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8043         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8044                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8045                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8046                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8047                                        Z));
8048       };
8049       if (N0.getOpcode() == PreferredFusedOpcode) {
8050         SDValue N02 = N0.getOperand(2);
8051         if (N02.getOpcode() == ISD::FP_EXTEND) {
8052           SDValue N020 = N02.getOperand(0);
8053           if (N020.getOpcode() == ISD::FMUL)
8054             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8055                                         N020.getOperand(0), N020.getOperand(1),
8056                                         N1);
8057         }
8058       }
8059 
8060       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8061       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8062       // FIXME: This turns two single-precision and one double-precision
8063       // operation into two double-precision operations, which might not be
8064       // interesting for all targets, especially GPUs.
8065       auto FoldFAddFPExtFMAFMul = [&] (
8066           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8067         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8068                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8069                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8070                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8071                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8072                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8073                                        Z));
8074       };
8075       if (N0.getOpcode() == ISD::FP_EXTEND) {
8076         SDValue N00 = N0.getOperand(0);
8077         if (N00.getOpcode() == PreferredFusedOpcode) {
8078           SDValue N002 = N00.getOperand(2);
8079           if (N002.getOpcode() == ISD::FMUL)
8080             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8081                                         N002.getOperand(0), N002.getOperand(1),
8082                                         N1);
8083         }
8084       }
8085 
8086       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
8087       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
8088       if (N1.getOpcode() == PreferredFusedOpcode) {
8089         SDValue N12 = N1.getOperand(2);
8090         if (N12.getOpcode() == ISD::FP_EXTEND) {
8091           SDValue N120 = N12.getOperand(0);
8092           if (N120.getOpcode() == ISD::FMUL)
8093             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8094                                         N120.getOperand(0), N120.getOperand(1),
8095                                         N0);
8096         }
8097       }
8098 
8099       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8100       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8101       // FIXME: This turns two single-precision and one double-precision
8102       // operation into two double-precision operations, which might not be
8103       // interesting for all targets, especially GPUs.
8104       if (N1.getOpcode() == ISD::FP_EXTEND) {
8105         SDValue N10 = N1.getOperand(0);
8106         if (N10.getOpcode() == PreferredFusedOpcode) {
8107           SDValue N102 = N10.getOperand(2);
8108           if (N102.getOpcode() == ISD::FMUL)
8109             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8110                                         N102.getOperand(0), N102.getOperand(1),
8111                                         N0);
8112         }
8113       }
8114     }
8115   }
8116 
8117   return SDValue();
8118 }
8119 
8120 /// Try to perform FMA combining on a given FSUB node.
8121 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8122   SDValue N0 = N->getOperand(0);
8123   SDValue N1 = N->getOperand(1);
8124   EVT VT = N->getValueType(0);
8125   SDLoc SL(N);
8126 
8127   const TargetOptions &Options = DAG.getTarget().Options;
8128   bool AllowFusion =
8129       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8130 
8131   // Floating-point multiply-add with intermediate rounding.
8132   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8133 
8134   // Floating-point multiply-add without intermediate rounding.
8135   bool HasFMA =
8136       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8137       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8138 
8139   // No valid opcode, do not combine.
8140   if (!HasFMAD && !HasFMA)
8141     return SDValue();
8142 
8143   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8144   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8145     return SDValue();
8146 
8147   // Always prefer FMAD to FMA for precision.
8148   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8149   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8150   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8151 
8152   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8153   if (N0.getOpcode() == ISD::FMUL &&
8154       (Aggressive || N0->hasOneUse())) {
8155     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8156                        N0.getOperand(0), N0.getOperand(1),
8157                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8158   }
8159 
8160   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8161   // Note: Commutes FSUB operands.
8162   if (N1.getOpcode() == ISD::FMUL &&
8163       (Aggressive || N1->hasOneUse()))
8164     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8165                        DAG.getNode(ISD::FNEG, SL, VT,
8166                                    N1.getOperand(0)),
8167                        N1.getOperand(1), N0);
8168 
8169   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8170   if (N0.getOpcode() == ISD::FNEG &&
8171       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8172       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8173     SDValue N00 = N0.getOperand(0).getOperand(0);
8174     SDValue N01 = N0.getOperand(0).getOperand(1);
8175     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8176                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8177                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8178   }
8179 
8180   // Look through FP_EXTEND nodes to do more combining.
8181   if (AllowFusion && LookThroughFPExt) {
8182     // fold (fsub (fpext (fmul x, y)), z)
8183     //   -> (fma (fpext x), (fpext y), (fneg z))
8184     if (N0.getOpcode() == ISD::FP_EXTEND) {
8185       SDValue N00 = N0.getOperand(0);
8186       if (N00.getOpcode() == ISD::FMUL)
8187         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8188                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8189                                        N00.getOperand(0)),
8190                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8191                                        N00.getOperand(1)),
8192                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8193     }
8194 
8195     // fold (fsub x, (fpext (fmul y, z)))
8196     //   -> (fma (fneg (fpext y)), (fpext z), x)
8197     // Note: Commutes FSUB operands.
8198     if (N1.getOpcode() == ISD::FP_EXTEND) {
8199       SDValue N10 = N1.getOperand(0);
8200       if (N10.getOpcode() == ISD::FMUL)
8201         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8202                            DAG.getNode(ISD::FNEG, SL, VT,
8203                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8204                                                    N10.getOperand(0))),
8205                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8206                                        N10.getOperand(1)),
8207                            N0);
8208     }
8209 
8210     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8211     //   -> (fneg (fma (fpext x), (fpext y), z))
8212     // Note: This could be removed with appropriate canonicalization of the
8213     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8214     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8215     // from implementing the canonicalization in visitFSUB.
8216     if (N0.getOpcode() == ISD::FP_EXTEND) {
8217       SDValue N00 = N0.getOperand(0);
8218       if (N00.getOpcode() == ISD::FNEG) {
8219         SDValue N000 = N00.getOperand(0);
8220         if (N000.getOpcode() == ISD::FMUL) {
8221           return DAG.getNode(ISD::FNEG, SL, VT,
8222                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8223                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8224                                                      N000.getOperand(0)),
8225                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8226                                                      N000.getOperand(1)),
8227                                          N1));
8228         }
8229       }
8230     }
8231 
8232     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8233     //   -> (fneg (fma (fpext x)), (fpext y), z)
8234     // Note: This could be removed with appropriate canonicalization of the
8235     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8236     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8237     // from implementing the canonicalization in visitFSUB.
8238     if (N0.getOpcode() == ISD::FNEG) {
8239       SDValue N00 = N0.getOperand(0);
8240       if (N00.getOpcode() == ISD::FP_EXTEND) {
8241         SDValue N000 = N00.getOperand(0);
8242         if (N000.getOpcode() == ISD::FMUL) {
8243           return DAG.getNode(ISD::FNEG, SL, VT,
8244                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8245                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8246                                                      N000.getOperand(0)),
8247                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8248                                                      N000.getOperand(1)),
8249                                          N1));
8250         }
8251       }
8252     }
8253 
8254   }
8255 
8256   // More folding opportunities when target permits.
8257   if ((AllowFusion || HasFMAD) && Aggressive) {
8258     // fold (fsub (fma x, y, (fmul u, v)), z)
8259     //   -> (fma x, y (fma u, v, (fneg z)))
8260     if (N0.getOpcode() == PreferredFusedOpcode &&
8261         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8262       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8263                          N0.getOperand(0), N0.getOperand(1),
8264                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8265                                      N0.getOperand(2).getOperand(0),
8266                                      N0.getOperand(2).getOperand(1),
8267                                      DAG.getNode(ISD::FNEG, SL, VT,
8268                                                  N1)));
8269     }
8270 
8271     // fold (fsub x, (fma y, z, (fmul u, v)))
8272     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8273     if (N1.getOpcode() == PreferredFusedOpcode &&
8274         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8275       SDValue N20 = N1.getOperand(2).getOperand(0);
8276       SDValue N21 = N1.getOperand(2).getOperand(1);
8277       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8278                          DAG.getNode(ISD::FNEG, SL, VT,
8279                                      N1.getOperand(0)),
8280                          N1.getOperand(1),
8281                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8282                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8283 
8284                                      N21, N0));
8285     }
8286 
8287     if (AllowFusion && LookThroughFPExt) {
8288       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8289       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8290       if (N0.getOpcode() == PreferredFusedOpcode) {
8291         SDValue N02 = N0.getOperand(2);
8292         if (N02.getOpcode() == ISD::FP_EXTEND) {
8293           SDValue N020 = N02.getOperand(0);
8294           if (N020.getOpcode() == ISD::FMUL)
8295             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8296                                N0.getOperand(0), N0.getOperand(1),
8297                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8298                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8299                                                        N020.getOperand(0)),
8300                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8301                                                        N020.getOperand(1)),
8302                                            DAG.getNode(ISD::FNEG, SL, VT,
8303                                                        N1)));
8304         }
8305       }
8306 
8307       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8308       //   -> (fma (fpext x), (fpext y),
8309       //           (fma (fpext u), (fpext v), (fneg z)))
8310       // FIXME: This turns two single-precision and one double-precision
8311       // operation into two double-precision operations, which might not be
8312       // interesting for all targets, especially GPUs.
8313       if (N0.getOpcode() == ISD::FP_EXTEND) {
8314         SDValue N00 = N0.getOperand(0);
8315         if (N00.getOpcode() == PreferredFusedOpcode) {
8316           SDValue N002 = N00.getOperand(2);
8317           if (N002.getOpcode() == ISD::FMUL)
8318             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8319                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8320                                            N00.getOperand(0)),
8321                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8322                                            N00.getOperand(1)),
8323                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8324                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8325                                                        N002.getOperand(0)),
8326                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8327                                                        N002.getOperand(1)),
8328                                            DAG.getNode(ISD::FNEG, SL, VT,
8329                                                        N1)));
8330         }
8331       }
8332 
8333       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8334       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8335       if (N1.getOpcode() == PreferredFusedOpcode &&
8336         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8337         SDValue N120 = N1.getOperand(2).getOperand(0);
8338         if (N120.getOpcode() == ISD::FMUL) {
8339           SDValue N1200 = N120.getOperand(0);
8340           SDValue N1201 = N120.getOperand(1);
8341           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8342                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8343                              N1.getOperand(1),
8344                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8345                                          DAG.getNode(ISD::FNEG, SL, VT,
8346                                              DAG.getNode(ISD::FP_EXTEND, SL,
8347                                                          VT, N1200)),
8348                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8349                                                      N1201),
8350                                          N0));
8351         }
8352       }
8353 
8354       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8355       //   -> (fma (fneg (fpext y)), (fpext z),
8356       //           (fma (fneg (fpext u)), (fpext v), x))
8357       // FIXME: This turns two single-precision and one double-precision
8358       // operation into two double-precision operations, which might not be
8359       // interesting for all targets, especially GPUs.
8360       if (N1.getOpcode() == ISD::FP_EXTEND &&
8361         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8362         SDValue N100 = N1.getOperand(0).getOperand(0);
8363         SDValue N101 = N1.getOperand(0).getOperand(1);
8364         SDValue N102 = N1.getOperand(0).getOperand(2);
8365         if (N102.getOpcode() == ISD::FMUL) {
8366           SDValue N1020 = N102.getOperand(0);
8367           SDValue N1021 = N102.getOperand(1);
8368           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8369                              DAG.getNode(ISD::FNEG, SL, VT,
8370                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8371                                                      N100)),
8372                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8373                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8374                                          DAG.getNode(ISD::FNEG, SL, VT,
8375                                              DAG.getNode(ISD::FP_EXTEND, SL,
8376                                                          VT, N1020)),
8377                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8378                                                      N1021),
8379                                          N0));
8380         }
8381       }
8382     }
8383   }
8384 
8385   return SDValue();
8386 }
8387 
8388 /// Try to perform FMA combining on a given FMUL node.
8389 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8390   SDValue N0 = N->getOperand(0);
8391   SDValue N1 = N->getOperand(1);
8392   EVT VT = N->getValueType(0);
8393   SDLoc SL(N);
8394 
8395   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8396 
8397   const TargetOptions &Options = DAG.getTarget().Options;
8398   bool AllowFusion =
8399       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8400 
8401   // Floating-point multiply-add with intermediate rounding.
8402   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8403 
8404   // Floating-point multiply-add without intermediate rounding.
8405   bool HasFMA =
8406       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8407       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8408 
8409   // No valid opcode, do not combine.
8410   if (!HasFMAD && !HasFMA)
8411     return SDValue();
8412 
8413   // Always prefer FMAD to FMA for precision.
8414   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8415   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8416 
8417   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8418   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8419   auto FuseFADD = [&](SDValue X, SDValue Y) {
8420     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8421       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8422       if (XC1 && XC1->isExactlyValue(+1.0))
8423         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8424       if (XC1 && XC1->isExactlyValue(-1.0))
8425         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8426                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8427     }
8428     return SDValue();
8429   };
8430 
8431   if (SDValue FMA = FuseFADD(N0, N1))
8432     return FMA;
8433   if (SDValue FMA = FuseFADD(N1, N0))
8434     return FMA;
8435 
8436   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8437   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8438   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8439   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8440   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8441     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8442       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8443       if (XC0 && XC0->isExactlyValue(+1.0))
8444         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8445                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8446                            Y);
8447       if (XC0 && XC0->isExactlyValue(-1.0))
8448         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8449                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8450                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8451 
8452       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8453       if (XC1 && XC1->isExactlyValue(+1.0))
8454         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8455                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8456       if (XC1 && XC1->isExactlyValue(-1.0))
8457         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8458     }
8459     return SDValue();
8460   };
8461 
8462   if (SDValue FMA = FuseFSUB(N0, N1))
8463     return FMA;
8464   if (SDValue FMA = FuseFSUB(N1, N0))
8465     return FMA;
8466 
8467   return SDValue();
8468 }
8469 
8470 SDValue DAGCombiner::visitFADD(SDNode *N) {
8471   SDValue N0 = N->getOperand(0);
8472   SDValue N1 = N->getOperand(1);
8473   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8474   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8475   EVT VT = N->getValueType(0);
8476   SDLoc DL(N);
8477   const TargetOptions &Options = DAG.getTarget().Options;
8478   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8479 
8480   // fold vector ops
8481   if (VT.isVector())
8482     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8483       return FoldedVOp;
8484 
8485   // fold (fadd c1, c2) -> c1 + c2
8486   if (N0CFP && N1CFP)
8487     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8488 
8489   // canonicalize constant to RHS
8490   if (N0CFP && !N1CFP)
8491     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8492 
8493   // fold (fadd A, (fneg B)) -> (fsub A, B)
8494   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8495       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8496     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8497                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8498 
8499   // fold (fadd (fneg A), B) -> (fsub B, A)
8500   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8501       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8502     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8503                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8504 
8505   // If 'unsafe math' is enabled, fold lots of things.
8506   if (Options.UnsafeFPMath) {
8507     // No FP constant should be created after legalization as Instruction
8508     // Selection pass has a hard time dealing with FP constants.
8509     bool AllowNewConst = (Level < AfterLegalizeDAG);
8510 
8511     // fold (fadd A, 0) -> A
8512     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8513       if (N1C->isZero())
8514         return N0;
8515 
8516     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8517     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8518         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8519       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8520                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8521                                      Flags),
8522                          Flags);
8523 
8524     // If allowed, fold (fadd (fneg x), x) -> 0.0
8525     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8526       return DAG.getConstantFP(0.0, DL, VT);
8527 
8528     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8529     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8530       return DAG.getConstantFP(0.0, DL, VT);
8531 
8532     // We can fold chains of FADD's of the same value into multiplications.
8533     // This transform is not safe in general because we are reducing the number
8534     // of rounding steps.
8535     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8536       if (N0.getOpcode() == ISD::FMUL) {
8537         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8538         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8539 
8540         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8541         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8542           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8543                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8544           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8545         }
8546 
8547         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8548         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8549             N1.getOperand(0) == N1.getOperand(1) &&
8550             N0.getOperand(0) == N1.getOperand(0)) {
8551           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8552                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8553           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8554         }
8555       }
8556 
8557       if (N1.getOpcode() == ISD::FMUL) {
8558         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8559         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8560 
8561         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8562         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8563           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8564                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8565           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8566         }
8567 
8568         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8569         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8570             N0.getOperand(0) == N0.getOperand(1) &&
8571             N1.getOperand(0) == N0.getOperand(0)) {
8572           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8573                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8574           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8575         }
8576       }
8577 
8578       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8579         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8580         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8581         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8582             (N0.getOperand(0) == N1)) {
8583           return DAG.getNode(ISD::FMUL, DL, VT,
8584                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8585         }
8586       }
8587 
8588       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8589         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8590         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8591         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8592             N1.getOperand(0) == N0) {
8593           return DAG.getNode(ISD::FMUL, DL, VT,
8594                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8595         }
8596       }
8597 
8598       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8599       if (AllowNewConst &&
8600           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8601           N0.getOperand(0) == N0.getOperand(1) &&
8602           N1.getOperand(0) == N1.getOperand(1) &&
8603           N0.getOperand(0) == N1.getOperand(0)) {
8604         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8605                            DAG.getConstantFP(4.0, DL, VT), Flags);
8606       }
8607     }
8608   } // enable-unsafe-fp-math
8609 
8610   // FADD -> FMA combines:
8611   if (SDValue Fused = visitFADDForFMACombine(N)) {
8612     AddToWorklist(Fused.getNode());
8613     return Fused;
8614   }
8615   return SDValue();
8616 }
8617 
8618 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8619   SDValue N0 = N->getOperand(0);
8620   SDValue N1 = N->getOperand(1);
8621   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8622   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8623   EVT VT = N->getValueType(0);
8624   SDLoc DL(N);
8625   const TargetOptions &Options = DAG.getTarget().Options;
8626   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8627 
8628   // fold vector ops
8629   if (VT.isVector())
8630     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8631       return FoldedVOp;
8632 
8633   // fold (fsub c1, c2) -> c1-c2
8634   if (N0CFP && N1CFP)
8635     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
8636 
8637   // fold (fsub A, (fneg B)) -> (fadd A, B)
8638   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8639     return DAG.getNode(ISD::FADD, DL, VT, N0,
8640                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8641 
8642   // If 'unsafe math' is enabled, fold lots of things.
8643   if (Options.UnsafeFPMath) {
8644     // (fsub A, 0) -> A
8645     if (N1CFP && N1CFP->isZero())
8646       return N0;
8647 
8648     // (fsub 0, B) -> -B
8649     if (N0CFP && N0CFP->isZero()) {
8650       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8651         return GetNegatedExpression(N1, DAG, LegalOperations);
8652       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8653         return DAG.getNode(ISD::FNEG, DL, VT, N1);
8654     }
8655 
8656     // (fsub x, x) -> 0.0
8657     if (N0 == N1)
8658       return DAG.getConstantFP(0.0f, DL, VT);
8659 
8660     // (fsub x, (fadd x, y)) -> (fneg y)
8661     // (fsub x, (fadd y, x)) -> (fneg y)
8662     if (N1.getOpcode() == ISD::FADD) {
8663       SDValue N10 = N1->getOperand(0);
8664       SDValue N11 = N1->getOperand(1);
8665 
8666       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8667         return GetNegatedExpression(N11, DAG, LegalOperations);
8668 
8669       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8670         return GetNegatedExpression(N10, DAG, LegalOperations);
8671     }
8672   }
8673 
8674   // FSUB -> FMA combines:
8675   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8676     AddToWorklist(Fused.getNode());
8677     return Fused;
8678   }
8679 
8680   return SDValue();
8681 }
8682 
8683 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8684   SDValue N0 = N->getOperand(0);
8685   SDValue N1 = N->getOperand(1);
8686   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8687   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8688   EVT VT = N->getValueType(0);
8689   SDLoc DL(N);
8690   const TargetOptions &Options = DAG.getTarget().Options;
8691   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8692 
8693   // fold vector ops
8694   if (VT.isVector()) {
8695     // This just handles C1 * C2 for vectors. Other vector folds are below.
8696     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8697       return FoldedVOp;
8698   }
8699 
8700   // fold (fmul c1, c2) -> c1*c2
8701   if (N0CFP && N1CFP)
8702     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8703 
8704   // canonicalize constant to RHS
8705   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8706      !isConstantFPBuildVectorOrConstantFP(N1))
8707     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8708 
8709   // fold (fmul A, 1.0) -> A
8710   if (N1CFP && N1CFP->isExactlyValue(1.0))
8711     return N0;
8712 
8713   if (Options.UnsafeFPMath) {
8714     // fold (fmul A, 0) -> 0
8715     if (N1CFP && N1CFP->isZero())
8716       return N1;
8717 
8718     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8719     if (N0.getOpcode() == ISD::FMUL) {
8720       // Fold scalars or any vector constants (not just splats).
8721       // This fold is done in general by InstCombine, but extra fmul insts
8722       // may have been generated during lowering.
8723       SDValue N00 = N0.getOperand(0);
8724       SDValue N01 = N0.getOperand(1);
8725       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8726       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8727       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8728 
8729       // Check 1: Make sure that the first operand of the inner multiply is NOT
8730       // a constant. Otherwise, we may induce infinite looping.
8731       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8732         // Check 2: Make sure that the second operand of the inner multiply and
8733         // the second operand of the outer multiply are constants.
8734         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8735             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8736           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8737           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8738         }
8739       }
8740     }
8741 
8742     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8743     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8744     // during an early run of DAGCombiner can prevent folding with fmuls
8745     // inserted during lowering.
8746     if (N0.getOpcode() == ISD::FADD &&
8747         (N0.getOperand(0) == N0.getOperand(1)) &&
8748         N0.hasOneUse()) {
8749       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8750       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8751       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8752     }
8753   }
8754 
8755   // fold (fmul X, 2.0) -> (fadd X, X)
8756   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8757     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8758 
8759   // fold (fmul X, -1.0) -> (fneg X)
8760   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8761     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8762       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8763 
8764   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8765   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8766     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8767       // Both can be negated for free, check to see if at least one is cheaper
8768       // negated.
8769       if (LHSNeg == 2 || RHSNeg == 2)
8770         return DAG.getNode(ISD::FMUL, DL, VT,
8771                            GetNegatedExpression(N0, DAG, LegalOperations),
8772                            GetNegatedExpression(N1, DAG, LegalOperations),
8773                            Flags);
8774     }
8775   }
8776 
8777   // FMUL -> FMA combines:
8778   if (SDValue Fused = visitFMULForFMACombine(N)) {
8779     AddToWorklist(Fused.getNode());
8780     return Fused;
8781   }
8782 
8783   return SDValue();
8784 }
8785 
8786 SDValue DAGCombiner::visitFMA(SDNode *N) {
8787   SDValue N0 = N->getOperand(0);
8788   SDValue N1 = N->getOperand(1);
8789   SDValue N2 = N->getOperand(2);
8790   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8791   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8792   EVT VT = N->getValueType(0);
8793   SDLoc DL(N);
8794   const TargetOptions &Options = DAG.getTarget().Options;
8795 
8796   // Constant fold FMA.
8797   if (isa<ConstantFPSDNode>(N0) &&
8798       isa<ConstantFPSDNode>(N1) &&
8799       isa<ConstantFPSDNode>(N2)) {
8800     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
8801   }
8802 
8803   if (Options.UnsafeFPMath) {
8804     if (N0CFP && N0CFP->isZero())
8805       return N2;
8806     if (N1CFP && N1CFP->isZero())
8807       return N2;
8808   }
8809   // TODO: The FMA node should have flags that propagate to these nodes.
8810   if (N0CFP && N0CFP->isExactlyValue(1.0))
8811     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8812   if (N1CFP && N1CFP->isExactlyValue(1.0))
8813     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8814 
8815   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8816   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8817      !isConstantFPBuildVectorOrConstantFP(N1))
8818     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8819 
8820   // TODO: FMA nodes should have flags that propagate to the created nodes.
8821   // For now, create a Flags object for use with all unsafe math transforms.
8822   SDNodeFlags Flags;
8823   Flags.setUnsafeAlgebra(true);
8824 
8825   if (Options.UnsafeFPMath) {
8826     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8827     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8828         isConstantFPBuildVectorOrConstantFP(N1) &&
8829         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8830       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8831                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
8832                                      &Flags), &Flags);
8833     }
8834 
8835     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8836     if (N0.getOpcode() == ISD::FMUL &&
8837         isConstantFPBuildVectorOrConstantFP(N1) &&
8838         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8839       return DAG.getNode(ISD::FMA, DL, VT,
8840                          N0.getOperand(0),
8841                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
8842                                      &Flags),
8843                          N2);
8844     }
8845   }
8846 
8847   // (fma x, 1, y) -> (fadd x, y)
8848   // (fma x, -1, y) -> (fadd (fneg x), y)
8849   if (N1CFP) {
8850     if (N1CFP->isExactlyValue(1.0))
8851       // TODO: The FMA node should have flags that propagate to this node.
8852       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
8853 
8854     if (N1CFP->isExactlyValue(-1.0) &&
8855         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8856       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
8857       AddToWorklist(RHSNeg.getNode());
8858       // TODO: The FMA node should have flags that propagate to this node.
8859       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
8860     }
8861   }
8862 
8863   if (Options.UnsafeFPMath) {
8864     // (fma x, c, x) -> (fmul x, (c+1))
8865     if (N1CFP && N0 == N2) {
8866       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8867                          DAG.getNode(ISD::FADD, DL, VT, N1,
8868                                      DAG.getConstantFP(1.0, DL, VT), &Flags),
8869                          &Flags);
8870     }
8871 
8872     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8873     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8874       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8875                          DAG.getNode(ISD::FADD, DL, VT, N1,
8876                                      DAG.getConstantFP(-1.0, DL, VT), &Flags),
8877                          &Flags);
8878     }
8879   }
8880 
8881   return SDValue();
8882 }
8883 
8884 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8885 // reciprocal.
8886 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8887 // Notice that this is not always beneficial. One reason is different target
8888 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8889 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8890 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8891 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8892   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8893   const SDNodeFlags *Flags = N->getFlags();
8894   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8895     return SDValue();
8896 
8897   // Skip if current node is a reciprocal.
8898   SDValue N0 = N->getOperand(0);
8899   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8900   if (N0CFP && N0CFP->isExactlyValue(1.0))
8901     return SDValue();
8902 
8903   // Exit early if the target does not want this transform or if there can't
8904   // possibly be enough uses of the divisor to make the transform worthwhile.
8905   SDValue N1 = N->getOperand(1);
8906   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8907   if (!MinUses || N1->use_size() < MinUses)
8908     return SDValue();
8909 
8910   // Find all FDIV users of the same divisor.
8911   // Use a set because duplicates may be present in the user list.
8912   SetVector<SDNode *> Users;
8913   for (auto *U : N1->uses()) {
8914     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8915       // This division is eligible for optimization only if global unsafe math
8916       // is enabled or if this division allows reciprocal formation.
8917       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8918         Users.insert(U);
8919     }
8920   }
8921 
8922   // Now that we have the actual number of divisor uses, make sure it meets
8923   // the minimum threshold specified by the target.
8924   if (Users.size() < MinUses)
8925     return SDValue();
8926 
8927   EVT VT = N->getValueType(0);
8928   SDLoc DL(N);
8929   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8930   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8931 
8932   // Dividend / Divisor -> Dividend * Reciprocal
8933   for (auto *U : Users) {
8934     SDValue Dividend = U->getOperand(0);
8935     if (Dividend != FPOne) {
8936       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8937                                     Reciprocal, Flags);
8938       CombineTo(U, NewNode);
8939     } else if (U != Reciprocal.getNode()) {
8940       // In the absence of fast-math-flags, this user node is always the
8941       // same node as Reciprocal, but with FMF they may be different nodes.
8942       CombineTo(U, Reciprocal);
8943     }
8944   }
8945   return SDValue(N, 0);  // N was replaced.
8946 }
8947 
8948 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8949   SDValue N0 = N->getOperand(0);
8950   SDValue N1 = N->getOperand(1);
8951   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8952   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8953   EVT VT = N->getValueType(0);
8954   SDLoc DL(N);
8955   const TargetOptions &Options = DAG.getTarget().Options;
8956   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8957 
8958   // fold vector ops
8959   if (VT.isVector())
8960     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8961       return FoldedVOp;
8962 
8963   // fold (fdiv c1, c2) -> c1/c2
8964   if (N0CFP && N1CFP)
8965     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8966 
8967   if (Options.UnsafeFPMath) {
8968     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8969     if (N1CFP) {
8970       // Compute the reciprocal 1.0 / c2.
8971       const APFloat &N1APF = N1CFP->getValueAPF();
8972       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8973       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8974       // Only do the transform if the reciprocal is a legal fp immediate that
8975       // isn't too nasty (eg NaN, denormal, ...).
8976       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8977           (!LegalOperations ||
8978            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8979            // backend)... we should handle this gracefully after Legalize.
8980            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8981            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8982            TLI.isFPImmLegal(Recip, VT)))
8983         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8984                            DAG.getConstantFP(Recip, DL, VT), Flags);
8985     }
8986 
8987     // If this FDIV is part of a reciprocal square root, it may be folded
8988     // into a target-specific square root estimate instruction.
8989     if (N1.getOpcode() == ISD::FSQRT) {
8990       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
8991         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8992       }
8993     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8994                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8995       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8996                                           Flags)) {
8997         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8998         AddToWorklist(RV.getNode());
8999         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9000       }
9001     } else if (N1.getOpcode() == ISD::FP_ROUND &&
9002                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9003       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9004                                           Flags)) {
9005         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9006         AddToWorklist(RV.getNode());
9007         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9008       }
9009     } else if (N1.getOpcode() == ISD::FMUL) {
9010       // Look through an FMUL. Even though this won't remove the FDIV directly,
9011       // it's still worthwhile to get rid of the FSQRT if possible.
9012       SDValue SqrtOp;
9013       SDValue OtherOp;
9014       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9015         SqrtOp = N1.getOperand(0);
9016         OtherOp = N1.getOperand(1);
9017       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
9018         SqrtOp = N1.getOperand(1);
9019         OtherOp = N1.getOperand(0);
9020       }
9021       if (SqrtOp.getNode()) {
9022         // We found a FSQRT, so try to make this fold:
9023         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9024         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9025           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9026           AddToWorklist(RV.getNode());
9027           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9028         }
9029       }
9030     }
9031 
9032     // Fold into a reciprocal estimate and multiply instead of a real divide.
9033     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
9034       AddToWorklist(RV.getNode());
9035       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9036     }
9037   }
9038 
9039   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
9040   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9041     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9042       // Both can be negated for free, check to see if at least one is cheaper
9043       // negated.
9044       if (LHSNeg == 2 || RHSNeg == 2)
9045         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
9046                            GetNegatedExpression(N0, DAG, LegalOperations),
9047                            GetNegatedExpression(N1, DAG, LegalOperations),
9048                            Flags);
9049     }
9050   }
9051 
9052   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
9053     return CombineRepeatedDivisors;
9054 
9055   return SDValue();
9056 }
9057 
9058 SDValue DAGCombiner::visitFREM(SDNode *N) {
9059   SDValue N0 = N->getOperand(0);
9060   SDValue N1 = N->getOperand(1);
9061   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9062   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9063   EVT VT = N->getValueType(0);
9064 
9065   // fold (frem c1, c2) -> fmod(c1,c2)
9066   if (N0CFP && N1CFP)
9067     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
9068                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
9069 
9070   return SDValue();
9071 }
9072 
9073 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
9074   if (!DAG.getTarget().Options.UnsafeFPMath)
9075     return SDValue();
9076 
9077   SDValue N0 = N->getOperand(0);
9078   if (TLI.isFsqrtCheap(N0, DAG))
9079     return SDValue();
9080 
9081   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
9082   // For now, create a Flags object for use with all unsafe math transforms.
9083   SDNodeFlags Flags;
9084   Flags.setUnsafeAlgebra(true);
9085   return buildSqrtEstimate(N0, &Flags);
9086 }
9087 
9088 /// copysign(x, fp_extend(y)) -> copysign(x, y)
9089 /// copysign(x, fp_round(y)) -> copysign(x, y)
9090 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9091   SDValue N1 = N->getOperand(1);
9092   if ((N1.getOpcode() == ISD::FP_EXTEND ||
9093        N1.getOpcode() == ISD::FP_ROUND)) {
9094     // Do not optimize out type conversion of f128 type yet.
9095     // For some targets like x86_64, configuration is changed to keep one f128
9096     // value in one SSE register, but instruction selection cannot handle
9097     // FCOPYSIGN on SSE registers yet.
9098     EVT N1VT = N1->getValueType(0);
9099     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9100     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9101   }
9102   return false;
9103 }
9104 
9105 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9106   SDValue N0 = N->getOperand(0);
9107   SDValue N1 = N->getOperand(1);
9108   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9109   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9110   EVT VT = N->getValueType(0);
9111 
9112   if (N0CFP && N1CFP) // Constant fold
9113     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9114 
9115   if (N1CFP) {
9116     const APFloat &V = N1CFP->getValueAPF();
9117     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
9118     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9119     if (!V.isNegative()) {
9120       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9121         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9122     } else {
9123       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9124         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9125                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9126     }
9127   }
9128 
9129   // copysign(fabs(x), y) -> copysign(x, y)
9130   // copysign(fneg(x), y) -> copysign(x, y)
9131   // copysign(copysign(x,z), y) -> copysign(x, y)
9132   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9133       N0.getOpcode() == ISD::FCOPYSIGN)
9134     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9135 
9136   // copysign(x, abs(y)) -> abs(x)
9137   if (N1.getOpcode() == ISD::FABS)
9138     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9139 
9140   // copysign(x, copysign(y,z)) -> copysign(x, z)
9141   if (N1.getOpcode() == ISD::FCOPYSIGN)
9142     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9143 
9144   // copysign(x, fp_extend(y)) -> copysign(x, y)
9145   // copysign(x, fp_round(y)) -> copysign(x, y)
9146   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9147     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9148 
9149   return SDValue();
9150 }
9151 
9152 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9153   SDValue N0 = N->getOperand(0);
9154   EVT VT = N->getValueType(0);
9155   EVT OpVT = N0.getValueType();
9156 
9157   // fold (sint_to_fp c1) -> c1fp
9158   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9159       // ...but only if the target supports immediate floating-point values
9160       (!LegalOperations ||
9161        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9162     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9163 
9164   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9165   // but UINT_TO_FP is legal on this target, try to convert.
9166   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9167       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9168     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9169     if (DAG.SignBitIsZero(N0))
9170       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9171   }
9172 
9173   // The next optimizations are desirable only if SELECT_CC can be lowered.
9174   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9175     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9176     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9177         !VT.isVector() &&
9178         (!LegalOperations ||
9179          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9180       SDLoc DL(N);
9181       SDValue Ops[] =
9182         { N0.getOperand(0), N0.getOperand(1),
9183           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9184           N0.getOperand(2) };
9185       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9186     }
9187 
9188     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9189     //      (select_cc x, y, 1.0, 0.0,, cc)
9190     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9191         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9192         (!LegalOperations ||
9193          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9194       SDLoc DL(N);
9195       SDValue Ops[] =
9196         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9197           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9198           N0.getOperand(0).getOperand(2) };
9199       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9200     }
9201   }
9202 
9203   return SDValue();
9204 }
9205 
9206 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9207   SDValue N0 = N->getOperand(0);
9208   EVT VT = N->getValueType(0);
9209   EVT OpVT = N0.getValueType();
9210 
9211   // fold (uint_to_fp c1) -> c1fp
9212   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9213       // ...but only if the target supports immediate floating-point values
9214       (!LegalOperations ||
9215        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9216     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9217 
9218   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9219   // but SINT_TO_FP is legal on this target, try to convert.
9220   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9221       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9222     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9223     if (DAG.SignBitIsZero(N0))
9224       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9225   }
9226 
9227   // The next optimizations are desirable only if SELECT_CC can be lowered.
9228   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9229     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9230 
9231     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9232         (!LegalOperations ||
9233          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9234       SDLoc DL(N);
9235       SDValue Ops[] =
9236         { N0.getOperand(0), N0.getOperand(1),
9237           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9238           N0.getOperand(2) };
9239       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9240     }
9241   }
9242 
9243   return SDValue();
9244 }
9245 
9246 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9247 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9248   SDValue N0 = N->getOperand(0);
9249   EVT VT = N->getValueType(0);
9250 
9251   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9252     return SDValue();
9253 
9254   SDValue Src = N0.getOperand(0);
9255   EVT SrcVT = Src.getValueType();
9256   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9257   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9258 
9259   // We can safely assume the conversion won't overflow the output range,
9260   // because (for example) (uint8_t)18293.f is undefined behavior.
9261 
9262   // Since we can assume the conversion won't overflow, our decision as to
9263   // whether the input will fit in the float should depend on the minimum
9264   // of the input range and output range.
9265 
9266   // This means this is also safe for a signed input and unsigned output, since
9267   // a negative input would lead to undefined behavior.
9268   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9269   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9270   unsigned ActualSize = std::min(InputSize, OutputSize);
9271   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9272 
9273   // We can only fold away the float conversion if the input range can be
9274   // represented exactly in the float range.
9275   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9276     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9277       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9278                                                        : ISD::ZERO_EXTEND;
9279       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9280     }
9281     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9282       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9283     return DAG.getBitcast(VT, Src);
9284   }
9285   return SDValue();
9286 }
9287 
9288 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9289   SDValue N0 = N->getOperand(0);
9290   EVT VT = N->getValueType(0);
9291 
9292   // fold (fp_to_sint c1fp) -> c1
9293   if (isConstantFPBuildVectorOrConstantFP(N0))
9294     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9295 
9296   return FoldIntToFPToInt(N, DAG);
9297 }
9298 
9299 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9300   SDValue N0 = N->getOperand(0);
9301   EVT VT = N->getValueType(0);
9302 
9303   // fold (fp_to_uint c1fp) -> c1
9304   if (isConstantFPBuildVectorOrConstantFP(N0))
9305     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9306 
9307   return FoldIntToFPToInt(N, DAG);
9308 }
9309 
9310 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9311   SDValue N0 = N->getOperand(0);
9312   SDValue N1 = N->getOperand(1);
9313   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9314   EVT VT = N->getValueType(0);
9315 
9316   // fold (fp_round c1fp) -> c1fp
9317   if (N0CFP)
9318     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9319 
9320   // fold (fp_round (fp_extend x)) -> x
9321   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9322     return N0.getOperand(0);
9323 
9324   // fold (fp_round (fp_round x)) -> (fp_round x)
9325   if (N0.getOpcode() == ISD::FP_ROUND) {
9326     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9327     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9328 
9329     // Skip this folding if it results in an fp_round from f80 to f16.
9330     //
9331     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9332     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9333     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9334     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9335     // x86.
9336     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9337       return SDValue();
9338 
9339     // If the first fp_round isn't a value preserving truncation, it might
9340     // introduce a tie in the second fp_round, that wouldn't occur in the
9341     // single-step fp_round we want to fold to.
9342     // In other words, double rounding isn't the same as rounding.
9343     // Also, this is a value preserving truncation iff both fp_round's are.
9344     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9345       SDLoc DL(N);
9346       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9347                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9348     }
9349   }
9350 
9351   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9352   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9353     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9354                               N0.getOperand(0), N1);
9355     AddToWorklist(Tmp.getNode());
9356     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9357                        Tmp, N0.getOperand(1));
9358   }
9359 
9360   return SDValue();
9361 }
9362 
9363 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9364   SDValue N0 = N->getOperand(0);
9365   EVT VT = N->getValueType(0);
9366   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9367   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9368 
9369   // fold (fp_round_inreg c1fp) -> c1fp
9370   if (N0CFP && isTypeLegal(EVT)) {
9371     SDLoc DL(N);
9372     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9373     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9374   }
9375 
9376   return SDValue();
9377 }
9378 
9379 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9380   SDValue N0 = N->getOperand(0);
9381   EVT VT = N->getValueType(0);
9382 
9383   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9384   if (N->hasOneUse() &&
9385       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9386     return SDValue();
9387 
9388   // fold (fp_extend c1fp) -> c1fp
9389   if (isConstantFPBuildVectorOrConstantFP(N0))
9390     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9391 
9392   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9393   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9394       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9395     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9396 
9397   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9398   // value of X.
9399   if (N0.getOpcode() == ISD::FP_ROUND
9400       && N0.getNode()->getConstantOperandVal(1) == 1) {
9401     SDValue In = N0.getOperand(0);
9402     if (In.getValueType() == VT) return In;
9403     if (VT.bitsLT(In.getValueType()))
9404       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9405                          In, N0.getOperand(1));
9406     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9407   }
9408 
9409   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9410   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9411        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9412     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9413     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9414                                      LN0->getChain(),
9415                                      LN0->getBasePtr(), N0.getValueType(),
9416                                      LN0->getMemOperand());
9417     CombineTo(N, ExtLoad);
9418     CombineTo(N0.getNode(),
9419               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9420                           N0.getValueType(), ExtLoad,
9421                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9422               ExtLoad.getValue(1));
9423     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9424   }
9425 
9426   return SDValue();
9427 }
9428 
9429 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9430   SDValue N0 = N->getOperand(0);
9431   EVT VT = N->getValueType(0);
9432 
9433   // fold (fceil c1) -> fceil(c1)
9434   if (isConstantFPBuildVectorOrConstantFP(N0))
9435     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9436 
9437   return SDValue();
9438 }
9439 
9440 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9441   SDValue N0 = N->getOperand(0);
9442   EVT VT = N->getValueType(0);
9443 
9444   // fold (ftrunc c1) -> ftrunc(c1)
9445   if (isConstantFPBuildVectorOrConstantFP(N0))
9446     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9447 
9448   return SDValue();
9449 }
9450 
9451 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9452   SDValue N0 = N->getOperand(0);
9453   EVT VT = N->getValueType(0);
9454 
9455   // fold (ffloor c1) -> ffloor(c1)
9456   if (isConstantFPBuildVectorOrConstantFP(N0))
9457     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9458 
9459   return SDValue();
9460 }
9461 
9462 // FIXME: FNEG and FABS have a lot in common; refactor.
9463 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9464   SDValue N0 = N->getOperand(0);
9465   EVT VT = N->getValueType(0);
9466 
9467   // Constant fold FNEG.
9468   if (isConstantFPBuildVectorOrConstantFP(N0))
9469     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9470 
9471   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9472                          &DAG.getTarget().Options))
9473     return GetNegatedExpression(N0, DAG, LegalOperations);
9474 
9475   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9476   // constant pool values.
9477   if (!TLI.isFNegFree(VT) &&
9478       N0.getOpcode() == ISD::BITCAST &&
9479       N0.getNode()->hasOneUse()) {
9480     SDValue Int = N0.getOperand(0);
9481     EVT IntVT = Int.getValueType();
9482     if (IntVT.isInteger() && !IntVT.isVector()) {
9483       APInt SignMask;
9484       if (N0.getValueType().isVector()) {
9485         // For a vector, get a mask such as 0x80... per scalar element
9486         // and splat it.
9487         SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits());
9488         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9489       } else {
9490         // For a scalar, just generate 0x80...
9491         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9492       }
9493       SDLoc DL0(N0);
9494       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9495                         DAG.getConstant(SignMask, DL0, IntVT));
9496       AddToWorklist(Int.getNode());
9497       return DAG.getBitcast(VT, Int);
9498     }
9499   }
9500 
9501   // (fneg (fmul c, x)) -> (fmul -c, x)
9502   if (N0.getOpcode() == ISD::FMUL &&
9503       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9504     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9505     if (CFP1) {
9506       APFloat CVal = CFP1->getValueAPF();
9507       CVal.changeSign();
9508       if (Level >= AfterLegalizeDAG &&
9509           (TLI.isFPImmLegal(CVal, VT) ||
9510            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9511         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9512                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9513                                        N0.getOperand(1)),
9514                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9515     }
9516   }
9517 
9518   return SDValue();
9519 }
9520 
9521 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9522   SDValue N0 = N->getOperand(0);
9523   SDValue N1 = N->getOperand(1);
9524   EVT VT = N->getValueType(0);
9525   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9526   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9527 
9528   if (N0CFP && N1CFP) {
9529     const APFloat &C0 = N0CFP->getValueAPF();
9530     const APFloat &C1 = N1CFP->getValueAPF();
9531     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9532   }
9533 
9534   // Canonicalize to constant on RHS.
9535   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9536      !isConstantFPBuildVectorOrConstantFP(N1))
9537     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9538 
9539   return SDValue();
9540 }
9541 
9542 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9543   SDValue N0 = N->getOperand(0);
9544   SDValue N1 = N->getOperand(1);
9545   EVT VT = N->getValueType(0);
9546   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9547   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9548 
9549   if (N0CFP && N1CFP) {
9550     const APFloat &C0 = N0CFP->getValueAPF();
9551     const APFloat &C1 = N1CFP->getValueAPF();
9552     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9553   }
9554 
9555   // Canonicalize to constant on RHS.
9556   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9557      !isConstantFPBuildVectorOrConstantFP(N1))
9558     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9559 
9560   return SDValue();
9561 }
9562 
9563 SDValue DAGCombiner::visitFABS(SDNode *N) {
9564   SDValue N0 = N->getOperand(0);
9565   EVT VT = N->getValueType(0);
9566 
9567   // fold (fabs c1) -> fabs(c1)
9568   if (isConstantFPBuildVectorOrConstantFP(N0))
9569     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9570 
9571   // fold (fabs (fabs x)) -> (fabs x)
9572   if (N0.getOpcode() == ISD::FABS)
9573     return N->getOperand(0);
9574 
9575   // fold (fabs (fneg x)) -> (fabs x)
9576   // fold (fabs (fcopysign x, y)) -> (fabs x)
9577   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9578     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9579 
9580   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9581   // constant pool values.
9582   if (!TLI.isFAbsFree(VT) &&
9583       N0.getOpcode() == ISD::BITCAST &&
9584       N0.getNode()->hasOneUse()) {
9585     SDValue Int = N0.getOperand(0);
9586     EVT IntVT = Int.getValueType();
9587     if (IntVT.isInteger() && !IntVT.isVector()) {
9588       APInt SignMask;
9589       if (N0.getValueType().isVector()) {
9590         // For a vector, get a mask such as 0x7f... per scalar element
9591         // and splat it.
9592         SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits());
9593         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9594       } else {
9595         // For a scalar, just generate 0x7f...
9596         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9597       }
9598       SDLoc DL(N0);
9599       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9600                         DAG.getConstant(SignMask, DL, IntVT));
9601       AddToWorklist(Int.getNode());
9602       return DAG.getBitcast(N->getValueType(0), Int);
9603     }
9604   }
9605 
9606   return SDValue();
9607 }
9608 
9609 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9610   SDValue Chain = N->getOperand(0);
9611   SDValue N1 = N->getOperand(1);
9612   SDValue N2 = N->getOperand(2);
9613 
9614   // If N is a constant we could fold this into a fallthrough or unconditional
9615   // branch. However that doesn't happen very often in normal code, because
9616   // Instcombine/SimplifyCFG should have handled the available opportunities.
9617   // If we did this folding here, it would be necessary to update the
9618   // MachineBasicBlock CFG, which is awkward.
9619 
9620   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9621   // on the target.
9622   if (N1.getOpcode() == ISD::SETCC &&
9623       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9624                                    N1.getOperand(0).getValueType())) {
9625     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9626                        Chain, N1.getOperand(2),
9627                        N1.getOperand(0), N1.getOperand(1), N2);
9628   }
9629 
9630   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9631       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9632        (N1.getOperand(0).hasOneUse() &&
9633         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9634     SDNode *Trunc = nullptr;
9635     if (N1.getOpcode() == ISD::TRUNCATE) {
9636       // Look pass the truncate.
9637       Trunc = N1.getNode();
9638       N1 = N1.getOperand(0);
9639     }
9640 
9641     // Match this pattern so that we can generate simpler code:
9642     //
9643     //   %a = ...
9644     //   %b = and i32 %a, 2
9645     //   %c = srl i32 %b, 1
9646     //   brcond i32 %c ...
9647     //
9648     // into
9649     //
9650     //   %a = ...
9651     //   %b = and i32 %a, 2
9652     //   %c = setcc eq %b, 0
9653     //   brcond %c ...
9654     //
9655     // This applies only when the AND constant value has one bit set and the
9656     // SRL constant is equal to the log2 of the AND constant. The back-end is
9657     // smart enough to convert the result into a TEST/JMP sequence.
9658     SDValue Op0 = N1.getOperand(0);
9659     SDValue Op1 = N1.getOperand(1);
9660 
9661     if (Op0.getOpcode() == ISD::AND &&
9662         Op1.getOpcode() == ISD::Constant) {
9663       SDValue AndOp1 = Op0.getOperand(1);
9664 
9665       if (AndOp1.getOpcode() == ISD::Constant) {
9666         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9667 
9668         if (AndConst.isPowerOf2() &&
9669             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9670           SDLoc DL(N);
9671           SDValue SetCC =
9672             DAG.getSetCC(DL,
9673                          getSetCCResultType(Op0.getValueType()),
9674                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9675                          ISD::SETNE);
9676 
9677           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9678                                           MVT::Other, Chain, SetCC, N2);
9679           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9680           // will convert it back to (X & C1) >> C2.
9681           CombineTo(N, NewBRCond, false);
9682           // Truncate is dead.
9683           if (Trunc)
9684             deleteAndRecombine(Trunc);
9685           // Replace the uses of SRL with SETCC
9686           WorklistRemover DeadNodes(*this);
9687           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9688           deleteAndRecombine(N1.getNode());
9689           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9690         }
9691       }
9692     }
9693 
9694     if (Trunc)
9695       // Restore N1 if the above transformation doesn't match.
9696       N1 = N->getOperand(1);
9697   }
9698 
9699   // Transform br(xor(x, y)) -> br(x != y)
9700   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9701   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9702     SDNode *TheXor = N1.getNode();
9703     SDValue Op0 = TheXor->getOperand(0);
9704     SDValue Op1 = TheXor->getOperand(1);
9705     if (Op0.getOpcode() == Op1.getOpcode()) {
9706       // Avoid missing important xor optimizations.
9707       if (SDValue Tmp = visitXOR(TheXor)) {
9708         if (Tmp.getNode() != TheXor) {
9709           DEBUG(dbgs() << "\nReplacing.8 ";
9710                 TheXor->dump(&DAG);
9711                 dbgs() << "\nWith: ";
9712                 Tmp.getNode()->dump(&DAG);
9713                 dbgs() << '\n');
9714           WorklistRemover DeadNodes(*this);
9715           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9716           deleteAndRecombine(TheXor);
9717           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9718                              MVT::Other, Chain, Tmp, N2);
9719         }
9720 
9721         // visitXOR has changed XOR's operands or replaced the XOR completely,
9722         // bail out.
9723         return SDValue(N, 0);
9724       }
9725     }
9726 
9727     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9728       bool Equal = false;
9729       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9730           Op0.getOpcode() == ISD::XOR) {
9731         TheXor = Op0.getNode();
9732         Equal = true;
9733       }
9734 
9735       EVT SetCCVT = N1.getValueType();
9736       if (LegalTypes)
9737         SetCCVT = getSetCCResultType(SetCCVT);
9738       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9739                                    SetCCVT,
9740                                    Op0, Op1,
9741                                    Equal ? ISD::SETEQ : ISD::SETNE);
9742       // Replace the uses of XOR with SETCC
9743       WorklistRemover DeadNodes(*this);
9744       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9745       deleteAndRecombine(N1.getNode());
9746       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9747                          MVT::Other, Chain, SetCC, N2);
9748     }
9749   }
9750 
9751   return SDValue();
9752 }
9753 
9754 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9755 //
9756 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9757   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9758   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9759 
9760   // If N is a constant we could fold this into a fallthrough or unconditional
9761   // branch. However that doesn't happen very often in normal code, because
9762   // Instcombine/SimplifyCFG should have handled the available opportunities.
9763   // If we did this folding here, it would be necessary to update the
9764   // MachineBasicBlock CFG, which is awkward.
9765 
9766   // Use SimplifySetCC to simplify SETCC's.
9767   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9768                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9769                                false);
9770   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9771 
9772   // fold to a simpler setcc
9773   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9774     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9775                        N->getOperand(0), Simp.getOperand(2),
9776                        Simp.getOperand(0), Simp.getOperand(1),
9777                        N->getOperand(4));
9778 
9779   return SDValue();
9780 }
9781 
9782 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9783 /// and that N may be folded in the load / store addressing mode.
9784 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9785                                     SelectionDAG &DAG,
9786                                     const TargetLowering &TLI) {
9787   EVT VT;
9788   unsigned AS;
9789 
9790   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9791     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9792       return false;
9793     VT = LD->getMemoryVT();
9794     AS = LD->getAddressSpace();
9795   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9796     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9797       return false;
9798     VT = ST->getMemoryVT();
9799     AS = ST->getAddressSpace();
9800   } else
9801     return false;
9802 
9803   TargetLowering::AddrMode AM;
9804   if (N->getOpcode() == ISD::ADD) {
9805     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9806     if (Offset)
9807       // [reg +/- imm]
9808       AM.BaseOffs = Offset->getSExtValue();
9809     else
9810       // [reg +/- reg]
9811       AM.Scale = 1;
9812   } else if (N->getOpcode() == ISD::SUB) {
9813     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9814     if (Offset)
9815       // [reg +/- imm]
9816       AM.BaseOffs = -Offset->getSExtValue();
9817     else
9818       // [reg +/- reg]
9819       AM.Scale = 1;
9820   } else
9821     return false;
9822 
9823   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9824                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9825 }
9826 
9827 /// Try turning a load/store into a pre-indexed load/store when the base
9828 /// pointer is an add or subtract and it has other uses besides the load/store.
9829 /// After the transformation, the new indexed load/store has effectively folded
9830 /// the add/subtract in and all of its other uses are redirected to the
9831 /// new load/store.
9832 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9833   if (Level < AfterLegalizeDAG)
9834     return false;
9835 
9836   bool isLoad = true;
9837   SDValue Ptr;
9838   EVT VT;
9839   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9840     if (LD->isIndexed())
9841       return false;
9842     VT = LD->getMemoryVT();
9843     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9844         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9845       return false;
9846     Ptr = LD->getBasePtr();
9847   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9848     if (ST->isIndexed())
9849       return false;
9850     VT = ST->getMemoryVT();
9851     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9852         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9853       return false;
9854     Ptr = ST->getBasePtr();
9855     isLoad = false;
9856   } else {
9857     return false;
9858   }
9859 
9860   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9861   // out.  There is no reason to make this a preinc/predec.
9862   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9863       Ptr.getNode()->hasOneUse())
9864     return false;
9865 
9866   // Ask the target to do addressing mode selection.
9867   SDValue BasePtr;
9868   SDValue Offset;
9869   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9870   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9871     return false;
9872 
9873   // Backends without true r+i pre-indexed forms may need to pass a
9874   // constant base with a variable offset so that constant coercion
9875   // will work with the patterns in canonical form.
9876   bool Swapped = false;
9877   if (isa<ConstantSDNode>(BasePtr)) {
9878     std::swap(BasePtr, Offset);
9879     Swapped = true;
9880   }
9881 
9882   // Don't create a indexed load / store with zero offset.
9883   if (isNullConstant(Offset))
9884     return false;
9885 
9886   // Try turning it into a pre-indexed load / store except when:
9887   // 1) The new base ptr is a frame index.
9888   // 2) If N is a store and the new base ptr is either the same as or is a
9889   //    predecessor of the value being stored.
9890   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9891   //    that would create a cycle.
9892   // 4) All uses are load / store ops that use it as old base ptr.
9893 
9894   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9895   // (plus the implicit offset) to a register to preinc anyway.
9896   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9897     return false;
9898 
9899   // Check #2.
9900   if (!isLoad) {
9901     SDValue Val = cast<StoreSDNode>(N)->getValue();
9902     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9903       return false;
9904   }
9905 
9906   // Caches for hasPredecessorHelper.
9907   SmallPtrSet<const SDNode *, 32> Visited;
9908   SmallVector<const SDNode *, 16> Worklist;
9909   Worklist.push_back(N);
9910 
9911   // If the offset is a constant, there may be other adds of constants that
9912   // can be folded with this one. We should do this to avoid having to keep
9913   // a copy of the original base pointer.
9914   SmallVector<SDNode *, 16> OtherUses;
9915   if (isa<ConstantSDNode>(Offset))
9916     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9917                               UE = BasePtr.getNode()->use_end();
9918          UI != UE; ++UI) {
9919       SDUse &Use = UI.getUse();
9920       // Skip the use that is Ptr and uses of other results from BasePtr's
9921       // node (important for nodes that return multiple results).
9922       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9923         continue;
9924 
9925       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9926         continue;
9927 
9928       if (Use.getUser()->getOpcode() != ISD::ADD &&
9929           Use.getUser()->getOpcode() != ISD::SUB) {
9930         OtherUses.clear();
9931         break;
9932       }
9933 
9934       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9935       if (!isa<ConstantSDNode>(Op1)) {
9936         OtherUses.clear();
9937         break;
9938       }
9939 
9940       // FIXME: In some cases, we can be smarter about this.
9941       if (Op1.getValueType() != Offset.getValueType()) {
9942         OtherUses.clear();
9943         break;
9944       }
9945 
9946       OtherUses.push_back(Use.getUser());
9947     }
9948 
9949   if (Swapped)
9950     std::swap(BasePtr, Offset);
9951 
9952   // Now check for #3 and #4.
9953   bool RealUse = false;
9954 
9955   for (SDNode *Use : Ptr.getNode()->uses()) {
9956     if (Use == N)
9957       continue;
9958     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9959       return false;
9960 
9961     // If Ptr may be folded in addressing mode of other use, then it's
9962     // not profitable to do this transformation.
9963     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9964       RealUse = true;
9965   }
9966 
9967   if (!RealUse)
9968     return false;
9969 
9970   SDValue Result;
9971   if (isLoad)
9972     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9973                                 BasePtr, Offset, AM);
9974   else
9975     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9976                                  BasePtr, Offset, AM);
9977   ++PreIndexedNodes;
9978   ++NodesCombined;
9979   DEBUG(dbgs() << "\nReplacing.4 ";
9980         N->dump(&DAG);
9981         dbgs() << "\nWith: ";
9982         Result.getNode()->dump(&DAG);
9983         dbgs() << '\n');
9984   WorklistRemover DeadNodes(*this);
9985   if (isLoad) {
9986     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9987     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9988   } else {
9989     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9990   }
9991 
9992   // Finally, since the node is now dead, remove it from the graph.
9993   deleteAndRecombine(N);
9994 
9995   if (Swapped)
9996     std::swap(BasePtr, Offset);
9997 
9998   // Replace other uses of BasePtr that can be updated to use Ptr
9999   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
10000     unsigned OffsetIdx = 1;
10001     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
10002       OffsetIdx = 0;
10003     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
10004            BasePtr.getNode() && "Expected BasePtr operand");
10005 
10006     // We need to replace ptr0 in the following expression:
10007     //   x0 * offset0 + y0 * ptr0 = t0
10008     // knowing that
10009     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
10010     //
10011     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
10012     // indexed load/store and the expresion that needs to be re-written.
10013     //
10014     // Therefore, we have:
10015     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
10016 
10017     ConstantSDNode *CN =
10018       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
10019     int X0, X1, Y0, Y1;
10020     const APInt &Offset0 = CN->getAPIntValue();
10021     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
10022 
10023     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
10024     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
10025     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
10026     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
10027 
10028     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
10029 
10030     APInt CNV = Offset0;
10031     if (X0 < 0) CNV = -CNV;
10032     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
10033     else CNV = CNV - Offset1;
10034 
10035     SDLoc DL(OtherUses[i]);
10036 
10037     // We can now generate the new expression.
10038     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
10039     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
10040 
10041     SDValue NewUse = DAG.getNode(Opcode,
10042                                  DL,
10043                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
10044     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
10045     deleteAndRecombine(OtherUses[i]);
10046   }
10047 
10048   // Replace the uses of Ptr with uses of the updated base value.
10049   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
10050   deleteAndRecombine(Ptr.getNode());
10051 
10052   return true;
10053 }
10054 
10055 /// Try to combine a load/store with a add/sub of the base pointer node into a
10056 /// post-indexed load/store. The transformation folded the add/subtract into the
10057 /// new indexed load/store effectively and all of its uses are redirected to the
10058 /// new load/store.
10059 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
10060   if (Level < AfterLegalizeDAG)
10061     return false;
10062 
10063   bool isLoad = true;
10064   SDValue Ptr;
10065   EVT VT;
10066   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10067     if (LD->isIndexed())
10068       return false;
10069     VT = LD->getMemoryVT();
10070     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
10071         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
10072       return false;
10073     Ptr = LD->getBasePtr();
10074   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10075     if (ST->isIndexed())
10076       return false;
10077     VT = ST->getMemoryVT();
10078     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
10079         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
10080       return false;
10081     Ptr = ST->getBasePtr();
10082     isLoad = false;
10083   } else {
10084     return false;
10085   }
10086 
10087   if (Ptr.getNode()->hasOneUse())
10088     return false;
10089 
10090   for (SDNode *Op : Ptr.getNode()->uses()) {
10091     if (Op == N ||
10092         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10093       continue;
10094 
10095     SDValue BasePtr;
10096     SDValue Offset;
10097     ISD::MemIndexedMode AM = ISD::UNINDEXED;
10098     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10099       // Don't create a indexed load / store with zero offset.
10100       if (isNullConstant(Offset))
10101         continue;
10102 
10103       // Try turning it into a post-indexed load / store except when
10104       // 1) All uses are load / store ops that use it as base ptr (and
10105       //    it may be folded as addressing mmode).
10106       // 2) Op must be independent of N, i.e. Op is neither a predecessor
10107       //    nor a successor of N. Otherwise, if Op is folded that would
10108       //    create a cycle.
10109 
10110       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10111         continue;
10112 
10113       // Check for #1.
10114       bool TryNext = false;
10115       for (SDNode *Use : BasePtr.getNode()->uses()) {
10116         if (Use == Ptr.getNode())
10117           continue;
10118 
10119         // If all the uses are load / store addresses, then don't do the
10120         // transformation.
10121         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10122           bool RealUse = false;
10123           for (SDNode *UseUse : Use->uses()) {
10124             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10125               RealUse = true;
10126           }
10127 
10128           if (!RealUse) {
10129             TryNext = true;
10130             break;
10131           }
10132         }
10133       }
10134 
10135       if (TryNext)
10136         continue;
10137 
10138       // Check for #2
10139       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10140         SDValue Result = isLoad
10141           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10142                                BasePtr, Offset, AM)
10143           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10144                                 BasePtr, Offset, AM);
10145         ++PostIndexedNodes;
10146         ++NodesCombined;
10147         DEBUG(dbgs() << "\nReplacing.5 ";
10148               N->dump(&DAG);
10149               dbgs() << "\nWith: ";
10150               Result.getNode()->dump(&DAG);
10151               dbgs() << '\n');
10152         WorklistRemover DeadNodes(*this);
10153         if (isLoad) {
10154           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10155           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10156         } else {
10157           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10158         }
10159 
10160         // Finally, since the node is now dead, remove it from the graph.
10161         deleteAndRecombine(N);
10162 
10163         // Replace the uses of Use with uses of the updated base value.
10164         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10165                                       Result.getValue(isLoad ? 1 : 0));
10166         deleteAndRecombine(Op);
10167         return true;
10168       }
10169     }
10170   }
10171 
10172   return false;
10173 }
10174 
10175 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10176 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10177   ISD::MemIndexedMode AM = LD->getAddressingMode();
10178   assert(AM != ISD::UNINDEXED);
10179   SDValue BP = LD->getOperand(1);
10180   SDValue Inc = LD->getOperand(2);
10181 
10182   // Some backends use TargetConstants for load offsets, but don't expect
10183   // TargetConstants in general ADD nodes. We can convert these constants into
10184   // regular Constants (if the constant is not opaque).
10185   assert((Inc.getOpcode() != ISD::TargetConstant ||
10186           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10187          "Cannot split out indexing using opaque target constants");
10188   if (Inc.getOpcode() == ISD::TargetConstant) {
10189     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10190     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10191                           ConstInc->getValueType(0));
10192   }
10193 
10194   unsigned Opc =
10195       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10196   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10197 }
10198 
10199 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10200   LoadSDNode *LD  = cast<LoadSDNode>(N);
10201   SDValue Chain = LD->getChain();
10202   SDValue Ptr   = LD->getBasePtr();
10203 
10204   // If load is not volatile and there are no uses of the loaded value (and
10205   // the updated indexed value in case of indexed loads), change uses of the
10206   // chain value into uses of the chain input (i.e. delete the dead load).
10207   if (!LD->isVolatile()) {
10208     if (N->getValueType(1) == MVT::Other) {
10209       // Unindexed loads.
10210       if (!N->hasAnyUseOfValue(0)) {
10211         // It's not safe to use the two value CombineTo variant here. e.g.
10212         // v1, chain2 = load chain1, loc
10213         // v2, chain3 = load chain2, loc
10214         // v3         = add v2, c
10215         // Now we replace use of chain2 with chain1.  This makes the second load
10216         // isomorphic to the one we are deleting, and thus makes this load live.
10217         DEBUG(dbgs() << "\nReplacing.6 ";
10218               N->dump(&DAG);
10219               dbgs() << "\nWith chain: ";
10220               Chain.getNode()->dump(&DAG);
10221               dbgs() << "\n");
10222         WorklistRemover DeadNodes(*this);
10223         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10224 
10225         if (N->use_empty())
10226           deleteAndRecombine(N);
10227 
10228         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10229       }
10230     } else {
10231       // Indexed loads.
10232       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10233 
10234       // If this load has an opaque TargetConstant offset, then we cannot split
10235       // the indexing into an add/sub directly (that TargetConstant may not be
10236       // valid for a different type of node, and we cannot convert an opaque
10237       // target constant into a regular constant).
10238       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10239                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10240 
10241       if (!N->hasAnyUseOfValue(0) &&
10242           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10243         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10244         SDValue Index;
10245         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10246           Index = SplitIndexingFromLoad(LD);
10247           // Try to fold the base pointer arithmetic into subsequent loads and
10248           // stores.
10249           AddUsersToWorklist(N);
10250         } else
10251           Index = DAG.getUNDEF(N->getValueType(1));
10252         DEBUG(dbgs() << "\nReplacing.7 ";
10253               N->dump(&DAG);
10254               dbgs() << "\nWith: ";
10255               Undef.getNode()->dump(&DAG);
10256               dbgs() << " and 2 other values\n");
10257         WorklistRemover DeadNodes(*this);
10258         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10259         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10260         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10261         deleteAndRecombine(N);
10262         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10263       }
10264     }
10265   }
10266 
10267   // If this load is directly stored, replace the load value with the stored
10268   // value.
10269   // TODO: Handle store large -> read small portion.
10270   // TODO: Handle TRUNCSTORE/LOADEXT
10271   if (OptLevel != CodeGenOpt::None &&
10272       ISD::isNormalLoad(N) && !LD->isVolatile()) {
10273     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10274       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10275       if (PrevST->getBasePtr() == Ptr &&
10276           PrevST->getValue().getValueType() == N->getValueType(0))
10277       return CombineTo(N, Chain.getOperand(1), Chain);
10278     }
10279   }
10280 
10281   // Try to infer better alignment information than the load already has.
10282   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10283     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10284       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10285         SDValue NewLoad = DAG.getExtLoad(
10286             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
10287             LD->getPointerInfo(), LD->getMemoryVT(), Align,
10288             LD->getMemOperand()->getFlags(), LD->getAAInfo());
10289         if (NewLoad.getNode() != N)
10290           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10291       }
10292     }
10293   }
10294 
10295   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10296                                                   : DAG.getSubtarget().useAA();
10297 #ifndef NDEBUG
10298   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10299       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10300     UseAA = false;
10301 #endif
10302   if (UseAA && LD->isUnindexed()) {
10303     // Walk up chain skipping non-aliasing memory nodes.
10304     SDValue BetterChain = FindBetterChain(N, Chain);
10305 
10306     // If there is a better chain.
10307     if (Chain != BetterChain) {
10308       SDValue ReplLoad;
10309 
10310       // Replace the chain to void dependency.
10311       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10312         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10313                                BetterChain, Ptr, LD->getMemOperand());
10314       } else {
10315         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10316                                   LD->getValueType(0),
10317                                   BetterChain, Ptr, LD->getMemoryVT(),
10318                                   LD->getMemOperand());
10319       }
10320 
10321       // Create token factor to keep old chain connected.
10322       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10323                                   MVT::Other, Chain, ReplLoad.getValue(1));
10324 
10325       // Make sure the new and old chains are cleaned up.
10326       AddToWorklist(Token.getNode());
10327 
10328       // Replace uses with load result and token factor. Don't add users
10329       // to work list.
10330       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10331     }
10332   }
10333 
10334   // Try transforming N to an indexed load.
10335   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10336     return SDValue(N, 0);
10337 
10338   // Try to slice up N to more direct loads if the slices are mapped to
10339   // different register banks or pairing can take place.
10340   if (SliceUpLoad(N))
10341     return SDValue(N, 0);
10342 
10343   return SDValue();
10344 }
10345 
10346 namespace {
10347 /// \brief Helper structure used to slice a load in smaller loads.
10348 /// Basically a slice is obtained from the following sequence:
10349 /// Origin = load Ty1, Base
10350 /// Shift = srl Ty1 Origin, CstTy Amount
10351 /// Inst = trunc Shift to Ty2
10352 ///
10353 /// Then, it will be rewriten into:
10354 /// Slice = load SliceTy, Base + SliceOffset
10355 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10356 ///
10357 /// SliceTy is deduced from the number of bits that are actually used to
10358 /// build Inst.
10359 struct LoadedSlice {
10360   /// \brief Helper structure used to compute the cost of a slice.
10361   struct Cost {
10362     /// Are we optimizing for code size.
10363     bool ForCodeSize;
10364     /// Various cost.
10365     unsigned Loads;
10366     unsigned Truncates;
10367     unsigned CrossRegisterBanksCopies;
10368     unsigned ZExts;
10369     unsigned Shift;
10370 
10371     Cost(bool ForCodeSize = false)
10372         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10373           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10374 
10375     /// \brief Get the cost of one isolated slice.
10376     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10377         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10378           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10379       EVT TruncType = LS.Inst->getValueType(0);
10380       EVT LoadedType = LS.getLoadedType();
10381       if (TruncType != LoadedType &&
10382           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10383         ZExts = 1;
10384     }
10385 
10386     /// \brief Account for slicing gain in the current cost.
10387     /// Slicing provide a few gains like removing a shift or a
10388     /// truncate. This method allows to grow the cost of the original
10389     /// load with the gain from this slice.
10390     void addSliceGain(const LoadedSlice &LS) {
10391       // Each slice saves a truncate.
10392       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10393       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10394                               LS.Inst->getValueType(0)))
10395         ++Truncates;
10396       // If there is a shift amount, this slice gets rid of it.
10397       if (LS.Shift)
10398         ++Shift;
10399       // If this slice can merge a cross register bank copy, account for it.
10400       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10401         ++CrossRegisterBanksCopies;
10402     }
10403 
10404     Cost &operator+=(const Cost &RHS) {
10405       Loads += RHS.Loads;
10406       Truncates += RHS.Truncates;
10407       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10408       ZExts += RHS.ZExts;
10409       Shift += RHS.Shift;
10410       return *this;
10411     }
10412 
10413     bool operator==(const Cost &RHS) const {
10414       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10415              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10416              ZExts == RHS.ZExts && Shift == RHS.Shift;
10417     }
10418 
10419     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10420 
10421     bool operator<(const Cost &RHS) const {
10422       // Assume cross register banks copies are as expensive as loads.
10423       // FIXME: Do we want some more target hooks?
10424       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10425       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10426       // Unless we are optimizing for code size, consider the
10427       // expensive operation first.
10428       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10429         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10430       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10431              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10432     }
10433 
10434     bool operator>(const Cost &RHS) const { return RHS < *this; }
10435 
10436     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10437 
10438     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10439   };
10440   // The last instruction that represent the slice. This should be a
10441   // truncate instruction.
10442   SDNode *Inst;
10443   // The original load instruction.
10444   LoadSDNode *Origin;
10445   // The right shift amount in bits from the original load.
10446   unsigned Shift;
10447   // The DAG from which Origin came from.
10448   // This is used to get some contextual information about legal types, etc.
10449   SelectionDAG *DAG;
10450 
10451   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10452               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10453       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10454 
10455   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10456   /// \return Result is \p BitWidth and has used bits set to 1 and
10457   ///         not used bits set to 0.
10458   APInt getUsedBits() const {
10459     // Reproduce the trunc(lshr) sequence:
10460     // - Start from the truncated value.
10461     // - Zero extend to the desired bit width.
10462     // - Shift left.
10463     assert(Origin && "No original load to compare against.");
10464     unsigned BitWidth = Origin->getValueSizeInBits(0);
10465     assert(Inst && "This slice is not bound to an instruction");
10466     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10467            "Extracted slice is bigger than the whole type!");
10468     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10469     UsedBits.setAllBits();
10470     UsedBits = UsedBits.zext(BitWidth);
10471     UsedBits <<= Shift;
10472     return UsedBits;
10473   }
10474 
10475   /// \brief Get the size of the slice to be loaded in bytes.
10476   unsigned getLoadedSize() const {
10477     unsigned SliceSize = getUsedBits().countPopulation();
10478     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10479     return SliceSize / 8;
10480   }
10481 
10482   /// \brief Get the type that will be loaded for this slice.
10483   /// Note: This may not be the final type for the slice.
10484   EVT getLoadedType() const {
10485     assert(DAG && "Missing context");
10486     LLVMContext &Ctxt = *DAG->getContext();
10487     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10488   }
10489 
10490   /// \brief Get the alignment of the load used for this slice.
10491   unsigned getAlignment() const {
10492     unsigned Alignment = Origin->getAlignment();
10493     unsigned Offset = getOffsetFromBase();
10494     if (Offset != 0)
10495       Alignment = MinAlign(Alignment, Alignment + Offset);
10496     return Alignment;
10497   }
10498 
10499   /// \brief Check if this slice can be rewritten with legal operations.
10500   bool isLegal() const {
10501     // An invalid slice is not legal.
10502     if (!Origin || !Inst || !DAG)
10503       return false;
10504 
10505     // Offsets are for indexed load only, we do not handle that.
10506     if (!Origin->getOffset().isUndef())
10507       return false;
10508 
10509     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10510 
10511     // Check that the type is legal.
10512     EVT SliceType = getLoadedType();
10513     if (!TLI.isTypeLegal(SliceType))
10514       return false;
10515 
10516     // Check that the load is legal for this type.
10517     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10518       return false;
10519 
10520     // Check that the offset can be computed.
10521     // 1. Check its type.
10522     EVT PtrType = Origin->getBasePtr().getValueType();
10523     if (PtrType == MVT::Untyped || PtrType.isExtended())
10524       return false;
10525 
10526     // 2. Check that it fits in the immediate.
10527     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10528       return false;
10529 
10530     // 3. Check that the computation is legal.
10531     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10532       return false;
10533 
10534     // Check that the zext is legal if it needs one.
10535     EVT TruncateType = Inst->getValueType(0);
10536     if (TruncateType != SliceType &&
10537         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10538       return false;
10539 
10540     return true;
10541   }
10542 
10543   /// \brief Get the offset in bytes of this slice in the original chunk of
10544   /// bits.
10545   /// \pre DAG != nullptr.
10546   uint64_t getOffsetFromBase() const {
10547     assert(DAG && "Missing context.");
10548     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10549     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10550     uint64_t Offset = Shift / 8;
10551     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10552     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10553            "The size of the original loaded type is not a multiple of a"
10554            " byte.");
10555     // If Offset is bigger than TySizeInBytes, it means we are loading all
10556     // zeros. This should have been optimized before in the process.
10557     assert(TySizeInBytes > Offset &&
10558            "Invalid shift amount for given loaded size");
10559     if (IsBigEndian)
10560       Offset = TySizeInBytes - Offset - getLoadedSize();
10561     return Offset;
10562   }
10563 
10564   /// \brief Generate the sequence of instructions to load the slice
10565   /// represented by this object and redirect the uses of this slice to
10566   /// this new sequence of instructions.
10567   /// \pre this->Inst && this->Origin are valid Instructions and this
10568   /// object passed the legal check: LoadedSlice::isLegal returned true.
10569   /// \return The last instruction of the sequence used to load the slice.
10570   SDValue loadSlice() const {
10571     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10572     const SDValue &OldBaseAddr = Origin->getBasePtr();
10573     SDValue BaseAddr = OldBaseAddr;
10574     // Get the offset in that chunk of bytes w.r.t. the endianess.
10575     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10576     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10577     if (Offset) {
10578       // BaseAddr = BaseAddr + Offset.
10579       EVT ArithType = BaseAddr.getValueType();
10580       SDLoc DL(Origin);
10581       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10582                               DAG->getConstant(Offset, DL, ArithType));
10583     }
10584 
10585     // Create the type of the loaded slice according to its size.
10586     EVT SliceType = getLoadedType();
10587 
10588     // Create the load for the slice.
10589     SDValue LastInst =
10590         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10591                      Origin->getPointerInfo().getWithOffset(Offset),
10592                      getAlignment(), Origin->getMemOperand()->getFlags());
10593     // If the final type is not the same as the loaded type, this means that
10594     // we have to pad with zero. Create a zero extend for that.
10595     EVT FinalType = Inst->getValueType(0);
10596     if (SliceType != FinalType)
10597       LastInst =
10598           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10599     return LastInst;
10600   }
10601 
10602   /// \brief Check if this slice can be merged with an expensive cross register
10603   /// bank copy. E.g.,
10604   /// i = load i32
10605   /// f = bitcast i32 i to float
10606   bool canMergeExpensiveCrossRegisterBankCopy() const {
10607     if (!Inst || !Inst->hasOneUse())
10608       return false;
10609     SDNode *Use = *Inst->use_begin();
10610     if (Use->getOpcode() != ISD::BITCAST)
10611       return false;
10612     assert(DAG && "Missing context");
10613     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10614     EVT ResVT = Use->getValueType(0);
10615     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10616     const TargetRegisterClass *ArgRC =
10617         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10618     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10619       return false;
10620 
10621     // At this point, we know that we perform a cross-register-bank copy.
10622     // Check if it is expensive.
10623     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10624     // Assume bitcasts are cheap, unless both register classes do not
10625     // explicitly share a common sub class.
10626     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10627       return false;
10628 
10629     // Check if it will be merged with the load.
10630     // 1. Check the alignment constraint.
10631     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10632         ResVT.getTypeForEVT(*DAG->getContext()));
10633 
10634     if (RequiredAlignment > getAlignment())
10635       return false;
10636 
10637     // 2. Check that the load is a legal operation for that type.
10638     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10639       return false;
10640 
10641     // 3. Check that we do not have a zext in the way.
10642     if (Inst->getValueType(0) != getLoadedType())
10643       return false;
10644 
10645     return true;
10646   }
10647 };
10648 }
10649 
10650 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10651 /// \p UsedBits looks like 0..0 1..1 0..0.
10652 static bool areUsedBitsDense(const APInt &UsedBits) {
10653   // If all the bits are one, this is dense!
10654   if (UsedBits.isAllOnesValue())
10655     return true;
10656 
10657   // Get rid of the unused bits on the right.
10658   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10659   // Get rid of the unused bits on the left.
10660   if (NarrowedUsedBits.countLeadingZeros())
10661     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10662   // Check that the chunk of bits is completely used.
10663   return NarrowedUsedBits.isAllOnesValue();
10664 }
10665 
10666 /// \brief Check whether or not \p First and \p Second are next to each other
10667 /// in memory. This means that there is no hole between the bits loaded
10668 /// by \p First and the bits loaded by \p Second.
10669 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10670                                      const LoadedSlice &Second) {
10671   assert(First.Origin == Second.Origin && First.Origin &&
10672          "Unable to match different memory origins.");
10673   APInt UsedBits = First.getUsedBits();
10674   assert((UsedBits & Second.getUsedBits()) == 0 &&
10675          "Slices are not supposed to overlap.");
10676   UsedBits |= Second.getUsedBits();
10677   return areUsedBitsDense(UsedBits);
10678 }
10679 
10680 /// \brief Adjust the \p GlobalLSCost according to the target
10681 /// paring capabilities and the layout of the slices.
10682 /// \pre \p GlobalLSCost should account for at least as many loads as
10683 /// there is in the slices in \p LoadedSlices.
10684 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10685                                  LoadedSlice::Cost &GlobalLSCost) {
10686   unsigned NumberOfSlices = LoadedSlices.size();
10687   // If there is less than 2 elements, no pairing is possible.
10688   if (NumberOfSlices < 2)
10689     return;
10690 
10691   // Sort the slices so that elements that are likely to be next to each
10692   // other in memory are next to each other in the list.
10693   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10694             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10695     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10696     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10697   });
10698   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10699   // First (resp. Second) is the first (resp. Second) potentially candidate
10700   // to be placed in a paired load.
10701   const LoadedSlice *First = nullptr;
10702   const LoadedSlice *Second = nullptr;
10703   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10704                 // Set the beginning of the pair.
10705                                                            First = Second) {
10706 
10707     Second = &LoadedSlices[CurrSlice];
10708 
10709     // If First is NULL, it means we start a new pair.
10710     // Get to the next slice.
10711     if (!First)
10712       continue;
10713 
10714     EVT LoadedType = First->getLoadedType();
10715 
10716     // If the types of the slices are different, we cannot pair them.
10717     if (LoadedType != Second->getLoadedType())
10718       continue;
10719 
10720     // Check if the target supplies paired loads for this type.
10721     unsigned RequiredAlignment = 0;
10722     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10723       // move to the next pair, this type is hopeless.
10724       Second = nullptr;
10725       continue;
10726     }
10727     // Check if we meet the alignment requirement.
10728     if (RequiredAlignment > First->getAlignment())
10729       continue;
10730 
10731     // Check that both loads are next to each other in memory.
10732     if (!areSlicesNextToEachOther(*First, *Second))
10733       continue;
10734 
10735     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10736     --GlobalLSCost.Loads;
10737     // Move to the next pair.
10738     Second = nullptr;
10739   }
10740 }
10741 
10742 /// \brief Check the profitability of all involved LoadedSlice.
10743 /// Currently, it is considered profitable if there is exactly two
10744 /// involved slices (1) which are (2) next to each other in memory, and
10745 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10746 ///
10747 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10748 /// the elements themselves.
10749 ///
10750 /// FIXME: When the cost model will be mature enough, we can relax
10751 /// constraints (1) and (2).
10752 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10753                                 const APInt &UsedBits, bool ForCodeSize) {
10754   unsigned NumberOfSlices = LoadedSlices.size();
10755   if (StressLoadSlicing)
10756     return NumberOfSlices > 1;
10757 
10758   // Check (1).
10759   if (NumberOfSlices != 2)
10760     return false;
10761 
10762   // Check (2).
10763   if (!areUsedBitsDense(UsedBits))
10764     return false;
10765 
10766   // Check (3).
10767   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10768   // The original code has one big load.
10769   OrigCost.Loads = 1;
10770   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10771     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10772     // Accumulate the cost of all the slices.
10773     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10774     GlobalSlicingCost += SliceCost;
10775 
10776     // Account as cost in the original configuration the gain obtained
10777     // with the current slices.
10778     OrigCost.addSliceGain(LS);
10779   }
10780 
10781   // If the target supports paired load, adjust the cost accordingly.
10782   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10783   return OrigCost > GlobalSlicingCost;
10784 }
10785 
10786 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10787 /// operations, split it in the various pieces being extracted.
10788 ///
10789 /// This sort of thing is introduced by SROA.
10790 /// This slicing takes care not to insert overlapping loads.
10791 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10792 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10793   if (Level < AfterLegalizeDAG)
10794     return false;
10795 
10796   LoadSDNode *LD = cast<LoadSDNode>(N);
10797   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10798       !LD->getValueType(0).isInteger())
10799     return false;
10800 
10801   // Keep track of already used bits to detect overlapping values.
10802   // In that case, we will just abort the transformation.
10803   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10804 
10805   SmallVector<LoadedSlice, 4> LoadedSlices;
10806 
10807   // Check if this load is used as several smaller chunks of bits.
10808   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10809   // of computation for each trunc.
10810   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10811        UI != UIEnd; ++UI) {
10812     // Skip the uses of the chain.
10813     if (UI.getUse().getResNo() != 0)
10814       continue;
10815 
10816     SDNode *User = *UI;
10817     unsigned Shift = 0;
10818 
10819     // Check if this is a trunc(lshr).
10820     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10821         isa<ConstantSDNode>(User->getOperand(1))) {
10822       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10823       User = *User->use_begin();
10824     }
10825 
10826     // At this point, User is a Truncate, iff we encountered, trunc or
10827     // trunc(lshr).
10828     if (User->getOpcode() != ISD::TRUNCATE)
10829       return false;
10830 
10831     // The width of the type must be a power of 2 and greater than 8-bits.
10832     // Otherwise the load cannot be represented in LLVM IR.
10833     // Moreover, if we shifted with a non-8-bits multiple, the slice
10834     // will be across several bytes. We do not support that.
10835     unsigned Width = User->getValueSizeInBits(0);
10836     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10837       return 0;
10838 
10839     // Build the slice for this chain of computations.
10840     LoadedSlice LS(User, LD, Shift, &DAG);
10841     APInt CurrentUsedBits = LS.getUsedBits();
10842 
10843     // Check if this slice overlaps with another.
10844     if ((CurrentUsedBits & UsedBits) != 0)
10845       return false;
10846     // Update the bits used globally.
10847     UsedBits |= CurrentUsedBits;
10848 
10849     // Check if the new slice would be legal.
10850     if (!LS.isLegal())
10851       return false;
10852 
10853     // Record the slice.
10854     LoadedSlices.push_back(LS);
10855   }
10856 
10857   // Abort slicing if it does not seem to be profitable.
10858   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10859     return false;
10860 
10861   ++SlicedLoads;
10862 
10863   // Rewrite each chain to use an independent load.
10864   // By construction, each chain can be represented by a unique load.
10865 
10866   // Prepare the argument for the new token factor for all the slices.
10867   SmallVector<SDValue, 8> ArgChains;
10868   for (SmallVectorImpl<LoadedSlice>::const_iterator
10869            LSIt = LoadedSlices.begin(),
10870            LSItEnd = LoadedSlices.end();
10871        LSIt != LSItEnd; ++LSIt) {
10872     SDValue SliceInst = LSIt->loadSlice();
10873     CombineTo(LSIt->Inst, SliceInst, true);
10874     if (SliceInst.getOpcode() != ISD::LOAD)
10875       SliceInst = SliceInst.getOperand(0);
10876     assert(SliceInst->getOpcode() == ISD::LOAD &&
10877            "It takes more than a zext to get to the loaded slice!!");
10878     ArgChains.push_back(SliceInst.getValue(1));
10879   }
10880 
10881   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10882                               ArgChains);
10883   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10884   return true;
10885 }
10886 
10887 /// Check to see if V is (and load (ptr), imm), where the load is having
10888 /// specific bytes cleared out.  If so, return the byte size being masked out
10889 /// and the shift amount.
10890 static std::pair<unsigned, unsigned>
10891 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10892   std::pair<unsigned, unsigned> Result(0, 0);
10893 
10894   // Check for the structure we're looking for.
10895   if (V->getOpcode() != ISD::AND ||
10896       !isa<ConstantSDNode>(V->getOperand(1)) ||
10897       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10898     return Result;
10899 
10900   // Check the chain and pointer.
10901   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10902   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10903 
10904   // The store should be chained directly to the load or be an operand of a
10905   // tokenfactor.
10906   if (LD == Chain.getNode())
10907     ; // ok.
10908   else if (Chain->getOpcode() != ISD::TokenFactor)
10909     return Result; // Fail.
10910   else {
10911     bool isOk = false;
10912     for (const SDValue &ChainOp : Chain->op_values())
10913       if (ChainOp.getNode() == LD) {
10914         isOk = true;
10915         break;
10916       }
10917     if (!isOk) return Result;
10918   }
10919 
10920   // This only handles simple types.
10921   if (V.getValueType() != MVT::i16 &&
10922       V.getValueType() != MVT::i32 &&
10923       V.getValueType() != MVT::i64)
10924     return Result;
10925 
10926   // Check the constant mask.  Invert it so that the bits being masked out are
10927   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10928   // follow the sign bit for uniformity.
10929   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10930   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10931   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10932   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10933   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10934   if (NotMaskLZ == 64) return Result;  // All zero mask.
10935 
10936   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10937   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10938     return Result;
10939 
10940   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10941   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10942     NotMaskLZ -= 64-V.getValueSizeInBits();
10943 
10944   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10945   switch (MaskedBytes) {
10946   case 1:
10947   case 2:
10948   case 4: break;
10949   default: return Result; // All one mask, or 5-byte mask.
10950   }
10951 
10952   // Verify that the first bit starts at a multiple of mask so that the access
10953   // is aligned the same as the access width.
10954   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10955 
10956   Result.first = MaskedBytes;
10957   Result.second = NotMaskTZ/8;
10958   return Result;
10959 }
10960 
10961 
10962 /// Check to see if IVal is something that provides a value as specified by
10963 /// MaskInfo. If so, replace the specified store with a narrower store of
10964 /// truncated IVal.
10965 static SDNode *
10966 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10967                                 SDValue IVal, StoreSDNode *St,
10968                                 DAGCombiner *DC) {
10969   unsigned NumBytes = MaskInfo.first;
10970   unsigned ByteShift = MaskInfo.second;
10971   SelectionDAG &DAG = DC->getDAG();
10972 
10973   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10974   // that uses this.  If not, this is not a replacement.
10975   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10976                                   ByteShift*8, (ByteShift+NumBytes)*8);
10977   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10978 
10979   // Check that it is legal on the target to do this.  It is legal if the new
10980   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10981   // legalization.
10982   MVT VT = MVT::getIntegerVT(NumBytes*8);
10983   if (!DC->isTypeLegal(VT))
10984     return nullptr;
10985 
10986   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10987   // shifted by ByteShift and truncated down to NumBytes.
10988   if (ByteShift) {
10989     SDLoc DL(IVal);
10990     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10991                        DAG.getConstant(ByteShift*8, DL,
10992                                     DC->getShiftAmountTy(IVal.getValueType())));
10993   }
10994 
10995   // Figure out the offset for the store and the alignment of the access.
10996   unsigned StOffset;
10997   unsigned NewAlign = St->getAlignment();
10998 
10999   if (DAG.getDataLayout().isLittleEndian())
11000     StOffset = ByteShift;
11001   else
11002     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
11003 
11004   SDValue Ptr = St->getBasePtr();
11005   if (StOffset) {
11006     SDLoc DL(IVal);
11007     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11008                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11009     NewAlign = MinAlign(NewAlign, StOffset);
11010   }
11011 
11012   // Truncate down to the new size.
11013   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
11014 
11015   ++OpsNarrowed;
11016   return DAG
11017       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
11018                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
11019       .getNode();
11020 }
11021 
11022 
11023 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11024 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
11025 /// narrowing the load and store if it would end up being a win for performance
11026 /// or code size.
11027 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
11028   StoreSDNode *ST  = cast<StoreSDNode>(N);
11029   if (ST->isVolatile())
11030     return SDValue();
11031 
11032   SDValue Chain = ST->getChain();
11033   SDValue Value = ST->getValue();
11034   SDValue Ptr   = ST->getBasePtr();
11035   EVT VT = Value.getValueType();
11036 
11037   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
11038     return SDValue();
11039 
11040   unsigned Opc = Value.getOpcode();
11041 
11042   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
11043   // is a byte mask indicating a consecutive number of bytes, check to see if
11044   // Y is known to provide just those bytes.  If so, we try to replace the
11045   // load + replace + store sequence with a single (narrower) store, which makes
11046   // the load dead.
11047   if (Opc == ISD::OR) {
11048     std::pair<unsigned, unsigned> MaskedLoad;
11049     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
11050     if (MaskedLoad.first)
11051       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11052                                                   Value.getOperand(1), ST,this))
11053         return SDValue(NewST, 0);
11054 
11055     // Or is commutative, so try swapping X and Y.
11056     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
11057     if (MaskedLoad.first)
11058       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11059                                                   Value.getOperand(0), ST,this))
11060         return SDValue(NewST, 0);
11061   }
11062 
11063   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
11064       Value.getOperand(1).getOpcode() != ISD::Constant)
11065     return SDValue();
11066 
11067   SDValue N0 = Value.getOperand(0);
11068   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11069       Chain == SDValue(N0.getNode(), 1)) {
11070     LoadSDNode *LD = cast<LoadSDNode>(N0);
11071     if (LD->getBasePtr() != Ptr ||
11072         LD->getPointerInfo().getAddrSpace() !=
11073         ST->getPointerInfo().getAddrSpace())
11074       return SDValue();
11075 
11076     // Find the type to narrow it the load / op / store to.
11077     SDValue N1 = Value.getOperand(1);
11078     unsigned BitWidth = N1.getValueSizeInBits();
11079     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
11080     if (Opc == ISD::AND)
11081       Imm ^= APInt::getAllOnesValue(BitWidth);
11082     if (Imm == 0 || Imm.isAllOnesValue())
11083       return SDValue();
11084     unsigned ShAmt = Imm.countTrailingZeros();
11085     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
11086     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
11087     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11088     // The narrowing should be profitable, the load/store operation should be
11089     // legal (or custom) and the store size should be equal to the NewVT width.
11090     while (NewBW < BitWidth &&
11091            (NewVT.getStoreSizeInBits() != NewBW ||
11092             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11093             !TLI.isNarrowingProfitable(VT, NewVT))) {
11094       NewBW = NextPowerOf2(NewBW);
11095       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11096     }
11097     if (NewBW >= BitWidth)
11098       return SDValue();
11099 
11100     // If the lsb changed does not start at the type bitwidth boundary,
11101     // start at the previous one.
11102     if (ShAmt % NewBW)
11103       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11104     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11105                                    std::min(BitWidth, ShAmt + NewBW));
11106     if ((Imm & Mask) == Imm) {
11107       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11108       if (Opc == ISD::AND)
11109         NewImm ^= APInt::getAllOnesValue(NewBW);
11110       uint64_t PtrOff = ShAmt / 8;
11111       // For big endian targets, we need to adjust the offset to the pointer to
11112       // load the correct bytes.
11113       if (DAG.getDataLayout().isBigEndian())
11114         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11115 
11116       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11117       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11118       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11119         return SDValue();
11120 
11121       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11122                                    Ptr.getValueType(), Ptr,
11123                                    DAG.getConstant(PtrOff, SDLoc(LD),
11124                                                    Ptr.getValueType()));
11125       SDValue NewLD =
11126           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11127                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11128                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
11129       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11130                                    DAG.getConstant(NewImm, SDLoc(Value),
11131                                                    NewVT));
11132       SDValue NewST =
11133           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11134                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11135 
11136       AddToWorklist(NewPtr.getNode());
11137       AddToWorklist(NewLD.getNode());
11138       AddToWorklist(NewVal.getNode());
11139       WorklistRemover DeadNodes(*this);
11140       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11141       ++OpsNarrowed;
11142       return NewST;
11143     }
11144   }
11145 
11146   return SDValue();
11147 }
11148 
11149 /// For a given floating point load / store pair, if the load value isn't used
11150 /// by any other operations, then consider transforming the pair to integer
11151 /// load / store operations if the target deems the transformation profitable.
11152 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11153   StoreSDNode *ST  = cast<StoreSDNode>(N);
11154   SDValue Chain = ST->getChain();
11155   SDValue Value = ST->getValue();
11156   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11157       Value.hasOneUse() &&
11158       Chain == SDValue(Value.getNode(), 1)) {
11159     LoadSDNode *LD = cast<LoadSDNode>(Value);
11160     EVT VT = LD->getMemoryVT();
11161     if (!VT.isFloatingPoint() ||
11162         VT != ST->getMemoryVT() ||
11163         LD->isNonTemporal() ||
11164         ST->isNonTemporal() ||
11165         LD->getPointerInfo().getAddrSpace() != 0 ||
11166         ST->getPointerInfo().getAddrSpace() != 0)
11167       return SDValue();
11168 
11169     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11170     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11171         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11172         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11173         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11174       return SDValue();
11175 
11176     unsigned LDAlign = LD->getAlignment();
11177     unsigned STAlign = ST->getAlignment();
11178     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11179     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11180     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11181       return SDValue();
11182 
11183     SDValue NewLD =
11184         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
11185                     LD->getPointerInfo(), LDAlign);
11186 
11187     SDValue NewST =
11188         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
11189                      ST->getPointerInfo(), STAlign);
11190 
11191     AddToWorklist(NewLD.getNode());
11192     AddToWorklist(NewST.getNode());
11193     WorklistRemover DeadNodes(*this);
11194     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11195     ++LdStFP2Int;
11196     return NewST;
11197   }
11198 
11199   return SDValue();
11200 }
11201 
11202 namespace {
11203 /// Helper struct to parse and store a memory address as base + index + offset.
11204 /// We ignore sign extensions when it is safe to do so.
11205 /// The following two expressions are not equivalent. To differentiate we need
11206 /// to store whether there was a sign extension involved in the index
11207 /// computation.
11208 ///  (load (i64 add (i64 copyfromreg %c)
11209 ///                 (i64 signextend (add (i8 load %index)
11210 ///                                      (i8 1))))
11211 /// vs
11212 ///
11213 /// (load (i64 add (i64 copyfromreg %c)
11214 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11215 ///                                         (i32 1)))))
11216 struct BaseIndexOffset {
11217   SDValue Base;
11218   SDValue Index;
11219   int64_t Offset;
11220   bool IsIndexSignExt;
11221 
11222   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11223 
11224   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11225                   bool IsIndexSignExt) :
11226     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11227 
11228   bool equalBaseIndex(const BaseIndexOffset &Other) {
11229     return Other.Base == Base && Other.Index == Index &&
11230       Other.IsIndexSignExt == IsIndexSignExt;
11231   }
11232 
11233   /// Parses tree in Ptr for base, index, offset addresses.
11234   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11235     bool IsIndexSignExt = false;
11236 
11237     // Split up a folded GlobalAddress+Offset into its component parts.
11238     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11239       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11240         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11241                                                     SDLoc(GA),
11242                                                     GA->getValueType(0),
11243                                                     /*Offset=*/0,
11244                                                     /*isTargetGA=*/false,
11245                                                     GA->getTargetFlags()),
11246                                SDValue(),
11247                                GA->getOffset(),
11248                                IsIndexSignExt);
11249       }
11250 
11251     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11252     // instruction, then it could be just the BASE or everything else we don't
11253     // know how to handle. Just use Ptr as BASE and give up.
11254     if (Ptr->getOpcode() != ISD::ADD)
11255       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11256 
11257     // We know that we have at least an ADD instruction. Try to pattern match
11258     // the simple case of BASE + OFFSET.
11259     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11260       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11261       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11262                               IsIndexSignExt);
11263     }
11264 
11265     // Inside a loop the current BASE pointer is calculated using an ADD and a
11266     // MUL instruction. In this case Ptr is the actual BASE pointer.
11267     // (i64 add (i64 %array_ptr)
11268     //          (i64 mul (i64 %induction_var)
11269     //                   (i64 %element_size)))
11270     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11271       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11272 
11273     // Look at Base + Index + Offset cases.
11274     SDValue Base = Ptr->getOperand(0);
11275     SDValue IndexOffset = Ptr->getOperand(1);
11276 
11277     // Skip signextends.
11278     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11279       IndexOffset = IndexOffset->getOperand(0);
11280       IsIndexSignExt = true;
11281     }
11282 
11283     // Either the case of Base + Index (no offset) or something else.
11284     if (IndexOffset->getOpcode() != ISD::ADD)
11285       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11286 
11287     // Now we have the case of Base + Index + offset.
11288     SDValue Index = IndexOffset->getOperand(0);
11289     SDValue Offset = IndexOffset->getOperand(1);
11290 
11291     if (!isa<ConstantSDNode>(Offset))
11292       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11293 
11294     // Ignore signextends.
11295     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11296       Index = Index->getOperand(0);
11297       IsIndexSignExt = true;
11298     } else IsIndexSignExt = false;
11299 
11300     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11301     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11302   }
11303 };
11304 } // namespace
11305 
11306 // This is a helper function for visitMUL to check the profitability
11307 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11308 // MulNode is the original multiply, AddNode is (add x, c1),
11309 // and ConstNode is c2.
11310 //
11311 // If the (add x, c1) has multiple uses, we could increase
11312 // the number of adds if we make this transformation.
11313 // It would only be worth doing this if we can remove a
11314 // multiply in the process. Check for that here.
11315 // To illustrate:
11316 //     (A + c1) * c3
11317 //     (A + c2) * c3
11318 // We're checking for cases where we have common "c3 * A" expressions.
11319 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11320                                               SDValue &AddNode,
11321                                               SDValue &ConstNode) {
11322   APInt Val;
11323 
11324   // If the add only has one use, this would be OK to do.
11325   if (AddNode.getNode()->hasOneUse())
11326     return true;
11327 
11328   // Walk all the users of the constant with which we're multiplying.
11329   for (SDNode *Use : ConstNode->uses()) {
11330 
11331     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11332       continue;
11333 
11334     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11335       SDNode *OtherOp;
11336       SDNode *MulVar = AddNode.getOperand(0).getNode();
11337 
11338       // OtherOp is what we're multiplying against the constant.
11339       if (Use->getOperand(0) == ConstNode)
11340         OtherOp = Use->getOperand(1).getNode();
11341       else
11342         OtherOp = Use->getOperand(0).getNode();
11343 
11344       // Check to see if multiply is with the same operand of our "add".
11345       //
11346       //     ConstNode  = CONST
11347       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11348       //     ...
11349       //     AddNode  = (A + c1)  <-- MulVar is A.
11350       //         = AddNode * ConstNode   <-- current visiting instruction.
11351       //
11352       // If we make this transformation, we will have a common
11353       // multiply (ConstNode * A) that we can save.
11354       if (OtherOp == MulVar)
11355         return true;
11356 
11357       // Now check to see if a future expansion will give us a common
11358       // multiply.
11359       //
11360       //     ConstNode  = CONST
11361       //     AddNode    = (A + c1)
11362       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11363       //     ...
11364       //     OtherOp = (A + c2)
11365       //     Use     = OtherOp * ConstNode <-- visiting Use.
11366       //
11367       // If we make this transformation, we will have a common
11368       // multiply (CONST * A) after we also do the same transformation
11369       // to the "t2" instruction.
11370       if (OtherOp->getOpcode() == ISD::ADD &&
11371           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11372           OtherOp->getOperand(0).getNode() == MulVar)
11373         return true;
11374     }
11375   }
11376 
11377   // Didn't find a case where this would be profitable.
11378   return false;
11379 }
11380 
11381 SDValue DAGCombiner::getMergedConstantVectorStore(
11382     SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11383     SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11384   SmallVector<SDValue, 8> BuildVector;
11385 
11386   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11387     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11388     Chains.push_back(St->getChain());
11389     BuildVector.push_back(St->getValue());
11390   }
11391 
11392   return DAG.getBuildVector(Ty, SL, BuildVector);
11393 }
11394 
11395 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11396                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11397                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11398   // Make sure we have something to merge.
11399   if (NumStores < 2)
11400     return false;
11401 
11402   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11403   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11404   unsigned LatestNodeUsed = 0;
11405 
11406   for (unsigned i=0; i < NumStores; ++i) {
11407     // Find a chain for the new wide-store operand. Notice that some
11408     // of the store nodes that we found may not be selected for inclusion
11409     // in the wide store. The chain we use needs to be the chain of the
11410     // latest store node which is *used* and replaced by the wide store.
11411     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11412       LatestNodeUsed = i;
11413   }
11414 
11415   SmallVector<SDValue, 8> Chains;
11416 
11417   // The latest Node in the DAG.
11418   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11419   SDLoc DL(StoreNodes[0].MemNode);
11420 
11421   SDValue StoredVal;
11422   if (UseVector) {
11423     bool IsVec = MemVT.isVector();
11424     unsigned Elts = NumStores;
11425     if (IsVec) {
11426       // When merging vector stores, get the total number of elements.
11427       Elts *= MemVT.getVectorNumElements();
11428     }
11429     // Get the type for the merged vector store.
11430     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11431     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11432 
11433     if (IsConstantSrc) {
11434       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11435     } else {
11436       SmallVector<SDValue, 8> Ops;
11437       for (unsigned i = 0; i < NumStores; ++i) {
11438         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11439         SDValue Val = St->getValue();
11440         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11441         if (Val.getValueType() != MemVT)
11442           return false;
11443         Ops.push_back(Val);
11444         Chains.push_back(St->getChain());
11445       }
11446 
11447       // Build the extracted vector elements back into a vector.
11448       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11449                               DL, Ty, Ops);    }
11450   } else {
11451     // We should always use a vector store when merging extracted vector
11452     // elements, so this path implies a store of constants.
11453     assert(IsConstantSrc && "Merged vector elements should use vector store");
11454 
11455     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11456     APInt StoreInt(SizeInBits, 0);
11457 
11458     // Construct a single integer constant which is made of the smaller
11459     // constant inputs.
11460     bool IsLE = DAG.getDataLayout().isLittleEndian();
11461     for (unsigned i = 0; i < NumStores; ++i) {
11462       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11463       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11464       Chains.push_back(St->getChain());
11465 
11466       SDValue Val = St->getValue();
11467       StoreInt <<= ElementSizeBytes * 8;
11468       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11469         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11470       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11471         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11472       } else {
11473         llvm_unreachable("Invalid constant element type");
11474       }
11475     }
11476 
11477     // Create the new Load and Store operations.
11478     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11479     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11480   }
11481 
11482   assert(!Chains.empty());
11483 
11484   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11485   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11486                                   FirstInChain->getBasePtr(),
11487                                   FirstInChain->getPointerInfo(),
11488                                   FirstInChain->getAlignment());
11489 
11490   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11491                                                   : DAG.getSubtarget().useAA();
11492   if (UseAA) {
11493     // Replace all merged stores with the new store.
11494     for (unsigned i = 0; i < NumStores; ++i)
11495       CombineTo(StoreNodes[i].MemNode, NewStore);
11496   } else {
11497     // Replace the last store with the new store.
11498     CombineTo(LatestOp, NewStore);
11499     // Erase all other stores.
11500     for (unsigned i = 0; i < NumStores; ++i) {
11501       if (StoreNodes[i].MemNode == LatestOp)
11502         continue;
11503       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11504       // ReplaceAllUsesWith will replace all uses that existed when it was
11505       // called, but graph optimizations may cause new ones to appear. For
11506       // example, the case in pr14333 looks like
11507       //
11508       //  St's chain -> St -> another store -> X
11509       //
11510       // And the only difference from St to the other store is the chain.
11511       // When we change it's chain to be St's chain they become identical,
11512       // get CSEed and the net result is that X is now a use of St.
11513       // Since we know that St is redundant, just iterate.
11514       while (!St->use_empty())
11515         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11516       deleteAndRecombine(St);
11517     }
11518   }
11519 
11520   return true;
11521 }
11522 
11523 void DAGCombiner::getStoreMergeAndAliasCandidates(
11524     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11525     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11526   // This holds the base pointer, index, and the offset in bytes from the base
11527   // pointer.
11528   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11529 
11530   // We must have a base and an offset.
11531   if (!BasePtr.Base.getNode())
11532     return;
11533 
11534   // Do not handle stores to undef base pointers.
11535   if (BasePtr.Base.isUndef())
11536     return;
11537 
11538   // Walk up the chain and look for nodes with offsets from the same
11539   // base pointer. Stop when reaching an instruction with a different kind
11540   // or instruction which has a different base pointer.
11541   EVT MemVT = St->getMemoryVT();
11542   unsigned Seq = 0;
11543   StoreSDNode *Index = St;
11544 
11545 
11546   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11547                                                   : DAG.getSubtarget().useAA();
11548 
11549   if (UseAA) {
11550     // Look at other users of the same chain. Stores on the same chain do not
11551     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11552     // to be on the same chain, so don't bother looking at adjacent chains.
11553 
11554     SDValue Chain = St->getChain();
11555     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11556       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11557         if (I.getOperandNo() != 0)
11558           continue;
11559 
11560         if (OtherST->isVolatile() || OtherST->isIndexed())
11561           continue;
11562 
11563         if (OtherST->getMemoryVT() != MemVT)
11564           continue;
11565 
11566         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11567 
11568         if (Ptr.equalBaseIndex(BasePtr))
11569           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11570       }
11571     }
11572 
11573     return;
11574   }
11575 
11576   while (Index) {
11577     // If the chain has more than one use, then we can't reorder the mem ops.
11578     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11579       break;
11580 
11581     // Find the base pointer and offset for this memory node.
11582     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11583 
11584     // Check that the base pointer is the same as the original one.
11585     if (!Ptr.equalBaseIndex(BasePtr))
11586       break;
11587 
11588     // The memory operands must not be volatile.
11589     if (Index->isVolatile() || Index->isIndexed())
11590       break;
11591 
11592     // No truncation.
11593     if (Index->isTruncatingStore())
11594       break;
11595 
11596     // The stored memory type must be the same.
11597     if (Index->getMemoryVT() != MemVT)
11598       break;
11599 
11600     // We do not allow under-aligned stores in order to prevent
11601     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11602     // be irrelevant here; what MATTERS is that we not move memory
11603     // operations that potentially overlap past each-other.
11604     if (Index->getAlignment() < MemVT.getStoreSize())
11605       break;
11606 
11607     // We found a potential memory operand to merge.
11608     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11609 
11610     // Find the next memory operand in the chain. If the next operand in the
11611     // chain is a store then move up and continue the scan with the next
11612     // memory operand. If the next operand is a load save it and use alias
11613     // information to check if it interferes with anything.
11614     SDNode *NextInChain = Index->getChain().getNode();
11615     while (1) {
11616       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11617         // We found a store node. Use it for the next iteration.
11618         Index = STn;
11619         break;
11620       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11621         if (Ldn->isVolatile()) {
11622           Index = nullptr;
11623           break;
11624         }
11625 
11626         // Save the load node for later. Continue the scan.
11627         AliasLoadNodes.push_back(Ldn);
11628         NextInChain = Ldn->getChain().getNode();
11629         continue;
11630       } else {
11631         Index = nullptr;
11632         break;
11633       }
11634     }
11635   }
11636 }
11637 
11638 // We need to check that merging these stores does not cause a loop
11639 // in the DAG. Any store candidate may depend on another candidate
11640 // indirectly through its operand (we already consider dependencies
11641 // through the chain). Check in parallel by searching up from
11642 // non-chain operands of candidates.
11643 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11644     SmallVectorImpl<MemOpLink> &StoreNodes) {
11645   SmallPtrSet<const SDNode *, 16> Visited;
11646   SmallVector<const SDNode *, 8> Worklist;
11647   // search ops of store candidates
11648   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11649     SDNode *n = StoreNodes[i].MemNode;
11650     // Potential loops may happen only through non-chain operands
11651     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11652       Worklist.push_back(n->getOperand(j).getNode());
11653   }
11654   // search through DAG. We can stop early if we find a storenode
11655   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11656     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11657       return false;
11658   }
11659   return true;
11660 }
11661 
11662 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11663   if (OptLevel == CodeGenOpt::None)
11664     return false;
11665 
11666   EVT MemVT = St->getMemoryVT();
11667   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11668   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11669       Attribute::NoImplicitFloat);
11670 
11671   // This function cannot currently deal with non-byte-sized memory sizes.
11672   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11673     return false;
11674 
11675   if (!MemVT.isSimple())
11676     return false;
11677 
11678   // Perform an early exit check. Do not bother looking at stored values that
11679   // are not constants, loads, or extracted vector elements.
11680   SDValue StoredVal = St->getValue();
11681   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11682   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11683                        isa<ConstantFPSDNode>(StoredVal);
11684   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11685                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11686 
11687   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11688     return false;
11689 
11690   // Don't merge vectors into wider vectors if the source data comes from loads.
11691   // TODO: This restriction can be lifted by using logic similar to the
11692   // ExtractVecSrc case.
11693   if (MemVT.isVector() && IsLoadSrc)
11694     return false;
11695 
11696   // Only look at ends of store sequences.
11697   SDValue Chain = SDValue(St, 0);
11698   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11699     return false;
11700 
11701   // Save the LoadSDNodes that we find in the chain.
11702   // We need to make sure that these nodes do not interfere with
11703   // any of the store nodes.
11704   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11705 
11706   // Save the StoreSDNodes that we find in the chain.
11707   SmallVector<MemOpLink, 8> StoreNodes;
11708 
11709   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11710 
11711   // Check if there is anything to merge.
11712   if (StoreNodes.size() < 2)
11713     return false;
11714 
11715   // only do dependence check in AA case
11716   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11717                                                   : DAG.getSubtarget().useAA();
11718   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11719     return false;
11720 
11721   // Sort the memory operands according to their distance from the
11722   // base pointer.  As a secondary criteria: make sure stores coming
11723   // later in the code come first in the list. This is important for
11724   // the non-UseAA case, because we're merging stores into the FINAL
11725   // store along a chain which potentially contains aliasing stores.
11726   // Thus, if there are multiple stores to the same address, the last
11727   // one can be considered for merging but not the others.
11728   std::sort(StoreNodes.begin(), StoreNodes.end(),
11729             [](MemOpLink LHS, MemOpLink RHS) {
11730     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11731            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11732             LHS.SequenceNum < RHS.SequenceNum);
11733   });
11734 
11735   // Scan the memory operations on the chain and find the first non-consecutive
11736   // store memory address.
11737   unsigned LastConsecutiveStore = 0;
11738   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11739   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11740 
11741     // Check that the addresses are consecutive starting from the second
11742     // element in the list of stores.
11743     if (i > 0) {
11744       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11745       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11746         break;
11747     }
11748 
11749     // Check if this store interferes with any of the loads that we found.
11750     // If we find a load that alias with this store. Stop the sequence.
11751     if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) {
11752           return isAlias(Ldn, StoreNodes[i].MemNode);
11753         }))
11754       break;
11755 
11756     // Mark this node as useful.
11757     LastConsecutiveStore = i;
11758   }
11759 
11760   // The node with the lowest store address.
11761   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11762   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11763   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11764   LLVMContext &Context = *DAG.getContext();
11765   const DataLayout &DL = DAG.getDataLayout();
11766 
11767   // Store the constants into memory as one consecutive store.
11768   if (IsConstantSrc) {
11769     unsigned LastLegalType = 0;
11770     unsigned LastLegalVectorType = 0;
11771     bool NonZero = false;
11772     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11773       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11774       SDValue StoredVal = St->getValue();
11775 
11776       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11777         NonZero |= !C->isNullValue();
11778       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11779         NonZero |= !C->getConstantFPValue()->isNullValue();
11780       } else {
11781         // Non-constant.
11782         break;
11783       }
11784 
11785       // Find a legal type for the constant store.
11786       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11787       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11788       bool IsFast;
11789       if (TLI.isTypeLegal(StoreTy) &&
11790           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11791                                  FirstStoreAlign, &IsFast) && IsFast) {
11792         LastLegalType = i+1;
11793       // Or check whether a truncstore is legal.
11794       } else if (TLI.getTypeAction(Context, StoreTy) ==
11795                  TargetLowering::TypePromoteInteger) {
11796         EVT LegalizedStoredValueTy =
11797           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11798         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11799             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11800                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11801             IsFast) {
11802           LastLegalType = i + 1;
11803         }
11804       }
11805 
11806       // We only use vectors if the constant is known to be zero or the target
11807       // allows it and the function is not marked with the noimplicitfloat
11808       // attribute.
11809       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11810                                                         FirstStoreAS)) &&
11811           !NoVectors) {
11812         // Find a legal type for the vector store.
11813         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11814         if (TLI.isTypeLegal(Ty) &&
11815             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11816                                    FirstStoreAlign, &IsFast) && IsFast)
11817           LastLegalVectorType = i + 1;
11818       }
11819     }
11820 
11821     // Check if we found a legal integer type to store.
11822     if (LastLegalType == 0 && LastLegalVectorType == 0)
11823       return false;
11824 
11825     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11826     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11827 
11828     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11829                                            true, UseVector);
11830   }
11831 
11832   // When extracting multiple vector elements, try to store them
11833   // in one vector store rather than a sequence of scalar stores.
11834   if (IsExtractVecSrc) {
11835     unsigned NumStoresToMerge = 0;
11836     bool IsVec = MemVT.isVector();
11837     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11838       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11839       unsigned StoreValOpcode = St->getValue().getOpcode();
11840       // This restriction could be loosened.
11841       // Bail out if any stored values are not elements extracted from a vector.
11842       // It should be possible to handle mixed sources, but load sources need
11843       // more careful handling (see the block of code below that handles
11844       // consecutive loads).
11845       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11846           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11847         return false;
11848 
11849       // Find a legal type for the vector store.
11850       unsigned Elts = i + 1;
11851       if (IsVec) {
11852         // When merging vector stores, get the total number of elements.
11853         Elts *= MemVT.getVectorNumElements();
11854       }
11855       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11856       bool IsFast;
11857       if (TLI.isTypeLegal(Ty) &&
11858           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11859                                  FirstStoreAlign, &IsFast) && IsFast)
11860         NumStoresToMerge = i + 1;
11861     }
11862 
11863     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11864                                            false, true);
11865   }
11866 
11867   // Below we handle the case of multiple consecutive stores that
11868   // come from multiple consecutive loads. We merge them into a single
11869   // wide load and a single wide store.
11870 
11871   // Look for load nodes which are used by the stored values.
11872   SmallVector<MemOpLink, 8> LoadNodes;
11873 
11874   // Find acceptable loads. Loads need to have the same chain (token factor),
11875   // must not be zext, volatile, indexed, and they must be consecutive.
11876   BaseIndexOffset LdBasePtr;
11877   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11878     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11879     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11880     if (!Ld) break;
11881 
11882     // Loads must only have one use.
11883     if (!Ld->hasNUsesOfValue(1, 0))
11884       break;
11885 
11886     // The memory operands must not be volatile.
11887     if (Ld->isVolatile() || Ld->isIndexed())
11888       break;
11889 
11890     // We do not accept ext loads.
11891     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11892       break;
11893 
11894     // The stored memory type must be the same.
11895     if (Ld->getMemoryVT() != MemVT)
11896       break;
11897 
11898     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11899     // If this is not the first ptr that we check.
11900     if (LdBasePtr.Base.getNode()) {
11901       // The base ptr must be the same.
11902       if (!LdPtr.equalBaseIndex(LdBasePtr))
11903         break;
11904     } else {
11905       // Check that all other base pointers are the same as this one.
11906       LdBasePtr = LdPtr;
11907     }
11908 
11909     // We found a potential memory operand to merge.
11910     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11911   }
11912 
11913   if (LoadNodes.size() < 2)
11914     return false;
11915 
11916   // If we have load/store pair instructions and we only have two values,
11917   // don't bother.
11918   unsigned RequiredAlignment;
11919   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11920       St->getAlignment() >= RequiredAlignment)
11921     return false;
11922 
11923   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11924   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11925   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11926 
11927   // Scan the memory operations on the chain and find the first non-consecutive
11928   // load memory address. These variables hold the index in the store node
11929   // array.
11930   unsigned LastConsecutiveLoad = 0;
11931   // This variable refers to the size and not index in the array.
11932   unsigned LastLegalVectorType = 0;
11933   unsigned LastLegalIntegerType = 0;
11934   StartAddress = LoadNodes[0].OffsetFromBase;
11935   SDValue FirstChain = FirstLoad->getChain();
11936   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11937     // All loads must share the same chain.
11938     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11939       break;
11940 
11941     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11942     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11943       break;
11944     LastConsecutiveLoad = i;
11945     // Find a legal type for the vector store.
11946     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11947     bool IsFastSt, IsFastLd;
11948     if (TLI.isTypeLegal(StoreTy) &&
11949         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11950                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11951         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11952                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11953       LastLegalVectorType = i + 1;
11954     }
11955 
11956     // Find a legal type for the integer store.
11957     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11958     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11959     if (TLI.isTypeLegal(StoreTy) &&
11960         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11961                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11962         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11963                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11964       LastLegalIntegerType = i + 1;
11965     // Or check whether a truncstore and extload is legal.
11966     else if (TLI.getTypeAction(Context, StoreTy) ==
11967              TargetLowering::TypePromoteInteger) {
11968       EVT LegalizedStoredValueTy =
11969         TLI.getTypeToTransformTo(Context, StoreTy);
11970       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11971           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11972           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11973           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11974           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11975                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11976           IsFastSt &&
11977           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11978                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11979           IsFastLd)
11980         LastLegalIntegerType = i+1;
11981     }
11982   }
11983 
11984   // Only use vector types if the vector type is larger than the integer type.
11985   // If they are the same, use integers.
11986   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11987   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11988 
11989   // We add +1 here because the LastXXX variables refer to location while
11990   // the NumElem refers to array/index size.
11991   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11992   NumElem = std::min(LastLegalType, NumElem);
11993 
11994   if (NumElem < 2)
11995     return false;
11996 
11997   // Collect the chains from all merged stores.
11998   SmallVector<SDValue, 8> MergeStoreChains;
11999   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
12000 
12001   // The latest Node in the DAG.
12002   unsigned LatestNodeUsed = 0;
12003   for (unsigned i=1; i<NumElem; ++i) {
12004     // Find a chain for the new wide-store operand. Notice that some
12005     // of the store nodes that we found may not be selected for inclusion
12006     // in the wide store. The chain we use needs to be the chain of the
12007     // latest store node which is *used* and replaced by the wide store.
12008     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
12009       LatestNodeUsed = i;
12010 
12011     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
12012   }
12013 
12014   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
12015 
12016   // Find if it is better to use vectors or integers to load and store
12017   // to memory.
12018   EVT JointMemOpVT;
12019   if (UseVectorTy) {
12020     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12021   } else {
12022     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12023     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12024   }
12025 
12026   SDLoc LoadDL(LoadNodes[0].MemNode);
12027   SDLoc StoreDL(StoreNodes[0].MemNode);
12028 
12029   // The merged loads are required to have the same incoming chain, so
12030   // using the first's chain is acceptable.
12031   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12032                                 FirstLoad->getBasePtr(),
12033                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
12034 
12035   SDValue NewStoreChain =
12036     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
12037 
12038   SDValue NewStore =
12039       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12040                    FirstInChain->getPointerInfo(), FirstStoreAlign);
12041 
12042   // Transfer chain users from old loads to the new load.
12043   for (unsigned i = 0; i < NumElem; ++i) {
12044     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12045     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12046                                   SDValue(NewLoad.getNode(), 1));
12047   }
12048 
12049   if (UseAA) {
12050     // Replace the all stores with the new store.
12051     for (unsigned i = 0; i < NumElem; ++i)
12052       CombineTo(StoreNodes[i].MemNode, NewStore);
12053   } else {
12054     // Replace the last store with the new store.
12055     CombineTo(LatestOp, NewStore);
12056     // Erase all other stores.
12057     for (unsigned i = 0; i < NumElem; ++i) {
12058       // Remove all Store nodes.
12059       if (StoreNodes[i].MemNode == LatestOp)
12060         continue;
12061       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12062       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
12063       deleteAndRecombine(St);
12064     }
12065   }
12066 
12067   return true;
12068 }
12069 
12070 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12071   SDLoc SL(ST);
12072   SDValue ReplStore;
12073 
12074   // Replace the chain to avoid dependency.
12075   if (ST->isTruncatingStore()) {
12076     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12077                                   ST->getBasePtr(), ST->getMemoryVT(),
12078                                   ST->getMemOperand());
12079   } else {
12080     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12081                              ST->getMemOperand());
12082   }
12083 
12084   // Create token to keep both nodes around.
12085   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12086                               MVT::Other, ST->getChain(), ReplStore);
12087 
12088   // Make sure the new and old chains are cleaned up.
12089   AddToWorklist(Token.getNode());
12090 
12091   // Don't add users to work list.
12092   return CombineTo(ST, Token, false);
12093 }
12094 
12095 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12096   SDValue Value = ST->getValue();
12097   if (Value.getOpcode() == ISD::TargetConstantFP)
12098     return SDValue();
12099 
12100   SDLoc DL(ST);
12101 
12102   SDValue Chain = ST->getChain();
12103   SDValue Ptr = ST->getBasePtr();
12104 
12105   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12106 
12107   // NOTE: If the original store is volatile, this transform must not increase
12108   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12109   // processor operation but an i64 (which is not legal) requires two.  So the
12110   // transform should not be done in this case.
12111 
12112   SDValue Tmp;
12113   switch (CFP->getSimpleValueType(0).SimpleTy) {
12114   default:
12115     llvm_unreachable("Unknown FP type");
12116   case MVT::f16:    // We don't do this for these yet.
12117   case MVT::f80:
12118   case MVT::f128:
12119   case MVT::ppcf128:
12120     return SDValue();
12121   case MVT::f32:
12122     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12123         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12124       ;
12125       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12126                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12127                             MVT::i32);
12128       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12129     }
12130 
12131     return SDValue();
12132   case MVT::f64:
12133     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12134          !ST->isVolatile()) ||
12135         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12136       ;
12137       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12138                             getZExtValue(), SDLoc(CFP), MVT::i64);
12139       return DAG.getStore(Chain, DL, Tmp,
12140                           Ptr, ST->getMemOperand());
12141     }
12142 
12143     if (!ST->isVolatile() &&
12144         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12145       // Many FP stores are not made apparent until after legalize, e.g. for
12146       // argument passing.  Since this is so common, custom legalize the
12147       // 64-bit integer store into two 32-bit stores.
12148       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12149       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12150       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12151       if (DAG.getDataLayout().isBigEndian())
12152         std::swap(Lo, Hi);
12153 
12154       unsigned Alignment = ST->getAlignment();
12155       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12156       AAMDNodes AAInfo = ST->getAAInfo();
12157 
12158       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12159                                  ST->getAlignment(), MMOFlags, AAInfo);
12160       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12161                         DAG.getConstant(4, DL, Ptr.getValueType()));
12162       Alignment = MinAlign(Alignment, 4U);
12163       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12164                                  ST->getPointerInfo().getWithOffset(4),
12165                                  Alignment, MMOFlags, AAInfo);
12166       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12167                          St0, St1);
12168     }
12169 
12170     return SDValue();
12171   }
12172 }
12173 
12174 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12175   StoreSDNode *ST  = cast<StoreSDNode>(N);
12176   SDValue Chain = ST->getChain();
12177   SDValue Value = ST->getValue();
12178   SDValue Ptr   = ST->getBasePtr();
12179 
12180   // If this is a store of a bit convert, store the input value if the
12181   // resultant store does not need a higher alignment than the original.
12182   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12183       ST->isUnindexed()) {
12184     EVT SVT = Value.getOperand(0).getValueType();
12185     if (((!LegalOperations && !ST->isVolatile()) ||
12186          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12187         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12188       unsigned OrigAlign = ST->getAlignment();
12189       bool Fast = false;
12190       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12191                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12192           Fast) {
12193         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12194                             ST->getPointerInfo(), OrigAlign,
12195                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
12196       }
12197     }
12198   }
12199 
12200   // Turn 'store undef, Ptr' -> nothing.
12201   if (Value.isUndef() && ST->isUnindexed())
12202     return Chain;
12203 
12204   // Try to infer better alignment information than the store already has.
12205   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12206     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12207       if (Align > ST->getAlignment()) {
12208         SDValue NewStore =
12209             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12210                               ST->getMemoryVT(), Align,
12211                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
12212         if (NewStore.getNode() != N)
12213           return CombineTo(ST, NewStore, true);
12214       }
12215     }
12216   }
12217 
12218   // Try transforming a pair floating point load / store ops to integer
12219   // load / store ops.
12220   if (SDValue NewST = TransformFPLoadStorePair(N))
12221     return NewST;
12222 
12223   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12224                                                   : DAG.getSubtarget().useAA();
12225 #ifndef NDEBUG
12226   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12227       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12228     UseAA = false;
12229 #endif
12230   if (UseAA && ST->isUnindexed()) {
12231     // FIXME: We should do this even without AA enabled. AA will just allow
12232     // FindBetterChain to work in more situations. The problem with this is that
12233     // any combine that expects memory operations to be on consecutive chains
12234     // first needs to be updated to look for users of the same chain.
12235 
12236     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12237     // adjacent stores.
12238     if (findBetterNeighborChains(ST)) {
12239       // replaceStoreChain uses CombineTo, which handled all of the worklist
12240       // manipulation. Return the original node to not do anything else.
12241       return SDValue(ST, 0);
12242     }
12243     Chain = ST->getChain();
12244   }
12245 
12246   // Try transforming N to an indexed store.
12247   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12248     return SDValue(N, 0);
12249 
12250   // FIXME: is there such a thing as a truncating indexed store?
12251   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12252       Value.getValueType().isInteger()) {
12253     // See if we can simplify the input to this truncstore with knowledge that
12254     // only the low bits are being used.  For example:
12255     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12256     SDValue Shorter = GetDemandedBits(
12257         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12258                                     ST->getMemoryVT().getScalarSizeInBits()));
12259     AddToWorklist(Value.getNode());
12260     if (Shorter.getNode())
12261       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12262                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12263 
12264     // Otherwise, see if we can simplify the operation with
12265     // SimplifyDemandedBits, which only works if the value has a single use.
12266     if (SimplifyDemandedBits(
12267             Value,
12268             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12269                                  ST->getMemoryVT().getScalarSizeInBits())))
12270       return SDValue(N, 0);
12271   }
12272 
12273   // If this is a load followed by a store to the same location, then the store
12274   // is dead/noop.
12275   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12276     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12277         ST->isUnindexed() && !ST->isVolatile() &&
12278         // There can't be any side effects between the load and store, such as
12279         // a call or store.
12280         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12281       // The store is dead, remove it.
12282       return Chain;
12283     }
12284   }
12285 
12286   // If this is a store followed by a store with the same value to the same
12287   // location, then the store is dead/noop.
12288   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12289     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12290         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12291         ST1->isUnindexed() && !ST1->isVolatile()) {
12292       // The store is dead, remove it.
12293       return Chain;
12294     }
12295   }
12296 
12297   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12298   // truncating store.  We can do this even if this is already a truncstore.
12299   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12300       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12301       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12302                             ST->getMemoryVT())) {
12303     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12304                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12305   }
12306 
12307   // Only perform this optimization before the types are legal, because we
12308   // don't want to perform this optimization on every DAGCombine invocation.
12309   if (!LegalTypes) {
12310     bool EverChanged = false;
12311 
12312     do {
12313       // There can be multiple store sequences on the same chain.
12314       // Keep trying to merge store sequences until we are unable to do so
12315       // or until we merge the last store on the chain.
12316       bool Changed = MergeConsecutiveStores(ST);
12317       EverChanged |= Changed;
12318       if (!Changed) break;
12319     } while (ST->getOpcode() != ISD::DELETED_NODE);
12320 
12321     if (EverChanged)
12322       return SDValue(N, 0);
12323   }
12324 
12325   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12326   //
12327   // Make sure to do this only after attempting to merge stores in order to
12328   //  avoid changing the types of some subset of stores due to visit order,
12329   //  preventing their merging.
12330   if (isa<ConstantFPSDNode>(Value)) {
12331     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12332       return NewSt;
12333   }
12334 
12335   if (SDValue NewSt = splitMergedValStore(ST))
12336     return NewSt;
12337 
12338   return ReduceLoadOpStoreWidth(N);
12339 }
12340 
12341 /// For the instruction sequence of store below, F and I values
12342 /// are bundled together as an i64 value before being stored into memory.
12343 /// Sometimes it is more efficent to generate separate stores for F and I,
12344 /// which can remove the bitwise instructions or sink them to colder places.
12345 ///
12346 ///   (store (or (zext (bitcast F to i32) to i64),
12347 ///              (shl (zext I to i64), 32)), addr)  -->
12348 ///   (store F, addr) and (store I, addr+4)
12349 ///
12350 /// Similarly, splitting for other merged store can also be beneficial, like:
12351 /// For pair of {i32, i32}, i64 store --> two i32 stores.
12352 /// For pair of {i32, i16}, i64 store --> two i32 stores.
12353 /// For pair of {i16, i16}, i32 store --> two i16 stores.
12354 /// For pair of {i16, i8},  i32 store --> two i16 stores.
12355 /// For pair of {i8, i8},   i16 store --> two i8 stores.
12356 ///
12357 /// We allow each target to determine specifically which kind of splitting is
12358 /// supported.
12359 ///
12360 /// The store patterns are commonly seen from the simple code snippet below
12361 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
12362 ///   void goo(const std::pair<int, float> &);
12363 ///   hoo() {
12364 ///     ...
12365 ///     goo(std::make_pair(tmp, ftmp));
12366 ///     ...
12367 ///   }
12368 ///
12369 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
12370   if (OptLevel == CodeGenOpt::None)
12371     return SDValue();
12372 
12373   SDValue Val = ST->getValue();
12374   SDLoc DL(ST);
12375 
12376   // Match OR operand.
12377   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
12378     return SDValue();
12379 
12380   // Match SHL operand and get Lower and Higher parts of Val.
12381   SDValue Op1 = Val.getOperand(0);
12382   SDValue Op2 = Val.getOperand(1);
12383   SDValue Lo, Hi;
12384   if (Op1.getOpcode() != ISD::SHL) {
12385     std::swap(Op1, Op2);
12386     if (Op1.getOpcode() != ISD::SHL)
12387       return SDValue();
12388   }
12389   Lo = Op2;
12390   Hi = Op1.getOperand(0);
12391   if (!Op1.hasOneUse())
12392     return SDValue();
12393 
12394   // Match shift amount to HalfValBitSize.
12395   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
12396   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
12397   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
12398     return SDValue();
12399 
12400   // Lo and Hi are zero-extended from int with size less equal than 32
12401   // to i64.
12402   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
12403       !Lo.getOperand(0).getValueType().isScalarInteger() ||
12404       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
12405       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
12406       !Hi.getOperand(0).getValueType().isScalarInteger() ||
12407       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
12408     return SDValue();
12409 
12410   if (!TLI.isMultiStoresCheaperThanBitsMerge(Lo.getOperand(0),
12411                                              Hi.getOperand(0)))
12412     return SDValue();
12413 
12414   // Start to split store.
12415   unsigned Alignment = ST->getAlignment();
12416   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12417   AAMDNodes AAInfo = ST->getAAInfo();
12418 
12419   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
12420   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
12421   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
12422   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
12423 
12424   SDValue Chain = ST->getChain();
12425   SDValue Ptr = ST->getBasePtr();
12426   // Lower value store.
12427   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12428                              ST->getAlignment(), MMOFlags, AAInfo);
12429   Ptr =
12430       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12431                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
12432   // Higher value store.
12433   SDValue St1 =
12434       DAG.getStore(St0, DL, Hi, Ptr,
12435                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
12436                    Alignment / 2, MMOFlags, AAInfo);
12437   return St1;
12438 }
12439 
12440 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12441   SDValue InVec = N->getOperand(0);
12442   SDValue InVal = N->getOperand(1);
12443   SDValue EltNo = N->getOperand(2);
12444   SDLoc DL(N);
12445 
12446   // If the inserted element is an UNDEF, just use the input vector.
12447   if (InVal.isUndef())
12448     return InVec;
12449 
12450   EVT VT = InVec.getValueType();
12451 
12452   // If we can't generate a legal BUILD_VECTOR, exit
12453   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12454     return SDValue();
12455 
12456   // Check that we know which element is being inserted
12457   if (!isa<ConstantSDNode>(EltNo))
12458     return SDValue();
12459   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12460 
12461   // Canonicalize insert_vector_elt dag nodes.
12462   // Example:
12463   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12464   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12465   //
12466   // Do this only if the child insert_vector node has one use; also
12467   // do this only if indices are both constants and Idx1 < Idx0.
12468   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12469       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12470     unsigned OtherElt =
12471       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12472     if (Elt < OtherElt) {
12473       // Swap nodes.
12474       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
12475                                   InVec.getOperand(0), InVal, EltNo);
12476       AddToWorklist(NewOp.getNode());
12477       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12478                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12479     }
12480   }
12481 
12482   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12483   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12484   // vector elements.
12485   SmallVector<SDValue, 8> Ops;
12486   // Do not combine these two vectors if the output vector will not replace
12487   // the input vector.
12488   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12489     Ops.append(InVec.getNode()->op_begin(),
12490                InVec.getNode()->op_end());
12491   } else if (InVec.isUndef()) {
12492     unsigned NElts = VT.getVectorNumElements();
12493     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12494   } else {
12495     return SDValue();
12496   }
12497 
12498   // Insert the element
12499   if (Elt < Ops.size()) {
12500     // All the operands of BUILD_VECTOR must have the same type;
12501     // we enforce that here.
12502     EVT OpVT = Ops[0].getValueType();
12503     if (InVal.getValueType() != OpVT)
12504       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12505                 DAG.getNode(ISD::ANY_EXTEND, DL, OpVT, InVal) :
12506                 DAG.getNode(ISD::TRUNCATE, DL, OpVT, InVal);
12507     Ops[Elt] = InVal;
12508   }
12509 
12510   // Return the new vector
12511   return DAG.getBuildVector(VT, DL, Ops);
12512 }
12513 
12514 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12515     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12516   assert(!OriginalLoad->isVolatile());
12517 
12518   EVT ResultVT = EVE->getValueType(0);
12519   EVT VecEltVT = InVecVT.getVectorElementType();
12520   unsigned Align = OriginalLoad->getAlignment();
12521   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12522       VecEltVT.getTypeForEVT(*DAG.getContext()));
12523 
12524   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12525     return SDValue();
12526 
12527   Align = NewAlign;
12528 
12529   SDValue NewPtr = OriginalLoad->getBasePtr();
12530   SDValue Offset;
12531   EVT PtrType = NewPtr.getValueType();
12532   MachinePointerInfo MPI;
12533   SDLoc DL(EVE);
12534   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12535     int Elt = ConstEltNo->getZExtValue();
12536     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12537     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12538     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12539   } else {
12540     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12541     Offset = DAG.getNode(
12542         ISD::MUL, DL, PtrType, Offset,
12543         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12544     MPI = OriginalLoad->getPointerInfo();
12545   }
12546   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12547 
12548   // The replacement we need to do here is a little tricky: we need to
12549   // replace an extractelement of a load with a load.
12550   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12551   // Note that this replacement assumes that the extractvalue is the only
12552   // use of the load; that's okay because we don't want to perform this
12553   // transformation in other cases anyway.
12554   SDValue Load;
12555   SDValue Chain;
12556   if (ResultVT.bitsGT(VecEltVT)) {
12557     // If the result type of vextract is wider than the load, then issue an
12558     // extending load instead.
12559     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12560                                                   VecEltVT)
12561                                    ? ISD::ZEXTLOAD
12562                                    : ISD::EXTLOAD;
12563     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
12564                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
12565                           Align, OriginalLoad->getMemOperand()->getFlags(),
12566                           OriginalLoad->getAAInfo());
12567     Chain = Load.getValue(1);
12568   } else {
12569     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
12570                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
12571                        OriginalLoad->getAAInfo());
12572     Chain = Load.getValue(1);
12573     if (ResultVT.bitsLT(VecEltVT))
12574       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12575     else
12576       Load = DAG.getBitcast(ResultVT, Load);
12577   }
12578   WorklistRemover DeadNodes(*this);
12579   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12580   SDValue To[] = { Load, Chain };
12581   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12582   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12583   // worklist explicitly as well.
12584   AddToWorklist(Load.getNode());
12585   AddUsersToWorklist(Load.getNode()); // Add users too
12586   // Make sure to revisit this node to clean it up; it will usually be dead.
12587   AddToWorklist(EVE);
12588   ++OpsNarrowed;
12589   return SDValue(EVE, 0);
12590 }
12591 
12592 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12593   // (vextract (scalar_to_vector val, 0) -> val
12594   SDValue InVec = N->getOperand(0);
12595   EVT VT = InVec.getValueType();
12596   EVT NVT = N->getValueType(0);
12597 
12598   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12599     // Check if the result type doesn't match the inserted element type. A
12600     // SCALAR_TO_VECTOR may truncate the inserted element and the
12601     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12602     SDValue InOp = InVec.getOperand(0);
12603     if (InOp.getValueType() != NVT) {
12604       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12605       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12606     }
12607     return InOp;
12608   }
12609 
12610   SDValue EltNo = N->getOperand(1);
12611   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12612 
12613   // extract_vector_elt (build_vector x, y), 1 -> y
12614   if (ConstEltNo &&
12615       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12616       TLI.isTypeLegal(VT) &&
12617       (InVec.hasOneUse() ||
12618        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12619     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12620     EVT InEltVT = Elt.getValueType();
12621 
12622     // Sometimes build_vector's scalar input types do not match result type.
12623     if (NVT == InEltVT)
12624       return Elt;
12625 
12626     // TODO: It may be useful to truncate if free if the build_vector implicitly
12627     // converts.
12628   }
12629 
12630   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12631   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12632       ConstEltNo->isNullValue() && VT.isInteger()) {
12633     SDValue BCSrc = InVec.getOperand(0);
12634     if (BCSrc.getValueType().isScalarInteger())
12635       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12636   }
12637 
12638   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
12639   //
12640   // This only really matters if the index is non-constant since other combines
12641   // on the constant elements already work.
12642   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12643       EltNo == InVec.getOperand(2)) {
12644     SDValue Elt = InVec.getOperand(1);
12645     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
12646   }
12647 
12648   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12649   // We only perform this optimization before the op legalization phase because
12650   // we may introduce new vector instructions which are not backed by TD
12651   // patterns. For example on AVX, extracting elements from a wide vector
12652   // without using extract_subvector. However, if we can find an underlying
12653   // scalar value, then we can always use that.
12654   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12655     int NumElem = VT.getVectorNumElements();
12656     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12657     // Find the new index to extract from.
12658     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12659 
12660     // Extracting an undef index is undef.
12661     if (OrigElt == -1)
12662       return DAG.getUNDEF(NVT);
12663 
12664     // Select the right vector half to extract from.
12665     SDValue SVInVec;
12666     if (OrigElt < NumElem) {
12667       SVInVec = InVec->getOperand(0);
12668     } else {
12669       SVInVec = InVec->getOperand(1);
12670       OrigElt -= NumElem;
12671     }
12672 
12673     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12674       SDValue InOp = SVInVec.getOperand(OrigElt);
12675       if (InOp.getValueType() != NVT) {
12676         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12677         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12678       }
12679 
12680       return InOp;
12681     }
12682 
12683     // FIXME: We should handle recursing on other vector shuffles and
12684     // scalar_to_vector here as well.
12685 
12686     if (!LegalOperations) {
12687       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12688       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12689                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12690     }
12691   }
12692 
12693   bool BCNumEltsChanged = false;
12694   EVT ExtVT = VT.getVectorElementType();
12695   EVT LVT = ExtVT;
12696 
12697   // If the result of load has to be truncated, then it's not necessarily
12698   // profitable.
12699   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12700     return SDValue();
12701 
12702   if (InVec.getOpcode() == ISD::BITCAST) {
12703     // Don't duplicate a load with other uses.
12704     if (!InVec.hasOneUse())
12705       return SDValue();
12706 
12707     EVT BCVT = InVec.getOperand(0).getValueType();
12708     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12709       return SDValue();
12710     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12711       BCNumEltsChanged = true;
12712     InVec = InVec.getOperand(0);
12713     ExtVT = BCVT.getVectorElementType();
12714   }
12715 
12716   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12717   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12718       ISD::isNormalLoad(InVec.getNode()) &&
12719       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12720     SDValue Index = N->getOperand(1);
12721     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
12722       if (!OrigLoad->isVolatile()) {
12723         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12724                                                              OrigLoad);
12725       }
12726     }
12727   }
12728 
12729   // Perform only after legalization to ensure build_vector / vector_shuffle
12730   // optimizations have already been done.
12731   if (!LegalOperations) return SDValue();
12732 
12733   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12734   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12735   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12736 
12737   if (ConstEltNo) {
12738     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12739 
12740     LoadSDNode *LN0 = nullptr;
12741     const ShuffleVectorSDNode *SVN = nullptr;
12742     if (ISD::isNormalLoad(InVec.getNode())) {
12743       LN0 = cast<LoadSDNode>(InVec);
12744     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12745                InVec.getOperand(0).getValueType() == ExtVT &&
12746                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12747       // Don't duplicate a load with other uses.
12748       if (!InVec.hasOneUse())
12749         return SDValue();
12750 
12751       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12752     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12753       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12754       // =>
12755       // (load $addr+1*size)
12756 
12757       // Don't duplicate a load with other uses.
12758       if (!InVec.hasOneUse())
12759         return SDValue();
12760 
12761       // If the bit convert changed the number of elements, it is unsafe
12762       // to examine the mask.
12763       if (BCNumEltsChanged)
12764         return SDValue();
12765 
12766       // Select the input vector, guarding against out of range extract vector.
12767       unsigned NumElems = VT.getVectorNumElements();
12768       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12769       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12770 
12771       if (InVec.getOpcode() == ISD::BITCAST) {
12772         // Don't duplicate a load with other uses.
12773         if (!InVec.hasOneUse())
12774           return SDValue();
12775 
12776         InVec = InVec.getOperand(0);
12777       }
12778       if (ISD::isNormalLoad(InVec.getNode())) {
12779         LN0 = cast<LoadSDNode>(InVec);
12780         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12781         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12782       }
12783     }
12784 
12785     // Make sure we found a non-volatile load and the extractelement is
12786     // the only use.
12787     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12788       return SDValue();
12789 
12790     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12791     if (Elt == -1)
12792       return DAG.getUNDEF(LVT);
12793 
12794     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12795   }
12796 
12797   return SDValue();
12798 }
12799 
12800 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12801 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12802   // We perform this optimization post type-legalization because
12803   // the type-legalizer often scalarizes integer-promoted vectors.
12804   // Performing this optimization before may create bit-casts which
12805   // will be type-legalized to complex code sequences.
12806   // We perform this optimization only before the operation legalizer because we
12807   // may introduce illegal operations.
12808   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12809     return SDValue();
12810 
12811   unsigned NumInScalars = N->getNumOperands();
12812   SDLoc DL(N);
12813   EVT VT = N->getValueType(0);
12814 
12815   // Check to see if this is a BUILD_VECTOR of a bunch of values
12816   // which come from any_extend or zero_extend nodes. If so, we can create
12817   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12818   // optimizations. We do not handle sign-extend because we can't fill the sign
12819   // using shuffles.
12820   EVT SourceType = MVT::Other;
12821   bool AllAnyExt = true;
12822 
12823   for (unsigned i = 0; i != NumInScalars; ++i) {
12824     SDValue In = N->getOperand(i);
12825     // Ignore undef inputs.
12826     if (In.isUndef()) continue;
12827 
12828     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12829     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12830 
12831     // Abort if the element is not an extension.
12832     if (!ZeroExt && !AnyExt) {
12833       SourceType = MVT::Other;
12834       break;
12835     }
12836 
12837     // The input is a ZeroExt or AnyExt. Check the original type.
12838     EVT InTy = In.getOperand(0).getValueType();
12839 
12840     // Check that all of the widened source types are the same.
12841     if (SourceType == MVT::Other)
12842       // First time.
12843       SourceType = InTy;
12844     else if (InTy != SourceType) {
12845       // Multiple income types. Abort.
12846       SourceType = MVT::Other;
12847       break;
12848     }
12849 
12850     // Check if all of the extends are ANY_EXTENDs.
12851     AllAnyExt &= AnyExt;
12852   }
12853 
12854   // In order to have valid types, all of the inputs must be extended from the
12855   // same source type and all of the inputs must be any or zero extend.
12856   // Scalar sizes must be a power of two.
12857   EVT OutScalarTy = VT.getScalarType();
12858   bool ValidTypes = SourceType != MVT::Other &&
12859                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12860                  isPowerOf2_32(SourceType.getSizeInBits());
12861 
12862   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12863   // turn into a single shuffle instruction.
12864   if (!ValidTypes)
12865     return SDValue();
12866 
12867   bool isLE = DAG.getDataLayout().isLittleEndian();
12868   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12869   assert(ElemRatio > 1 && "Invalid element size ratio");
12870   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12871                                DAG.getConstant(0, DL, SourceType);
12872 
12873   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12874   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12875 
12876   // Populate the new build_vector
12877   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12878     SDValue Cast = N->getOperand(i);
12879     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12880             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12881             Cast.isUndef()) && "Invalid cast opcode");
12882     SDValue In;
12883     if (Cast.isUndef())
12884       In = DAG.getUNDEF(SourceType);
12885     else
12886       In = Cast->getOperand(0);
12887     unsigned Index = isLE ? (i * ElemRatio) :
12888                             (i * ElemRatio + (ElemRatio - 1));
12889 
12890     assert(Index < Ops.size() && "Invalid index");
12891     Ops[Index] = In;
12892   }
12893 
12894   // The type of the new BUILD_VECTOR node.
12895   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12896   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12897          "Invalid vector size");
12898   // Check if the new vector type is legal.
12899   if (!isTypeLegal(VecVT)) return SDValue();
12900 
12901   // Make the new BUILD_VECTOR.
12902   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
12903 
12904   // The new BUILD_VECTOR node has the potential to be further optimized.
12905   AddToWorklist(BV.getNode());
12906   // Bitcast to the desired type.
12907   return DAG.getBitcast(VT, BV);
12908 }
12909 
12910 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12911   EVT VT = N->getValueType(0);
12912 
12913   unsigned NumInScalars = N->getNumOperands();
12914   SDLoc DL(N);
12915 
12916   EVT SrcVT = MVT::Other;
12917   unsigned Opcode = ISD::DELETED_NODE;
12918   unsigned NumDefs = 0;
12919 
12920   for (unsigned i = 0; i != NumInScalars; ++i) {
12921     SDValue In = N->getOperand(i);
12922     unsigned Opc = In.getOpcode();
12923 
12924     if (Opc == ISD::UNDEF)
12925       continue;
12926 
12927     // If all scalar values are floats and converted from integers.
12928     if (Opcode == ISD::DELETED_NODE &&
12929         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12930       Opcode = Opc;
12931     }
12932 
12933     if (Opc != Opcode)
12934       return SDValue();
12935 
12936     EVT InVT = In.getOperand(0).getValueType();
12937 
12938     // If all scalar values are typed differently, bail out. It's chosen to
12939     // simplify BUILD_VECTOR of integer types.
12940     if (SrcVT == MVT::Other)
12941       SrcVT = InVT;
12942     if (SrcVT != InVT)
12943       return SDValue();
12944     NumDefs++;
12945   }
12946 
12947   // If the vector has just one element defined, it's not worth to fold it into
12948   // a vectorized one.
12949   if (NumDefs < 2)
12950     return SDValue();
12951 
12952   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12953          && "Should only handle conversion from integer to float.");
12954   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12955 
12956   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12957 
12958   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12959     return SDValue();
12960 
12961   // Just because the floating-point vector type is legal does not necessarily
12962   // mean that the corresponding integer vector type is.
12963   if (!isTypeLegal(NVT))
12964     return SDValue();
12965 
12966   SmallVector<SDValue, 8> Opnds;
12967   for (unsigned i = 0; i != NumInScalars; ++i) {
12968     SDValue In = N->getOperand(i);
12969 
12970     if (In.isUndef())
12971       Opnds.push_back(DAG.getUNDEF(SrcVT));
12972     else
12973       Opnds.push_back(In.getOperand(0));
12974   }
12975   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
12976   AddToWorklist(BV.getNode());
12977 
12978   return DAG.getNode(Opcode, DL, VT, BV);
12979 }
12980 
12981 SDValue DAGCombiner::createBuildVecShuffle(SDLoc DL, SDNode *N,
12982                                            ArrayRef<int> VectorMask,
12983                                            SDValue VecIn1, SDValue VecIn2,
12984                                            unsigned LeftIdx) {
12985   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12986   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
12987 
12988   EVT VT = N->getValueType(0);
12989   EVT InVT1 = VecIn1.getValueType();
12990   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
12991 
12992   unsigned Vec2Offset = InVT1.getVectorNumElements();
12993   unsigned NumElems = VT.getVectorNumElements();
12994   unsigned ShuffleNumElems = NumElems;
12995 
12996   // We can't generate a shuffle node with mismatched input and output types.
12997   // Try to make the types match the type of the output.
12998   if (InVT1 != VT || InVT2 != VT) {
12999     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13000       // If the output vector length is a multiple of both input lengths,
13001       // we can concatenate them and pad the rest with undefs.
13002       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13003       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13004       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13005       ConcatOps[0] = VecIn1;
13006       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13007       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13008       VecIn2 = SDValue();
13009     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13010       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13011         return SDValue();
13012 
13013       if (!VecIn2.getNode()) {
13014         // If we only have one input vector, and it's twice the size of the
13015         // output, split it in two.
13016         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13017                              DAG.getConstant(NumElems, DL, IdxTy));
13018         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13019         // Since we now have shorter input vectors, adjust the offset of the
13020         // second vector's start.
13021         Vec2Offset = NumElems;
13022       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13023         // VecIn1 is wider than the output, and we have another, possibly
13024         // smaller input. Pad the smaller input with undefs, shuffle at the
13025         // input vector width, and extract the output.
13026         // The shuffle type is different than VT, so check legality again.
13027         if (LegalOperations &&
13028             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13029           return SDValue();
13030 
13031         if (InVT1 != InVT2)
13032           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13033                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13034         ShuffleNumElems = NumElems * 2;
13035       } else {
13036         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13037         // than VecIn1. We can't handle this for now - this case will disappear
13038         // when we start sorting the vectors by type.
13039         return SDValue();
13040       }
13041     } else {
13042       // TODO: Support cases where the length mismatch isn't exactly by a
13043       // factor of 2.
13044       // TODO: Move this check upwards, so that if we have bad type
13045       // mismatches, we don't create any DAG nodes.
13046       return SDValue();
13047     }
13048   }
13049 
13050   // Initialize mask to undef.
13051   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13052 
13053   // Only need to run up to the number of elements actually used, not the
13054   // total number of elements in the shuffle - if we are shuffling a wider
13055   // vector, the high lanes should be set to undef.
13056   for (unsigned i = 0; i != NumElems; ++i) {
13057     if (VectorMask[i] <= 0)
13058       continue;
13059 
13060     SDValue Extract = N->getOperand(i);
13061     unsigned ExtIndex =
13062         cast<ConstantSDNode>(Extract.getOperand(1))->getZExtValue();
13063 
13064     if (VectorMask[i] == (int)LeftIdx) {
13065       Mask[i] = ExtIndex;
13066     } else if (VectorMask[i] == (int)LeftIdx + 1) {
13067       Mask[i] = Vec2Offset + ExtIndex;
13068     }
13069   }
13070 
13071   // The type the input vectors may have changed above.
13072   InVT1 = VecIn1.getValueType();
13073 
13074   // If we already have a VecIn2, it should have the same type as VecIn1.
13075   // If we don't, get an undef/zero vector of the appropriate type.
13076   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13077   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13078 
13079   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13080   if (ShuffleNumElems > NumElems)
13081     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13082 
13083   return Shuffle;
13084 }
13085 
13086 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13087 // operations. If the types of the vectors we're extracting from allow it,
13088 // turn this into a vector_shuffle node.
13089 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13090   SDLoc DL(N);
13091   EVT VT = N->getValueType(0);
13092 
13093   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13094   if (!isTypeLegal(VT))
13095     return SDValue();
13096 
13097   // May only combine to shuffle after legalize if shuffle is legal.
13098   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13099     return SDValue();
13100 
13101   bool UsesZeroVector = false;
13102   unsigned NumElems = N->getNumOperands();
13103 
13104   // Record, for each element of the newly built vector, which input vector
13105   // that element comes from. -1 stands for undef, 0 for the zero vector,
13106   // and positive values for the input vectors.
13107   // VectorMask maps each element to its vector number, and VecIn maps vector
13108   // numbers to their initial SDValues.
13109 
13110   SmallVector<int, 8> VectorMask(NumElems, -1);
13111   SmallVector<SDValue, 8> VecIn;
13112   VecIn.push_back(SDValue());
13113 
13114   for (unsigned i = 0; i != NumElems; ++i) {
13115     SDValue Op = N->getOperand(i);
13116 
13117     if (Op.isUndef())
13118       continue;
13119 
13120     // See if we can use a blend with a zero vector.
13121     // TODO: Should we generalize this to a blend with an arbitrary constant
13122     // vector?
13123     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13124       UsesZeroVector = true;
13125       VectorMask[i] = 0;
13126       continue;
13127     }
13128 
13129     // Not an undef or zero. If the input is something other than an
13130     // EXTRACT_VECTOR_ELT with a constant index, bail out.
13131     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13132         !isa<ConstantSDNode>(Op.getOperand(1)))
13133       return SDValue();
13134 
13135     SDValue ExtractedFromVec = Op.getOperand(0);
13136 
13137     // All inputs must have the same element type as the output.
13138     if (VT.getVectorElementType() !=
13139         ExtractedFromVec.getValueType().getVectorElementType())
13140       return SDValue();
13141 
13142     // Have we seen this input vector before?
13143     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13144     // a map back from SDValues to numbers isn't worth it.
13145     unsigned Idx = std::distance(
13146         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13147     if (Idx == VecIn.size())
13148       VecIn.push_back(ExtractedFromVec);
13149 
13150     VectorMask[i] = Idx;
13151   }
13152 
13153   // If we didn't find at least one input vector, bail out.
13154   if (VecIn.size() < 2)
13155     return SDValue();
13156 
13157   // TODO: We want to sort the vectors by descending length, so that adjacent
13158   // pairs have similar length, and the longer vector is always first in the
13159   // pair.
13160 
13161   // TODO: Should this fire if some of the input vectors has illegal type (like
13162   // it does now), or should we let legalization run its course first?
13163 
13164   // Shuffle phase:
13165   // Take pairs of vectors, and shuffle them so that the result has elements
13166   // from these vectors in the correct places.
13167   // For example, given:
13168   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13169   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13170   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13171   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13172   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13173   // We will generate:
13174   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13175   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13176   SmallVector<SDValue, 4> Shuffles;
13177   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13178     unsigned LeftIdx = 2 * In + 1;
13179     SDValue VecLeft = VecIn[LeftIdx];
13180     SDValue VecRight =
13181         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13182 
13183     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13184                                                 VecRight, LeftIdx))
13185       Shuffles.push_back(Shuffle);
13186     else
13187       return SDValue();
13188   }
13189 
13190   // If we need the zero vector as an "ingredient" in the blend tree, add it
13191   // to the list of shuffles.
13192   if (UsesZeroVector)
13193     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13194                                       : DAG.getConstantFP(0.0, DL, VT));
13195 
13196   // If we only have one shuffle, we're done.
13197   if (Shuffles.size() == 1)
13198     return Shuffles[0];
13199 
13200   // Update the vector mask to point to the post-shuffle vectors.
13201   for (int &Vec : VectorMask)
13202     if (Vec == 0)
13203       Vec = Shuffles.size() - 1;
13204     else
13205       Vec = (Vec - 1) / 2;
13206 
13207   // More than one shuffle. Generate a binary tree of blends, e.g. if from
13208   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13209   // generate:
13210   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13211   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13212   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13213   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13214   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13215   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13216   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13217 
13218   // Make sure the initial size of the shuffle list is even.
13219   if (Shuffles.size() % 2)
13220     Shuffles.push_back(DAG.getUNDEF(VT));
13221 
13222   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13223     if (CurSize % 2) {
13224       Shuffles[CurSize] = DAG.getUNDEF(VT);
13225       CurSize++;
13226     }
13227     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13228       int Left = 2 * In;
13229       int Right = 2 * In + 1;
13230       SmallVector<int, 8> Mask(NumElems, -1);
13231       for (unsigned i = 0; i != NumElems; ++i) {
13232         if (VectorMask[i] == Left) {
13233           Mask[i] = i;
13234           VectorMask[i] = In;
13235         } else if (VectorMask[i] == Right) {
13236           Mask[i] = i + NumElems;
13237           VectorMask[i] = In;
13238         }
13239       }
13240 
13241       Shuffles[In] =
13242           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13243     }
13244   }
13245 
13246   return Shuffles[0];
13247 }
13248 
13249 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13250   EVT VT = N->getValueType(0);
13251 
13252   // A vector built entirely of undefs is undef.
13253   if (ISD::allOperandsUndef(N))
13254     return DAG.getUNDEF(VT);
13255 
13256   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13257     return V;
13258 
13259   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13260     return V;
13261 
13262   if (SDValue V = reduceBuildVecToShuffle(N))
13263     return V;
13264 
13265   return SDValue();
13266 }
13267 
13268 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13269   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13270   EVT OpVT = N->getOperand(0).getValueType();
13271 
13272   // If the operands are legal vectors, leave them alone.
13273   if (TLI.isTypeLegal(OpVT))
13274     return SDValue();
13275 
13276   SDLoc DL(N);
13277   EVT VT = N->getValueType(0);
13278   SmallVector<SDValue, 8> Ops;
13279 
13280   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13281   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13282 
13283   // Keep track of what we encounter.
13284   bool AnyInteger = false;
13285   bool AnyFP = false;
13286   for (const SDValue &Op : N->ops()) {
13287     if (ISD::BITCAST == Op.getOpcode() &&
13288         !Op.getOperand(0).getValueType().isVector())
13289       Ops.push_back(Op.getOperand(0));
13290     else if (ISD::UNDEF == Op.getOpcode())
13291       Ops.push_back(ScalarUndef);
13292     else
13293       return SDValue();
13294 
13295     // Note whether we encounter an integer or floating point scalar.
13296     // If it's neither, bail out, it could be something weird like x86mmx.
13297     EVT LastOpVT = Ops.back().getValueType();
13298     if (LastOpVT.isFloatingPoint())
13299       AnyFP = true;
13300     else if (LastOpVT.isInteger())
13301       AnyInteger = true;
13302     else
13303       return SDValue();
13304   }
13305 
13306   // If any of the operands is a floating point scalar bitcast to a vector,
13307   // use floating point types throughout, and bitcast everything.
13308   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
13309   if (AnyFP) {
13310     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
13311     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13312     if (AnyInteger) {
13313       for (SDValue &Op : Ops) {
13314         if (Op.getValueType() == SVT)
13315           continue;
13316         if (Op.isUndef())
13317           Op = ScalarUndef;
13318         else
13319           Op = DAG.getBitcast(SVT, Op);
13320       }
13321     }
13322   }
13323 
13324   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
13325                                VT.getSizeInBits() / SVT.getSizeInBits());
13326   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
13327 }
13328 
13329 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
13330 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
13331 // most two distinct vectors the same size as the result, attempt to turn this
13332 // into a legal shuffle.
13333 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
13334   EVT VT = N->getValueType(0);
13335   EVT OpVT = N->getOperand(0).getValueType();
13336   int NumElts = VT.getVectorNumElements();
13337   int NumOpElts = OpVT.getVectorNumElements();
13338 
13339   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
13340   SmallVector<int, 8> Mask;
13341 
13342   for (SDValue Op : N->ops()) {
13343     // Peek through any bitcast.
13344     while (Op.getOpcode() == ISD::BITCAST)
13345       Op = Op.getOperand(0);
13346 
13347     // UNDEF nodes convert to UNDEF shuffle mask values.
13348     if (Op.isUndef()) {
13349       Mask.append((unsigned)NumOpElts, -1);
13350       continue;
13351     }
13352 
13353     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13354       return SDValue();
13355 
13356     // What vector are we extracting the subvector from and at what index?
13357     SDValue ExtVec = Op.getOperand(0);
13358 
13359     // We want the EVT of the original extraction to correctly scale the
13360     // extraction index.
13361     EVT ExtVT = ExtVec.getValueType();
13362 
13363     // Peek through any bitcast.
13364     while (ExtVec.getOpcode() == ISD::BITCAST)
13365       ExtVec = ExtVec.getOperand(0);
13366 
13367     // UNDEF nodes convert to UNDEF shuffle mask values.
13368     if (ExtVec.isUndef()) {
13369       Mask.append((unsigned)NumOpElts, -1);
13370       continue;
13371     }
13372 
13373     if (!isa<ConstantSDNode>(Op.getOperand(1)))
13374       return SDValue();
13375     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13376 
13377     // Ensure that we are extracting a subvector from a vector the same
13378     // size as the result.
13379     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13380       return SDValue();
13381 
13382     // Scale the subvector index to account for any bitcast.
13383     int NumExtElts = ExtVT.getVectorNumElements();
13384     if (0 == (NumExtElts % NumElts))
13385       ExtIdx /= (NumExtElts / NumElts);
13386     else if (0 == (NumElts % NumExtElts))
13387       ExtIdx *= (NumElts / NumExtElts);
13388     else
13389       return SDValue();
13390 
13391     // At most we can reference 2 inputs in the final shuffle.
13392     if (SV0.isUndef() || SV0 == ExtVec) {
13393       SV0 = ExtVec;
13394       for (int i = 0; i != NumOpElts; ++i)
13395         Mask.push_back(i + ExtIdx);
13396     } else if (SV1.isUndef() || SV1 == ExtVec) {
13397       SV1 = ExtVec;
13398       for (int i = 0; i != NumOpElts; ++i)
13399         Mask.push_back(i + ExtIdx + NumElts);
13400     } else {
13401       return SDValue();
13402     }
13403   }
13404 
13405   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13406     return SDValue();
13407 
13408   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13409                               DAG.getBitcast(VT, SV1), Mask);
13410 }
13411 
13412 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13413   // If we only have one input vector, we don't need to do any concatenation.
13414   if (N->getNumOperands() == 1)
13415     return N->getOperand(0);
13416 
13417   // Check if all of the operands are undefs.
13418   EVT VT = N->getValueType(0);
13419   if (ISD::allOperandsUndef(N))
13420     return DAG.getUNDEF(VT);
13421 
13422   // Optimize concat_vectors where all but the first of the vectors are undef.
13423   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13424         return Op.isUndef();
13425       })) {
13426     SDValue In = N->getOperand(0);
13427     assert(In.getValueType().isVector() && "Must concat vectors");
13428 
13429     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13430     if (In->getOpcode() == ISD::BITCAST &&
13431         !In->getOperand(0)->getValueType(0).isVector()) {
13432       SDValue Scalar = In->getOperand(0);
13433 
13434       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13435       // look through the trunc so we can still do the transform:
13436       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13437       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13438           !TLI.isTypeLegal(Scalar.getValueType()) &&
13439           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13440         Scalar = Scalar->getOperand(0);
13441 
13442       EVT SclTy = Scalar->getValueType(0);
13443 
13444       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13445         return SDValue();
13446 
13447       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13448                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13449       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13450         return SDValue();
13451 
13452       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
13453       return DAG.getBitcast(VT, Res);
13454     }
13455   }
13456 
13457   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13458   // We have already tested above for an UNDEF only concatenation.
13459   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13460   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13461   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13462     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13463   };
13464   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13465     SmallVector<SDValue, 8> Opnds;
13466     EVT SVT = VT.getScalarType();
13467 
13468     EVT MinVT = SVT;
13469     if (!SVT.isFloatingPoint()) {
13470       // If BUILD_VECTOR are from built from integer, they may have different
13471       // operand types. Get the smallest type and truncate all operands to it.
13472       bool FoundMinVT = false;
13473       for (const SDValue &Op : N->ops())
13474         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13475           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13476           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13477           FoundMinVT = true;
13478         }
13479       assert(FoundMinVT && "Concat vector type mismatch");
13480     }
13481 
13482     for (const SDValue &Op : N->ops()) {
13483       EVT OpVT = Op.getValueType();
13484       unsigned NumElts = OpVT.getVectorNumElements();
13485 
13486       if (ISD::UNDEF == Op.getOpcode())
13487         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13488 
13489       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13490         if (SVT.isFloatingPoint()) {
13491           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13492           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13493         } else {
13494           for (unsigned i = 0; i != NumElts; ++i)
13495             Opnds.push_back(
13496                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13497         }
13498       }
13499     }
13500 
13501     assert(VT.getVectorNumElements() == Opnds.size() &&
13502            "Concat vector type mismatch");
13503     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13504   }
13505 
13506   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13507   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13508     return V;
13509 
13510   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13511   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13512     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13513       return V;
13514 
13515   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13516   // nodes often generate nop CONCAT_VECTOR nodes.
13517   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13518   // place the incoming vectors at the exact same location.
13519   SDValue SingleSource = SDValue();
13520   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13521 
13522   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13523     SDValue Op = N->getOperand(i);
13524 
13525     if (Op.isUndef())
13526       continue;
13527 
13528     // Check if this is the identity extract:
13529     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13530       return SDValue();
13531 
13532     // Find the single incoming vector for the extract_subvector.
13533     if (SingleSource.getNode()) {
13534       if (Op.getOperand(0) != SingleSource)
13535         return SDValue();
13536     } else {
13537       SingleSource = Op.getOperand(0);
13538 
13539       // Check the source type is the same as the type of the result.
13540       // If not, this concat may extend the vector, so we can not
13541       // optimize it away.
13542       if (SingleSource.getValueType() != N->getValueType(0))
13543         return SDValue();
13544     }
13545 
13546     unsigned IdentityIndex = i * PartNumElem;
13547     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13548     // The extract index must be constant.
13549     if (!CS)
13550       return SDValue();
13551 
13552     // Check that we are reading from the identity index.
13553     if (CS->getZExtValue() != IdentityIndex)
13554       return SDValue();
13555   }
13556 
13557   if (SingleSource.getNode())
13558     return SingleSource;
13559 
13560   return SDValue();
13561 }
13562 
13563 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13564   EVT NVT = N->getValueType(0);
13565   SDValue V = N->getOperand(0);
13566 
13567   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13568     // Combine:
13569     //    (extract_subvec (concat V1, V2, ...), i)
13570     // Into:
13571     //    Vi if possible
13572     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13573     // type.
13574     if (V->getOperand(0).getValueType() != NVT)
13575       return SDValue();
13576     unsigned Idx = N->getConstantOperandVal(1);
13577     unsigned NumElems = NVT.getVectorNumElements();
13578     assert((Idx % NumElems) == 0 &&
13579            "IDX in concat is not a multiple of the result vector length.");
13580     return V->getOperand(Idx / NumElems);
13581   }
13582 
13583   // Skip bitcasting
13584   if (V->getOpcode() == ISD::BITCAST)
13585     V = V.getOperand(0);
13586 
13587   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13588     // Handle only simple case where vector being inserted and vector
13589     // being extracted are of same type, and are half size of larger vectors.
13590     EVT BigVT = V->getOperand(0).getValueType();
13591     EVT SmallVT = V->getOperand(1).getValueType();
13592     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13593       return SDValue();
13594 
13595     // Only handle cases where both indexes are constants with the same type.
13596     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13597     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13598 
13599     if (InsIdx && ExtIdx &&
13600         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13601         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13602       // Combine:
13603       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13604       // Into:
13605       //    indices are equal or bit offsets are equal => V1
13606       //    otherwise => (extract_subvec V1, ExtIdx)
13607       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
13608           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
13609         return DAG.getBitcast(NVT, V->getOperand(1));
13610       return DAG.getNode(
13611           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
13612           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13613           N->getOperand(1));
13614     }
13615   }
13616 
13617   return SDValue();
13618 }
13619 
13620 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13621                                                  SDValue V, SelectionDAG &DAG) {
13622   SDLoc DL(V);
13623   EVT VT = V.getValueType();
13624 
13625   switch (V.getOpcode()) {
13626   default:
13627     return V;
13628 
13629   case ISD::CONCAT_VECTORS: {
13630     EVT OpVT = V->getOperand(0).getValueType();
13631     int OpSize = OpVT.getVectorNumElements();
13632     SmallBitVector OpUsedElements(OpSize, false);
13633     bool FoundSimplification = false;
13634     SmallVector<SDValue, 4> NewOps;
13635     NewOps.reserve(V->getNumOperands());
13636     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13637       SDValue Op = V->getOperand(i);
13638       bool OpUsed = false;
13639       for (int j = 0; j < OpSize; ++j)
13640         if (UsedElements[i * OpSize + j]) {
13641           OpUsedElements[j] = true;
13642           OpUsed = true;
13643         }
13644       NewOps.push_back(
13645           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13646                  : DAG.getUNDEF(OpVT));
13647       FoundSimplification |= Op == NewOps.back();
13648       OpUsedElements.reset();
13649     }
13650     if (FoundSimplification)
13651       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13652     return V;
13653   }
13654 
13655   case ISD::INSERT_SUBVECTOR: {
13656     SDValue BaseV = V->getOperand(0);
13657     SDValue SubV = V->getOperand(1);
13658     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13659     if (!IdxN)
13660       return V;
13661 
13662     int SubSize = SubV.getValueType().getVectorNumElements();
13663     int Idx = IdxN->getZExtValue();
13664     bool SubVectorUsed = false;
13665     SmallBitVector SubUsedElements(SubSize, false);
13666     for (int i = 0; i < SubSize; ++i)
13667       if (UsedElements[i + Idx]) {
13668         SubVectorUsed = true;
13669         SubUsedElements[i] = true;
13670         UsedElements[i + Idx] = false;
13671       }
13672 
13673     // Now recurse on both the base and sub vectors.
13674     SDValue SimplifiedSubV =
13675         SubVectorUsed
13676             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13677             : DAG.getUNDEF(SubV.getValueType());
13678     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13679     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13680       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13681                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13682     return V;
13683   }
13684   }
13685 }
13686 
13687 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13688                                        SDValue N1, SelectionDAG &DAG) {
13689   EVT VT = SVN->getValueType(0);
13690   int NumElts = VT.getVectorNumElements();
13691   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13692   for (int M : SVN->getMask())
13693     if (M >= 0 && M < NumElts)
13694       N0UsedElements[M] = true;
13695     else if (M >= NumElts)
13696       N1UsedElements[M - NumElts] = true;
13697 
13698   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13699   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13700   if (S0 == N0 && S1 == N1)
13701     return SDValue();
13702 
13703   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13704 }
13705 
13706 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13707 // or turn a shuffle of a single concat into simpler shuffle then concat.
13708 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13709   EVT VT = N->getValueType(0);
13710   unsigned NumElts = VT.getVectorNumElements();
13711 
13712   SDValue N0 = N->getOperand(0);
13713   SDValue N1 = N->getOperand(1);
13714   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13715 
13716   SmallVector<SDValue, 4> Ops;
13717   EVT ConcatVT = N0.getOperand(0).getValueType();
13718   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13719   unsigned NumConcats = NumElts / NumElemsPerConcat;
13720 
13721   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13722   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13723   // half vector elements.
13724   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13725       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13726                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13727     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13728                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13729     N1 = DAG.getUNDEF(ConcatVT);
13730     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13731   }
13732 
13733   // Look at every vector that's inserted. We're looking for exact
13734   // subvector-sized copies from a concatenated vector
13735   for (unsigned I = 0; I != NumConcats; ++I) {
13736     // Make sure we're dealing with a copy.
13737     unsigned Begin = I * NumElemsPerConcat;
13738     bool AllUndef = true, NoUndef = true;
13739     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13740       if (SVN->getMaskElt(J) >= 0)
13741         AllUndef = false;
13742       else
13743         NoUndef = false;
13744     }
13745 
13746     if (NoUndef) {
13747       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13748         return SDValue();
13749 
13750       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13751         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13752           return SDValue();
13753 
13754       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13755       if (FirstElt < N0.getNumOperands())
13756         Ops.push_back(N0.getOperand(FirstElt));
13757       else
13758         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13759 
13760     } else if (AllUndef) {
13761       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13762     } else { // Mixed with general masks and undefs, can't do optimization.
13763       return SDValue();
13764     }
13765   }
13766 
13767   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13768 }
13769 
13770 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13771   EVT VT = N->getValueType(0);
13772   unsigned NumElts = VT.getVectorNumElements();
13773 
13774   SDValue N0 = N->getOperand(0);
13775   SDValue N1 = N->getOperand(1);
13776 
13777   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13778 
13779   // Canonicalize shuffle undef, undef -> undef
13780   if (N0.isUndef() && N1.isUndef())
13781     return DAG.getUNDEF(VT);
13782 
13783   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13784 
13785   // Canonicalize shuffle v, v -> v, undef
13786   if (N0 == N1) {
13787     SmallVector<int, 8> NewMask;
13788     for (unsigned i = 0; i != NumElts; ++i) {
13789       int Idx = SVN->getMaskElt(i);
13790       if (Idx >= (int)NumElts) Idx -= NumElts;
13791       NewMask.push_back(Idx);
13792     }
13793     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
13794   }
13795 
13796   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13797   if (N0.isUndef())
13798     return DAG.getCommutedVectorShuffle(*SVN);
13799 
13800   // Remove references to rhs if it is undef
13801   if (N1.isUndef()) {
13802     bool Changed = false;
13803     SmallVector<int, 8> NewMask;
13804     for (unsigned i = 0; i != NumElts; ++i) {
13805       int Idx = SVN->getMaskElt(i);
13806       if (Idx >= (int)NumElts) {
13807         Idx = -1;
13808         Changed = true;
13809       }
13810       NewMask.push_back(Idx);
13811     }
13812     if (Changed)
13813       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
13814   }
13815 
13816   // If it is a splat, check if the argument vector is another splat or a
13817   // build_vector.
13818   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13819     SDNode *V = N0.getNode();
13820 
13821     // If this is a bit convert that changes the element type of the vector but
13822     // not the number of vector elements, look through it.  Be careful not to
13823     // look though conversions that change things like v4f32 to v2f64.
13824     if (V->getOpcode() == ISD::BITCAST) {
13825       SDValue ConvInput = V->getOperand(0);
13826       if (ConvInput.getValueType().isVector() &&
13827           ConvInput.getValueType().getVectorNumElements() == NumElts)
13828         V = ConvInput.getNode();
13829     }
13830 
13831     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13832       assert(V->getNumOperands() == NumElts &&
13833              "BUILD_VECTOR has wrong number of operands");
13834       SDValue Base;
13835       bool AllSame = true;
13836       for (unsigned i = 0; i != NumElts; ++i) {
13837         if (!V->getOperand(i).isUndef()) {
13838           Base = V->getOperand(i);
13839           break;
13840         }
13841       }
13842       // Splat of <u, u, u, u>, return <u, u, u, u>
13843       if (!Base.getNode())
13844         return N0;
13845       for (unsigned i = 0; i != NumElts; ++i) {
13846         if (V->getOperand(i) != Base) {
13847           AllSame = false;
13848           break;
13849         }
13850       }
13851       // Splat of <x, x, x, x>, return <x, x, x, x>
13852       if (AllSame)
13853         return N0;
13854 
13855       // Canonicalize any other splat as a build_vector.
13856       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13857       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13858       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13859 
13860       // We may have jumped through bitcasts, so the type of the
13861       // BUILD_VECTOR may not match the type of the shuffle.
13862       if (V->getValueType(0) != VT)
13863         NewBV = DAG.getBitcast(VT, NewBV);
13864       return NewBV;
13865     }
13866   }
13867 
13868   // There are various patterns used to build up a vector from smaller vectors,
13869   // subvectors, or elements. Scan chains of these and replace unused insertions
13870   // or components with undef.
13871   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13872     return S;
13873 
13874   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13875       Level < AfterLegalizeVectorOps &&
13876       (N1.isUndef() ||
13877       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13878        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13879     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13880       return V;
13881   }
13882 
13883   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13884   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13885   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13886     SmallVector<SDValue, 8> Ops;
13887     for (int M : SVN->getMask()) {
13888       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13889       if (M >= 0) {
13890         int Idx = M % NumElts;
13891         SDValue &S = (M < (int)NumElts ? N0 : N1);
13892         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13893           Op = S.getOperand(Idx);
13894         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13895           if (Idx == 0)
13896             Op = S.getOperand(0);
13897         } else {
13898           // Operand can't be combined - bail out.
13899           break;
13900         }
13901       }
13902       Ops.push_back(Op);
13903     }
13904     if (Ops.size() == VT.getVectorNumElements()) {
13905       // BUILD_VECTOR requires all inputs to be of the same type, find the
13906       // maximum type and extend them all.
13907       EVT SVT = VT.getScalarType();
13908       if (SVT.isInteger())
13909         for (SDValue &Op : Ops)
13910           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13911       if (SVT != VT.getScalarType())
13912         for (SDValue &Op : Ops)
13913           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13914                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13915                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13916       return DAG.getBuildVector(VT, SDLoc(N), Ops);
13917     }
13918   }
13919 
13920   // If this shuffle only has a single input that is a bitcasted shuffle,
13921   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13922   // back to their original types.
13923   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13924       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13925       TLI.isTypeLegal(VT)) {
13926 
13927     // Peek through the bitcast only if there is one user.
13928     SDValue BC0 = N0;
13929     while (BC0.getOpcode() == ISD::BITCAST) {
13930       if (!BC0.hasOneUse())
13931         break;
13932       BC0 = BC0.getOperand(0);
13933     }
13934 
13935     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13936       if (Scale == 1)
13937         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13938 
13939       SmallVector<int, 8> NewMask;
13940       for (int M : Mask)
13941         for (int s = 0; s != Scale; ++s)
13942           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13943       return NewMask;
13944     };
13945 
13946     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13947       EVT SVT = VT.getScalarType();
13948       EVT InnerVT = BC0->getValueType(0);
13949       EVT InnerSVT = InnerVT.getScalarType();
13950 
13951       // Determine which shuffle works with the smaller scalar type.
13952       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13953       EVT ScaleSVT = ScaleVT.getScalarType();
13954 
13955       if (TLI.isTypeLegal(ScaleVT) &&
13956           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13957           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13958 
13959         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13960         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13961 
13962         // Scale the shuffle masks to the smaller scalar type.
13963         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13964         SmallVector<int, 8> InnerMask =
13965             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13966         SmallVector<int, 8> OuterMask =
13967             ScaleShuffleMask(SVN->getMask(), OuterScale);
13968 
13969         // Merge the shuffle masks.
13970         SmallVector<int, 8> NewMask;
13971         for (int M : OuterMask)
13972           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13973 
13974         // Test for shuffle mask legality over both commutations.
13975         SDValue SV0 = BC0->getOperand(0);
13976         SDValue SV1 = BC0->getOperand(1);
13977         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13978         if (!LegalMask) {
13979           std::swap(SV0, SV1);
13980           ShuffleVectorSDNode::commuteMask(NewMask);
13981           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13982         }
13983 
13984         if (LegalMask) {
13985           SV0 = DAG.getBitcast(ScaleVT, SV0);
13986           SV1 = DAG.getBitcast(ScaleVT, SV1);
13987           return DAG.getBitcast(
13988               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13989         }
13990       }
13991     }
13992   }
13993 
13994   // Canonicalize shuffles according to rules:
13995   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13996   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13997   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13998   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13999       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
14000       TLI.isTypeLegal(VT)) {
14001     // The incoming shuffle must be of the same type as the result of the
14002     // current shuffle.
14003     assert(N1->getOperand(0).getValueType() == VT &&
14004            "Shuffle types don't match");
14005 
14006     SDValue SV0 = N1->getOperand(0);
14007     SDValue SV1 = N1->getOperand(1);
14008     bool HasSameOp0 = N0 == SV0;
14009     bool IsSV1Undef = SV1.isUndef();
14010     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
14011       // Commute the operands of this shuffle so that next rule
14012       // will trigger.
14013       return DAG.getCommutedVectorShuffle(*SVN);
14014   }
14015 
14016   // Try to fold according to rules:
14017   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14018   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14019   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14020   // Don't try to fold shuffles with illegal type.
14021   // Only fold if this shuffle is the only user of the other shuffle.
14022   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
14023       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
14024     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
14025 
14026     // The incoming shuffle must be of the same type as the result of the
14027     // current shuffle.
14028     assert(OtherSV->getOperand(0).getValueType() == VT &&
14029            "Shuffle types don't match");
14030 
14031     SDValue SV0, SV1;
14032     SmallVector<int, 4> Mask;
14033     // Compute the combined shuffle mask for a shuffle with SV0 as the first
14034     // operand, and SV1 as the second operand.
14035     for (unsigned i = 0; i != NumElts; ++i) {
14036       int Idx = SVN->getMaskElt(i);
14037       if (Idx < 0) {
14038         // Propagate Undef.
14039         Mask.push_back(Idx);
14040         continue;
14041       }
14042 
14043       SDValue CurrentVec;
14044       if (Idx < (int)NumElts) {
14045         // This shuffle index refers to the inner shuffle N0. Lookup the inner
14046         // shuffle mask to identify which vector is actually referenced.
14047         Idx = OtherSV->getMaskElt(Idx);
14048         if (Idx < 0) {
14049           // Propagate Undef.
14050           Mask.push_back(Idx);
14051           continue;
14052         }
14053 
14054         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
14055                                            : OtherSV->getOperand(1);
14056       } else {
14057         // This shuffle index references an element within N1.
14058         CurrentVec = N1;
14059       }
14060 
14061       // Simple case where 'CurrentVec' is UNDEF.
14062       if (CurrentVec.isUndef()) {
14063         Mask.push_back(-1);
14064         continue;
14065       }
14066 
14067       // Canonicalize the shuffle index. We don't know yet if CurrentVec
14068       // will be the first or second operand of the combined shuffle.
14069       Idx = Idx % NumElts;
14070       if (!SV0.getNode() || SV0 == CurrentVec) {
14071         // Ok. CurrentVec is the left hand side.
14072         // Update the mask accordingly.
14073         SV0 = CurrentVec;
14074         Mask.push_back(Idx);
14075         continue;
14076       }
14077 
14078       // Bail out if we cannot convert the shuffle pair into a single shuffle.
14079       if (SV1.getNode() && SV1 != CurrentVec)
14080         return SDValue();
14081 
14082       // Ok. CurrentVec is the right hand side.
14083       // Update the mask accordingly.
14084       SV1 = CurrentVec;
14085       Mask.push_back(Idx + NumElts);
14086     }
14087 
14088     // Check if all indices in Mask are Undef. In case, propagate Undef.
14089     bool isUndefMask = true;
14090     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
14091       isUndefMask &= Mask[i] < 0;
14092 
14093     if (isUndefMask)
14094       return DAG.getUNDEF(VT);
14095 
14096     if (!SV0.getNode())
14097       SV0 = DAG.getUNDEF(VT);
14098     if (!SV1.getNode())
14099       SV1 = DAG.getUNDEF(VT);
14100 
14101     // Avoid introducing shuffles with illegal mask.
14102     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14103       ShuffleVectorSDNode::commuteMask(Mask);
14104 
14105       if (!TLI.isShuffleMaskLegal(Mask, VT))
14106         return SDValue();
14107 
14108       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14109       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14110       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14111       std::swap(SV0, SV1);
14112     }
14113 
14114     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14115     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14116     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14117     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14118   }
14119 
14120   return SDValue();
14121 }
14122 
14123 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14124   SDValue InVal = N->getOperand(0);
14125   EVT VT = N->getValueType(0);
14126 
14127   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14128   // with a VECTOR_SHUFFLE.
14129   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14130     SDValue InVec = InVal->getOperand(0);
14131     SDValue EltNo = InVal->getOperand(1);
14132 
14133     // FIXME: We could support implicit truncation if the shuffle can be
14134     // scaled to a smaller vector scalar type.
14135     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
14136     if (C0 && VT == InVec.getValueType() &&
14137         VT.getScalarType() == InVal.getValueType()) {
14138       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
14139       int Elt = C0->getZExtValue();
14140       NewMask[0] = Elt;
14141 
14142       if (TLI.isShuffleMaskLegal(NewMask, VT))
14143         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
14144                                     NewMask);
14145     }
14146   }
14147 
14148   return SDValue();
14149 }
14150 
14151 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
14152   EVT VT = N->getValueType(0);
14153   SDValue N0 = N->getOperand(0);
14154   SDValue N1 = N->getOperand(1);
14155   SDValue N2 = N->getOperand(2);
14156 
14157   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
14158   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
14159   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
14160   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
14161       N0.getOperand(1).getValueType() == N1.getValueType() &&
14162       N0.getOperand(2) == N2)
14163     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
14164                        N1, N2);
14165 
14166   if (N0.getValueType() != N1.getValueType())
14167     return SDValue();
14168 
14169   // If the input vector is a concatenation, and the insert replaces
14170   // one of the halves, we can optimize into a single concat_vectors.
14171   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
14172       N2.getOpcode() == ISD::Constant) {
14173     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
14174 
14175     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14176     // (concat_vectors Z, Y)
14177     if (InsIdx == 0)
14178       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
14179                          N0.getOperand(1));
14180 
14181     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14182     // (concat_vectors X, Z)
14183     if (InsIdx == VT.getVectorNumElements() / 2)
14184       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
14185                          N1);
14186   }
14187 
14188   return SDValue();
14189 }
14190 
14191 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
14192   SDValue N0 = N->getOperand(0);
14193 
14194   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
14195   if (N0->getOpcode() == ISD::FP16_TO_FP)
14196     return N0->getOperand(0);
14197 
14198   return SDValue();
14199 }
14200 
14201 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
14202   SDValue N0 = N->getOperand(0);
14203 
14204   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
14205   if (N0->getOpcode() == ISD::AND) {
14206     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
14207     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
14208       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
14209                          N0.getOperand(0));
14210     }
14211   }
14212 
14213   return SDValue();
14214 }
14215 
14216 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
14217 /// with the destination vector and a zero vector.
14218 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
14219 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
14220 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
14221   EVT VT = N->getValueType(0);
14222   SDValue LHS = N->getOperand(0);
14223   SDValue RHS = N->getOperand(1);
14224   SDLoc DL(N);
14225 
14226   // Make sure we're not running after operation legalization where it
14227   // may have custom lowered the vector shuffles.
14228   if (LegalOperations)
14229     return SDValue();
14230 
14231   if (N->getOpcode() != ISD::AND)
14232     return SDValue();
14233 
14234   if (RHS.getOpcode() == ISD::BITCAST)
14235     RHS = RHS.getOperand(0);
14236 
14237   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
14238     return SDValue();
14239 
14240   EVT RVT = RHS.getValueType();
14241   unsigned NumElts = RHS.getNumOperands();
14242 
14243   // Attempt to create a valid clear mask, splitting the mask into
14244   // sub elements and checking to see if each is
14245   // all zeros or all ones - suitable for shuffle masking.
14246   auto BuildClearMask = [&](int Split) {
14247     int NumSubElts = NumElts * Split;
14248     int NumSubBits = RVT.getScalarSizeInBits() / Split;
14249 
14250     SmallVector<int, 8> Indices;
14251     for (int i = 0; i != NumSubElts; ++i) {
14252       int EltIdx = i / Split;
14253       int SubIdx = i % Split;
14254       SDValue Elt = RHS.getOperand(EltIdx);
14255       if (Elt.isUndef()) {
14256         Indices.push_back(-1);
14257         continue;
14258       }
14259 
14260       APInt Bits;
14261       if (isa<ConstantSDNode>(Elt))
14262         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
14263       else if (isa<ConstantFPSDNode>(Elt))
14264         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
14265       else
14266         return SDValue();
14267 
14268       // Extract the sub element from the constant bit mask.
14269       if (DAG.getDataLayout().isBigEndian()) {
14270         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
14271       } else {
14272         Bits = Bits.lshr(SubIdx * NumSubBits);
14273       }
14274 
14275       if (Split > 1)
14276         Bits = Bits.trunc(NumSubBits);
14277 
14278       if (Bits.isAllOnesValue())
14279         Indices.push_back(i);
14280       else if (Bits == 0)
14281         Indices.push_back(i + NumSubElts);
14282       else
14283         return SDValue();
14284     }
14285 
14286     // Let's see if the target supports this vector_shuffle.
14287     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
14288     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
14289     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
14290       return SDValue();
14291 
14292     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
14293     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
14294                                                    DAG.getBitcast(ClearVT, LHS),
14295                                                    Zero, Indices));
14296   };
14297 
14298   // Determine maximum split level (byte level masking).
14299   int MaxSplit = 1;
14300   if (RVT.getScalarSizeInBits() % 8 == 0)
14301     MaxSplit = RVT.getScalarSizeInBits() / 8;
14302 
14303   for (int Split = 1; Split <= MaxSplit; ++Split)
14304     if (RVT.getScalarSizeInBits() % Split == 0)
14305       if (SDValue S = BuildClearMask(Split))
14306         return S;
14307 
14308   return SDValue();
14309 }
14310 
14311 /// Visit a binary vector operation, like ADD.
14312 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
14313   assert(N->getValueType(0).isVector() &&
14314          "SimplifyVBinOp only works on vectors!");
14315 
14316   SDValue LHS = N->getOperand(0);
14317   SDValue RHS = N->getOperand(1);
14318   SDValue Ops[] = {LHS, RHS};
14319 
14320   // See if we can constant fold the vector operation.
14321   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
14322           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
14323     return Fold;
14324 
14325   // Try to convert a constant mask AND into a shuffle clear mask.
14326   if (SDValue Shuffle = XformToShuffleWithZero(N))
14327     return Shuffle;
14328 
14329   // Type legalization might introduce new shuffles in the DAG.
14330   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
14331   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
14332   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
14333       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
14334       LHS.getOperand(1).isUndef() &&
14335       RHS.getOperand(1).isUndef()) {
14336     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
14337     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
14338 
14339     if (SVN0->getMask().equals(SVN1->getMask())) {
14340       EVT VT = N->getValueType(0);
14341       SDValue UndefVector = LHS.getOperand(1);
14342       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
14343                                      LHS.getOperand(0), RHS.getOperand(0),
14344                                      N->getFlags());
14345       AddUsersToWorklist(N);
14346       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
14347                                   SVN0->getMask());
14348     }
14349   }
14350 
14351   return SDValue();
14352 }
14353 
14354 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
14355                                     SDValue N2) {
14356   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
14357 
14358   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
14359                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
14360 
14361   // If we got a simplified select_cc node back from SimplifySelectCC, then
14362   // break it down into a new SETCC node, and a new SELECT node, and then return
14363   // the SELECT node, since we were called with a SELECT node.
14364   if (SCC.getNode()) {
14365     // Check to see if we got a select_cc back (to turn into setcc/select).
14366     // Otherwise, just return whatever node we got back, like fabs.
14367     if (SCC.getOpcode() == ISD::SELECT_CC) {
14368       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
14369                                   N0.getValueType(),
14370                                   SCC.getOperand(0), SCC.getOperand(1),
14371                                   SCC.getOperand(4));
14372       AddToWorklist(SETCC.getNode());
14373       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14374                            SCC.getOperand(2), SCC.getOperand(3));
14375     }
14376 
14377     return SCC;
14378   }
14379   return SDValue();
14380 }
14381 
14382 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14383 /// being selected between, see if we can simplify the select.  Callers of this
14384 /// should assume that TheSelect is deleted if this returns true.  As such, they
14385 /// should return the appropriate thing (e.g. the node) back to the top-level of
14386 /// the DAG combiner loop to avoid it being looked at.
14387 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14388                                     SDValue RHS) {
14389 
14390   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14391   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14392   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14393     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14394       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14395       SDValue Sqrt = RHS;
14396       ISD::CondCode CC;
14397       SDValue CmpLHS;
14398       const ConstantFPSDNode *Zero = nullptr;
14399 
14400       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14401         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14402         CmpLHS = TheSelect->getOperand(0);
14403         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14404       } else {
14405         // SELECT or VSELECT
14406         SDValue Cmp = TheSelect->getOperand(0);
14407         if (Cmp.getOpcode() == ISD::SETCC) {
14408           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14409           CmpLHS = Cmp.getOperand(0);
14410           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14411         }
14412       }
14413       if (Zero && Zero->isZero() &&
14414           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14415           CC == ISD::SETULT || CC == ISD::SETLT)) {
14416         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14417         CombineTo(TheSelect, Sqrt);
14418         return true;
14419       }
14420     }
14421   }
14422   // Cannot simplify select with vector condition
14423   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14424 
14425   // If this is a select from two identical things, try to pull the operation
14426   // through the select.
14427   if (LHS.getOpcode() != RHS.getOpcode() ||
14428       !LHS.hasOneUse() || !RHS.hasOneUse())
14429     return false;
14430 
14431   // If this is a load and the token chain is identical, replace the select
14432   // of two loads with a load through a select of the address to load from.
14433   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14434   // constants have been dropped into the constant pool.
14435   if (LHS.getOpcode() == ISD::LOAD) {
14436     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14437     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14438 
14439     // Token chains must be identical.
14440     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14441         // Do not let this transformation reduce the number of volatile loads.
14442         LLD->isVolatile() || RLD->isVolatile() ||
14443         // FIXME: If either is a pre/post inc/dec load,
14444         // we'd need to split out the address adjustment.
14445         LLD->isIndexed() || RLD->isIndexed() ||
14446         // If this is an EXTLOAD, the VT's must match.
14447         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14448         // If this is an EXTLOAD, the kind of extension must match.
14449         (LLD->getExtensionType() != RLD->getExtensionType() &&
14450          // The only exception is if one of the extensions is anyext.
14451          LLD->getExtensionType() != ISD::EXTLOAD &&
14452          RLD->getExtensionType() != ISD::EXTLOAD) ||
14453         // FIXME: this discards src value information.  This is
14454         // over-conservative. It would be beneficial to be able to remember
14455         // both potential memory locations.  Since we are discarding
14456         // src value info, don't do the transformation if the memory
14457         // locations are not in the default address space.
14458         LLD->getPointerInfo().getAddrSpace() != 0 ||
14459         RLD->getPointerInfo().getAddrSpace() != 0 ||
14460         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14461                                       LLD->getBasePtr().getValueType()))
14462       return false;
14463 
14464     // Check that the select condition doesn't reach either load.  If so,
14465     // folding this will induce a cycle into the DAG.  If not, this is safe to
14466     // xform, so create a select of the addresses.
14467     SDValue Addr;
14468     if (TheSelect->getOpcode() == ISD::SELECT) {
14469       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14470       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14471           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14472         return false;
14473       // The loads must not depend on one another.
14474       if (LLD->isPredecessorOf(RLD) ||
14475           RLD->isPredecessorOf(LLD))
14476         return false;
14477       Addr = DAG.getSelect(SDLoc(TheSelect),
14478                            LLD->getBasePtr().getValueType(),
14479                            TheSelect->getOperand(0), LLD->getBasePtr(),
14480                            RLD->getBasePtr());
14481     } else {  // Otherwise SELECT_CC
14482       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14483       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14484 
14485       if ((LLD->hasAnyUseOfValue(1) &&
14486            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14487           (RLD->hasAnyUseOfValue(1) &&
14488            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14489         return false;
14490 
14491       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14492                          LLD->getBasePtr().getValueType(),
14493                          TheSelect->getOperand(0),
14494                          TheSelect->getOperand(1),
14495                          LLD->getBasePtr(), RLD->getBasePtr(),
14496                          TheSelect->getOperand(4));
14497     }
14498 
14499     SDValue Load;
14500     // It is safe to replace the two loads if they have different alignments,
14501     // but the new load must be the minimum (most restrictive) alignment of the
14502     // inputs.
14503     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14504     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
14505     if (!RLD->isInvariant())
14506       MMOFlags &= ~MachineMemOperand::MOInvariant;
14507     if (!RLD->isDereferenceable())
14508       MMOFlags &= ~MachineMemOperand::MODereferenceable;
14509     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14510       // FIXME: Discards pointer and AA info.
14511       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
14512                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
14513                          MMOFlags);
14514     } else {
14515       // FIXME: Discards pointer and AA info.
14516       Load = DAG.getExtLoad(
14517           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
14518                                                   : LLD->getExtensionType(),
14519           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
14520           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
14521     }
14522 
14523     // Users of the select now use the result of the load.
14524     CombineTo(TheSelect, Load);
14525 
14526     // Users of the old loads now use the new load's chain.  We know the
14527     // old-load value is dead now.
14528     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14529     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14530     return true;
14531   }
14532 
14533   return false;
14534 }
14535 
14536 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14537 /// where 'cond' is the comparison specified by CC.
14538 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
14539                                       SDValue N2, SDValue N3, ISD::CondCode CC,
14540                                       bool NotExtCompare) {
14541   // (x ? y : y) -> y.
14542   if (N2 == N3) return N2;
14543 
14544   EVT VT = N2.getValueType();
14545   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14546   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14547 
14548   // Determine if the condition we're dealing with is constant
14549   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14550                               N0, N1, CC, DL, false);
14551   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14552 
14553   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14554     // fold select_cc true, x, y -> x
14555     // fold select_cc false, x, y -> y
14556     return !SCCC->isNullValue() ? N2 : N3;
14557   }
14558 
14559   // Check to see if we can simplify the select into an fabs node
14560   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14561     // Allow either -0.0 or 0.0
14562     if (CFP->isZero()) {
14563       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14564       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14565           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14566           N2 == N3.getOperand(0))
14567         return DAG.getNode(ISD::FABS, DL, VT, N0);
14568 
14569       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14570       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14571           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14572           N2.getOperand(0) == N3)
14573         return DAG.getNode(ISD::FABS, DL, VT, N3);
14574     }
14575   }
14576 
14577   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14578   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14579   // in it.  This is a win when the constant is not otherwise available because
14580   // it replaces two constant pool loads with one.  We only do this if the FP
14581   // type is known to be legal, because if it isn't, then we are before legalize
14582   // types an we want the other legalization to happen first (e.g. to avoid
14583   // messing with soft float) and if the ConstantFP is not legal, because if
14584   // it is legal, we may not need to store the FP constant in a constant pool.
14585   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14586     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14587       if (TLI.isTypeLegal(N2.getValueType()) &&
14588           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14589                TargetLowering::Legal &&
14590            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14591            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14592           // If both constants have multiple uses, then we won't need to do an
14593           // extra load, they are likely around in registers for other users.
14594           (TV->hasOneUse() || FV->hasOneUse())) {
14595         Constant *Elts[] = {
14596           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14597           const_cast<ConstantFP*>(TV->getConstantFPValue())
14598         };
14599         Type *FPTy = Elts[0]->getType();
14600         const DataLayout &TD = DAG.getDataLayout();
14601 
14602         // Create a ConstantArray of the two constants.
14603         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14604         SDValue CPIdx =
14605             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14606                                 TD.getPrefTypeAlignment(FPTy));
14607         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14608 
14609         // Get the offsets to the 0 and 1 element of the array so that we can
14610         // select between them.
14611         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14612         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14613         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14614 
14615         SDValue Cond = DAG.getSetCC(DL,
14616                                     getSetCCResultType(N0.getValueType()),
14617                                     N0, N1, CC);
14618         AddToWorklist(Cond.getNode());
14619         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14620                                           Cond, One, Zero);
14621         AddToWorklist(CstOffset.getNode());
14622         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14623                             CstOffset);
14624         AddToWorklist(CPIdx.getNode());
14625         return DAG.getLoad(
14626             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14627             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14628             Alignment);
14629       }
14630     }
14631 
14632   // Check to see if we can perform the "gzip trick", transforming
14633   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14634   if (isNullConstant(N3) && CC == ISD::SETLT &&
14635       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14636        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14637     EVT XType = N0.getValueType();
14638     EVT AType = N2.getValueType();
14639     if (XType.bitsGE(AType)) {
14640       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14641       // single-bit constant.
14642       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14643         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14644         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14645         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14646                                        getShiftAmountTy(N0.getValueType()));
14647         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14648                                     XType, N0, ShCt);
14649         AddToWorklist(Shift.getNode());
14650 
14651         if (XType.bitsGT(AType)) {
14652           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14653           AddToWorklist(Shift.getNode());
14654         }
14655 
14656         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14657       }
14658 
14659       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14660                                   XType, N0,
14661                                   DAG.getConstant(XType.getSizeInBits() - 1,
14662                                                   SDLoc(N0),
14663                                          getShiftAmountTy(N0.getValueType())));
14664       AddToWorklist(Shift.getNode());
14665 
14666       if (XType.bitsGT(AType)) {
14667         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14668         AddToWorklist(Shift.getNode());
14669       }
14670 
14671       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14672     }
14673   }
14674 
14675   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14676   // where y is has a single bit set.
14677   // A plaintext description would be, we can turn the SELECT_CC into an AND
14678   // when the condition can be materialized as an all-ones register.  Any
14679   // single bit-test can be materialized as an all-ones register with
14680   // shift-left and shift-right-arith.
14681   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14682       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14683     SDValue AndLHS = N0->getOperand(0);
14684     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14685     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14686       // Shift the tested bit over the sign bit.
14687       const APInt &AndMask = ConstAndRHS->getAPIntValue();
14688       SDValue ShlAmt =
14689         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14690                         getShiftAmountTy(AndLHS.getValueType()));
14691       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14692 
14693       // Now arithmetic right shift it all the way over, so the result is either
14694       // all-ones, or zero.
14695       SDValue ShrAmt =
14696         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14697                         getShiftAmountTy(Shl.getValueType()));
14698       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14699 
14700       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14701     }
14702   }
14703 
14704   // fold select C, 16, 0 -> shl C, 4
14705   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14706       TLI.getBooleanContents(N0.getValueType()) ==
14707           TargetLowering::ZeroOrOneBooleanContent) {
14708 
14709     // If the caller doesn't want us to simplify this into a zext of a compare,
14710     // don't do it.
14711     if (NotExtCompare && N2C->isOne())
14712       return SDValue();
14713 
14714     // Get a SetCC of the condition
14715     // NOTE: Don't create a SETCC if it's not legal on this target.
14716     if (!LegalOperations ||
14717         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14718       SDValue Temp, SCC;
14719       // cast from setcc result type to select result type
14720       if (LegalTypes) {
14721         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14722                             N0, N1, CC);
14723         if (N2.getValueType().bitsLT(SCC.getValueType()))
14724           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14725                                         N2.getValueType());
14726         else
14727           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14728                              N2.getValueType(), SCC);
14729       } else {
14730         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14731         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14732                            N2.getValueType(), SCC);
14733       }
14734 
14735       AddToWorklist(SCC.getNode());
14736       AddToWorklist(Temp.getNode());
14737 
14738       if (N2C->isOne())
14739         return Temp;
14740 
14741       // shl setcc result by log2 n2c
14742       return DAG.getNode(
14743           ISD::SHL, DL, N2.getValueType(), Temp,
14744           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14745                           getShiftAmountTy(Temp.getValueType())));
14746     }
14747   }
14748 
14749   // Check to see if this is an integer abs.
14750   // select_cc setg[te] X,  0,  X, -X ->
14751   // select_cc setgt    X, -1,  X, -X ->
14752   // select_cc setl[te] X,  0, -X,  X ->
14753   // select_cc setlt    X,  1, -X,  X ->
14754   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14755   if (N1C) {
14756     ConstantSDNode *SubC = nullptr;
14757     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14758          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14759         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14760       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14761     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14762               (N1C->isOne() && CC == ISD::SETLT)) &&
14763              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14764       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14765 
14766     EVT XType = N0.getValueType();
14767     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14768       SDLoc DL(N0);
14769       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14770                                   N0,
14771                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14772                                          getShiftAmountTy(N0.getValueType())));
14773       SDValue Add = DAG.getNode(ISD::ADD, DL,
14774                                 XType, N0, Shift);
14775       AddToWorklist(Shift.getNode());
14776       AddToWorklist(Add.getNode());
14777       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14778     }
14779   }
14780 
14781   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14782   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14783   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14784   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14785   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14786   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14787   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14788   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14789   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14790     SDValue ValueOnZero = N2;
14791     SDValue Count = N3;
14792     // If the condition is NE instead of E, swap the operands.
14793     if (CC == ISD::SETNE)
14794       std::swap(ValueOnZero, Count);
14795     // Check if the value on zero is a constant equal to the bits in the type.
14796     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14797       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14798         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14799         // legal, combine to just cttz.
14800         if ((Count.getOpcode() == ISD::CTTZ ||
14801              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14802             N0 == Count.getOperand(0) &&
14803             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14804           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14805         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14806         // legal, combine to just ctlz.
14807         if ((Count.getOpcode() == ISD::CTLZ ||
14808              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14809             N0 == Count.getOperand(0) &&
14810             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14811           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14812       }
14813     }
14814   }
14815 
14816   return SDValue();
14817 }
14818 
14819 /// This is a stub for TargetLowering::SimplifySetCC.
14820 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
14821                                    ISD::CondCode Cond, const SDLoc &DL,
14822                                    bool foldBooleans) {
14823   TargetLowering::DAGCombinerInfo
14824     DagCombineInfo(DAG, Level, false, this);
14825   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14826 }
14827 
14828 /// Given an ISD::SDIV node expressing a divide by constant, return
14829 /// a DAG expression to select that will generate the same value by multiplying
14830 /// by a magic number.
14831 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14832 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14833   // when optimising for minimum size, we don't want to expand a div to a mul
14834   // and a shift.
14835   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14836     return SDValue();
14837 
14838   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14839   if (!C)
14840     return SDValue();
14841 
14842   // Avoid division by zero.
14843   if (C->isNullValue())
14844     return SDValue();
14845 
14846   std::vector<SDNode*> Built;
14847   SDValue S =
14848       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14849 
14850   for (SDNode *N : Built)
14851     AddToWorklist(N);
14852   return S;
14853 }
14854 
14855 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14856 /// DAG expression that will generate the same value by right shifting.
14857 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14858   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14859   if (!C)
14860     return SDValue();
14861 
14862   // Avoid division by zero.
14863   if (C->isNullValue())
14864     return SDValue();
14865 
14866   std::vector<SDNode *> Built;
14867   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14868 
14869   for (SDNode *N : Built)
14870     AddToWorklist(N);
14871   return S;
14872 }
14873 
14874 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14875 /// expression that will generate the same value by multiplying by a magic
14876 /// number.
14877 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14878 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14879   // when optimising for minimum size, we don't want to expand a div to a mul
14880   // and a shift.
14881   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14882     return SDValue();
14883 
14884   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14885   if (!C)
14886     return SDValue();
14887 
14888   // Avoid division by zero.
14889   if (C->isNullValue())
14890     return SDValue();
14891 
14892   std::vector<SDNode*> Built;
14893   SDValue S =
14894       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14895 
14896   for (SDNode *N : Built)
14897     AddToWorklist(N);
14898   return S;
14899 }
14900 
14901 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14902   if (Level >= AfterLegalizeDAG)
14903     return SDValue();
14904 
14905   // Expose the DAG combiner to the target combiner implementations.
14906   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14907 
14908   unsigned Iterations = 0;
14909   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14910     if (Iterations) {
14911       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14912       // For the reciprocal, we need to find the zero of the function:
14913       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14914       //     =>
14915       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14916       //     does not require additional intermediate precision]
14917       EVT VT = Op.getValueType();
14918       SDLoc DL(Op);
14919       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14920 
14921       AddToWorklist(Est.getNode());
14922 
14923       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14924       for (unsigned i = 0; i < Iterations; ++i) {
14925         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14926         AddToWorklist(NewEst.getNode());
14927 
14928         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14929         AddToWorklist(NewEst.getNode());
14930 
14931         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14932         AddToWorklist(NewEst.getNode());
14933 
14934         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14935         AddToWorklist(Est.getNode());
14936       }
14937     }
14938     return Est;
14939   }
14940 
14941   return SDValue();
14942 }
14943 
14944 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14945 /// For the reciprocal sqrt, we need to find the zero of the function:
14946 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14947 ///     =>
14948 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14949 /// As a result, we precompute A/2 prior to the iteration loop.
14950 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
14951                                          unsigned Iterations,
14952                                          SDNodeFlags *Flags, bool Reciprocal) {
14953   EVT VT = Arg.getValueType();
14954   SDLoc DL(Arg);
14955   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14956 
14957   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14958   // this entire sequence requires only one FP constant.
14959   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14960   AddToWorklist(HalfArg.getNode());
14961 
14962   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14963   AddToWorklist(HalfArg.getNode());
14964 
14965   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14966   for (unsigned i = 0; i < Iterations; ++i) {
14967     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14968     AddToWorklist(NewEst.getNode());
14969 
14970     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14971     AddToWorklist(NewEst.getNode());
14972 
14973     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14974     AddToWorklist(NewEst.getNode());
14975 
14976     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14977     AddToWorklist(Est.getNode());
14978   }
14979 
14980   // If non-reciprocal square root is requested, multiply the result by Arg.
14981   if (!Reciprocal) {
14982     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14983     AddToWorklist(Est.getNode());
14984   }
14985 
14986   return Est;
14987 }
14988 
14989 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14990 /// For the reciprocal sqrt, we need to find the zero of the function:
14991 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14992 ///     =>
14993 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14994 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
14995                                          unsigned Iterations,
14996                                          SDNodeFlags *Flags, bool Reciprocal) {
14997   EVT VT = Arg.getValueType();
14998   SDLoc DL(Arg);
14999   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
15000   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
15001 
15002   // This routine must enter the loop below to work correctly
15003   // when (Reciprocal == false).
15004   assert(Iterations > 0);
15005 
15006   // Newton iterations for reciprocal square root:
15007   // E = (E * -0.5) * ((A * E) * E + -3.0)
15008   for (unsigned i = 0; i < Iterations; ++i) {
15009     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
15010     AddToWorklist(AE.getNode());
15011 
15012     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
15013     AddToWorklist(AEE.getNode());
15014 
15015     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
15016     AddToWorklist(RHS.getNode());
15017 
15018     // When calculating a square root at the last iteration build:
15019     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
15020     // (notice a common subexpression)
15021     SDValue LHS;
15022     if (Reciprocal || (i + 1) < Iterations) {
15023       // RSQRT: LHS = (E * -0.5)
15024       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
15025     } else {
15026       // SQRT: LHS = (A * E) * -0.5
15027       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
15028     }
15029     AddToWorklist(LHS.getNode());
15030 
15031     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
15032     AddToWorklist(Est.getNode());
15033   }
15034 
15035   return Est;
15036 }
15037 
15038 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
15039 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
15040 /// Op can be zero.
15041 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
15042                                            bool Reciprocal) {
15043   if (Level >= AfterLegalizeDAG)
15044     return SDValue();
15045 
15046   // Expose the DAG combiner to the target combiner implementations.
15047   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
15048   unsigned Iterations = 0;
15049   bool UseOneConstNR = false;
15050   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
15051     AddToWorklist(Est.getNode());
15052     if (Iterations) {
15053       Est = UseOneConstNR
15054                 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
15055                 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
15056     }
15057     return Est;
15058   }
15059 
15060   return SDValue();
15061 }
15062 
15063 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15064   return buildSqrtEstimateImpl(Op, Flags, true);
15065 }
15066 
15067 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15068   SDValue Est = buildSqrtEstimateImpl(Op, Flags, false);
15069   if (!Est)
15070     return SDValue();
15071 
15072   // Unfortunately, Est is now NaN if the input was exactly 0.
15073   // Select out this case and force the answer to 0.
15074   EVT VT = Est.getValueType();
15075   SDLoc DL(Op);
15076   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
15077   EVT CCVT = getSetCCResultType(VT);
15078   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, Zero, ISD::SETEQ);
15079   AddToWorklist(ZeroCmp.getNode());
15080 
15081   Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, ZeroCmp,
15082                     Zero, Est);
15083   AddToWorklist(Est.getNode());
15084   return Est;
15085 }
15086 
15087 /// Return true if base is a frame index, which is known not to alias with
15088 /// anything but itself.  Provides base object and offset as results.
15089 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
15090                            const GlobalValue *&GV, const void *&CV) {
15091   // Assume it is a primitive operation.
15092   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
15093 
15094   // If it's an adding a simple constant then integrate the offset.
15095   if (Base.getOpcode() == ISD::ADD) {
15096     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
15097       Base = Base.getOperand(0);
15098       Offset += C->getZExtValue();
15099     }
15100   }
15101 
15102   // Return the underlying GlobalValue, and update the Offset.  Return false
15103   // for GlobalAddressSDNode since the same GlobalAddress may be represented
15104   // by multiple nodes with different offsets.
15105   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
15106     GV = G->getGlobal();
15107     Offset += G->getOffset();
15108     return false;
15109   }
15110 
15111   // Return the underlying Constant value, and update the Offset.  Return false
15112   // for ConstantSDNodes since the same constant pool entry may be represented
15113   // by multiple nodes with different offsets.
15114   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
15115     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
15116                                          : (const void *)C->getConstVal();
15117     Offset += C->getOffset();
15118     return false;
15119   }
15120   // If it's any of the following then it can't alias with anything but itself.
15121   return isa<FrameIndexSDNode>(Base);
15122 }
15123 
15124 /// Return true if there is any possibility that the two addresses overlap.
15125 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
15126   // If they are the same then they must be aliases.
15127   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
15128 
15129   // If they are both volatile then they cannot be reordered.
15130   if (Op0->isVolatile() && Op1->isVolatile()) return true;
15131 
15132   // If one operation reads from invariant memory, and the other may store, they
15133   // cannot alias. These should really be checking the equivalent of mayWrite,
15134   // but it only matters for memory nodes other than load /store.
15135   if (Op0->isInvariant() && Op1->writeMem())
15136     return false;
15137 
15138   if (Op1->isInvariant() && Op0->writeMem())
15139     return false;
15140 
15141   // Gather base node and offset information.
15142   SDValue Base1, Base2;
15143   int64_t Offset1, Offset2;
15144   const GlobalValue *GV1, *GV2;
15145   const void *CV1, *CV2;
15146   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
15147                                       Base1, Offset1, GV1, CV1);
15148   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
15149                                       Base2, Offset2, GV2, CV2);
15150 
15151   // If they have a same base address then check to see if they overlap.
15152   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
15153     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15154              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15155 
15156   // It is possible for different frame indices to alias each other, mostly
15157   // when tail call optimization reuses return address slots for arguments.
15158   // To catch this case, look up the actual index of frame indices to compute
15159   // the real alias relationship.
15160   if (isFrameIndex1 && isFrameIndex2) {
15161     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
15162     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
15163     Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
15164     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15165              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15166   }
15167 
15168   // Otherwise, if we know what the bases are, and they aren't identical, then
15169   // we know they cannot alias.
15170   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
15171     return false;
15172 
15173   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
15174   // compared to the size and offset of the access, we may be able to prove they
15175   // do not alias.  This check is conservative for now to catch cases created by
15176   // splitting vector types.
15177   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
15178       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
15179       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
15180        Op1->getMemoryVT().getSizeInBits() >> 3) &&
15181       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
15182     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
15183     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
15184 
15185     // There is no overlap between these relatively aligned accesses of similar
15186     // size, return no alias.
15187     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
15188         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
15189       return false;
15190   }
15191 
15192   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
15193                    ? CombinerGlobalAA
15194                    : DAG.getSubtarget().useAA();
15195 #ifndef NDEBUG
15196   if (CombinerAAOnlyFunc.getNumOccurrences() &&
15197       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
15198     UseAA = false;
15199 #endif
15200   if (UseAA &&
15201       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
15202     // Use alias analysis information.
15203     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
15204                                  Op1->getSrcValueOffset());
15205     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
15206         Op0->getSrcValueOffset() - MinOffset;
15207     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
15208         Op1->getSrcValueOffset() - MinOffset;
15209     AliasResult AAResult =
15210         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
15211                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
15212                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
15213                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
15214     if (AAResult == NoAlias)
15215       return false;
15216   }
15217 
15218   // Otherwise we have to assume they alias.
15219   return true;
15220 }
15221 
15222 /// Walk up chain skipping non-aliasing memory nodes,
15223 /// looking for aliasing nodes and adding them to the Aliases vector.
15224 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
15225                                    SmallVectorImpl<SDValue> &Aliases) {
15226   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
15227   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
15228 
15229   // Get alias information for node.
15230   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
15231 
15232   // Starting off.
15233   Chains.push_back(OriginalChain);
15234   unsigned Depth = 0;
15235 
15236   // Look at each chain and determine if it is an alias.  If so, add it to the
15237   // aliases list.  If not, then continue up the chain looking for the next
15238   // candidate.
15239   while (!Chains.empty()) {
15240     SDValue Chain = Chains.pop_back_val();
15241 
15242     // For TokenFactor nodes, look at each operand and only continue up the
15243     // chain until we reach the depth limit.
15244     //
15245     // FIXME: The depth check could be made to return the last non-aliasing
15246     // chain we found before we hit a tokenfactor rather than the original
15247     // chain.
15248     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
15249       Aliases.clear();
15250       Aliases.push_back(OriginalChain);
15251       return;
15252     }
15253 
15254     // Don't bother if we've been before.
15255     if (!Visited.insert(Chain.getNode()).second)
15256       continue;
15257 
15258     switch (Chain.getOpcode()) {
15259     case ISD::EntryToken:
15260       // Entry token is ideal chain operand, but handled in FindBetterChain.
15261       break;
15262 
15263     case ISD::LOAD:
15264     case ISD::STORE: {
15265       // Get alias information for Chain.
15266       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
15267           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
15268 
15269       // If chain is alias then stop here.
15270       if (!(IsLoad && IsOpLoad) &&
15271           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
15272         Aliases.push_back(Chain);
15273       } else {
15274         // Look further up the chain.
15275         Chains.push_back(Chain.getOperand(0));
15276         ++Depth;
15277       }
15278       break;
15279     }
15280 
15281     case ISD::TokenFactor:
15282       // We have to check each of the operands of the token factor for "small"
15283       // token factors, so we queue them up.  Adding the operands to the queue
15284       // (stack) in reverse order maintains the original order and increases the
15285       // likelihood that getNode will find a matching token factor (CSE.)
15286       if (Chain.getNumOperands() > 16) {
15287         Aliases.push_back(Chain);
15288         break;
15289       }
15290       for (unsigned n = Chain.getNumOperands(); n;)
15291         Chains.push_back(Chain.getOperand(--n));
15292       ++Depth;
15293       break;
15294 
15295     default:
15296       // For all other instructions we will just have to take what we can get.
15297       Aliases.push_back(Chain);
15298       break;
15299     }
15300   }
15301 }
15302 
15303 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
15304 /// (aliasing node.)
15305 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
15306   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
15307 
15308   // Accumulate all the aliases to this node.
15309   GatherAllAliases(N, OldChain, Aliases);
15310 
15311   // If no operands then chain to entry token.
15312   if (Aliases.size() == 0)
15313     return DAG.getEntryNode();
15314 
15315   // If a single operand then chain to it.  We don't need to revisit it.
15316   if (Aliases.size() == 1)
15317     return Aliases[0];
15318 
15319   // Construct a custom tailored token factor.
15320   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
15321 }
15322 
15323 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
15324   // This holds the base pointer, index, and the offset in bytes from the base
15325   // pointer.
15326   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
15327 
15328   // We must have a base and an offset.
15329   if (!BasePtr.Base.getNode())
15330     return false;
15331 
15332   // Do not handle stores to undef base pointers.
15333   if (BasePtr.Base.isUndef())
15334     return false;
15335 
15336   SmallVector<StoreSDNode *, 8> ChainedStores;
15337   ChainedStores.push_back(St);
15338 
15339   // Walk up the chain and look for nodes with offsets from the same
15340   // base pointer. Stop when reaching an instruction with a different kind
15341   // or instruction which has a different base pointer.
15342   StoreSDNode *Index = St;
15343   while (Index) {
15344     // If the chain has more than one use, then we can't reorder the mem ops.
15345     if (Index != St && !SDValue(Index, 0)->hasOneUse())
15346       break;
15347 
15348     if (Index->isVolatile() || Index->isIndexed())
15349       break;
15350 
15351     // Find the base pointer and offset for this memory node.
15352     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
15353 
15354     // Check that the base pointer is the same as the original one.
15355     if (!Ptr.equalBaseIndex(BasePtr))
15356       break;
15357 
15358     // Find the next memory operand in the chain. If the next operand in the
15359     // chain is a store then move up and continue the scan with the next
15360     // memory operand. If the next operand is a load save it and use alias
15361     // information to check if it interferes with anything.
15362     SDNode *NextInChain = Index->getChain().getNode();
15363     while (true) {
15364       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
15365         // We found a store node. Use it for the next iteration.
15366         if (STn->isVolatile() || STn->isIndexed()) {
15367           Index = nullptr;
15368           break;
15369         }
15370         ChainedStores.push_back(STn);
15371         Index = STn;
15372         break;
15373       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
15374         NextInChain = Ldn->getChain().getNode();
15375         continue;
15376       } else {
15377         Index = nullptr;
15378         break;
15379       }
15380     }
15381   }
15382 
15383   bool MadeChangeToSt = false;
15384   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
15385 
15386   for (StoreSDNode *ChainedStore : ChainedStores) {
15387     SDValue Chain = ChainedStore->getChain();
15388     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15389 
15390     if (Chain != BetterChain) {
15391       if (ChainedStore == St)
15392         MadeChangeToSt = true;
15393       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15394     }
15395   }
15396 
15397   // Do all replacements after finding the replacements to make to avoid making
15398   // the chains more complicated by introducing new TokenFactors.
15399   for (auto Replacement : BetterChains)
15400     replaceStoreChain(Replacement.first, Replacement.second);
15401 
15402   return MadeChangeToSt;
15403 }
15404 
15405 /// This is the entry point for the file.
15406 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15407                            CodeGenOpt::Level OptLevel) {
15408   /// This is the main entry point to this class.
15409   DAGCombiner(*this, AA, OptLevel).Run(Level);
15410 }
15411