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 && !Op.getNode()->getFlags()->hasNoSignedZeros())
626       return 0;
627 
628     // fold (fneg (fsub A, B)) -> (fsub B, A)
629     return 1;
630 
631   case ISD::FMUL:
632   case ISD::FDIV:
633     if (Options->HonorSignDependentRoundingFPMath()) return 0;
634 
635     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
636     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
637                                     Options, Depth + 1))
638       return V;
639 
640     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
641                               Depth + 1);
642 
643   case ISD::FP_EXTEND:
644   case ISD::FP_ROUND:
645   case ISD::FSIN:
646     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
647                               Depth + 1);
648   }
649 }
650 
651 /// If isNegatibleForFree returns true, return the newly negated expression.
652 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
653                                     bool LegalOperations, unsigned Depth = 0) {
654   const TargetOptions &Options = DAG.getTarget().Options;
655   // fneg is removable even if it has multiple uses.
656   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
657 
658   // Don't allow anything with multiple uses.
659   assert(Op.hasOneUse() && "Unknown reuse!");
660 
661   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
662 
663   const SDNodeFlags *Flags = Op.getNode()->getFlags();
664 
665   switch (Op.getOpcode()) {
666   default: llvm_unreachable("Unknown code");
667   case ISD::ConstantFP: {
668     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
669     V.changeSign();
670     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
671   }
672   case ISD::FADD:
673     // FIXME: determine better conditions for this xform.
674     assert(Options.UnsafeFPMath);
675 
676     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
677     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
678                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
679       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
680                          GetNegatedExpression(Op.getOperand(0), DAG,
681                                               LegalOperations, Depth+1),
682                          Op.getOperand(1), Flags);
683     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
684     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
685                        GetNegatedExpression(Op.getOperand(1), DAG,
686                                             LegalOperations, Depth+1),
687                        Op.getOperand(0), Flags);
688   case ISD::FSUB:
689     // fold (fneg (fsub 0, B)) -> B
690     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
691       if (N0CFP->isZero())
692         return Op.getOperand(1);
693 
694     // fold (fneg (fsub A, B)) -> (fsub B, A)
695     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
696                        Op.getOperand(1), Op.getOperand(0), Flags);
697 
698   case ISD::FMUL:
699   case ISD::FDIV:
700     assert(!Options.HonorSignDependentRoundingFPMath());
701 
702     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
703     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
704                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
705       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
706                          GetNegatedExpression(Op.getOperand(0), DAG,
707                                               LegalOperations, Depth+1),
708                          Op.getOperand(1), Flags);
709 
710     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
711     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
712                        Op.getOperand(0),
713                        GetNegatedExpression(Op.getOperand(1), DAG,
714                                             LegalOperations, Depth+1), Flags);
715 
716   case ISD::FP_EXTEND:
717   case ISD::FSIN:
718     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
719                        GetNegatedExpression(Op.getOperand(0), DAG,
720                                             LegalOperations, Depth+1));
721   case ISD::FP_ROUND:
722       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
723                          GetNegatedExpression(Op.getOperand(0), DAG,
724                                               LegalOperations, Depth+1),
725                          Op.getOperand(1));
726   }
727 }
728 
729 // APInts must be the same size for most operations, this helper
730 // function zero extends the shorter of the pair so that they match.
731 // We provide an Offset so that we can create bitwidths that won't overflow.
732 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
733   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
734   LHS = LHS.zextOrSelf(Bits);
735   RHS = RHS.zextOrSelf(Bits);
736 }
737 
738 // Return true if this node is a setcc, or is a select_cc
739 // that selects between the target values used for true and false, making it
740 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
741 // the appropriate nodes based on the type of node we are checking. This
742 // simplifies life a bit for the callers.
743 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
744                                     SDValue &CC) const {
745   if (N.getOpcode() == ISD::SETCC) {
746     LHS = N.getOperand(0);
747     RHS = N.getOperand(1);
748     CC  = N.getOperand(2);
749     return true;
750   }
751 
752   if (N.getOpcode() != ISD::SELECT_CC ||
753       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
754       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
755     return false;
756 
757   if (TLI.getBooleanContents(N.getValueType()) ==
758       TargetLowering::UndefinedBooleanContent)
759     return false;
760 
761   LHS = N.getOperand(0);
762   RHS = N.getOperand(1);
763   CC  = N.getOperand(4);
764   return true;
765 }
766 
767 /// Return true if this is a SetCC-equivalent operation with only one use.
768 /// If this is true, it allows the users to invert the operation for free when
769 /// it is profitable to do so.
770 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
771   SDValue N0, N1, N2;
772   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
773     return true;
774   return false;
775 }
776 
777 // \brief Returns the SDNode if it is a constant float BuildVector
778 // or constant float.
779 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
780   if (isa<ConstantFPSDNode>(N))
781     return N.getNode();
782   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
783     return N.getNode();
784   return nullptr;
785 }
786 
787 // Determines if it is a constant integer or a build vector of constant
788 // integers (and undefs).
789 // Do not permit build vector implicit truncation.
790 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
791   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
792     return !(Const->isOpaque() && NoOpaques);
793   if (N.getOpcode() != ISD::BUILD_VECTOR)
794     return false;
795   unsigned BitWidth = N.getScalarValueSizeInBits();
796   for (const SDValue &Op : N->op_values()) {
797     if (Op.isUndef())
798       continue;
799     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
800     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
801         (Const->isOpaque() && NoOpaques))
802       return false;
803   }
804   return true;
805 }
806 
807 // Determines if it is a constant null integer or a splatted vector of a
808 // constant null integer (with no undefs).
809 // Build vector implicit truncation is not an issue for null values.
810 static bool isNullConstantOrNullSplatConstant(SDValue N) {
811   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
812     return Splat->isNullValue();
813   return false;
814 }
815 
816 // Determines if it is a constant integer of one or a splatted vector of a
817 // constant integer of one (with no undefs).
818 // Do not permit build vector implicit truncation.
819 static bool isOneConstantOrOneSplatConstant(SDValue N) {
820   unsigned BitWidth = N.getScalarValueSizeInBits();
821   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
822     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
823   return false;
824 }
825 
826 // Determines if it is a constant integer of all ones or a splatted vector of a
827 // constant integer of all ones (with no undefs).
828 // Do not permit build vector implicit truncation.
829 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
830   unsigned BitWidth = N.getScalarValueSizeInBits();
831   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
832     return Splat->isAllOnesValue() &&
833            Splat->getAPIntValue().getBitWidth() == BitWidth;
834   return false;
835 }
836 
837 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
838 // undef's.
839 static bool isAnyConstantBuildVector(const SDNode *N) {
840   return ISD::isBuildVectorOfConstantSDNodes(N) ||
841          ISD::isBuildVectorOfConstantFPSDNodes(N);
842 }
843 
844 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
845                                     SDValue N1) {
846   EVT VT = N0.getValueType();
847   if (N0.getOpcode() == Opc) {
848     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
849       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
850         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
851         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
852           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
853         return SDValue();
854       }
855       if (N0.hasOneUse()) {
856         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
857         // use
858         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
859         if (!OpNode.getNode())
860           return SDValue();
861         AddToWorklist(OpNode.getNode());
862         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
863       }
864     }
865   }
866 
867   if (N1.getOpcode() == Opc) {
868     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
869       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
870         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
871         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
872           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
873         return SDValue();
874       }
875       if (N1.hasOneUse()) {
876         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
877         // use
878         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
879         if (!OpNode.getNode())
880           return SDValue();
881         AddToWorklist(OpNode.getNode());
882         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
883       }
884     }
885   }
886 
887   return SDValue();
888 }
889 
890 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
891                                bool AddTo) {
892   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
893   ++NodesCombined;
894   DEBUG(dbgs() << "\nReplacing.1 ";
895         N->dump(&DAG);
896         dbgs() << "\nWith: ";
897         To[0].getNode()->dump(&DAG);
898         dbgs() << " and " << NumTo-1 << " other values\n");
899   for (unsigned i = 0, e = NumTo; i != e; ++i)
900     assert((!To[i].getNode() ||
901             N->getValueType(i) == To[i].getValueType()) &&
902            "Cannot combine value to value of different type!");
903 
904   WorklistRemover DeadNodes(*this);
905   DAG.ReplaceAllUsesWith(N, To);
906   if (AddTo) {
907     // Push the new nodes and any users onto the worklist
908     for (unsigned i = 0, e = NumTo; i != e; ++i) {
909       if (To[i].getNode()) {
910         AddToWorklist(To[i].getNode());
911         AddUsersToWorklist(To[i].getNode());
912       }
913     }
914   }
915 
916   // Finally, if the node is now dead, remove it from the graph.  The node
917   // may not be dead if the replacement process recursively simplified to
918   // something else needing this node.
919   if (N->use_empty())
920     deleteAndRecombine(N);
921   return SDValue(N, 0);
922 }
923 
924 void DAGCombiner::
925 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
926   // Replace all uses.  If any nodes become isomorphic to other nodes and
927   // are deleted, make sure to remove them from our worklist.
928   WorklistRemover DeadNodes(*this);
929   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
930 
931   // Push the new node and any (possibly new) users onto the worklist.
932   AddToWorklist(TLO.New.getNode());
933   AddUsersToWorklist(TLO.New.getNode());
934 
935   // Finally, if the node is now dead, remove it from the graph.  The node
936   // may not be dead if the replacement process recursively simplified to
937   // something else needing this node.
938   if (TLO.Old.getNode()->use_empty())
939     deleteAndRecombine(TLO.Old.getNode());
940 }
941 
942 /// Check the specified integer node value to see if it can be simplified or if
943 /// things it uses can be simplified by bit propagation. If so, return true.
944 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
945   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
946   APInt KnownZero, KnownOne;
947   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
948     return false;
949 
950   // Revisit the node.
951   AddToWorklist(Op.getNode());
952 
953   // Replace the old value with the new one.
954   ++NodesCombined;
955   DEBUG(dbgs() << "\nReplacing.2 ";
956         TLO.Old.getNode()->dump(&DAG);
957         dbgs() << "\nWith: ";
958         TLO.New.getNode()->dump(&DAG);
959         dbgs() << '\n');
960 
961   CommitTargetLoweringOpt(TLO);
962   return true;
963 }
964 
965 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
966   SDLoc DL(Load);
967   EVT VT = Load->getValueType(0);
968   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
969 
970   DEBUG(dbgs() << "\nReplacing.9 ";
971         Load->dump(&DAG);
972         dbgs() << "\nWith: ";
973         Trunc.getNode()->dump(&DAG);
974         dbgs() << '\n');
975   WorklistRemover DeadNodes(*this);
976   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
977   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
978   deleteAndRecombine(Load);
979   AddToWorklist(Trunc.getNode());
980 }
981 
982 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
983   Replace = false;
984   SDLoc DL(Op);
985   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
986     LoadSDNode *LD = cast<LoadSDNode>(Op);
987     EVT MemVT = LD->getMemoryVT();
988     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
989       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
990                                                        : ISD::EXTLOAD)
991       : LD->getExtensionType();
992     Replace = true;
993     return DAG.getExtLoad(ExtType, DL, PVT,
994                           LD->getChain(), LD->getBasePtr(),
995                           MemVT, LD->getMemOperand());
996   }
997 
998   unsigned Opc = Op.getOpcode();
999   switch (Opc) {
1000   default: break;
1001   case ISD::AssertSext:
1002     return DAG.getNode(ISD::AssertSext, DL, PVT,
1003                        SExtPromoteOperand(Op.getOperand(0), PVT),
1004                        Op.getOperand(1));
1005   case ISD::AssertZext:
1006     return DAG.getNode(ISD::AssertZext, DL, PVT,
1007                        ZExtPromoteOperand(Op.getOperand(0), PVT),
1008                        Op.getOperand(1));
1009   case ISD::Constant: {
1010     unsigned ExtOpc =
1011       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1012     return DAG.getNode(ExtOpc, DL, PVT, Op);
1013   }
1014   }
1015 
1016   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1017     return SDValue();
1018   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1019 }
1020 
1021 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1022   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1023     return SDValue();
1024   EVT OldVT = Op.getValueType();
1025   SDLoc DL(Op);
1026   bool Replace = false;
1027   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1028   if (!NewOp.getNode())
1029     return SDValue();
1030   AddToWorklist(NewOp.getNode());
1031 
1032   if (Replace)
1033     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1034   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1035                      DAG.getValueType(OldVT));
1036 }
1037 
1038 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1039   EVT OldVT = Op.getValueType();
1040   SDLoc DL(Op);
1041   bool Replace = false;
1042   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1043   if (!NewOp.getNode())
1044     return SDValue();
1045   AddToWorklist(NewOp.getNode());
1046 
1047   if (Replace)
1048     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1049   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1050 }
1051 
1052 /// Promote the specified integer binary operation if the target indicates it is
1053 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1054 /// i32 since i16 instructions are longer.
1055 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1056   if (!LegalOperations)
1057     return SDValue();
1058 
1059   EVT VT = Op.getValueType();
1060   if (VT.isVector() || !VT.isInteger())
1061     return SDValue();
1062 
1063   // If operation type is 'undesirable', e.g. i16 on x86, consider
1064   // promoting it.
1065   unsigned Opc = Op.getOpcode();
1066   if (TLI.isTypeDesirableForOp(Opc, VT))
1067     return SDValue();
1068 
1069   EVT PVT = VT;
1070   // Consult target whether it is a good idea to promote this operation and
1071   // what's the right type to promote it to.
1072   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1073     assert(PVT != VT && "Don't know what type to promote to!");
1074 
1075     bool Replace0 = false;
1076     SDValue N0 = Op.getOperand(0);
1077     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1078     if (!NN0.getNode())
1079       return SDValue();
1080 
1081     bool Replace1 = false;
1082     SDValue N1 = Op.getOperand(1);
1083     SDValue NN1;
1084     if (N0 == N1)
1085       NN1 = NN0;
1086     else {
1087       NN1 = PromoteOperand(N1, PVT, Replace1);
1088       if (!NN1.getNode())
1089         return SDValue();
1090     }
1091 
1092     AddToWorklist(NN0.getNode());
1093     if (NN1.getNode())
1094       AddToWorklist(NN1.getNode());
1095 
1096     if (Replace0)
1097       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1098     if (Replace1)
1099       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1100 
1101     DEBUG(dbgs() << "\nPromoting ";
1102           Op.getNode()->dump(&DAG));
1103     SDLoc DL(Op);
1104     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1105                        DAG.getNode(Opc, DL, PVT, NN0, NN1));
1106   }
1107   return SDValue();
1108 }
1109 
1110 /// Promote the specified integer shift operation if the target indicates it is
1111 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1112 /// i32 since i16 instructions are longer.
1113 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1114   if (!LegalOperations)
1115     return SDValue();
1116 
1117   EVT VT = Op.getValueType();
1118   if (VT.isVector() || !VT.isInteger())
1119     return SDValue();
1120 
1121   // If operation type is 'undesirable', e.g. i16 on x86, consider
1122   // promoting it.
1123   unsigned Opc = Op.getOpcode();
1124   if (TLI.isTypeDesirableForOp(Opc, VT))
1125     return SDValue();
1126 
1127   EVT PVT = VT;
1128   // Consult target whether it is a good idea to promote this operation and
1129   // what's the right type to promote it to.
1130   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1131     assert(PVT != VT && "Don't know what type to promote to!");
1132 
1133     bool Replace = false;
1134     SDValue N0 = Op.getOperand(0);
1135     if (Opc == ISD::SRA)
1136       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1137     else if (Opc == ISD::SRL)
1138       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1139     else
1140       N0 = PromoteOperand(N0, PVT, Replace);
1141     if (!N0.getNode())
1142       return SDValue();
1143 
1144     AddToWorklist(N0.getNode());
1145     if (Replace)
1146       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1147 
1148     DEBUG(dbgs() << "\nPromoting ";
1149           Op.getNode()->dump(&DAG));
1150     SDLoc DL(Op);
1151     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1152                        DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1)));
1153   }
1154   return SDValue();
1155 }
1156 
1157 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1158   if (!LegalOperations)
1159     return SDValue();
1160 
1161   EVT VT = Op.getValueType();
1162   if (VT.isVector() || !VT.isInteger())
1163     return SDValue();
1164 
1165   // If operation type is 'undesirable', e.g. i16 on x86, consider
1166   // promoting it.
1167   unsigned Opc = Op.getOpcode();
1168   if (TLI.isTypeDesirableForOp(Opc, VT))
1169     return SDValue();
1170 
1171   EVT PVT = VT;
1172   // Consult target whether it is a good idea to promote this operation and
1173   // what's the right type to promote it to.
1174   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1175     assert(PVT != VT && "Don't know what type to promote to!");
1176     // fold (aext (aext x)) -> (aext x)
1177     // fold (aext (zext x)) -> (zext x)
1178     // fold (aext (sext x)) -> (sext x)
1179     DEBUG(dbgs() << "\nPromoting ";
1180           Op.getNode()->dump(&DAG));
1181     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1182   }
1183   return SDValue();
1184 }
1185 
1186 bool DAGCombiner::PromoteLoad(SDValue Op) {
1187   if (!LegalOperations)
1188     return false;
1189 
1190   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1191     return false;
1192 
1193   EVT VT = Op.getValueType();
1194   if (VT.isVector() || !VT.isInteger())
1195     return false;
1196 
1197   // If operation type is 'undesirable', e.g. i16 on x86, consider
1198   // promoting it.
1199   unsigned Opc = Op.getOpcode();
1200   if (TLI.isTypeDesirableForOp(Opc, VT))
1201     return false;
1202 
1203   EVT PVT = VT;
1204   // Consult target whether it is a good idea to promote this operation and
1205   // what's the right type to promote it to.
1206   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1207     assert(PVT != VT && "Don't know what type to promote to!");
1208 
1209     SDLoc DL(Op);
1210     SDNode *N = Op.getNode();
1211     LoadSDNode *LD = cast<LoadSDNode>(N);
1212     EVT MemVT = LD->getMemoryVT();
1213     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1214       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1215                                                        : ISD::EXTLOAD)
1216       : LD->getExtensionType();
1217     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1218                                    LD->getChain(), LD->getBasePtr(),
1219                                    MemVT, LD->getMemOperand());
1220     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1221 
1222     DEBUG(dbgs() << "\nPromoting ";
1223           N->dump(&DAG);
1224           dbgs() << "\nTo: ";
1225           Result.getNode()->dump(&DAG);
1226           dbgs() << '\n');
1227     WorklistRemover DeadNodes(*this);
1228     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1229     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1230     deleteAndRecombine(N);
1231     AddToWorklist(Result.getNode());
1232     return true;
1233   }
1234   return false;
1235 }
1236 
1237 /// \brief Recursively delete a node which has no uses and any operands for
1238 /// which it is the only use.
1239 ///
1240 /// Note that this both deletes the nodes and removes them from the worklist.
1241 /// It also adds any nodes who have had a user deleted to the worklist as they
1242 /// may now have only one use and subject to other combines.
1243 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1244   if (!N->use_empty())
1245     return false;
1246 
1247   SmallSetVector<SDNode *, 16> Nodes;
1248   Nodes.insert(N);
1249   do {
1250     N = Nodes.pop_back_val();
1251     if (!N)
1252       continue;
1253 
1254     if (N->use_empty()) {
1255       for (const SDValue &ChildN : N->op_values())
1256         Nodes.insert(ChildN.getNode());
1257 
1258       removeFromWorklist(N);
1259       DAG.DeleteNode(N);
1260     } else {
1261       AddToWorklist(N);
1262     }
1263   } while (!Nodes.empty());
1264   return true;
1265 }
1266 
1267 //===----------------------------------------------------------------------===//
1268 //  Main DAG Combiner implementation
1269 //===----------------------------------------------------------------------===//
1270 
1271 void DAGCombiner::Run(CombineLevel AtLevel) {
1272   // set the instance variables, so that the various visit routines may use it.
1273   Level = AtLevel;
1274   LegalOperations = Level >= AfterLegalizeVectorOps;
1275   LegalTypes = Level >= AfterLegalizeTypes;
1276 
1277   // Add all the dag nodes to the worklist.
1278   for (SDNode &Node : DAG.allnodes())
1279     AddToWorklist(&Node);
1280 
1281   // Create a dummy node (which is not added to allnodes), that adds a reference
1282   // to the root node, preventing it from being deleted, and tracking any
1283   // changes of the root.
1284   HandleSDNode Dummy(DAG.getRoot());
1285 
1286   // While the worklist isn't empty, find a node and try to combine it.
1287   while (!WorklistMap.empty()) {
1288     SDNode *N;
1289     // The Worklist holds the SDNodes in order, but it may contain null entries.
1290     do {
1291       N = Worklist.pop_back_val();
1292     } while (!N);
1293 
1294     bool GoodWorklistEntry = WorklistMap.erase(N);
1295     (void)GoodWorklistEntry;
1296     assert(GoodWorklistEntry &&
1297            "Found a worklist entry without a corresponding map entry!");
1298 
1299     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1300     // N is deleted from the DAG, since they too may now be dead or may have a
1301     // reduced number of uses, allowing other xforms.
1302     if (recursivelyDeleteUnusedNodes(N))
1303       continue;
1304 
1305     WorklistRemover DeadNodes(*this);
1306 
1307     // If this combine is running after legalizing the DAG, re-legalize any
1308     // nodes pulled off the worklist.
1309     if (Level == AfterLegalizeDAG) {
1310       SmallSetVector<SDNode *, 16> UpdatedNodes;
1311       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1312 
1313       for (SDNode *LN : UpdatedNodes) {
1314         AddToWorklist(LN);
1315         AddUsersToWorklist(LN);
1316       }
1317       if (!NIsValid)
1318         continue;
1319     }
1320 
1321     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1322 
1323     // Add any operands of the new node which have not yet been combined to the
1324     // worklist as well. Because the worklist uniques things already, this
1325     // won't repeatedly process the same operand.
1326     CombinedNodes.insert(N);
1327     for (const SDValue &ChildN : N->op_values())
1328       if (!CombinedNodes.count(ChildN.getNode()))
1329         AddToWorklist(ChildN.getNode());
1330 
1331     SDValue RV = combine(N);
1332 
1333     if (!RV.getNode())
1334       continue;
1335 
1336     ++NodesCombined;
1337 
1338     // If we get back the same node we passed in, rather than a new node or
1339     // zero, we know that the node must have defined multiple values and
1340     // CombineTo was used.  Since CombineTo takes care of the worklist
1341     // mechanics for us, we have no work to do in this case.
1342     if (RV.getNode() == N)
1343       continue;
1344 
1345     assert(N->getOpcode() != ISD::DELETED_NODE &&
1346            RV.getOpcode() != ISD::DELETED_NODE &&
1347            "Node was deleted but visit returned new node!");
1348 
1349     DEBUG(dbgs() << " ... into: ";
1350           RV.getNode()->dump(&DAG));
1351 
1352     if (N->getNumValues() == RV.getNode()->getNumValues())
1353       DAG.ReplaceAllUsesWith(N, RV.getNode());
1354     else {
1355       assert(N->getValueType(0) == RV.getValueType() &&
1356              N->getNumValues() == 1 && "Type mismatch");
1357       SDValue OpV = RV;
1358       DAG.ReplaceAllUsesWith(N, &OpV);
1359     }
1360 
1361     // Push the new node and any users onto the worklist
1362     AddToWorklist(RV.getNode());
1363     AddUsersToWorklist(RV.getNode());
1364 
1365     // Finally, if the node is now dead, remove it from the graph.  The node
1366     // may not be dead if the replacement process recursively simplified to
1367     // something else needing this node. This will also take care of adding any
1368     // operands which have lost a user to the worklist.
1369     recursivelyDeleteUnusedNodes(N);
1370   }
1371 
1372   // If the root changed (e.g. it was a dead load, update the root).
1373   DAG.setRoot(Dummy.getValue());
1374   DAG.RemoveDeadNodes();
1375 }
1376 
1377 SDValue DAGCombiner::visit(SDNode *N) {
1378   switch (N->getOpcode()) {
1379   default: break;
1380   case ISD::TokenFactor:        return visitTokenFactor(N);
1381   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1382   case ISD::ADD:                return visitADD(N);
1383   case ISD::SUB:                return visitSUB(N);
1384   case ISD::ADDC:               return visitADDC(N);
1385   case ISD::SUBC:               return visitSUBC(N);
1386   case ISD::ADDE:               return visitADDE(N);
1387   case ISD::SUBE:               return visitSUBE(N);
1388   case ISD::MUL:                return visitMUL(N);
1389   case ISD::SDIV:               return visitSDIV(N);
1390   case ISD::UDIV:               return visitUDIV(N);
1391   case ISD::SREM:
1392   case ISD::UREM:               return visitREM(N);
1393   case ISD::MULHU:              return visitMULHU(N);
1394   case ISD::MULHS:              return visitMULHS(N);
1395   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1396   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1397   case ISD::SMULO:              return visitSMULO(N);
1398   case ISD::UMULO:              return visitUMULO(N);
1399   case ISD::SMIN:
1400   case ISD::SMAX:
1401   case ISD::UMIN:
1402   case ISD::UMAX:               return visitIMINMAX(N);
1403   case ISD::AND:                return visitAND(N);
1404   case ISD::OR:                 return visitOR(N);
1405   case ISD::XOR:                return visitXOR(N);
1406   case ISD::SHL:                return visitSHL(N);
1407   case ISD::SRA:                return visitSRA(N);
1408   case ISD::SRL:                return visitSRL(N);
1409   case ISD::ROTR:
1410   case ISD::ROTL:               return visitRotate(N);
1411   case ISD::BSWAP:              return visitBSWAP(N);
1412   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1413   case ISD::CTLZ:               return visitCTLZ(N);
1414   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1415   case ISD::CTTZ:               return visitCTTZ(N);
1416   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1417   case ISD::CTPOP:              return visitCTPOP(N);
1418   case ISD::SELECT:             return visitSELECT(N);
1419   case ISD::VSELECT:            return visitVSELECT(N);
1420   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1421   case ISD::SETCC:              return visitSETCC(N);
1422   case ISD::SETCCE:             return visitSETCCE(N);
1423   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1424   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1425   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1426   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1427   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1428   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1429   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1430   case ISD::BITCAST:            return visitBITCAST(N);
1431   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1432   case ISD::FADD:               return visitFADD(N);
1433   case ISD::FSUB:               return visitFSUB(N);
1434   case ISD::FMUL:               return visitFMUL(N);
1435   case ISD::FMA:                return visitFMA(N);
1436   case ISD::FDIV:               return visitFDIV(N);
1437   case ISD::FREM:               return visitFREM(N);
1438   case ISD::FSQRT:              return visitFSQRT(N);
1439   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1440   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1441   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1442   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1443   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1444   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1445   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1446   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1447   case ISD::FNEG:               return visitFNEG(N);
1448   case ISD::FABS:               return visitFABS(N);
1449   case ISD::FFLOOR:             return visitFFLOOR(N);
1450   case ISD::FMINNUM:            return visitFMINNUM(N);
1451   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1452   case ISD::FCEIL:              return visitFCEIL(N);
1453   case ISD::FTRUNC:             return visitFTRUNC(N);
1454   case ISD::BRCOND:             return visitBRCOND(N);
1455   case ISD::BR_CC:              return visitBR_CC(N);
1456   case ISD::LOAD:               return visitLOAD(N);
1457   case ISD::STORE:              return visitSTORE(N);
1458   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1459   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1460   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1461   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1462   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1463   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1464   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1465   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1466   case ISD::MGATHER:            return visitMGATHER(N);
1467   case ISD::MLOAD:              return visitMLOAD(N);
1468   case ISD::MSCATTER:           return visitMSCATTER(N);
1469   case ISD::MSTORE:             return visitMSTORE(N);
1470   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1471   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1472   }
1473   return SDValue();
1474 }
1475 
1476 SDValue DAGCombiner::combine(SDNode *N) {
1477   SDValue RV = visit(N);
1478 
1479   // If nothing happened, try a target-specific DAG combine.
1480   if (!RV.getNode()) {
1481     assert(N->getOpcode() != ISD::DELETED_NODE &&
1482            "Node was deleted but visit returned NULL!");
1483 
1484     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1485         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1486 
1487       // Expose the DAG combiner to the target combiner impls.
1488       TargetLowering::DAGCombinerInfo
1489         DagCombineInfo(DAG, Level, false, this);
1490 
1491       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1492     }
1493   }
1494 
1495   // If nothing happened still, try promoting the operation.
1496   if (!RV.getNode()) {
1497     switch (N->getOpcode()) {
1498     default: break;
1499     case ISD::ADD:
1500     case ISD::SUB:
1501     case ISD::MUL:
1502     case ISD::AND:
1503     case ISD::OR:
1504     case ISD::XOR:
1505       RV = PromoteIntBinOp(SDValue(N, 0));
1506       break;
1507     case ISD::SHL:
1508     case ISD::SRA:
1509     case ISD::SRL:
1510       RV = PromoteIntShiftOp(SDValue(N, 0));
1511       break;
1512     case ISD::SIGN_EXTEND:
1513     case ISD::ZERO_EXTEND:
1514     case ISD::ANY_EXTEND:
1515       RV = PromoteExtend(SDValue(N, 0));
1516       break;
1517     case ISD::LOAD:
1518       if (PromoteLoad(SDValue(N, 0)))
1519         RV = SDValue(N, 0);
1520       break;
1521     }
1522   }
1523 
1524   // If N is a commutative binary node, try commuting it to enable more
1525   // sdisel CSE.
1526   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1527       N->getNumValues() == 1) {
1528     SDValue N0 = N->getOperand(0);
1529     SDValue N1 = N->getOperand(1);
1530 
1531     // Constant operands are canonicalized to RHS.
1532     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1533       SDValue Ops[] = {N1, N0};
1534       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1535                                             N->getFlags());
1536       if (CSENode)
1537         return SDValue(CSENode, 0);
1538     }
1539   }
1540 
1541   return RV;
1542 }
1543 
1544 /// Given a node, return its input chain if it has one, otherwise return a null
1545 /// sd operand.
1546 static SDValue getInputChainForNode(SDNode *N) {
1547   if (unsigned NumOps = N->getNumOperands()) {
1548     if (N->getOperand(0).getValueType() == MVT::Other)
1549       return N->getOperand(0);
1550     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1551       return N->getOperand(NumOps-1);
1552     for (unsigned i = 1; i < NumOps-1; ++i)
1553       if (N->getOperand(i).getValueType() == MVT::Other)
1554         return N->getOperand(i);
1555   }
1556   return SDValue();
1557 }
1558 
1559 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1560   // If N has two operands, where one has an input chain equal to the other,
1561   // the 'other' chain is redundant.
1562   if (N->getNumOperands() == 2) {
1563     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1564       return N->getOperand(0);
1565     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1566       return N->getOperand(1);
1567   }
1568 
1569   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1570   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1571   SmallPtrSet<SDNode*, 16> SeenOps;
1572   bool Changed = false;             // If we should replace this token factor.
1573 
1574   // Start out with this token factor.
1575   TFs.push_back(N);
1576 
1577   // Iterate through token factors.  The TFs grows when new token factors are
1578   // encountered.
1579   for (unsigned i = 0; i < TFs.size(); ++i) {
1580     SDNode *TF = TFs[i];
1581 
1582     // Check each of the operands.
1583     for (const SDValue &Op : TF->op_values()) {
1584 
1585       switch (Op.getOpcode()) {
1586       case ISD::EntryToken:
1587         // Entry tokens don't need to be added to the list. They are
1588         // redundant.
1589         Changed = true;
1590         break;
1591 
1592       case ISD::TokenFactor:
1593         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1594           // Queue up for processing.
1595           TFs.push_back(Op.getNode());
1596           // Clean up in case the token factor is removed.
1597           AddToWorklist(Op.getNode());
1598           Changed = true;
1599           break;
1600         }
1601         LLVM_FALLTHROUGH;
1602 
1603       default:
1604         // Only add if it isn't already in the list.
1605         if (SeenOps.insert(Op.getNode()).second)
1606           Ops.push_back(Op);
1607         else
1608           Changed = true;
1609         break;
1610       }
1611     }
1612   }
1613 
1614   SDValue Result;
1615 
1616   // If we've changed things around then replace token factor.
1617   if (Changed) {
1618     if (Ops.empty()) {
1619       // The entry token is the only possible outcome.
1620       Result = DAG.getEntryNode();
1621     } else {
1622       // New and improved token factor.
1623       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1624     }
1625 
1626     // Add users to worklist if AA is enabled, since it may introduce
1627     // a lot of new chained token factors while removing memory deps.
1628     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1629       : DAG.getSubtarget().useAA();
1630     return CombineTo(N, Result, UseAA /*add to worklist*/);
1631   }
1632 
1633   return Result;
1634 }
1635 
1636 /// MERGE_VALUES can always be eliminated.
1637 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1638   WorklistRemover DeadNodes(*this);
1639   // Replacing results may cause a different MERGE_VALUES to suddenly
1640   // be CSE'd with N, and carry its uses with it. Iterate until no
1641   // uses remain, to ensure that the node can be safely deleted.
1642   // First add the users of this node to the work list so that they
1643   // can be tried again once they have new operands.
1644   AddUsersToWorklist(N);
1645   do {
1646     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1647       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1648   } while (!N->use_empty());
1649   deleteAndRecombine(N);
1650   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1651 }
1652 
1653 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1654 /// ConstantSDNode pointer else nullptr.
1655 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1656   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1657   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1658 }
1659 
1660 SDValue DAGCombiner::visitADD(SDNode *N) {
1661   SDValue N0 = N->getOperand(0);
1662   SDValue N1 = N->getOperand(1);
1663   EVT VT = N0.getValueType();
1664   SDLoc DL(N);
1665 
1666   // fold vector ops
1667   if (VT.isVector()) {
1668     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1669       return FoldedVOp;
1670 
1671     // fold (add x, 0) -> x, vector edition
1672     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1673       return N0;
1674     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1675       return N1;
1676   }
1677 
1678   // fold (add x, undef) -> undef
1679   if (N0.isUndef())
1680     return N0;
1681 
1682   if (N1.isUndef())
1683     return N1;
1684 
1685   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1686     // canonicalize constant to RHS
1687     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1688       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1689     // fold (add c1, c2) -> c1+c2
1690     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1691                                       N1.getNode());
1692   }
1693 
1694   // fold (add x, 0) -> x
1695   if (isNullConstant(N1))
1696     return N0;
1697 
1698   // fold ((c1-A)+c2) -> (c1+c2)-A
1699   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1700     if (N0.getOpcode() == ISD::SUB)
1701       if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1702         return DAG.getNode(ISD::SUB, DL, VT,
1703                            DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1704                            N0.getOperand(1));
1705       }
1706   }
1707 
1708   // reassociate add
1709   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1710     return RADD;
1711 
1712   // fold ((0-A) + B) -> B-A
1713   if (N0.getOpcode() == ISD::SUB &&
1714       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1715     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1716 
1717   // fold (A + (0-B)) -> A-B
1718   if (N1.getOpcode() == ISD::SUB &&
1719       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1720     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1721 
1722   // fold (A+(B-A)) -> B
1723   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1724     return N1.getOperand(0);
1725 
1726   // fold ((B-A)+A) -> B
1727   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1728     return N0.getOperand(0);
1729 
1730   // fold (A+(B-(A+C))) to (B-C)
1731   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1732       N0 == N1.getOperand(1).getOperand(0))
1733     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1734                        N1.getOperand(1).getOperand(1));
1735 
1736   // fold (A+(B-(C+A))) to (B-C)
1737   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1738       N0 == N1.getOperand(1).getOperand(1))
1739     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1740                        N1.getOperand(1).getOperand(0));
1741 
1742   // fold (A+((B-A)+or-C)) to (B+or-C)
1743   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1744       N1.getOperand(0).getOpcode() == ISD::SUB &&
1745       N0 == N1.getOperand(0).getOperand(1))
1746     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1747                        N1.getOperand(1));
1748 
1749   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1750   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1751     SDValue N00 = N0.getOperand(0);
1752     SDValue N01 = N0.getOperand(1);
1753     SDValue N10 = N1.getOperand(0);
1754     SDValue N11 = N1.getOperand(1);
1755 
1756     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1757       return DAG.getNode(ISD::SUB, DL, VT,
1758                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1759                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1760   }
1761 
1762   if (SimplifyDemandedBits(SDValue(N, 0)))
1763     return SDValue(N, 0);
1764 
1765   // fold (a+b) -> (a|b) iff a and b share no bits.
1766   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1767       VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1768     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1769 
1770   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1771   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1772       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1773     return DAG.getNode(ISD::SUB, DL, VT, N0,
1774                        DAG.getNode(ISD::SHL, DL, VT,
1775                                    N1.getOperand(0).getOperand(1),
1776                                    N1.getOperand(1)));
1777   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1778       isNullConstantOrNullSplatConstant(N0.getOperand(0).getOperand(0)))
1779     return DAG.getNode(ISD::SUB, DL, VT, N1,
1780                        DAG.getNode(ISD::SHL, DL, VT,
1781                                    N0.getOperand(0).getOperand(1),
1782                                    N0.getOperand(1)));
1783 
1784   if (N1.getOpcode() == ISD::AND) {
1785     SDValue AndOp0 = N1.getOperand(0);
1786     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1787     unsigned DestBits = VT.getScalarSizeInBits();
1788 
1789     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1790     // and similar xforms where the inner op is either ~0 or 0.
1791     if (NumSignBits == DestBits &&
1792         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1793       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1794   }
1795 
1796   // add (sext i1), X -> sub X, (zext i1)
1797   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1798       N0.getOperand(0).getValueType() == MVT::i1 &&
1799       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1800     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1801     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1802   }
1803 
1804   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1805   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1806     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1807     if (TN->getVT() == MVT::i1) {
1808       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1809                                  DAG.getConstant(1, DL, VT));
1810       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1811     }
1812   }
1813 
1814   return SDValue();
1815 }
1816 
1817 SDValue DAGCombiner::visitADDC(SDNode *N) {
1818   SDValue N0 = N->getOperand(0);
1819   SDValue N1 = N->getOperand(1);
1820   EVT VT = N0.getValueType();
1821 
1822   // If the flag result is dead, turn this into an ADD.
1823   if (!N->hasAnyUseOfValue(1))
1824     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1825                      DAG.getNode(ISD::CARRY_FALSE,
1826                                  SDLoc(N), MVT::Glue));
1827 
1828   // canonicalize constant to RHS.
1829   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1830   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1831   if (N0C && !N1C)
1832     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1833 
1834   // fold (addc x, 0) -> x + no carry out
1835   if (isNullConstant(N1))
1836     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1837                                         SDLoc(N), MVT::Glue));
1838 
1839   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1840   APInt LHSZero, LHSOne;
1841   APInt RHSZero, RHSOne;
1842   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1843 
1844   if (LHSZero.getBoolValue()) {
1845     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1846 
1847     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1848     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1849     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1850       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1851                        DAG.getNode(ISD::CARRY_FALSE,
1852                                    SDLoc(N), MVT::Glue));
1853   }
1854 
1855   return SDValue();
1856 }
1857 
1858 SDValue DAGCombiner::visitADDE(SDNode *N) {
1859   SDValue N0 = N->getOperand(0);
1860   SDValue N1 = N->getOperand(1);
1861   SDValue CarryIn = N->getOperand(2);
1862 
1863   // canonicalize constant to RHS
1864   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1865   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1866   if (N0C && !N1C)
1867     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1868                        N1, N0, CarryIn);
1869 
1870   // fold (adde x, y, false) -> (addc x, y)
1871   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1872     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1873 
1874   return SDValue();
1875 }
1876 
1877 // Since it may not be valid to emit a fold to zero for vector initializers
1878 // check if we can before folding.
1879 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
1880                              SelectionDAG &DAG, bool LegalOperations,
1881                              bool LegalTypes) {
1882   if (!VT.isVector())
1883     return DAG.getConstant(0, DL, VT);
1884   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1885     return DAG.getConstant(0, DL, VT);
1886   return SDValue();
1887 }
1888 
1889 SDValue DAGCombiner::visitSUB(SDNode *N) {
1890   SDValue N0 = N->getOperand(0);
1891   SDValue N1 = N->getOperand(1);
1892   EVT VT = N0.getValueType();
1893   SDLoc DL(N);
1894 
1895   // fold vector ops
1896   if (VT.isVector()) {
1897     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1898       return FoldedVOp;
1899 
1900     // fold (sub x, 0) -> x, vector edition
1901     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1902       return N0;
1903   }
1904 
1905   // fold (sub x, x) -> 0
1906   // FIXME: Refactor this and xor and other similar operations together.
1907   if (N0 == N1)
1908     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
1909   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1910       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1911     // fold (sub c1, c2) -> c1-c2
1912     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
1913                                       N1.getNode());
1914   }
1915 
1916   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1917 
1918   // fold (sub x, c) -> (add x, -c)
1919   if (N1C) {
1920     return DAG.getNode(ISD::ADD, DL, VT, N0,
1921                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1922   }
1923 
1924   if (isNullConstantOrNullSplatConstant(N0)) {
1925     unsigned BitWidth = VT.getScalarSizeInBits();
1926     // Right-shifting everything out but the sign bit followed by negation is
1927     // the same as flipping arithmetic/logical shift type without the negation:
1928     // -(X >>u 31) -> (X >>s 31)
1929     // -(X >>s 31) -> (X >>u 31)
1930     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
1931       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
1932       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
1933         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
1934         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
1935           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
1936       }
1937     }
1938 
1939     // 0 - X --> 0 if the sub is NUW.
1940     if (N->getFlags()->hasNoUnsignedWrap())
1941       return N0;
1942 
1943     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignBit(BitWidth))) {
1944       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
1945       // N1 must be 0 because negating the minimum signed value is undefined.
1946       if (N->getFlags()->hasNoSignedWrap())
1947         return N0;
1948 
1949       // 0 - X --> X if X is 0 or the minimum signed value.
1950       return N1;
1951     }
1952   }
1953 
1954   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1955   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
1956     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
1957 
1958   // fold A-(A-B) -> B
1959   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1960     return N1.getOperand(1);
1961 
1962   // fold (A+B)-A -> B
1963   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1964     return N0.getOperand(1);
1965 
1966   // fold (A+B)-B -> A
1967   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1968     return N0.getOperand(0);
1969 
1970   // fold C2-(A+C1) -> (C2-C1)-A
1971   if (N1.getOpcode() == ISD::ADD) {
1972     SDValue N11 = N1.getOperand(1);
1973     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
1974         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
1975       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
1976       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
1977     }
1978   }
1979 
1980   // fold ((A+(B+or-C))-B) -> A+or-C
1981   if (N0.getOpcode() == ISD::ADD &&
1982       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1983        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1984       N0.getOperand(1).getOperand(0) == N1)
1985     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
1986                        N0.getOperand(1).getOperand(1));
1987 
1988   // fold ((A+(C+B))-B) -> A+C
1989   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
1990       N0.getOperand(1).getOperand(1) == N1)
1991     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
1992                        N0.getOperand(1).getOperand(0));
1993 
1994   // fold ((A-(B-C))-C) -> A-B
1995   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
1996       N0.getOperand(1).getOperand(1) == N1)
1997     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
1998                        N0.getOperand(1).getOperand(0));
1999 
2000   // If either operand of a sub is undef, the result is undef
2001   if (N0.isUndef())
2002     return N0;
2003   if (N1.isUndef())
2004     return N1;
2005 
2006   // If the relocation model supports it, consider symbol offsets.
2007   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2008     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2009       // fold (sub Sym, c) -> Sym-c
2010       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2011         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2012                                     GA->getOffset() -
2013                                         (uint64_t)N1C->getSExtValue());
2014       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2015       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2016         if (GA->getGlobal() == GB->getGlobal())
2017           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2018                                  DL, VT);
2019     }
2020 
2021   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2022   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2023     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2024     if (TN->getVT() == MVT::i1) {
2025       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2026                                  DAG.getConstant(1, DL, VT));
2027       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2028     }
2029   }
2030 
2031   return SDValue();
2032 }
2033 
2034 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2035   SDValue N0 = N->getOperand(0);
2036   SDValue N1 = N->getOperand(1);
2037   EVT VT = N0.getValueType();
2038   SDLoc DL(N);
2039 
2040   // If the flag result is dead, turn this into an SUB.
2041   if (!N->hasAnyUseOfValue(1))
2042     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2043                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2044 
2045   // fold (subc x, x) -> 0 + no borrow
2046   if (N0 == N1)
2047     return CombineTo(N, DAG.getConstant(0, DL, VT),
2048                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2049 
2050   // fold (subc x, 0) -> x + no borrow
2051   if (isNullConstant(N1))
2052     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2053 
2054   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2055   if (isAllOnesConstant(N0))
2056     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2057                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2058 
2059   return SDValue();
2060 }
2061 
2062 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2063   SDValue N0 = N->getOperand(0);
2064   SDValue N1 = N->getOperand(1);
2065   SDValue CarryIn = N->getOperand(2);
2066 
2067   // fold (sube x, y, false) -> (subc x, y)
2068   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2069     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2070 
2071   return SDValue();
2072 }
2073 
2074 SDValue DAGCombiner::visitMUL(SDNode *N) {
2075   SDValue N0 = N->getOperand(0);
2076   SDValue N1 = N->getOperand(1);
2077   EVT VT = N0.getValueType();
2078 
2079   // fold (mul x, undef) -> 0
2080   if (N0.isUndef() || N1.isUndef())
2081     return DAG.getConstant(0, SDLoc(N), VT);
2082 
2083   bool N0IsConst = false;
2084   bool N1IsConst = false;
2085   bool N1IsOpaqueConst = false;
2086   bool N0IsOpaqueConst = false;
2087   APInt ConstValue0, ConstValue1;
2088   // fold vector ops
2089   if (VT.isVector()) {
2090     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2091       return FoldedVOp;
2092 
2093     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2094     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2095   } else {
2096     N0IsConst = isa<ConstantSDNode>(N0);
2097     if (N0IsConst) {
2098       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2099       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2100     }
2101     N1IsConst = isa<ConstantSDNode>(N1);
2102     if (N1IsConst) {
2103       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2104       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2105     }
2106   }
2107 
2108   // fold (mul c1, c2) -> c1*c2
2109   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2110     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2111                                       N0.getNode(), N1.getNode());
2112 
2113   // canonicalize constant to RHS (vector doesn't have to splat)
2114   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2115      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2116     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2117   // fold (mul x, 0) -> 0
2118   if (N1IsConst && ConstValue1 == 0)
2119     return N1;
2120   // We require a splat of the entire scalar bit width for non-contiguous
2121   // bit patterns.
2122   bool IsFullSplat =
2123     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2124   // fold (mul x, 1) -> x
2125   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2126     return N0;
2127   // fold (mul x, -1) -> 0-x
2128   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2129     SDLoc DL(N);
2130     return DAG.getNode(ISD::SUB, DL, VT,
2131                        DAG.getConstant(0, DL, VT), N0);
2132   }
2133   // fold (mul x, (1 << c)) -> x << c
2134   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2135       IsFullSplat) {
2136     SDLoc DL(N);
2137     return DAG.getNode(ISD::SHL, DL, VT, N0,
2138                        DAG.getConstant(ConstValue1.logBase2(), DL,
2139                                        getShiftAmountTy(N0.getValueType())));
2140   }
2141   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2142   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2143       IsFullSplat) {
2144     unsigned Log2Val = (-ConstValue1).logBase2();
2145     SDLoc DL(N);
2146     // FIXME: If the input is something that is easily negated (e.g. a
2147     // single-use add), we should put the negate there.
2148     return DAG.getNode(ISD::SUB, DL, VT,
2149                        DAG.getConstant(0, DL, VT),
2150                        DAG.getNode(ISD::SHL, DL, VT, N0,
2151                             DAG.getConstant(Log2Val, DL,
2152                                       getShiftAmountTy(N0.getValueType()))));
2153   }
2154 
2155   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2156   if (N0.getOpcode() == ISD::SHL &&
2157       isConstantOrConstantVector(N1) &&
2158       isConstantOrConstantVector(N0.getOperand(1))) {
2159     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2160     AddToWorklist(C3.getNode());
2161     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2162   }
2163 
2164   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2165   // use.
2166   {
2167     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2168 
2169     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2170     if (N0.getOpcode() == ISD::SHL &&
2171         isConstantOrConstantVector(N0.getOperand(1)) &&
2172         N0.getNode()->hasOneUse()) {
2173       Sh = N0; Y = N1;
2174     } else if (N1.getOpcode() == ISD::SHL &&
2175                isConstantOrConstantVector(N1.getOperand(1)) &&
2176                N1.getNode()->hasOneUse()) {
2177       Sh = N1; Y = N0;
2178     }
2179 
2180     if (Sh.getNode()) {
2181       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2182       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2183     }
2184   }
2185 
2186   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2187   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2188       N0.getOpcode() == ISD::ADD &&
2189       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2190       isMulAddWithConstProfitable(N, N0, N1))
2191       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2192                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2193                                      N0.getOperand(0), N1),
2194                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2195                                      N0.getOperand(1), N1));
2196 
2197   // reassociate mul
2198   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2199     return RMUL;
2200 
2201   return SDValue();
2202 }
2203 
2204 /// Return true if divmod libcall is available.
2205 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2206                                      const TargetLowering &TLI) {
2207   RTLIB::Libcall LC;
2208   EVT NodeType = Node->getValueType(0);
2209   if (!NodeType.isSimple())
2210     return false;
2211   switch (NodeType.getSimpleVT().SimpleTy) {
2212   default: return false; // No libcall for vector types.
2213   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2214   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2215   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2216   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2217   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2218   }
2219 
2220   return TLI.getLibcallName(LC) != nullptr;
2221 }
2222 
2223 /// Issue divrem if both quotient and remainder are needed.
2224 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2225   if (Node->use_empty())
2226     return SDValue(); // This is a dead node, leave it alone.
2227 
2228   unsigned Opcode = Node->getOpcode();
2229   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2230   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2231 
2232   // DivMod lib calls can still work on non-legal types if using lib-calls.
2233   EVT VT = Node->getValueType(0);
2234   if (VT.isVector() || !VT.isInteger())
2235     return SDValue();
2236 
2237   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2238     return SDValue();
2239 
2240   // If DIVREM is going to get expanded into a libcall,
2241   // but there is no libcall available, then don't combine.
2242   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2243       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2244     return SDValue();
2245 
2246   // If div is legal, it's better to do the normal expansion
2247   unsigned OtherOpcode = 0;
2248   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2249     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2250     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2251       return SDValue();
2252   } else {
2253     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2254     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2255       return SDValue();
2256   }
2257 
2258   SDValue Op0 = Node->getOperand(0);
2259   SDValue Op1 = Node->getOperand(1);
2260   SDValue combined;
2261   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2262          UE = Op0.getNode()->use_end(); UI != UE;) {
2263     SDNode *User = *UI++;
2264     if (User == Node || User->use_empty())
2265       continue;
2266     // Convert the other matching node(s), too;
2267     // otherwise, the DIVREM may get target-legalized into something
2268     // target-specific that we won't be able to recognize.
2269     unsigned UserOpc = User->getOpcode();
2270     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2271         User->getOperand(0) == Op0 &&
2272         User->getOperand(1) == Op1) {
2273       if (!combined) {
2274         if (UserOpc == OtherOpcode) {
2275           SDVTList VTs = DAG.getVTList(VT, VT);
2276           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2277         } else if (UserOpc == DivRemOpc) {
2278           combined = SDValue(User, 0);
2279         } else {
2280           assert(UserOpc == Opcode);
2281           continue;
2282         }
2283       }
2284       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2285         CombineTo(User, combined);
2286       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2287         CombineTo(User, combined.getValue(1));
2288     }
2289   }
2290   return combined;
2291 }
2292 
2293 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2294   SDValue N0 = N->getOperand(0);
2295   SDValue N1 = N->getOperand(1);
2296   EVT VT = N->getValueType(0);
2297 
2298   // fold vector ops
2299   if (VT.isVector())
2300     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2301       return FoldedVOp;
2302 
2303   SDLoc DL(N);
2304 
2305   // fold (sdiv c1, c2) -> c1/c2
2306   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2307   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2308   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2309     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2310   // fold (sdiv X, 1) -> X
2311   if (N1C && N1C->isOne())
2312     return N0;
2313   // fold (sdiv X, -1) -> 0-X
2314   if (N1C && N1C->isAllOnesValue())
2315     return DAG.getNode(ISD::SUB, DL, VT,
2316                        DAG.getConstant(0, DL, VT), N0);
2317 
2318   // If we know the sign bits of both operands are zero, strength reduce to a
2319   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2320   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2321     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2322 
2323   // fold (sdiv X, pow2) -> simple ops after legalize
2324   // FIXME: We check for the exact bit here because the generic lowering gives
2325   // better results in that case. The target-specific lowering should learn how
2326   // to handle exact sdivs efficiently.
2327   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2328       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2329       (N1C->getAPIntValue().isPowerOf2() ||
2330        (-N1C->getAPIntValue()).isPowerOf2())) {
2331     // Target-specific implementation of sdiv x, pow2.
2332     if (SDValue Res = BuildSDIVPow2(N))
2333       return Res;
2334 
2335     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2336 
2337     // Splat the sign bit into the register
2338     SDValue SGN =
2339         DAG.getNode(ISD::SRA, DL, VT, N0,
2340                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2341                                     getShiftAmountTy(N0.getValueType())));
2342     AddToWorklist(SGN.getNode());
2343 
2344     // Add (N0 < 0) ? abs2 - 1 : 0;
2345     SDValue SRL =
2346         DAG.getNode(ISD::SRL, DL, VT, SGN,
2347                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2348                                     getShiftAmountTy(SGN.getValueType())));
2349     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2350     AddToWorklist(SRL.getNode());
2351     AddToWorklist(ADD.getNode());    // Divide by pow2
2352     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2353                   DAG.getConstant(lg2, DL,
2354                                   getShiftAmountTy(ADD.getValueType())));
2355 
2356     // If we're dividing by a positive value, we're done.  Otherwise, we must
2357     // negate the result.
2358     if (N1C->getAPIntValue().isNonNegative())
2359       return SRA;
2360 
2361     AddToWorklist(SRA.getNode());
2362     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2363   }
2364 
2365   // If integer divide is expensive and we satisfy the requirements, emit an
2366   // alternate sequence.  Targets may check function attributes for size/speed
2367   // trade-offs.
2368   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2369   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2370     if (SDValue Op = BuildSDIV(N))
2371       return Op;
2372 
2373   // sdiv, srem -> sdivrem
2374   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2375   // Otherwise, we break the simplification logic in visitREM().
2376   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2377     if (SDValue DivRem = useDivRem(N))
2378         return DivRem;
2379 
2380   // undef / X -> 0
2381   if (N0.isUndef())
2382     return DAG.getConstant(0, DL, VT);
2383   // X / undef -> undef
2384   if (N1.isUndef())
2385     return N1;
2386 
2387   return SDValue();
2388 }
2389 
2390 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2391   SDValue N0 = N->getOperand(0);
2392   SDValue N1 = N->getOperand(1);
2393   EVT VT = N->getValueType(0);
2394 
2395   // fold vector ops
2396   if (VT.isVector())
2397     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2398       return FoldedVOp;
2399 
2400   SDLoc DL(N);
2401 
2402   // fold (udiv c1, c2) -> c1/c2
2403   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2404   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2405   if (N0C && N1C)
2406     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2407                                                     N0C, N1C))
2408       return Folded;
2409 
2410   // fold (udiv x, (1 << c)) -> x >>u c
2411   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2412     return DAG.getNode(ISD::SRL, DL, VT, N0,
2413                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2414                                        getShiftAmountTy(N0.getValueType())));
2415 
2416   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2417   if (N1.getOpcode() == ISD::SHL) {
2418     if (ConstantSDNode *SHC = isConstOrConstSplat(N1.getOperand(0))) {
2419       if (!SHC->isOpaque() && SHC->getAPIntValue().isPowerOf2()) {
2420         EVT ADDVT = N1.getOperand(1).getValueType();
2421         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2422                                   N1.getOperand(1),
2423                                   DAG.getConstant(SHC->getAPIntValue()
2424                                                                   .logBase2(),
2425                                                   DL, ADDVT));
2426         AddToWorklist(Add.getNode());
2427         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2428       }
2429     }
2430   }
2431 
2432   // fold (udiv x, c) -> alternate
2433   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2434   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2435     if (SDValue Op = BuildUDIV(N))
2436       return Op;
2437 
2438   // sdiv, srem -> sdivrem
2439   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2440   // Otherwise, we break the simplification logic in visitREM().
2441   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2442     if (SDValue DivRem = useDivRem(N))
2443         return DivRem;
2444 
2445   // undef / X -> 0
2446   if (N0.isUndef())
2447     return DAG.getConstant(0, DL, VT);
2448   // X / undef -> undef
2449   if (N1.isUndef())
2450     return N1;
2451 
2452   return SDValue();
2453 }
2454 
2455 // handles ISD::SREM and ISD::UREM
2456 SDValue DAGCombiner::visitREM(SDNode *N) {
2457   unsigned Opcode = N->getOpcode();
2458   SDValue N0 = N->getOperand(0);
2459   SDValue N1 = N->getOperand(1);
2460   EVT VT = N->getValueType(0);
2461   bool isSigned = (Opcode == ISD::SREM);
2462   SDLoc DL(N);
2463 
2464   // fold (rem c1, c2) -> c1%c2
2465   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2466   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2467   if (N0C && N1C)
2468     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2469       return Folded;
2470 
2471   if (isSigned) {
2472     // If we know the sign bits of both operands are zero, strength reduce to a
2473     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2474     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2475       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2476   } else {
2477     // fold (urem x, pow2) -> (and x, pow2-1)
2478     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2479         N1C->getAPIntValue().isPowerOf2()) {
2480       return DAG.getNode(ISD::AND, DL, VT, N0,
2481                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2482     }
2483     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2484     if (N1.getOpcode() == ISD::SHL) {
2485       ConstantSDNode *SHC = isConstOrConstSplat(N1.getOperand(0));
2486       if (SHC && !SHC->isOpaque() && SHC->getAPIntValue().isPowerOf2()) {
2487         APInt NegOne = APInt::getAllOnesValue(VT.getScalarSizeInBits());
2488         SDValue Add =
2489             DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2490         AddToWorklist(Add.getNode());
2491         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2492       }
2493     }
2494   }
2495 
2496   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2497 
2498   // If X/C can be simplified by the division-by-constant logic, lower
2499   // X%C to the equivalent of X-X/C*C.
2500   // To avoid mangling nodes, this simplification requires that the combine()
2501   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2502   // against this by skipping the simplification if isIntDivCheap().  When
2503   // div is not cheap, combine will not return a DIVREM.  Regardless,
2504   // checking cheapness here makes sense since the simplification results in
2505   // fatter code.
2506   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2507     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2508     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2509     AddToWorklist(Div.getNode());
2510     SDValue OptimizedDiv = combine(Div.getNode());
2511     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2512       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2513              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2514       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2515       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2516       AddToWorklist(Mul.getNode());
2517       return Sub;
2518     }
2519   }
2520 
2521   // sdiv, srem -> sdivrem
2522   if (SDValue DivRem = useDivRem(N))
2523     return DivRem.getValue(1);
2524 
2525   // undef % X -> 0
2526   if (N0.isUndef())
2527     return DAG.getConstant(0, DL, VT);
2528   // X % undef -> undef
2529   if (N1.isUndef())
2530     return N1;
2531 
2532   return SDValue();
2533 }
2534 
2535 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2536   SDValue N0 = N->getOperand(0);
2537   SDValue N1 = N->getOperand(1);
2538   EVT VT = N->getValueType(0);
2539   SDLoc DL(N);
2540 
2541   // fold (mulhs x, 0) -> 0
2542   if (isNullConstant(N1))
2543     return N1;
2544   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2545   if (isOneConstant(N1)) {
2546     SDLoc DL(N);
2547     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2548                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2549                                        getShiftAmountTy(N0.getValueType())));
2550   }
2551   // fold (mulhs x, undef) -> 0
2552   if (N0.isUndef() || N1.isUndef())
2553     return DAG.getConstant(0, SDLoc(N), VT);
2554 
2555   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2556   // plus a shift.
2557   if (VT.isSimple() && !VT.isVector()) {
2558     MVT Simple = VT.getSimpleVT();
2559     unsigned SimpleSize = Simple.getSizeInBits();
2560     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2561     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2562       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2563       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2564       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2565       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2566             DAG.getConstant(SimpleSize, DL,
2567                             getShiftAmountTy(N1.getValueType())));
2568       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2569     }
2570   }
2571 
2572   return SDValue();
2573 }
2574 
2575 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2576   SDValue N0 = N->getOperand(0);
2577   SDValue N1 = N->getOperand(1);
2578   EVT VT = N->getValueType(0);
2579   SDLoc DL(N);
2580 
2581   // fold (mulhu x, 0) -> 0
2582   if (isNullConstant(N1))
2583     return N1;
2584   // fold (mulhu x, 1) -> 0
2585   if (isOneConstant(N1))
2586     return DAG.getConstant(0, DL, N0.getValueType());
2587   // fold (mulhu x, undef) -> 0
2588   if (N0.isUndef() || N1.isUndef())
2589     return DAG.getConstant(0, DL, VT);
2590 
2591   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2592   // plus a shift.
2593   if (VT.isSimple() && !VT.isVector()) {
2594     MVT Simple = VT.getSimpleVT();
2595     unsigned SimpleSize = Simple.getSizeInBits();
2596     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2597     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2598       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2599       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2600       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2601       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2602             DAG.getConstant(SimpleSize, DL,
2603                             getShiftAmountTy(N1.getValueType())));
2604       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2605     }
2606   }
2607 
2608   return SDValue();
2609 }
2610 
2611 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2612 /// give the opcodes for the two computations that are being performed. Return
2613 /// true if a simplification was made.
2614 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2615                                                 unsigned HiOp) {
2616   // If the high half is not needed, just compute the low half.
2617   bool HiExists = N->hasAnyUseOfValue(1);
2618   if (!HiExists &&
2619       (!LegalOperations ||
2620        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2621     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2622     return CombineTo(N, Res, Res);
2623   }
2624 
2625   // If the low half is not needed, just compute the high half.
2626   bool LoExists = N->hasAnyUseOfValue(0);
2627   if (!LoExists &&
2628       (!LegalOperations ||
2629        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2630     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2631     return CombineTo(N, Res, Res);
2632   }
2633 
2634   // If both halves are used, return as it is.
2635   if (LoExists && HiExists)
2636     return SDValue();
2637 
2638   // If the two computed results can be simplified separately, separate them.
2639   if (LoExists) {
2640     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2641     AddToWorklist(Lo.getNode());
2642     SDValue LoOpt = combine(Lo.getNode());
2643     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2644         (!LegalOperations ||
2645          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2646       return CombineTo(N, LoOpt, LoOpt);
2647   }
2648 
2649   if (HiExists) {
2650     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2651     AddToWorklist(Hi.getNode());
2652     SDValue HiOpt = combine(Hi.getNode());
2653     if (HiOpt.getNode() && HiOpt != Hi &&
2654         (!LegalOperations ||
2655          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2656       return CombineTo(N, HiOpt, HiOpt);
2657   }
2658 
2659   return SDValue();
2660 }
2661 
2662 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2663   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2664     return Res;
2665 
2666   EVT VT = N->getValueType(0);
2667   SDLoc DL(N);
2668 
2669   // If the type is twice as wide is legal, transform the mulhu to a wider
2670   // multiply plus a shift.
2671   if (VT.isSimple() && !VT.isVector()) {
2672     MVT Simple = VT.getSimpleVT();
2673     unsigned SimpleSize = Simple.getSizeInBits();
2674     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2675     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2676       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2677       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2678       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2679       // Compute the high part as N1.
2680       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2681             DAG.getConstant(SimpleSize, DL,
2682                             getShiftAmountTy(Lo.getValueType())));
2683       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2684       // Compute the low part as N0.
2685       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2686       return CombineTo(N, Lo, Hi);
2687     }
2688   }
2689 
2690   return SDValue();
2691 }
2692 
2693 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2694   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2695     return Res;
2696 
2697   EVT VT = N->getValueType(0);
2698   SDLoc DL(N);
2699 
2700   // If the type is twice as wide is legal, transform the mulhu to a wider
2701   // multiply plus a shift.
2702   if (VT.isSimple() && !VT.isVector()) {
2703     MVT Simple = VT.getSimpleVT();
2704     unsigned SimpleSize = Simple.getSizeInBits();
2705     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2706     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2707       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2708       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2709       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2710       // Compute the high part as N1.
2711       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2712             DAG.getConstant(SimpleSize, DL,
2713                             getShiftAmountTy(Lo.getValueType())));
2714       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2715       // Compute the low part as N0.
2716       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2717       return CombineTo(N, Lo, Hi);
2718     }
2719   }
2720 
2721   return SDValue();
2722 }
2723 
2724 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2725   // (smulo x, 2) -> (saddo x, x)
2726   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2727     if (C2->getAPIntValue() == 2)
2728       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2729                          N->getOperand(0), N->getOperand(0));
2730 
2731   return SDValue();
2732 }
2733 
2734 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2735   // (umulo x, 2) -> (uaddo x, x)
2736   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2737     if (C2->getAPIntValue() == 2)
2738       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2739                          N->getOperand(0), N->getOperand(0));
2740 
2741   return SDValue();
2742 }
2743 
2744 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2745   SDValue N0 = N->getOperand(0);
2746   SDValue N1 = N->getOperand(1);
2747   EVT VT = N0.getValueType();
2748 
2749   // fold vector ops
2750   if (VT.isVector())
2751     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2752       return FoldedVOp;
2753 
2754   // fold (add c1, c2) -> c1+c2
2755   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2756   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2757   if (N0C && N1C)
2758     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2759 
2760   // canonicalize constant to RHS
2761   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2762      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2763     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2764 
2765   return SDValue();
2766 }
2767 
2768 /// If this is a binary operator with two operands of the same opcode, try to
2769 /// simplify it.
2770 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2771   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2772   EVT VT = N0.getValueType();
2773   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2774 
2775   // Bail early if none of these transforms apply.
2776   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2777 
2778   // For each of OP in AND/OR/XOR:
2779   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2780   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2781   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2782   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2783   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2784   //
2785   // do not sink logical op inside of a vector extend, since it may combine
2786   // into a vsetcc.
2787   EVT Op0VT = N0.getOperand(0).getValueType();
2788   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2789        N0.getOpcode() == ISD::SIGN_EXTEND ||
2790        N0.getOpcode() == ISD::BSWAP ||
2791        // Avoid infinite looping with PromoteIntBinOp.
2792        (N0.getOpcode() == ISD::ANY_EXTEND &&
2793         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2794        (N0.getOpcode() == ISD::TRUNCATE &&
2795         (!TLI.isZExtFree(VT, Op0VT) ||
2796          !TLI.isTruncateFree(Op0VT, VT)) &&
2797         TLI.isTypeLegal(Op0VT))) &&
2798       !VT.isVector() &&
2799       Op0VT == N1.getOperand(0).getValueType() &&
2800       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2801     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2802                                  N0.getOperand(0).getValueType(),
2803                                  N0.getOperand(0), N1.getOperand(0));
2804     AddToWorklist(ORNode.getNode());
2805     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2806   }
2807 
2808   // For each of OP in SHL/SRL/SRA/AND...
2809   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2810   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2811   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2812   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2813        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2814       N0.getOperand(1) == N1.getOperand(1)) {
2815     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2816                                  N0.getOperand(0).getValueType(),
2817                                  N0.getOperand(0), N1.getOperand(0));
2818     AddToWorklist(ORNode.getNode());
2819     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2820                        ORNode, N0.getOperand(1));
2821   }
2822 
2823   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2824   // Only perform this optimization up until type legalization, before
2825   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2826   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2827   // we don't want to undo this promotion.
2828   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2829   // on scalars.
2830   if ((N0.getOpcode() == ISD::BITCAST ||
2831        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2832        Level <= AfterLegalizeTypes) {
2833     SDValue In0 = N0.getOperand(0);
2834     SDValue In1 = N1.getOperand(0);
2835     EVT In0Ty = In0.getValueType();
2836     EVT In1Ty = In1.getValueType();
2837     SDLoc DL(N);
2838     // If both incoming values are integers, and the original types are the
2839     // same.
2840     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2841       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2842       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2843       AddToWorklist(Op.getNode());
2844       return BC;
2845     }
2846   }
2847 
2848   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2849   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2850   // If both shuffles use the same mask, and both shuffle within a single
2851   // vector, then it is worthwhile to move the swizzle after the operation.
2852   // The type-legalizer generates this pattern when loading illegal
2853   // vector types from memory. In many cases this allows additional shuffle
2854   // optimizations.
2855   // There are other cases where moving the shuffle after the xor/and/or
2856   // is profitable even if shuffles don't perform a swizzle.
2857   // If both shuffles use the same mask, and both shuffles have the same first
2858   // or second operand, then it might still be profitable to move the shuffle
2859   // after the xor/and/or operation.
2860   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2861     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2862     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2863 
2864     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2865            "Inputs to shuffles are not the same type");
2866 
2867     // Check that both shuffles use the same mask. The masks are known to be of
2868     // the same length because the result vector type is the same.
2869     // Check also that shuffles have only one use to avoid introducing extra
2870     // instructions.
2871     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2872         SVN0->getMask().equals(SVN1->getMask())) {
2873       SDValue ShOp = N0->getOperand(1);
2874 
2875       // Don't try to fold this node if it requires introducing a
2876       // build vector of all zeros that might be illegal at this stage.
2877       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2878         if (!LegalTypes)
2879           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2880         else
2881           ShOp = SDValue();
2882       }
2883 
2884       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2885       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2886       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2887       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2888         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2889                                       N0->getOperand(0), N1->getOperand(0));
2890         AddToWorklist(NewNode.getNode());
2891         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2892                                     SVN0->getMask());
2893       }
2894 
2895       // Don't try to fold this node if it requires introducing a
2896       // build vector of all zeros that might be illegal at this stage.
2897       ShOp = N0->getOperand(0);
2898       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2899         if (!LegalTypes)
2900           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2901         else
2902           ShOp = SDValue();
2903       }
2904 
2905       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2906       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2907       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2908       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2909         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2910                                       N0->getOperand(1), N1->getOperand(1));
2911         AddToWorklist(NewNode.getNode());
2912         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2913                                     SVN0->getMask());
2914       }
2915     }
2916   }
2917 
2918   return SDValue();
2919 }
2920 
2921 /// This contains all DAGCombine rules which reduce two values combined by
2922 /// an And operation to a single value. This makes them reusable in the context
2923 /// of visitSELECT(). Rules involving constants are not included as
2924 /// visitSELECT() already handles those cases.
2925 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2926                                   SDNode *LocReference) {
2927   EVT VT = N1.getValueType();
2928 
2929   // fold (and x, undef) -> 0
2930   if (N0.isUndef() || N1.isUndef())
2931     return DAG.getConstant(0, SDLoc(LocReference), VT);
2932   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2933   SDValue LL, LR, RL, RR, CC0, CC1;
2934   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2935     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2936     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2937 
2938     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2939         LL.getValueType().isInteger()) {
2940       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2941       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2942         EVT CCVT = getSetCCResultType(LR.getValueType());
2943         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2944           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2945                                        LR.getValueType(), LL, RL);
2946           AddToWorklist(ORNode.getNode());
2947           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2948         }
2949       }
2950       if (isAllOnesConstant(LR)) {
2951         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2952         if (Op1 == ISD::SETEQ) {
2953           EVT CCVT = getSetCCResultType(LR.getValueType());
2954           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2955             SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2956                                           LR.getValueType(), LL, RL);
2957             AddToWorklist(ANDNode.getNode());
2958             return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2959           }
2960         }
2961         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2962         if (Op1 == ISD::SETGT) {
2963           EVT CCVT = getSetCCResultType(LR.getValueType());
2964           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2965             SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2966                                          LR.getValueType(), LL, RL);
2967             AddToWorklist(ORNode.getNode());
2968             return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2969           }
2970         }
2971       }
2972     }
2973     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2974     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2975         Op0 == Op1 && LL.getValueType().isInteger() &&
2976       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2977                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2978       EVT CCVT = getSetCCResultType(LL.getValueType());
2979       if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2980         SDLoc DL(N0);
2981         SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2982                                       LL, DAG.getConstant(1, DL,
2983                                                           LL.getValueType()));
2984         AddToWorklist(ADDNode.getNode());
2985         return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2986                             DAG.getConstant(2, DL, LL.getValueType()),
2987                             ISD::SETUGE);
2988       }
2989     }
2990     // canonicalize equivalent to ll == rl
2991     if (LL == RR && LR == RL) {
2992       Op1 = ISD::getSetCCSwappedOperands(Op1);
2993       std::swap(RL, RR);
2994     }
2995     if (LL == RL && LR == RR) {
2996       bool isInteger = LL.getValueType().isInteger();
2997       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2998       if (Result != ISD::SETCC_INVALID &&
2999           (!LegalOperations ||
3000            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3001             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3002         EVT CCVT = getSetCCResultType(LL.getValueType());
3003         if (N0.getValueType() == CCVT ||
3004             (!LegalOperations && N0.getValueType() == MVT::i1))
3005           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3006                               LL, LR, Result);
3007       }
3008     }
3009   }
3010 
3011   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3012       VT.getSizeInBits() <= 64) {
3013     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3014       APInt ADDC = ADDI->getAPIntValue();
3015       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3016         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3017         // immediate for an add, but it is legal if its top c2 bits are set,
3018         // transform the ADD so the immediate doesn't need to be materialized
3019         // in a register.
3020         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3021           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3022                                              SRLI->getZExtValue());
3023           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3024             ADDC |= Mask;
3025             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3026               SDLoc DL(N0);
3027               SDValue NewAdd =
3028                 DAG.getNode(ISD::ADD, DL, VT,
3029                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3030               CombineTo(N0.getNode(), NewAdd);
3031               // Return N so it doesn't get rechecked!
3032               return SDValue(LocReference, 0);
3033             }
3034           }
3035         }
3036       }
3037     }
3038   }
3039 
3040   // Reduce bit extract of low half of an integer to the narrower type.
3041   // (and (srl i64:x, K), KMask) ->
3042   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3043   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3044     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3045       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3046         unsigned Size = VT.getSizeInBits();
3047         const APInt &AndMask = CAnd->getAPIntValue();
3048         unsigned ShiftBits = CShift->getZExtValue();
3049 
3050         // Bail out, this node will probably disappear anyway.
3051         if (ShiftBits == 0)
3052           return SDValue();
3053 
3054         unsigned MaskBits = AndMask.countTrailingOnes();
3055         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3056 
3057         if (APIntOps::isMask(AndMask) &&
3058             // Required bits must not span the two halves of the integer and
3059             // must fit in the half size type.
3060             (ShiftBits + MaskBits <= Size / 2) &&
3061             TLI.isNarrowingProfitable(VT, HalfVT) &&
3062             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3063             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3064             TLI.isTruncateFree(VT, HalfVT) &&
3065             TLI.isZExtFree(HalfVT, VT)) {
3066           // The isNarrowingProfitable is to avoid regressions on PPC and
3067           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3068           // on downstream users of this. Those patterns could probably be
3069           // extended to handle extensions mixed in.
3070 
3071           SDValue SL(N0);
3072           assert(MaskBits <= Size);
3073 
3074           // Extracting the highest bit of the low half.
3075           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3076           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3077                                       N0.getOperand(0));
3078 
3079           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3080           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3081           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3082           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3083           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3084         }
3085       }
3086     }
3087   }
3088 
3089   return SDValue();
3090 }
3091 
3092 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3093                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3094                                    bool &NarrowLoad) {
3095   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3096 
3097   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3098     return false;
3099 
3100   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3101   LoadedVT = LoadN->getMemoryVT();
3102 
3103   if (ExtVT == LoadedVT &&
3104       (!LegalOperations ||
3105        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3106     // ZEXTLOAD will match without needing to change the size of the value being
3107     // loaded.
3108     NarrowLoad = false;
3109     return true;
3110   }
3111 
3112   // Do not change the width of a volatile load.
3113   if (LoadN->isVolatile())
3114     return false;
3115 
3116   // Do not generate loads of non-round integer types since these can
3117   // be expensive (and would be wrong if the type is not byte sized).
3118   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3119     return false;
3120 
3121   if (LegalOperations &&
3122       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3123     return false;
3124 
3125   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3126     return false;
3127 
3128   NarrowLoad = true;
3129   return true;
3130 }
3131 
3132 SDValue DAGCombiner::visitAND(SDNode *N) {
3133   SDValue N0 = N->getOperand(0);
3134   SDValue N1 = N->getOperand(1);
3135   EVT VT = N1.getValueType();
3136 
3137   // x & x --> x
3138   if (N0 == N1)
3139     return N0;
3140 
3141   // fold vector ops
3142   if (VT.isVector()) {
3143     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3144       return FoldedVOp;
3145 
3146     // fold (and x, 0) -> 0, vector edition
3147     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3148       // do not return N0, because undef node may exist in N0
3149       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3150                              SDLoc(N), N0.getValueType());
3151     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3152       // do not return N1, because undef node may exist in N1
3153       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3154                              SDLoc(N), N1.getValueType());
3155 
3156     // fold (and x, -1) -> x, vector edition
3157     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3158       return N1;
3159     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3160       return N0;
3161   }
3162 
3163   // fold (and c1, c2) -> c1&c2
3164   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3165   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3166   if (N0C && N1C && !N1C->isOpaque())
3167     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3168   // canonicalize constant to RHS
3169   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3170      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3171     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3172   // fold (and x, -1) -> x
3173   if (isAllOnesConstant(N1))
3174     return N0;
3175   // if (and x, c) is known to be zero, return 0
3176   unsigned BitWidth = VT.getScalarSizeInBits();
3177   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3178                                    APInt::getAllOnesValue(BitWidth)))
3179     return DAG.getConstant(0, SDLoc(N), VT);
3180   // reassociate and
3181   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3182     return RAND;
3183   // fold (and (or x, C), D) -> D if (C & D) == D
3184   if (N1C && N0.getOpcode() == ISD::OR)
3185     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3186       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3187         return N1;
3188   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3189   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3190     SDValue N0Op0 = N0.getOperand(0);
3191     APInt Mask = ~N1C->getAPIntValue();
3192     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3193     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3194       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3195                                  N0.getValueType(), N0Op0);
3196 
3197       // Replace uses of the AND with uses of the Zero extend node.
3198       CombineTo(N, Zext);
3199 
3200       // We actually want to replace all uses of the any_extend with the
3201       // zero_extend, to avoid duplicating things.  This will later cause this
3202       // AND to be folded.
3203       CombineTo(N0.getNode(), Zext);
3204       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3205     }
3206   }
3207   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3208   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3209   // already be zero by virtue of the width of the base type of the load.
3210   //
3211   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3212   // more cases.
3213   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3214        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3215        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3216        N0.getOperand(0).getResNo() == 0) ||
3217       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3218     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3219                                          N0 : N0.getOperand(0) );
3220 
3221     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3222     // This can be a pure constant or a vector splat, in which case we treat the
3223     // vector as a scalar and use the splat value.
3224     APInt Constant = APInt::getNullValue(1);
3225     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3226       Constant = C->getAPIntValue();
3227     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3228       APInt SplatValue, SplatUndef;
3229       unsigned SplatBitSize;
3230       bool HasAnyUndefs;
3231       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3232                                              SplatBitSize, HasAnyUndefs);
3233       if (IsSplat) {
3234         // Undef bits can contribute to a possible optimisation if set, so
3235         // set them.
3236         SplatValue |= SplatUndef;
3237 
3238         // The splat value may be something like "0x00FFFFFF", which means 0 for
3239         // the first vector value and FF for the rest, repeating. We need a mask
3240         // that will apply equally to all members of the vector, so AND all the
3241         // lanes of the constant together.
3242         EVT VT = Vector->getValueType(0);
3243         unsigned BitWidth = VT.getScalarSizeInBits();
3244 
3245         // If the splat value has been compressed to a bitlength lower
3246         // than the size of the vector lane, we need to re-expand it to
3247         // the lane size.
3248         if (BitWidth > SplatBitSize)
3249           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3250                SplatBitSize < BitWidth;
3251                SplatBitSize = SplatBitSize * 2)
3252             SplatValue |= SplatValue.shl(SplatBitSize);
3253 
3254         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3255         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3256         if (SplatBitSize % BitWidth == 0) {
3257           Constant = APInt::getAllOnesValue(BitWidth);
3258           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3259             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3260         }
3261       }
3262     }
3263 
3264     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3265     // actually legal and isn't going to get expanded, else this is a false
3266     // optimisation.
3267     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3268                                                     Load->getValueType(0),
3269                                                     Load->getMemoryVT());
3270 
3271     // Resize the constant to the same size as the original memory access before
3272     // extension. If it is still the AllOnesValue then this AND is completely
3273     // unneeded.
3274     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3275 
3276     bool B;
3277     switch (Load->getExtensionType()) {
3278     default: B = false; break;
3279     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3280     case ISD::ZEXTLOAD:
3281     case ISD::NON_EXTLOAD: B = true; break;
3282     }
3283 
3284     if (B && Constant.isAllOnesValue()) {
3285       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3286       // preserve semantics once we get rid of the AND.
3287       SDValue NewLoad(Load, 0);
3288       if (Load->getExtensionType() == ISD::EXTLOAD) {
3289         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3290                               Load->getValueType(0), SDLoc(Load),
3291                               Load->getChain(), Load->getBasePtr(),
3292                               Load->getOffset(), Load->getMemoryVT(),
3293                               Load->getMemOperand());
3294         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3295         if (Load->getNumValues() == 3) {
3296           // PRE/POST_INC loads have 3 values.
3297           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3298                            NewLoad.getValue(2) };
3299           CombineTo(Load, To, 3, true);
3300         } else {
3301           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3302         }
3303       }
3304 
3305       // Fold the AND away, taking care not to fold to the old load node if we
3306       // replaced it.
3307       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3308 
3309       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3310     }
3311   }
3312 
3313   // fold (and (load x), 255) -> (zextload x, i8)
3314   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3315   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3316   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3317                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3318                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3319     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3320     LoadSDNode *LN0 = HasAnyExt
3321       ? cast<LoadSDNode>(N0.getOperand(0))
3322       : cast<LoadSDNode>(N0);
3323     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3324         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3325       auto NarrowLoad = false;
3326       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3327       EVT ExtVT, LoadedVT;
3328       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3329                            NarrowLoad)) {
3330         if (!NarrowLoad) {
3331           SDValue NewLoad =
3332             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3333                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3334                            LN0->getMemOperand());
3335           AddToWorklist(N);
3336           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3337           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3338         } else {
3339           EVT PtrType = LN0->getOperand(1).getValueType();
3340 
3341           unsigned Alignment = LN0->getAlignment();
3342           SDValue NewPtr = LN0->getBasePtr();
3343 
3344           // For big endian targets, we need to add an offset to the pointer
3345           // to load the correct bytes.  For little endian systems, we merely
3346           // need to read fewer bytes from the same pointer.
3347           if (DAG.getDataLayout().isBigEndian()) {
3348             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3349             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3350             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3351             SDLoc DL(LN0);
3352             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3353                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3354             Alignment = MinAlign(Alignment, PtrOff);
3355           }
3356 
3357           AddToWorklist(NewPtr.getNode());
3358 
3359           SDValue Load = DAG.getExtLoad(
3360               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3361               LN0->getPointerInfo(), ExtVT, Alignment,
3362               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3363           AddToWorklist(N);
3364           CombineTo(LN0, Load, Load.getValue(1));
3365           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3366         }
3367       }
3368     }
3369   }
3370 
3371   if (SDValue Combined = visitANDLike(N0, N1, N))
3372     return Combined;
3373 
3374   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3375   if (N0.getOpcode() == N1.getOpcode())
3376     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3377       return Tmp;
3378 
3379   // Masking the negated extension of a boolean is just the zero-extended
3380   // boolean:
3381   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3382   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3383   //
3384   // Note: the SimplifyDemandedBits fold below can make an information-losing
3385   // transform, and then we have no way to find this better fold.
3386   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3387     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3388     SDValue SubRHS = N0.getOperand(1);
3389     if (SubLHS && SubLHS->isNullValue()) {
3390       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3391           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3392         return SubRHS;
3393       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3394           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3395         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3396     }
3397   }
3398 
3399   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3400   // fold (and (sra)) -> (and (srl)) when possible.
3401   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
3402     return SDValue(N, 0);
3403 
3404   // fold (zext_inreg (extload x)) -> (zextload x)
3405   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3406     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3407     EVT MemVT = LN0->getMemoryVT();
3408     // If we zero all the possible extended bits, then we can turn this into
3409     // a zextload if we are running before legalize or the operation is legal.
3410     unsigned BitWidth = N1.getScalarValueSizeInBits();
3411     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3412                            BitWidth - MemVT.getScalarSizeInBits())) &&
3413         ((!LegalOperations && !LN0->isVolatile()) ||
3414          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3415       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3416                                        LN0->getChain(), LN0->getBasePtr(),
3417                                        MemVT, LN0->getMemOperand());
3418       AddToWorklist(N);
3419       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3420       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3421     }
3422   }
3423   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3424   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3425       N0.hasOneUse()) {
3426     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3427     EVT MemVT = LN0->getMemoryVT();
3428     // If we zero all the possible extended bits, then we can turn this into
3429     // a zextload if we are running before legalize or the operation is legal.
3430     unsigned BitWidth = N1.getScalarValueSizeInBits();
3431     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3432                            BitWidth - MemVT.getScalarSizeInBits())) &&
3433         ((!LegalOperations && !LN0->isVolatile()) ||
3434          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3435       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3436                                        LN0->getChain(), LN0->getBasePtr(),
3437                                        MemVT, LN0->getMemOperand());
3438       AddToWorklist(N);
3439       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3440       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3441     }
3442   }
3443   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3444   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3445     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3446                                            N0.getOperand(1), false))
3447       return BSwap;
3448   }
3449 
3450   return SDValue();
3451 }
3452 
3453 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3454 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3455                                         bool DemandHighBits) {
3456   if (!LegalOperations)
3457     return SDValue();
3458 
3459   EVT VT = N->getValueType(0);
3460   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3461     return SDValue();
3462   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3463     return SDValue();
3464 
3465   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3466   bool LookPassAnd0 = false;
3467   bool LookPassAnd1 = false;
3468   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3469       std::swap(N0, N1);
3470   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3471       std::swap(N0, N1);
3472   if (N0.getOpcode() == ISD::AND) {
3473     if (!N0.getNode()->hasOneUse())
3474       return SDValue();
3475     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3476     if (!N01C || N01C->getZExtValue() != 0xFF00)
3477       return SDValue();
3478     N0 = N0.getOperand(0);
3479     LookPassAnd0 = true;
3480   }
3481 
3482   if (N1.getOpcode() == ISD::AND) {
3483     if (!N1.getNode()->hasOneUse())
3484       return SDValue();
3485     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3486     if (!N11C || N11C->getZExtValue() != 0xFF)
3487       return SDValue();
3488     N1 = N1.getOperand(0);
3489     LookPassAnd1 = true;
3490   }
3491 
3492   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3493     std::swap(N0, N1);
3494   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3495     return SDValue();
3496   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3497     return SDValue();
3498 
3499   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3500   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3501   if (!N01C || !N11C)
3502     return SDValue();
3503   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3504     return SDValue();
3505 
3506   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3507   SDValue N00 = N0->getOperand(0);
3508   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3509     if (!N00.getNode()->hasOneUse())
3510       return SDValue();
3511     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3512     if (!N001C || N001C->getZExtValue() != 0xFF)
3513       return SDValue();
3514     N00 = N00.getOperand(0);
3515     LookPassAnd0 = true;
3516   }
3517 
3518   SDValue N10 = N1->getOperand(0);
3519   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3520     if (!N10.getNode()->hasOneUse())
3521       return SDValue();
3522     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3523     if (!N101C || N101C->getZExtValue() != 0xFF00)
3524       return SDValue();
3525     N10 = N10.getOperand(0);
3526     LookPassAnd1 = true;
3527   }
3528 
3529   if (N00 != N10)
3530     return SDValue();
3531 
3532   // Make sure everything beyond the low halfword gets set to zero since the SRL
3533   // 16 will clear the top bits.
3534   unsigned OpSizeInBits = VT.getSizeInBits();
3535   if (DemandHighBits && OpSizeInBits > 16) {
3536     // If the left-shift isn't masked out then the only way this is a bswap is
3537     // if all bits beyond the low 8 are 0. In that case the entire pattern
3538     // reduces to a left shift anyway: leave it for other parts of the combiner.
3539     if (!LookPassAnd0)
3540       return SDValue();
3541 
3542     // However, if the right shift isn't masked out then it might be because
3543     // it's not needed. See if we can spot that too.
3544     if (!LookPassAnd1 &&
3545         !DAG.MaskedValueIsZero(
3546             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3547       return SDValue();
3548   }
3549 
3550   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3551   if (OpSizeInBits > 16) {
3552     SDLoc DL(N);
3553     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3554                       DAG.getConstant(OpSizeInBits - 16, DL,
3555                                       getShiftAmountTy(VT)));
3556   }
3557   return Res;
3558 }
3559 
3560 /// Return true if the specified node is an element that makes up a 32-bit
3561 /// packed halfword byteswap.
3562 /// ((x & 0x000000ff) << 8) |
3563 /// ((x & 0x0000ff00) >> 8) |
3564 /// ((x & 0x00ff0000) << 8) |
3565 /// ((x & 0xff000000) >> 8)
3566 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3567   if (!N.getNode()->hasOneUse())
3568     return false;
3569 
3570   unsigned Opc = N.getOpcode();
3571   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3572     return false;
3573 
3574   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3575   if (!N1C)
3576     return false;
3577 
3578   unsigned Num;
3579   switch (N1C->getZExtValue()) {
3580   default:
3581     return false;
3582   case 0xFF:       Num = 0; break;
3583   case 0xFF00:     Num = 1; break;
3584   case 0xFF0000:   Num = 2; break;
3585   case 0xFF000000: Num = 3; break;
3586   }
3587 
3588   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3589   SDValue N0 = N.getOperand(0);
3590   if (Opc == ISD::AND) {
3591     if (Num == 0 || Num == 2) {
3592       // (x >> 8) & 0xff
3593       // (x >> 8) & 0xff0000
3594       if (N0.getOpcode() != ISD::SRL)
3595         return false;
3596       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3597       if (!C || C->getZExtValue() != 8)
3598         return false;
3599     } else {
3600       // (x << 8) & 0xff00
3601       // (x << 8) & 0xff000000
3602       if (N0.getOpcode() != ISD::SHL)
3603         return false;
3604       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3605       if (!C || C->getZExtValue() != 8)
3606         return false;
3607     }
3608   } else if (Opc == ISD::SHL) {
3609     // (x & 0xff) << 8
3610     // (x & 0xff0000) << 8
3611     if (Num != 0 && Num != 2)
3612       return false;
3613     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3614     if (!C || C->getZExtValue() != 8)
3615       return false;
3616   } else { // Opc == ISD::SRL
3617     // (x & 0xff00) >> 8
3618     // (x & 0xff000000) >> 8
3619     if (Num != 1 && Num != 3)
3620       return false;
3621     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3622     if (!C || C->getZExtValue() != 8)
3623       return false;
3624   }
3625 
3626   if (Parts[Num])
3627     return false;
3628 
3629   Parts[Num] = N0.getOperand(0).getNode();
3630   return true;
3631 }
3632 
3633 /// Match a 32-bit packed halfword bswap. That is
3634 /// ((x & 0x000000ff) << 8) |
3635 /// ((x & 0x0000ff00) >> 8) |
3636 /// ((x & 0x00ff0000) << 8) |
3637 /// ((x & 0xff000000) >> 8)
3638 /// => (rotl (bswap x), 16)
3639 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3640   if (!LegalOperations)
3641     return SDValue();
3642 
3643   EVT VT = N->getValueType(0);
3644   if (VT != MVT::i32)
3645     return SDValue();
3646   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3647     return SDValue();
3648 
3649   // Look for either
3650   // (or (or (and), (and)), (or (and), (and)))
3651   // (or (or (or (and), (and)), (and)), (and))
3652   if (N0.getOpcode() != ISD::OR)
3653     return SDValue();
3654   SDValue N00 = N0.getOperand(0);
3655   SDValue N01 = N0.getOperand(1);
3656   SDNode *Parts[4] = {};
3657 
3658   if (N1.getOpcode() == ISD::OR &&
3659       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3660     // (or (or (and), (and)), (or (and), (and)))
3661     SDValue N000 = N00.getOperand(0);
3662     if (!isBSwapHWordElement(N000, Parts))
3663       return SDValue();
3664 
3665     SDValue N001 = N00.getOperand(1);
3666     if (!isBSwapHWordElement(N001, Parts))
3667       return SDValue();
3668     SDValue N010 = N01.getOperand(0);
3669     if (!isBSwapHWordElement(N010, Parts))
3670       return SDValue();
3671     SDValue N011 = N01.getOperand(1);
3672     if (!isBSwapHWordElement(N011, Parts))
3673       return SDValue();
3674   } else {
3675     // (or (or (or (and), (and)), (and)), (and))
3676     if (!isBSwapHWordElement(N1, Parts))
3677       return SDValue();
3678     if (!isBSwapHWordElement(N01, Parts))
3679       return SDValue();
3680     if (N00.getOpcode() != ISD::OR)
3681       return SDValue();
3682     SDValue N000 = N00.getOperand(0);
3683     if (!isBSwapHWordElement(N000, Parts))
3684       return SDValue();
3685     SDValue N001 = N00.getOperand(1);
3686     if (!isBSwapHWordElement(N001, Parts))
3687       return SDValue();
3688   }
3689 
3690   // Make sure the parts are all coming from the same node.
3691   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3692     return SDValue();
3693 
3694   SDLoc DL(N);
3695   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3696                               SDValue(Parts[0], 0));
3697 
3698   // Result of the bswap should be rotated by 16. If it's not legal, then
3699   // do  (x << 16) | (x >> 16).
3700   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3701   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3702     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3703   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3704     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3705   return DAG.getNode(ISD::OR, DL, VT,
3706                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3707                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3708 }
3709 
3710 /// This contains all DAGCombine rules which reduce two values combined by
3711 /// an Or operation to a single value \see visitANDLike().
3712 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3713   EVT VT = N1.getValueType();
3714   // fold (or x, undef) -> -1
3715   if (!LegalOperations &&
3716       (N0.isUndef() || N1.isUndef())) {
3717     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3718     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3719                            SDLoc(LocReference), VT);
3720   }
3721   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3722   SDValue LL, LR, RL, RR, CC0, CC1;
3723   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3724     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3725     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3726 
3727     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3728       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3729       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3730       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3731         EVT CCVT = getSetCCResultType(LR.getValueType());
3732         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3733           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3734                                        LR.getValueType(), LL, RL);
3735           AddToWorklist(ORNode.getNode());
3736           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3737         }
3738       }
3739       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3740       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3741       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3742         EVT CCVT = getSetCCResultType(LR.getValueType());
3743         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3744           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3745                                         LR.getValueType(), LL, RL);
3746           AddToWorklist(ANDNode.getNode());
3747           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3748         }
3749       }
3750     }
3751     // canonicalize equivalent to ll == rl
3752     if (LL == RR && LR == RL) {
3753       Op1 = ISD::getSetCCSwappedOperands(Op1);
3754       std::swap(RL, RR);
3755     }
3756     if (LL == RL && LR == RR) {
3757       bool isInteger = LL.getValueType().isInteger();
3758       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3759       if (Result != ISD::SETCC_INVALID &&
3760           (!LegalOperations ||
3761            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3762             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3763         EVT CCVT = getSetCCResultType(LL.getValueType());
3764         if (N0.getValueType() == CCVT ||
3765             (!LegalOperations && N0.getValueType() == MVT::i1))
3766           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3767                               LL, LR, Result);
3768       }
3769     }
3770   }
3771 
3772   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3773   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3774       // Don't increase # computations.
3775       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3776     // We can only do this xform if we know that bits from X that are set in C2
3777     // but not in C1 are already zero.  Likewise for Y.
3778     if (const ConstantSDNode *N0O1C =
3779         getAsNonOpaqueConstant(N0.getOperand(1))) {
3780       if (const ConstantSDNode *N1O1C =
3781           getAsNonOpaqueConstant(N1.getOperand(1))) {
3782         // We can only do this xform if we know that bits from X that are set in
3783         // C2 but not in C1 are already zero.  Likewise for Y.
3784         const APInt &LHSMask = N0O1C->getAPIntValue();
3785         const APInt &RHSMask = N1O1C->getAPIntValue();
3786 
3787         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3788             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3789           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3790                                   N0.getOperand(0), N1.getOperand(0));
3791           SDLoc DL(LocReference);
3792           return DAG.getNode(ISD::AND, DL, VT, X,
3793                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3794         }
3795       }
3796     }
3797   }
3798 
3799   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3800   if (N0.getOpcode() == ISD::AND &&
3801       N1.getOpcode() == ISD::AND &&
3802       N0.getOperand(0) == N1.getOperand(0) &&
3803       // Don't increase # computations.
3804       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3805     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3806                             N0.getOperand(1), N1.getOperand(1));
3807     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3808   }
3809 
3810   return SDValue();
3811 }
3812 
3813 SDValue DAGCombiner::visitOR(SDNode *N) {
3814   SDValue N0 = N->getOperand(0);
3815   SDValue N1 = N->getOperand(1);
3816   EVT VT = N1.getValueType();
3817 
3818   // x | x --> x
3819   if (N0 == N1)
3820     return N0;
3821 
3822   // fold vector ops
3823   if (VT.isVector()) {
3824     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3825       return FoldedVOp;
3826 
3827     // fold (or x, 0) -> x, vector edition
3828     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3829       return N1;
3830     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3831       return N0;
3832 
3833     // fold (or x, -1) -> -1, vector edition
3834     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3835       // do not return N0, because undef node may exist in N0
3836       return DAG.getConstant(
3837           APInt::getAllOnesValue(N0.getScalarValueSizeInBits()), SDLoc(N),
3838           N0.getValueType());
3839     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3840       // do not return N1, because undef node may exist in N1
3841       return DAG.getConstant(
3842           APInt::getAllOnesValue(N1.getScalarValueSizeInBits()), SDLoc(N),
3843           N1.getValueType());
3844 
3845     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
3846     // Do this only if the resulting shuffle is legal.
3847     if (isa<ShuffleVectorSDNode>(N0) &&
3848         isa<ShuffleVectorSDNode>(N1) &&
3849         // Avoid folding a node with illegal type.
3850         TLI.isTypeLegal(VT)) {
3851       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
3852       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
3853       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
3854       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
3855       // Ensure both shuffles have a zero input.
3856       if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) {
3857         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
3858         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
3859         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3860         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3861         bool CanFold = true;
3862         int NumElts = VT.getVectorNumElements();
3863         SmallVector<int, 4> Mask(NumElts);
3864 
3865         for (int i = 0; i != NumElts; ++i) {
3866           int M0 = SV0->getMaskElt(i);
3867           int M1 = SV1->getMaskElt(i);
3868 
3869           // Determine if either index is pointing to a zero vector.
3870           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
3871           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
3872 
3873           // If one element is zero and the otherside is undef, keep undef.
3874           // This also handles the case that both are undef.
3875           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
3876             Mask[i] = -1;
3877             continue;
3878           }
3879 
3880           // Make sure only one of the elements is zero.
3881           if (M0Zero == M1Zero) {
3882             CanFold = false;
3883             break;
3884           }
3885 
3886           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
3887 
3888           // We have a zero and non-zero element. If the non-zero came from
3889           // SV0 make the index a LHS index. If it came from SV1, make it
3890           // a RHS index. We need to mod by NumElts because we don't care
3891           // which operand it came from in the original shuffles.
3892           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
3893         }
3894 
3895         if (CanFold) {
3896           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
3897           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
3898 
3899           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3900           if (!LegalMask) {
3901             std::swap(NewLHS, NewRHS);
3902             ShuffleVectorSDNode::commuteMask(Mask);
3903             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3904           }
3905 
3906           if (LegalMask)
3907             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
3908         }
3909       }
3910     }
3911   }
3912 
3913   // fold (or c1, c2) -> c1|c2
3914   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3915   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3916   if (N0C && N1C && !N1C->isOpaque())
3917     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3918   // canonicalize constant to RHS
3919   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3920      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3921     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3922   // fold (or x, 0) -> x
3923   if (isNullConstant(N1))
3924     return N0;
3925   // fold (or x, -1) -> -1
3926   if (isAllOnesConstant(N1))
3927     return N1;
3928   // fold (or x, c) -> c iff (x & ~c) == 0
3929   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3930     return N1;
3931 
3932   if (SDValue Combined = visitORLike(N0, N1, N))
3933     return Combined;
3934 
3935   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3936   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3937     return BSwap;
3938   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3939     return BSwap;
3940 
3941   // reassociate or
3942   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3943     return ROR;
3944   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3945   // iff (c1 & c2) == 0.
3946   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3947              isa<ConstantSDNode>(N0.getOperand(1))) {
3948     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3949     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3950       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3951                                                    N1C, C1))
3952         return DAG.getNode(
3953             ISD::AND, SDLoc(N), VT,
3954             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3955       return SDValue();
3956     }
3957   }
3958   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3959   if (N0.getOpcode() == N1.getOpcode())
3960     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3961       return Tmp;
3962 
3963   // See if this is some rotate idiom.
3964   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3965     return SDValue(Rot, 0);
3966 
3967   // Simplify the operands using demanded-bits information.
3968   if (!VT.isVector() &&
3969       SimplifyDemandedBits(SDValue(N, 0)))
3970     return SDValue(N, 0);
3971 
3972   return SDValue();
3973 }
3974 
3975 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3976 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3977   if (Op.getOpcode() == ISD::AND) {
3978     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3979       Mask = Op.getOperand(1);
3980       Op = Op.getOperand(0);
3981     } else {
3982       return false;
3983     }
3984   }
3985 
3986   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3987     Shift = Op;
3988     return true;
3989   }
3990 
3991   return false;
3992 }
3993 
3994 // Return true if we can prove that, whenever Neg and Pos are both in the
3995 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3996 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3997 //
3998 //     (or (shift1 X, Neg), (shift2 X, Pos))
3999 //
4000 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4001 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4002 // to consider shift amounts with defined behavior.
4003 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4004   // If EltSize is a power of 2 then:
4005   //
4006   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4007   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4008   //
4009   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4010   // for the stronger condition:
4011   //
4012   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4013   //
4014   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4015   // we can just replace Neg with Neg' for the rest of the function.
4016   //
4017   // In other cases we check for the even stronger condition:
4018   //
4019   //     Neg == EltSize - Pos                                    [B]
4020   //
4021   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4022   // behavior if Pos == 0 (and consequently Neg == EltSize).
4023   //
4024   // We could actually use [A] whenever EltSize is a power of 2, but the
4025   // only extra cases that it would match are those uninteresting ones
4026   // where Neg and Pos are never in range at the same time.  E.g. for
4027   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4028   // as well as (sub 32, Pos), but:
4029   //
4030   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4031   //
4032   // always invokes undefined behavior for 32-bit X.
4033   //
4034   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4035   unsigned MaskLoBits = 0;
4036   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4037     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4038       if (NegC->getAPIntValue() == EltSize - 1) {
4039         Neg = Neg.getOperand(0);
4040         MaskLoBits = Log2_64(EltSize);
4041       }
4042     }
4043   }
4044 
4045   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4046   if (Neg.getOpcode() != ISD::SUB)
4047     return false;
4048   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4049   if (!NegC)
4050     return false;
4051   SDValue NegOp1 = Neg.getOperand(1);
4052 
4053   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4054   // Pos'.  The truncation is redundant for the purpose of the equality.
4055   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4056     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4057       if (PosC->getAPIntValue() == EltSize - 1)
4058         Pos = Pos.getOperand(0);
4059 
4060   // The condition we need is now:
4061   //
4062   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4063   //
4064   // If NegOp1 == Pos then we need:
4065   //
4066   //              EltSize & Mask == NegC & Mask
4067   //
4068   // (because "x & Mask" is a truncation and distributes through subtraction).
4069   APInt Width;
4070   if (Pos == NegOp1)
4071     Width = NegC->getAPIntValue();
4072 
4073   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4074   // Then the condition we want to prove becomes:
4075   //
4076   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4077   //
4078   // which, again because "x & Mask" is a truncation, becomes:
4079   //
4080   //                NegC & Mask == (EltSize - PosC) & Mask
4081   //             EltSize & Mask == (NegC + PosC) & Mask
4082   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4083     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4084       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4085     else
4086       return false;
4087   } else
4088     return false;
4089 
4090   // Now we just need to check that EltSize & Mask == Width & Mask.
4091   if (MaskLoBits)
4092     // EltSize & Mask is 0 since Mask is EltSize - 1.
4093     return Width.getLoBits(MaskLoBits) == 0;
4094   return Width == EltSize;
4095 }
4096 
4097 // A subroutine of MatchRotate used once we have found an OR of two opposite
4098 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4099 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4100 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4101 // Neg with outer conversions stripped away.
4102 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4103                                        SDValue Neg, SDValue InnerPos,
4104                                        SDValue InnerNeg, unsigned PosOpcode,
4105                                        unsigned NegOpcode, const SDLoc &DL) {
4106   // fold (or (shl x, (*ext y)),
4107   //          (srl x, (*ext (sub 32, y)))) ->
4108   //   (rotl x, y) or (rotr x, (sub 32, y))
4109   //
4110   // fold (or (shl x, (*ext (sub 32, y))),
4111   //          (srl x, (*ext y))) ->
4112   //   (rotr x, y) or (rotl x, (sub 32, y))
4113   EVT VT = Shifted.getValueType();
4114   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4115     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4116     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4117                        HasPos ? Pos : Neg).getNode();
4118   }
4119 
4120   return nullptr;
4121 }
4122 
4123 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4124 // idioms for rotate, and if the target supports rotation instructions, generate
4125 // a rot[lr].
4126 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4127   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4128   EVT VT = LHS.getValueType();
4129   if (!TLI.isTypeLegal(VT)) return nullptr;
4130 
4131   // The target must have at least one rotate flavor.
4132   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4133   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4134   if (!HasROTL && !HasROTR) return nullptr;
4135 
4136   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4137   SDValue LHSShift;   // The shift.
4138   SDValue LHSMask;    // AND value if any.
4139   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4140     return nullptr; // Not part of a rotate.
4141 
4142   SDValue RHSShift;   // The shift.
4143   SDValue RHSMask;    // AND value if any.
4144   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4145     return nullptr; // Not part of a rotate.
4146 
4147   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4148     return nullptr;   // Not shifting the same value.
4149 
4150   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4151     return nullptr;   // Shifts must disagree.
4152 
4153   // Canonicalize shl to left side in a shl/srl pair.
4154   if (RHSShift.getOpcode() == ISD::SHL) {
4155     std::swap(LHS, RHS);
4156     std::swap(LHSShift, RHSShift);
4157     std::swap(LHSMask, RHSMask);
4158   }
4159 
4160   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4161   SDValue LHSShiftArg = LHSShift.getOperand(0);
4162   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4163   SDValue RHSShiftArg = RHSShift.getOperand(0);
4164   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4165 
4166   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4167   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4168   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4169     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4170     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4171     if ((LShVal + RShVal) != EltSizeInBits)
4172       return nullptr;
4173 
4174     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4175                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4176 
4177     // If there is an AND of either shifted operand, apply it to the result.
4178     if (LHSMask.getNode() || RHSMask.getNode()) {
4179       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4180       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4181 
4182       if (LHSMask.getNode()) {
4183         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4184         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4185                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4186                                        DAG.getConstant(RHSBits, DL, VT)));
4187       }
4188       if (RHSMask.getNode()) {
4189         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4190         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4191                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4192                                        DAG.getConstant(LHSBits, DL, VT)));
4193       }
4194 
4195       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4196     }
4197 
4198     return Rot.getNode();
4199   }
4200 
4201   // If there is a mask here, and we have a variable shift, we can't be sure
4202   // that we're masking out the right stuff.
4203   if (LHSMask.getNode() || RHSMask.getNode())
4204     return nullptr;
4205 
4206   // If the shift amount is sign/zext/any-extended just peel it off.
4207   SDValue LExtOp0 = LHSShiftAmt;
4208   SDValue RExtOp0 = RHSShiftAmt;
4209   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4210        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4211        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4212        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4213       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4214        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4215        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4216        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4217     LExtOp0 = LHSShiftAmt.getOperand(0);
4218     RExtOp0 = RHSShiftAmt.getOperand(0);
4219   }
4220 
4221   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4222                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4223   if (TryL)
4224     return TryL;
4225 
4226   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4227                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4228   if (TryR)
4229     return TryR;
4230 
4231   return nullptr;
4232 }
4233 
4234 SDValue DAGCombiner::visitXOR(SDNode *N) {
4235   SDValue N0 = N->getOperand(0);
4236   SDValue N1 = N->getOperand(1);
4237   EVT VT = N0.getValueType();
4238 
4239   // fold vector ops
4240   if (VT.isVector()) {
4241     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4242       return FoldedVOp;
4243 
4244     // fold (xor x, 0) -> x, vector edition
4245     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4246       return N1;
4247     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4248       return N0;
4249   }
4250 
4251   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4252   if (N0.isUndef() && N1.isUndef())
4253     return DAG.getConstant(0, SDLoc(N), VT);
4254   // fold (xor x, undef) -> undef
4255   if (N0.isUndef())
4256     return N0;
4257   if (N1.isUndef())
4258     return N1;
4259   // fold (xor c1, c2) -> c1^c2
4260   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4261   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4262   if (N0C && N1C)
4263     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4264   // canonicalize constant to RHS
4265   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4266      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4267     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4268   // fold (xor x, 0) -> x
4269   if (isNullConstant(N1))
4270     return N0;
4271   // reassociate xor
4272   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4273     return RXOR;
4274 
4275   // fold !(x cc y) -> (x !cc y)
4276   SDValue LHS, RHS, CC;
4277   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4278     bool isInt = LHS.getValueType().isInteger();
4279     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4280                                                isInt);
4281 
4282     if (!LegalOperations ||
4283         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4284       switch (N0.getOpcode()) {
4285       default:
4286         llvm_unreachable("Unhandled SetCC Equivalent!");
4287       case ISD::SETCC:
4288         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4289       case ISD::SELECT_CC:
4290         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4291                                N0.getOperand(3), NotCC);
4292       }
4293     }
4294   }
4295 
4296   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4297   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4298       N0.getNode()->hasOneUse() &&
4299       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4300     SDValue V = N0.getOperand(0);
4301     SDLoc DL(N0);
4302     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4303                     DAG.getConstant(1, DL, V.getValueType()));
4304     AddToWorklist(V.getNode());
4305     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4306   }
4307 
4308   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4309   if (isOneConstant(N1) && VT == MVT::i1 &&
4310       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4311     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4312     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4313       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4314       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4315       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4316       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4317       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4318     }
4319   }
4320   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4321   if (isAllOnesConstant(N1) &&
4322       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4323     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4324     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4325       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4326       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4327       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4328       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4329       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4330     }
4331   }
4332   // fold (xor (and x, y), y) -> (and (not x), y)
4333   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4334       N0->getOperand(1) == N1) {
4335     SDValue X = N0->getOperand(0);
4336     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4337     AddToWorklist(NotX.getNode());
4338     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4339   }
4340   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4341   if (N1C && N0.getOpcode() == ISD::XOR) {
4342     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4343       SDLoc DL(N);
4344       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4345                          DAG.getConstant(N1C->getAPIntValue() ^
4346                                          N00C->getAPIntValue(), DL, VT));
4347     }
4348     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4349       SDLoc DL(N);
4350       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4351                          DAG.getConstant(N1C->getAPIntValue() ^
4352                                          N01C->getAPIntValue(), DL, VT));
4353     }
4354   }
4355   // fold (xor x, x) -> 0
4356   if (N0 == N1)
4357     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4358 
4359   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4360   // Here is a concrete example of this equivalence:
4361   // i16   x ==  14
4362   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4363   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4364   //
4365   // =>
4366   //
4367   // i16     ~1      == 0b1111111111111110
4368   // i16 rol(~1, 14) == 0b1011111111111111
4369   //
4370   // Some additional tips to help conceptualize this transform:
4371   // - Try to see the operation as placing a single zero in a value of all ones.
4372   // - There exists no value for x which would allow the result to contain zero.
4373   // - Values of x larger than the bitwidth are undefined and do not require a
4374   //   consistent result.
4375   // - Pushing the zero left requires shifting one bits in from the right.
4376   // A rotate left of ~1 is a nice way of achieving the desired result.
4377   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4378       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4379     SDLoc DL(N);
4380     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4381                        N0.getOperand(1));
4382   }
4383 
4384   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4385   if (N0.getOpcode() == N1.getOpcode())
4386     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4387       return Tmp;
4388 
4389   // Simplify the expression using non-local knowledge.
4390   if (!VT.isVector() &&
4391       SimplifyDemandedBits(SDValue(N, 0)))
4392     return SDValue(N, 0);
4393 
4394   return SDValue();
4395 }
4396 
4397 /// Handle transforms common to the three shifts, when the shift amount is a
4398 /// constant.
4399 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4400   SDNode *LHS = N->getOperand(0).getNode();
4401   if (!LHS->hasOneUse()) return SDValue();
4402 
4403   // We want to pull some binops through shifts, so that we have (and (shift))
4404   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4405   // thing happens with address calculations, so it's important to canonicalize
4406   // it.
4407   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4408 
4409   switch (LHS->getOpcode()) {
4410   default: return SDValue();
4411   case ISD::OR:
4412   case ISD::XOR:
4413     HighBitSet = false; // We can only transform sra if the high bit is clear.
4414     break;
4415   case ISD::AND:
4416     HighBitSet = true;  // We can only transform sra if the high bit is set.
4417     break;
4418   case ISD::ADD:
4419     if (N->getOpcode() != ISD::SHL)
4420       return SDValue(); // only shl(add) not sr[al](add).
4421     HighBitSet = false; // We can only transform sra if the high bit is clear.
4422     break;
4423   }
4424 
4425   // We require the RHS of the binop to be a constant and not opaque as well.
4426   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4427   if (!BinOpCst) return SDValue();
4428 
4429   // FIXME: disable this unless the input to the binop is a shift by a constant.
4430   // If it is not a shift, it pessimizes some common cases like:
4431   //
4432   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4433   //    int bar(int *X, int i) { return X[i & 255]; }
4434   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4435   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4436        BinOpLHSVal->getOpcode() != ISD::SRA &&
4437        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4438       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4439     return SDValue();
4440 
4441   EVT VT = N->getValueType(0);
4442 
4443   // If this is a signed shift right, and the high bit is modified by the
4444   // logical operation, do not perform the transformation. The highBitSet
4445   // boolean indicates the value of the high bit of the constant which would
4446   // cause it to be modified for this operation.
4447   if (N->getOpcode() == ISD::SRA) {
4448     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4449     if (BinOpRHSSignSet != HighBitSet)
4450       return SDValue();
4451   }
4452 
4453   if (!TLI.isDesirableToCommuteWithShift(LHS))
4454     return SDValue();
4455 
4456   // Fold the constants, shifting the binop RHS by the shift amount.
4457   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4458                                N->getValueType(0),
4459                                LHS->getOperand(1), N->getOperand(1));
4460   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4461 
4462   // Create the new shift.
4463   SDValue NewShift = DAG.getNode(N->getOpcode(),
4464                                  SDLoc(LHS->getOperand(0)),
4465                                  VT, LHS->getOperand(0), N->getOperand(1));
4466 
4467   // Create the new binop.
4468   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4469 }
4470 
4471 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4472   assert(N->getOpcode() == ISD::TRUNCATE);
4473   assert(N->getOperand(0).getOpcode() == ISD::AND);
4474 
4475   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4476   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4477     SDValue N01 = N->getOperand(0).getOperand(1);
4478     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
4479       SDLoc DL(N);
4480       EVT TruncVT = N->getValueType(0);
4481       SDValue N00 = N->getOperand(0).getOperand(0);
4482       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
4483       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
4484       AddToWorklist(Trunc00.getNode());
4485       AddToWorklist(Trunc01.getNode());
4486       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
4487     }
4488   }
4489 
4490   return SDValue();
4491 }
4492 
4493 SDValue DAGCombiner::visitRotate(SDNode *N) {
4494   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4495   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4496       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4497     if (SDValue NewOp1 =
4498             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4499       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4500                          N->getOperand(0), NewOp1);
4501   }
4502   return SDValue();
4503 }
4504 
4505 SDValue DAGCombiner::visitSHL(SDNode *N) {
4506   SDValue N0 = N->getOperand(0);
4507   SDValue N1 = N->getOperand(1);
4508   EVT VT = N0.getValueType();
4509   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4510 
4511   // fold vector ops
4512   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4513   if (VT.isVector()) {
4514     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4515       return FoldedVOp;
4516 
4517     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4518     // If setcc produces all-one true value then:
4519     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4520     if (N1CV && N1CV->isConstant()) {
4521       if (N0.getOpcode() == ISD::AND) {
4522         SDValue N00 = N0->getOperand(0);
4523         SDValue N01 = N0->getOperand(1);
4524         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4525 
4526         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4527             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4528                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4529           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4530                                                      N01CV, N1CV))
4531             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4532         }
4533       } else {
4534         N1C = isConstOrConstSplat(N1);
4535       }
4536     }
4537   }
4538 
4539   // fold (shl c1, c2) -> c1<<c2
4540   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4541   if (N0C && N1C && !N1C->isOpaque())
4542     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4543   // fold (shl 0, x) -> 0
4544   if (isNullConstant(N0))
4545     return N0;
4546   // fold (shl x, c >= size(x)) -> undef
4547   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4548     return DAG.getUNDEF(VT);
4549   // fold (shl x, 0) -> x
4550   if (N1C && N1C->isNullValue())
4551     return N0;
4552   // fold (shl undef, x) -> 0
4553   if (N0.isUndef())
4554     return DAG.getConstant(0, SDLoc(N), VT);
4555   // if (shl x, c) is known to be zero, return 0
4556   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4557                             APInt::getAllOnesValue(OpSizeInBits)))
4558     return DAG.getConstant(0, SDLoc(N), VT);
4559   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4560   if (N1.getOpcode() == ISD::TRUNCATE &&
4561       N1.getOperand(0).getOpcode() == ISD::AND) {
4562     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4563       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4564   }
4565 
4566   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4567     return SDValue(N, 0);
4568 
4569   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4570   if (N1C && N0.getOpcode() == ISD::SHL) {
4571     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4572       SDLoc DL(N);
4573       APInt c1 = N0C1->getAPIntValue();
4574       APInt c2 = N1C->getAPIntValue();
4575       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4576 
4577       APInt Sum = c1 + c2;
4578       if (Sum.uge(OpSizeInBits))
4579         return DAG.getConstant(0, DL, VT);
4580 
4581       return DAG.getNode(
4582           ISD::SHL, DL, VT, N0.getOperand(0),
4583           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4584     }
4585   }
4586 
4587   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4588   // For this to be valid, the second form must not preserve any of the bits
4589   // that are shifted out by the inner shift in the first form.  This means
4590   // the outer shift size must be >= the number of bits added by the ext.
4591   // As a corollary, we don't care what kind of ext it is.
4592   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4593               N0.getOpcode() == ISD::ANY_EXTEND ||
4594               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4595       N0.getOperand(0).getOpcode() == ISD::SHL) {
4596     SDValue N0Op0 = N0.getOperand(0);
4597     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4598       APInt c1 = N0Op0C1->getAPIntValue();
4599       APInt c2 = N1C->getAPIntValue();
4600       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4601 
4602       EVT InnerShiftVT = N0Op0.getValueType();
4603       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4604       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
4605         SDLoc DL(N0);
4606         APInt Sum = c1 + c2;
4607         if (Sum.uge(OpSizeInBits))
4608           return DAG.getConstant(0, DL, VT);
4609 
4610         return DAG.getNode(
4611             ISD::SHL, DL, VT,
4612             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
4613             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4614       }
4615     }
4616   }
4617 
4618   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4619   // Only fold this if the inner zext has no other uses to avoid increasing
4620   // the total number of instructions.
4621   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4622       N0.getOperand(0).getOpcode() == ISD::SRL) {
4623     SDValue N0Op0 = N0.getOperand(0);
4624     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4625       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
4626         uint64_t c1 = N0Op0C1->getZExtValue();
4627         uint64_t c2 = N1C->getZExtValue();
4628         if (c1 == c2) {
4629           SDValue NewOp0 = N0.getOperand(0);
4630           EVT CountVT = NewOp0.getOperand(1).getValueType();
4631           SDLoc DL(N);
4632           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4633                                        NewOp0,
4634                                        DAG.getConstant(c2, DL, CountVT));
4635           AddToWorklist(NewSHL.getNode());
4636           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4637         }
4638       }
4639     }
4640   }
4641 
4642   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4643   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4644   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4645       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4646     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4647       uint64_t C1 = N0C1->getZExtValue();
4648       uint64_t C2 = N1C->getZExtValue();
4649       SDLoc DL(N);
4650       if (C1 <= C2)
4651         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4652                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4653       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4654                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4655     }
4656   }
4657 
4658   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4659   //                               (and (srl x, (sub c1, c2), MASK)
4660   // Only fold this if the inner shift has no other uses -- if it does, folding
4661   // this will increase the total number of instructions.
4662   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4663     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4664       uint64_t c1 = N0C1->getZExtValue();
4665       if (c1 < OpSizeInBits) {
4666         uint64_t c2 = N1C->getZExtValue();
4667         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4668         SDValue Shift;
4669         if (c2 > c1) {
4670           Mask = Mask.shl(c2 - c1);
4671           SDLoc DL(N);
4672           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4673                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4674         } else {
4675           Mask = Mask.lshr(c1 - c2);
4676           SDLoc DL(N);
4677           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4678                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4679         }
4680         SDLoc DL(N0);
4681         return DAG.getNode(ISD::AND, DL, VT, Shift,
4682                            DAG.getConstant(Mask, DL, VT));
4683       }
4684     }
4685   }
4686 
4687   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4688   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
4689       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
4690     unsigned BitSize = VT.getScalarSizeInBits();
4691     SDLoc DL(N);
4692     SDValue AllBits = DAG.getConstant(APInt::getAllOnesValue(BitSize), DL, VT);
4693     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
4694     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
4695   }
4696 
4697   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4698   // Variant of version done on multiply, except mul by a power of 2 is turned
4699   // into a shift.
4700   if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4701       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
4702       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
4703     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4704     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4705     AddToWorklist(Shl0.getNode());
4706     AddToWorklist(Shl1.getNode());
4707     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4708   }
4709 
4710   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4711   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
4712       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
4713       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
4714     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4715     AddToWorklist(Shl.getNode());
4716     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
4717   }
4718 
4719   if (N1C && !N1C->isOpaque())
4720     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4721       return NewSHL;
4722 
4723   return SDValue();
4724 }
4725 
4726 SDValue DAGCombiner::visitSRA(SDNode *N) {
4727   SDValue N0 = N->getOperand(0);
4728   SDValue N1 = N->getOperand(1);
4729   EVT VT = N0.getValueType();
4730   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4731 
4732   // Arithmetic shifting an all-sign-bit value is a no-op.
4733   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
4734     return N0;
4735 
4736   // fold vector ops
4737   if (VT.isVector())
4738     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4739       return FoldedVOp;
4740 
4741   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4742 
4743   // fold (sra c1, c2) -> (sra c1, c2)
4744   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4745   if (N0C && N1C && !N1C->isOpaque())
4746     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4747   // fold (sra 0, x) -> 0
4748   if (isNullConstant(N0))
4749     return N0;
4750   // fold (sra -1, x) -> -1
4751   if (isAllOnesConstant(N0))
4752     return N0;
4753   // fold (sra x, c >= size(x)) -> undef
4754   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4755     return DAG.getUNDEF(VT);
4756   // fold (sra x, 0) -> x
4757   if (N1C && N1C->isNullValue())
4758     return N0;
4759   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4760   // sext_inreg.
4761   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4762     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4763     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4764     if (VT.isVector())
4765       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4766                                ExtVT, VT.getVectorNumElements());
4767     if ((!LegalOperations ||
4768          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4769       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4770                          N0.getOperand(0), DAG.getValueType(ExtVT));
4771   }
4772 
4773   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4774   if (N1C && N0.getOpcode() == ISD::SRA) {
4775     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4776       SDLoc DL(N);
4777       APInt c1 = N0C1->getAPIntValue();
4778       APInt c2 = N1C->getAPIntValue();
4779       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4780 
4781       APInt Sum = c1 + c2;
4782       if (Sum.uge(OpSizeInBits))
4783         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
4784 
4785       return DAG.getNode(
4786           ISD::SRA, DL, VT, N0.getOperand(0),
4787           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4788     }
4789   }
4790 
4791   // fold (sra (shl X, m), (sub result_size, n))
4792   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4793   // result_size - n != m.
4794   // If truncate is free for the target sext(shl) is likely to result in better
4795   // code.
4796   if (N0.getOpcode() == ISD::SHL && N1C) {
4797     // Get the two constanst of the shifts, CN0 = m, CN = n.
4798     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4799     if (N01C) {
4800       LLVMContext &Ctx = *DAG.getContext();
4801       // Determine what the truncate's result bitsize and type would be.
4802       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4803 
4804       if (VT.isVector())
4805         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4806 
4807       // Determine the residual right-shift amount.
4808       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4809 
4810       // If the shift is not a no-op (in which case this should be just a sign
4811       // extend already), the truncated to type is legal, sign_extend is legal
4812       // on that type, and the truncate to that type is both legal and free,
4813       // perform the transform.
4814       if ((ShiftAmt > 0) &&
4815           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4816           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4817           TLI.isTruncateFree(VT, TruncVT)) {
4818 
4819         SDLoc DL(N);
4820         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4821             getShiftAmountTy(N0.getOperand(0).getValueType()));
4822         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4823                                     N0.getOperand(0), Amt);
4824         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4825                                     Shift);
4826         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4827                            N->getValueType(0), Trunc);
4828       }
4829     }
4830   }
4831 
4832   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4833   if (N1.getOpcode() == ISD::TRUNCATE &&
4834       N1.getOperand(0).getOpcode() == ISD::AND) {
4835     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4836       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4837   }
4838 
4839   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4840   //      if c1 is equal to the number of bits the trunc removes
4841   if (N0.getOpcode() == ISD::TRUNCATE &&
4842       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4843        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4844       N0.getOperand(0).hasOneUse() &&
4845       N0.getOperand(0).getOperand(1).hasOneUse() &&
4846       N1C) {
4847     SDValue N0Op0 = N0.getOperand(0);
4848     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4849       unsigned LargeShiftVal = LargeShift->getZExtValue();
4850       EVT LargeVT = N0Op0.getValueType();
4851 
4852       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4853         SDLoc DL(N);
4854         SDValue Amt =
4855           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4856                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4857         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4858                                   N0Op0.getOperand(0), Amt);
4859         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4860       }
4861     }
4862   }
4863 
4864   // Simplify, based on bits shifted out of the LHS.
4865   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4866     return SDValue(N, 0);
4867 
4868 
4869   // If the sign bit is known to be zero, switch this to a SRL.
4870   if (DAG.SignBitIsZero(N0))
4871     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4872 
4873   if (N1C && !N1C->isOpaque())
4874     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4875       return NewSRA;
4876 
4877   return SDValue();
4878 }
4879 
4880 SDValue DAGCombiner::visitSRL(SDNode *N) {
4881   SDValue N0 = N->getOperand(0);
4882   SDValue N1 = N->getOperand(1);
4883   EVT VT = N0.getValueType();
4884   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4885 
4886   // fold vector ops
4887   if (VT.isVector())
4888     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4889       return FoldedVOp;
4890 
4891   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4892 
4893   // fold (srl c1, c2) -> c1 >>u c2
4894   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4895   if (N0C && N1C && !N1C->isOpaque())
4896     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4897   // fold (srl 0, x) -> 0
4898   if (isNullConstant(N0))
4899     return N0;
4900   // fold (srl x, c >= size(x)) -> undef
4901   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4902     return DAG.getUNDEF(VT);
4903   // fold (srl x, 0) -> x
4904   if (N1C && N1C->isNullValue())
4905     return N0;
4906   // if (srl x, c) is known to be zero, return 0
4907   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4908                                    APInt::getAllOnesValue(OpSizeInBits)))
4909     return DAG.getConstant(0, SDLoc(N), VT);
4910 
4911   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4912   if (N1C && N0.getOpcode() == ISD::SRL) {
4913     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4914       SDLoc DL(N);
4915       APInt c1 = N0C1->getAPIntValue();
4916       APInt c2 = N1C->getAPIntValue();
4917       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4918 
4919       APInt Sum = c1 + c2;
4920       if (Sum.uge(OpSizeInBits))
4921         return DAG.getConstant(0, DL, VT);
4922 
4923       return DAG.getNode(
4924           ISD::SRL, DL, VT, N0.getOperand(0),
4925           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4926     }
4927   }
4928 
4929   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4930   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4931       N0.getOperand(0).getOpcode() == ISD::SRL &&
4932       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4933     uint64_t c1 =
4934       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4935     uint64_t c2 = N1C->getZExtValue();
4936     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4937     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4938     uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4939     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4940     if (c1 + OpSizeInBits == InnerShiftSize) {
4941       SDLoc DL(N0);
4942       if (c1 + c2 >= InnerShiftSize)
4943         return DAG.getConstant(0, DL, VT);
4944       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4945                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4946                                      N0.getOperand(0)->getOperand(0),
4947                                      DAG.getConstant(c1 + c2, DL,
4948                                                      ShiftCountVT)));
4949     }
4950   }
4951 
4952   // fold (srl (shl x, c), c) -> (and x, cst2)
4953   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4954       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
4955     SDLoc DL(N);
4956     APInt AllBits = APInt::getAllOnesValue(N0.getScalarValueSizeInBits());
4957     SDValue Mask =
4958         DAG.getNode(ISD::SRL, DL, VT, DAG.getConstant(AllBits, DL, VT), N1);
4959     AddToWorklist(Mask.getNode());
4960     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
4961   }
4962 
4963   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4964   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4965     // Shifting in all undef bits?
4966     EVT SmallVT = N0.getOperand(0).getValueType();
4967     unsigned BitSize = SmallVT.getScalarSizeInBits();
4968     if (N1C->getZExtValue() >= BitSize)
4969       return DAG.getUNDEF(VT);
4970 
4971     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4972       uint64_t ShiftAmt = N1C->getZExtValue();
4973       SDLoc DL0(N0);
4974       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4975                                        N0.getOperand(0),
4976                           DAG.getConstant(ShiftAmt, DL0,
4977                                           getShiftAmountTy(SmallVT)));
4978       AddToWorklist(SmallShift.getNode());
4979       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4980       SDLoc DL(N);
4981       return DAG.getNode(ISD::AND, DL, VT,
4982                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4983                          DAG.getConstant(Mask, DL, VT));
4984     }
4985   }
4986 
4987   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4988   // bit, which is unmodified by sra.
4989   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4990     if (N0.getOpcode() == ISD::SRA)
4991       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4992   }
4993 
4994   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4995   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4996       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4997     APInt KnownZero, KnownOne;
4998     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4999 
5000     // If any of the input bits are KnownOne, then the input couldn't be all
5001     // zeros, thus the result of the srl will always be zero.
5002     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5003 
5004     // If all of the bits input the to ctlz node are known to be zero, then
5005     // the result of the ctlz is "32" and the result of the shift is one.
5006     APInt UnknownBits = ~KnownZero;
5007     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5008 
5009     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5010     if ((UnknownBits & (UnknownBits - 1)) == 0) {
5011       // Okay, we know that only that the single bit specified by UnknownBits
5012       // could be set on input to the CTLZ node. If this bit is set, the SRL
5013       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5014       // to an SRL/XOR pair, which is likely to simplify more.
5015       unsigned ShAmt = UnknownBits.countTrailingZeros();
5016       SDValue Op = N0.getOperand(0);
5017 
5018       if (ShAmt) {
5019         SDLoc DL(N0);
5020         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5021                   DAG.getConstant(ShAmt, DL,
5022                                   getShiftAmountTy(Op.getValueType())));
5023         AddToWorklist(Op.getNode());
5024       }
5025 
5026       SDLoc DL(N);
5027       return DAG.getNode(ISD::XOR, DL, VT,
5028                          Op, DAG.getConstant(1, DL, VT));
5029     }
5030   }
5031 
5032   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5033   if (N1.getOpcode() == ISD::TRUNCATE &&
5034       N1.getOperand(0).getOpcode() == ISD::AND) {
5035     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5036       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5037   }
5038 
5039   // fold operands of srl based on knowledge that the low bits are not
5040   // demanded.
5041   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5042     return SDValue(N, 0);
5043 
5044   if (N1C && !N1C->isOpaque())
5045     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5046       return NewSRL;
5047 
5048   // Attempt to convert a srl of a load into a narrower zero-extending load.
5049   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5050     return NarrowLoad;
5051 
5052   // Here is a common situation. We want to optimize:
5053   //
5054   //   %a = ...
5055   //   %b = and i32 %a, 2
5056   //   %c = srl i32 %b, 1
5057   //   brcond i32 %c ...
5058   //
5059   // into
5060   //
5061   //   %a = ...
5062   //   %b = and %a, 2
5063   //   %c = setcc eq %b, 0
5064   //   brcond %c ...
5065   //
5066   // However when after the source operand of SRL is optimized into AND, the SRL
5067   // itself may not be optimized further. Look for it and add the BRCOND into
5068   // the worklist.
5069   if (N->hasOneUse()) {
5070     SDNode *Use = *N->use_begin();
5071     if (Use->getOpcode() == ISD::BRCOND)
5072       AddToWorklist(Use);
5073     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5074       // Also look pass the truncate.
5075       Use = *Use->use_begin();
5076       if (Use->getOpcode() == ISD::BRCOND)
5077         AddToWorklist(Use);
5078     }
5079   }
5080 
5081   return SDValue();
5082 }
5083 
5084 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5085   SDValue N0 = N->getOperand(0);
5086   EVT VT = N->getValueType(0);
5087 
5088   // fold (bswap c1) -> c2
5089   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5090     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5091   // fold (bswap (bswap x)) -> x
5092   if (N0.getOpcode() == ISD::BSWAP)
5093     return N0->getOperand(0);
5094   return SDValue();
5095 }
5096 
5097 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5098   SDValue N0 = N->getOperand(0);
5099 
5100   // fold (bitreverse (bitreverse x)) -> x
5101   if (N0.getOpcode() == ISD::BITREVERSE)
5102     return N0.getOperand(0);
5103   return SDValue();
5104 }
5105 
5106 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5107   SDValue N0 = N->getOperand(0);
5108   EVT VT = N->getValueType(0);
5109 
5110   // fold (ctlz c1) -> c2
5111   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5112     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5113   return SDValue();
5114 }
5115 
5116 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5117   SDValue N0 = N->getOperand(0);
5118   EVT VT = N->getValueType(0);
5119 
5120   // fold (ctlz_zero_undef c1) -> c2
5121   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5122     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5123   return SDValue();
5124 }
5125 
5126 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5127   SDValue N0 = N->getOperand(0);
5128   EVT VT = N->getValueType(0);
5129 
5130   // fold (cttz c1) -> c2
5131   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5132     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5133   return SDValue();
5134 }
5135 
5136 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5137   SDValue N0 = N->getOperand(0);
5138   EVT VT = N->getValueType(0);
5139 
5140   // fold (cttz_zero_undef c1) -> c2
5141   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5142     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5143   return SDValue();
5144 }
5145 
5146 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5147   SDValue N0 = N->getOperand(0);
5148   EVT VT = N->getValueType(0);
5149 
5150   // fold (ctpop c1) -> c2
5151   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5152     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5153   return SDValue();
5154 }
5155 
5156 
5157 /// \brief Generate Min/Max node
5158 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5159                                    SDValue RHS, SDValue True, SDValue False,
5160                                    ISD::CondCode CC, const TargetLowering &TLI,
5161                                    SelectionDAG &DAG) {
5162   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5163     return SDValue();
5164 
5165   switch (CC) {
5166   case ISD::SETOLT:
5167   case ISD::SETOLE:
5168   case ISD::SETLT:
5169   case ISD::SETLE:
5170   case ISD::SETULT:
5171   case ISD::SETULE: {
5172     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5173     if (TLI.isOperationLegal(Opcode, VT))
5174       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5175     return SDValue();
5176   }
5177   case ISD::SETOGT:
5178   case ISD::SETOGE:
5179   case ISD::SETGT:
5180   case ISD::SETGE:
5181   case ISD::SETUGT:
5182   case ISD::SETUGE: {
5183     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5184     if (TLI.isOperationLegal(Opcode, VT))
5185       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5186     return SDValue();
5187   }
5188   default:
5189     return SDValue();
5190   }
5191 }
5192 
5193 // TODO: We should handle other cases of selecting between {-1,0,1} here.
5194 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5195   SDValue Cond = N->getOperand(0);
5196   SDValue N1 = N->getOperand(1);
5197   SDValue N2 = N->getOperand(2);
5198   EVT VT = N->getValueType(0);
5199   EVT CondVT = Cond.getValueType();
5200   SDLoc DL(N);
5201 
5202   // fold (select Cond, 0, 1) -> (xor Cond, 1)
5203   // We can't do this reliably if integer based booleans have different contents
5204   // to floating point based booleans. This is because we can't tell whether we
5205   // have an integer-based boolean or a floating-point-based boolean unless we
5206   // can find the SETCC that produced it and inspect its operands. This is
5207   // fairly easy if C is the SETCC node, but it can potentially be
5208   // undiscoverable (or not reasonably discoverable). For example, it could be
5209   // in another basic block or it could require searching a complicated
5210   // expression.
5211   if (VT.isInteger() &&
5212       (CondVT == MVT::i1 || (CondVT.isInteger() &&
5213                              TLI.getBooleanContents(false, true) ==
5214                                  TargetLowering::ZeroOrOneBooleanContent &&
5215                              TLI.getBooleanContents(false, false) ==
5216                                  TargetLowering::ZeroOrOneBooleanContent)) &&
5217       isNullConstant(N1) && isOneConstant(N2)) {
5218     SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond,
5219                                   DAG.getConstant(1, DL, CondVT));
5220     if (VT.bitsEq(CondVT))
5221       return NotCond;
5222     return DAG.getZExtOrTrunc(NotCond, DL, VT);
5223   }
5224 
5225   return SDValue();
5226 }
5227 
5228 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5229   SDValue N0 = N->getOperand(0);
5230   SDValue N1 = N->getOperand(1);
5231   SDValue N2 = N->getOperand(2);
5232   EVT VT = N->getValueType(0);
5233   EVT VT0 = N0.getValueType();
5234 
5235   // fold (select C, X, X) -> X
5236   if (N1 == N2)
5237     return N1;
5238   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5239     // fold (select true, X, Y) -> X
5240     // fold (select false, X, Y) -> Y
5241     return !N0C->isNullValue() ? N1 : N2;
5242   }
5243   // fold (select C, 1, X) -> (or C, X)
5244   if (VT == MVT::i1 && isOneConstant(N1))
5245     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5246 
5247   if (SDValue V = foldSelectOfConstants(N))
5248     return V;
5249 
5250   // fold (select C, 0, X) -> (and (not C), X)
5251   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5252     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5253     AddToWorklist(NOTNode.getNode());
5254     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5255   }
5256   // fold (select C, X, 1) -> (or (not C), X)
5257   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5258     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5259     AddToWorklist(NOTNode.getNode());
5260     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5261   }
5262   // fold (select C, X, 0) -> (and C, X)
5263   if (VT == MVT::i1 && isNullConstant(N2))
5264     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5265   // fold (select X, X, Y) -> (or X, Y)
5266   // fold (select X, 1, Y) -> (or X, Y)
5267   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5268     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5269   // fold (select X, Y, X) -> (and X, Y)
5270   // fold (select X, Y, 0) -> (and X, Y)
5271   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5272     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5273 
5274   // If we can fold this based on the true/false value, do so.
5275   if (SimplifySelectOps(N, N1, N2))
5276     return SDValue(N, 0);  // Don't revisit N.
5277 
5278   if (VT0 == MVT::i1) {
5279     // The code in this block deals with the following 2 equivalences:
5280     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5281     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5282     // The target can specify its prefered form with the
5283     // shouldNormalizeToSelectSequence() callback. However we always transform
5284     // to the right anyway if we find the inner select exists in the DAG anyway
5285     // and we always transform to the left side if we know that we can further
5286     // optimize the combination of the conditions.
5287     bool normalizeToSequence
5288       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5289     // select (and Cond0, Cond1), X, Y
5290     //   -> select Cond0, (select Cond1, X, Y), Y
5291     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5292       SDValue Cond0 = N0->getOperand(0);
5293       SDValue Cond1 = N0->getOperand(1);
5294       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5295                                         N1.getValueType(), Cond1, N1, N2);
5296       if (normalizeToSequence || !InnerSelect.use_empty())
5297         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5298                            InnerSelect, N2);
5299     }
5300     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5301     if (N0->getOpcode() == ISD::OR && 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, N1,
5308                            InnerSelect);
5309     }
5310 
5311     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5312     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5313       SDValue N1_0 = N1->getOperand(0);
5314       SDValue N1_1 = N1->getOperand(1);
5315       SDValue N1_2 = N1->getOperand(2);
5316       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5317         // Create the actual and node if we can generate good code for it.
5318         if (!normalizeToSequence) {
5319           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5320                                     N0, N1_0);
5321           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5322                              N1_1, N2);
5323         }
5324         // Otherwise see if we can optimize the "and" to a better pattern.
5325         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5326           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5327                              N1_1, N2);
5328       }
5329     }
5330     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5331     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5332       SDValue N2_0 = N2->getOperand(0);
5333       SDValue N2_1 = N2->getOperand(1);
5334       SDValue N2_2 = N2->getOperand(2);
5335       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5336         // Create the actual or node if we can generate good code for it.
5337         if (!normalizeToSequence) {
5338           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5339                                    N0, N2_0);
5340           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5341                              N1, N2_2);
5342         }
5343         // Otherwise see if we can optimize to a better pattern.
5344         if (SDValue Combined = visitORLike(N0, N2_0, N))
5345           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5346                              N1, N2_2);
5347       }
5348     }
5349   }
5350 
5351   // select (xor Cond, 1), X, Y -> select Cond, Y, X
5352   // select (xor Cond, 0), X, Y -> selext Cond, X, Y
5353   if (VT0 == MVT::i1) {
5354     if (N0->getOpcode() == ISD::XOR) {
5355       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
5356         SDValue Cond0 = N0->getOperand(0);
5357         if (C->isOne())
5358           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5359                              Cond0, N2, N1);
5360         else
5361           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5362                              Cond0, N1, N2);
5363       }
5364     }
5365   }
5366 
5367   // fold selects based on a setcc into other things, such as min/max/abs
5368   if (N0.getOpcode() == ISD::SETCC) {
5369     // select x, y (fcmp lt x, y) -> fminnum x, y
5370     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5371     //
5372     // This is OK if we don't care about what happens if either operand is a
5373     // NaN.
5374     //
5375 
5376     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5377     // no signed zeros as well as no nans.
5378     const TargetOptions &Options = DAG.getTarget().Options;
5379     if (Options.UnsafeFPMath &&
5380         VT.isFloatingPoint() && N0.hasOneUse() &&
5381         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5382       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5383 
5384       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5385                                                 N0.getOperand(1), N1, N2, CC,
5386                                                 TLI, DAG))
5387         return FMinMax;
5388     }
5389 
5390     if ((!LegalOperations &&
5391          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5392         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5393       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5394                          N0.getOperand(0), N0.getOperand(1),
5395                          N1, N2, N0.getOperand(2));
5396     return SimplifySelect(SDLoc(N), N0, N1, N2);
5397   }
5398 
5399   return SDValue();
5400 }
5401 
5402 static
5403 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5404   SDLoc DL(N);
5405   EVT LoVT, HiVT;
5406   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5407 
5408   // Split the inputs.
5409   SDValue Lo, Hi, LL, LH, RL, RH;
5410   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5411   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5412 
5413   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5414   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5415 
5416   return std::make_pair(Lo, Hi);
5417 }
5418 
5419 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5420 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5421 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5422   SDLoc DL(N);
5423   SDValue Cond = N->getOperand(0);
5424   SDValue LHS = N->getOperand(1);
5425   SDValue RHS = N->getOperand(2);
5426   EVT VT = N->getValueType(0);
5427   int NumElems = VT.getVectorNumElements();
5428   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5429          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5430          Cond.getOpcode() == ISD::BUILD_VECTOR);
5431 
5432   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5433   // binary ones here.
5434   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5435     return SDValue();
5436 
5437   // We're sure we have an even number of elements due to the
5438   // concat_vectors we have as arguments to vselect.
5439   // Skip BV elements until we find one that's not an UNDEF
5440   // After we find an UNDEF element, keep looping until we get to half the
5441   // length of the BV and see if all the non-undef nodes are the same.
5442   ConstantSDNode *BottomHalf = nullptr;
5443   for (int i = 0; i < NumElems / 2; ++i) {
5444     if (Cond->getOperand(i)->isUndef())
5445       continue;
5446 
5447     if (BottomHalf == nullptr)
5448       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5449     else if (Cond->getOperand(i).getNode() != BottomHalf)
5450       return SDValue();
5451   }
5452 
5453   // Do the same for the second half of the BuildVector
5454   ConstantSDNode *TopHalf = nullptr;
5455   for (int i = NumElems / 2; i < NumElems; ++i) {
5456     if (Cond->getOperand(i)->isUndef())
5457       continue;
5458 
5459     if (TopHalf == nullptr)
5460       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5461     else if (Cond->getOperand(i).getNode() != TopHalf)
5462       return SDValue();
5463   }
5464 
5465   assert(TopHalf && BottomHalf &&
5466          "One half of the selector was all UNDEFs and the other was all the "
5467          "same value. This should have been addressed before this function.");
5468   return DAG.getNode(
5469       ISD::CONCAT_VECTORS, DL, VT,
5470       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5471       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5472 }
5473 
5474 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5475 
5476   if (Level >= AfterLegalizeTypes)
5477     return SDValue();
5478 
5479   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5480   SDValue Mask = MSC->getMask();
5481   SDValue Data  = MSC->getValue();
5482   SDLoc DL(N);
5483 
5484   // If the MSCATTER data type requires splitting and the mask is provided by a
5485   // SETCC, then split both nodes and its operands before legalization. This
5486   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5487   // and enables future optimizations (e.g. min/max pattern matching on X86).
5488   if (Mask.getOpcode() != ISD::SETCC)
5489     return SDValue();
5490 
5491   // Check if any splitting is required.
5492   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5493       TargetLowering::TypeSplitVector)
5494     return SDValue();
5495   SDValue MaskLo, MaskHi, Lo, Hi;
5496   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5497 
5498   EVT LoVT, HiVT;
5499   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5500 
5501   SDValue Chain = MSC->getChain();
5502 
5503   EVT MemoryVT = MSC->getMemoryVT();
5504   unsigned Alignment = MSC->getOriginalAlignment();
5505 
5506   EVT LoMemVT, HiMemVT;
5507   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5508 
5509   SDValue DataLo, DataHi;
5510   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5511 
5512   SDValue BasePtr = MSC->getBasePtr();
5513   SDValue IndexLo, IndexHi;
5514   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5515 
5516   MachineMemOperand *MMO = DAG.getMachineFunction().
5517     getMachineMemOperand(MSC->getPointerInfo(),
5518                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5519                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5520 
5521   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5522   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5523                             DL, OpsLo, MMO);
5524 
5525   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5526   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5527                             DL, OpsHi, MMO);
5528 
5529   AddToWorklist(Lo.getNode());
5530   AddToWorklist(Hi.getNode());
5531 
5532   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5533 }
5534 
5535 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5536 
5537   if (Level >= AfterLegalizeTypes)
5538     return SDValue();
5539 
5540   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5541   SDValue Mask = MST->getMask();
5542   SDValue Data  = MST->getValue();
5543   SDLoc DL(N);
5544 
5545   // If the MSTORE data type requires splitting and the mask is provided by a
5546   // SETCC, then split both nodes and its operands before legalization. This
5547   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5548   // and enables future optimizations (e.g. min/max pattern matching on X86).
5549   if (Mask.getOpcode() == ISD::SETCC) {
5550 
5551     // Check if any splitting is required.
5552     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5553         TargetLowering::TypeSplitVector)
5554       return SDValue();
5555 
5556     SDValue MaskLo, MaskHi, Lo, Hi;
5557     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5558 
5559     EVT LoVT, HiVT;
5560     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5561 
5562     SDValue Chain = MST->getChain();
5563     SDValue Ptr   = MST->getBasePtr();
5564 
5565     EVT MemoryVT = MST->getMemoryVT();
5566     unsigned Alignment = MST->getOriginalAlignment();
5567 
5568     // if Alignment is equal to the vector size,
5569     // take the half of it for the second part
5570     unsigned SecondHalfAlignment =
5571       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5572          Alignment/2 : Alignment;
5573 
5574     EVT LoMemVT, HiMemVT;
5575     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5576 
5577     SDValue DataLo, DataHi;
5578     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5579 
5580     MachineMemOperand *MMO = DAG.getMachineFunction().
5581       getMachineMemOperand(MST->getPointerInfo(),
5582                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5583                            Alignment, MST->getAAInfo(), MST->getRanges());
5584 
5585     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5586                             MST->isTruncatingStore());
5587 
5588     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5589     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5590                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5591 
5592     MMO = DAG.getMachineFunction().
5593       getMachineMemOperand(MST->getPointerInfo(),
5594                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5595                            SecondHalfAlignment, MST->getAAInfo(),
5596                            MST->getRanges());
5597 
5598     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5599                             MST->isTruncatingStore());
5600 
5601     AddToWorklist(Lo.getNode());
5602     AddToWorklist(Hi.getNode());
5603 
5604     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5605   }
5606   return SDValue();
5607 }
5608 
5609 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5610 
5611   if (Level >= AfterLegalizeTypes)
5612     return SDValue();
5613 
5614   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5615   SDValue Mask = MGT->getMask();
5616   SDLoc DL(N);
5617 
5618   // If the MGATHER result requires splitting and the mask is provided by a
5619   // SETCC, then split both nodes and its operands before legalization. This
5620   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5621   // and enables future optimizations (e.g. min/max pattern matching on X86).
5622 
5623   if (Mask.getOpcode() != ISD::SETCC)
5624     return SDValue();
5625 
5626   EVT VT = N->getValueType(0);
5627 
5628   // Check if any splitting is required.
5629   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5630       TargetLowering::TypeSplitVector)
5631     return SDValue();
5632 
5633   SDValue MaskLo, MaskHi, Lo, Hi;
5634   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5635 
5636   SDValue Src0 = MGT->getValue();
5637   SDValue Src0Lo, Src0Hi;
5638   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5639 
5640   EVT LoVT, HiVT;
5641   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5642 
5643   SDValue Chain = MGT->getChain();
5644   EVT MemoryVT = MGT->getMemoryVT();
5645   unsigned Alignment = MGT->getOriginalAlignment();
5646 
5647   EVT LoMemVT, HiMemVT;
5648   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5649 
5650   SDValue BasePtr = MGT->getBasePtr();
5651   SDValue Index = MGT->getIndex();
5652   SDValue IndexLo, IndexHi;
5653   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5654 
5655   MachineMemOperand *MMO = DAG.getMachineFunction().
5656     getMachineMemOperand(MGT->getPointerInfo(),
5657                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5658                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5659 
5660   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5661   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5662                             MMO);
5663 
5664   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5665   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5666                             MMO);
5667 
5668   AddToWorklist(Lo.getNode());
5669   AddToWorklist(Hi.getNode());
5670 
5671   // Build a factor node to remember that this load is independent of the
5672   // other one.
5673   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5674                       Hi.getValue(1));
5675 
5676   // Legalized the chain result - switch anything that used the old chain to
5677   // use the new one.
5678   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5679 
5680   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5681 
5682   SDValue RetOps[] = { GatherRes, Chain };
5683   return DAG.getMergeValues(RetOps, DL);
5684 }
5685 
5686 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5687 
5688   if (Level >= AfterLegalizeTypes)
5689     return SDValue();
5690 
5691   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5692   SDValue Mask = MLD->getMask();
5693   SDLoc DL(N);
5694 
5695   // If the MLOAD result requires splitting and the mask is provided by a
5696   // SETCC, then split both nodes and its operands before legalization. This
5697   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5698   // and enables future optimizations (e.g. min/max pattern matching on X86).
5699 
5700   if (Mask.getOpcode() == ISD::SETCC) {
5701     EVT VT = N->getValueType(0);
5702 
5703     // Check if any splitting is required.
5704     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5705         TargetLowering::TypeSplitVector)
5706       return SDValue();
5707 
5708     SDValue MaskLo, MaskHi, Lo, Hi;
5709     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5710 
5711     SDValue Src0 = MLD->getSrc0();
5712     SDValue Src0Lo, Src0Hi;
5713     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5714 
5715     EVT LoVT, HiVT;
5716     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5717 
5718     SDValue Chain = MLD->getChain();
5719     SDValue Ptr   = MLD->getBasePtr();
5720     EVT MemoryVT = MLD->getMemoryVT();
5721     unsigned Alignment = MLD->getOriginalAlignment();
5722 
5723     // if Alignment is equal to the vector size,
5724     // take the half of it for the second part
5725     unsigned SecondHalfAlignment =
5726       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5727          Alignment/2 : Alignment;
5728 
5729     EVT LoMemVT, HiMemVT;
5730     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5731 
5732     MachineMemOperand *MMO = DAG.getMachineFunction().
5733     getMachineMemOperand(MLD->getPointerInfo(),
5734                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5735                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5736 
5737     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5738                            ISD::NON_EXTLOAD);
5739 
5740     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5741     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5742                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5743 
5744     MMO = DAG.getMachineFunction().
5745     getMachineMemOperand(MLD->getPointerInfo(),
5746                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5747                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5748 
5749     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5750                            ISD::NON_EXTLOAD);
5751 
5752     AddToWorklist(Lo.getNode());
5753     AddToWorklist(Hi.getNode());
5754 
5755     // Build a factor node to remember that this load is independent of the
5756     // other one.
5757     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5758                         Hi.getValue(1));
5759 
5760     // Legalized the chain result - switch anything that used the old chain to
5761     // use the new one.
5762     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5763 
5764     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5765 
5766     SDValue RetOps[] = { LoadRes, Chain };
5767     return DAG.getMergeValues(RetOps, DL);
5768   }
5769   return SDValue();
5770 }
5771 
5772 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5773   SDValue N0 = N->getOperand(0);
5774   SDValue N1 = N->getOperand(1);
5775   SDValue N2 = N->getOperand(2);
5776   SDLoc DL(N);
5777 
5778   // Canonicalize integer abs.
5779   // vselect (setg[te] X,  0),  X, -X ->
5780   // vselect (setgt    X, -1),  X, -X ->
5781   // vselect (setl[te] X,  0), -X,  X ->
5782   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5783   if (N0.getOpcode() == ISD::SETCC) {
5784     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5785     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5786     bool isAbs = false;
5787     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5788 
5789     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5790          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5791         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5792       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5793     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5794              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5795       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5796 
5797     if (isAbs) {
5798       EVT VT = LHS.getValueType();
5799       SDValue Shift = DAG.getNode(
5800           ISD::SRA, DL, VT, LHS,
5801           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
5802       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5803       AddToWorklist(Shift.getNode());
5804       AddToWorklist(Add.getNode());
5805       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5806     }
5807   }
5808 
5809   if (SimplifySelectOps(N, N1, N2))
5810     return SDValue(N, 0);  // Don't revisit N.
5811 
5812   // If the VSELECT result requires splitting and the mask is provided by a
5813   // SETCC, then split both nodes and its operands before legalization. This
5814   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5815   // and enables future optimizations (e.g. min/max pattern matching on X86).
5816   if (N0.getOpcode() == ISD::SETCC) {
5817     EVT VT = N->getValueType(0);
5818 
5819     // Check if any splitting is required.
5820     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5821         TargetLowering::TypeSplitVector)
5822       return SDValue();
5823 
5824     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5825     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5826     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5827     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5828 
5829     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5830     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5831 
5832     // Add the new VSELECT nodes to the work list in case they need to be split
5833     // again.
5834     AddToWorklist(Lo.getNode());
5835     AddToWorklist(Hi.getNode());
5836 
5837     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5838   }
5839 
5840   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5841   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5842     return N1;
5843   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5844   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5845     return N2;
5846 
5847   // The ConvertSelectToConcatVector function is assuming both the above
5848   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5849   // and addressed.
5850   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5851       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5852       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5853     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5854       return CV;
5855   }
5856 
5857   return SDValue();
5858 }
5859 
5860 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5861   SDValue N0 = N->getOperand(0);
5862   SDValue N1 = N->getOperand(1);
5863   SDValue N2 = N->getOperand(2);
5864   SDValue N3 = N->getOperand(3);
5865   SDValue N4 = N->getOperand(4);
5866   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5867 
5868   // fold select_cc lhs, rhs, x, x, cc -> x
5869   if (N2 == N3)
5870     return N2;
5871 
5872   // Determine if the condition we're dealing with is constant
5873   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5874                                   CC, SDLoc(N), false)) {
5875     AddToWorklist(SCC.getNode());
5876 
5877     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5878       if (!SCCC->isNullValue())
5879         return N2;    // cond always true -> true val
5880       else
5881         return N3;    // cond always false -> false val
5882     } else if (SCC->isUndef()) {
5883       // When the condition is UNDEF, just return the first operand. This is
5884       // coherent the DAG creation, no setcc node is created in this case
5885       return N2;
5886     } else if (SCC.getOpcode() == ISD::SETCC) {
5887       // Fold to a simpler select_cc
5888       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5889                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5890                          SCC.getOperand(2));
5891     }
5892   }
5893 
5894   // If we can fold this based on the true/false value, do so.
5895   if (SimplifySelectOps(N, N2, N3))
5896     return SDValue(N, 0);  // Don't revisit N.
5897 
5898   // fold select_cc into other things, such as min/max/abs
5899   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5900 }
5901 
5902 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5903   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5904                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5905                        SDLoc(N));
5906 }
5907 
5908 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5909   SDValue LHS = N->getOperand(0);
5910   SDValue RHS = N->getOperand(1);
5911   SDValue Carry = N->getOperand(2);
5912   SDValue Cond = N->getOperand(3);
5913 
5914   // If Carry is false, fold to a regular SETCC.
5915   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5916     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5917 
5918   return SDValue();
5919 }
5920 
5921 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5922 /// a build_vector of constants.
5923 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5924 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5925 /// Vector extends are not folded if operations are legal; this is to
5926 /// avoid introducing illegal build_vector dag nodes.
5927 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5928                                          SelectionDAG &DAG, bool LegalTypes,
5929                                          bool LegalOperations) {
5930   unsigned Opcode = N->getOpcode();
5931   SDValue N0 = N->getOperand(0);
5932   EVT VT = N->getValueType(0);
5933 
5934   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5935          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5936          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5937          && "Expected EXTEND dag node in input!");
5938 
5939   // fold (sext c1) -> c1
5940   // fold (zext c1) -> c1
5941   // fold (aext c1) -> c1
5942   if (isa<ConstantSDNode>(N0))
5943     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5944 
5945   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5946   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5947   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5948   EVT SVT = VT.getScalarType();
5949   if (!(VT.isVector() &&
5950       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5951       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5952     return nullptr;
5953 
5954   // We can fold this node into a build_vector.
5955   unsigned VTBits = SVT.getSizeInBits();
5956   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
5957   SmallVector<SDValue, 8> Elts;
5958   unsigned NumElts = VT.getVectorNumElements();
5959   SDLoc DL(N);
5960 
5961   for (unsigned i=0; i != NumElts; ++i) {
5962     SDValue Op = N0->getOperand(i);
5963     if (Op->isUndef()) {
5964       Elts.push_back(DAG.getUNDEF(SVT));
5965       continue;
5966     }
5967 
5968     SDLoc DL(Op);
5969     // Get the constant value and if needed trunc it to the size of the type.
5970     // Nodes like build_vector might have constants wider than the scalar type.
5971     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5972     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5973       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5974     else
5975       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5976   }
5977 
5978   return DAG.getBuildVector(VT, DL, Elts).getNode();
5979 }
5980 
5981 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5982 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5983 // transformation. Returns true if extension are possible and the above
5984 // mentioned transformation is profitable.
5985 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5986                                     unsigned ExtOpc,
5987                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5988                                     const TargetLowering &TLI) {
5989   bool HasCopyToRegUses = false;
5990   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5991   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5992                             UE = N0.getNode()->use_end();
5993        UI != UE; ++UI) {
5994     SDNode *User = *UI;
5995     if (User == N)
5996       continue;
5997     if (UI.getUse().getResNo() != N0.getResNo())
5998       continue;
5999     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6000     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6001       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6002       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6003         // Sign bits will be lost after a zext.
6004         return false;
6005       bool Add = false;
6006       for (unsigned i = 0; i != 2; ++i) {
6007         SDValue UseOp = User->getOperand(i);
6008         if (UseOp == N0)
6009           continue;
6010         if (!isa<ConstantSDNode>(UseOp))
6011           return false;
6012         Add = true;
6013       }
6014       if (Add)
6015         ExtendNodes.push_back(User);
6016       continue;
6017     }
6018     // If truncates aren't free and there are users we can't
6019     // extend, it isn't worthwhile.
6020     if (!isTruncFree)
6021       return false;
6022     // Remember if this value is live-out.
6023     if (User->getOpcode() == ISD::CopyToReg)
6024       HasCopyToRegUses = true;
6025   }
6026 
6027   if (HasCopyToRegUses) {
6028     bool BothLiveOut = false;
6029     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6030          UI != UE; ++UI) {
6031       SDUse &Use = UI.getUse();
6032       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6033         BothLiveOut = true;
6034         break;
6035       }
6036     }
6037     if (BothLiveOut)
6038       // Both unextended and extended values are live out. There had better be
6039       // a good reason for the transformation.
6040       return ExtendNodes.size();
6041   }
6042   return true;
6043 }
6044 
6045 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6046                                   SDValue Trunc, SDValue ExtLoad,
6047                                   const SDLoc &DL, ISD::NodeType ExtType) {
6048   // Extend SetCC uses if necessary.
6049   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6050     SDNode *SetCC = SetCCs[i];
6051     SmallVector<SDValue, 4> Ops;
6052 
6053     for (unsigned j = 0; j != 2; ++j) {
6054       SDValue SOp = SetCC->getOperand(j);
6055       if (SOp == Trunc)
6056         Ops.push_back(ExtLoad);
6057       else
6058         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6059     }
6060 
6061     Ops.push_back(SetCC->getOperand(2));
6062     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6063   }
6064 }
6065 
6066 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6067 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6068   SDValue N0 = N->getOperand(0);
6069   EVT DstVT = N->getValueType(0);
6070   EVT SrcVT = N0.getValueType();
6071 
6072   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6073           N->getOpcode() == ISD::ZERO_EXTEND) &&
6074          "Unexpected node type (not an extend)!");
6075 
6076   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6077   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6078   //   (v8i32 (sext (v8i16 (load x))))
6079   // into:
6080   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6081   //                          (v4i32 (sextload (x + 16)))))
6082   // Where uses of the original load, i.e.:
6083   //   (v8i16 (load x))
6084   // are replaced with:
6085   //   (v8i16 (truncate
6086   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6087   //                            (v4i32 (sextload (x + 16)))))))
6088   //
6089   // This combine is only applicable to illegal, but splittable, vectors.
6090   // All legal types, and illegal non-vector types, are handled elsewhere.
6091   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6092   //
6093   if (N0->getOpcode() != ISD::LOAD)
6094     return SDValue();
6095 
6096   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6097 
6098   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6099       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6100       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6101     return SDValue();
6102 
6103   SmallVector<SDNode *, 4> SetCCs;
6104   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6105     return SDValue();
6106 
6107   ISD::LoadExtType ExtType =
6108       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6109 
6110   // Try to split the vector types to get down to legal types.
6111   EVT SplitSrcVT = SrcVT;
6112   EVT SplitDstVT = DstVT;
6113   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6114          SplitSrcVT.getVectorNumElements() > 1) {
6115     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6116     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6117   }
6118 
6119   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6120     return SDValue();
6121 
6122   SDLoc DL(N);
6123   const unsigned NumSplits =
6124       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6125   const unsigned Stride = SplitSrcVT.getStoreSize();
6126   SmallVector<SDValue, 4> Loads;
6127   SmallVector<SDValue, 4> Chains;
6128 
6129   SDValue BasePtr = LN0->getBasePtr();
6130   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6131     const unsigned Offset = Idx * Stride;
6132     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6133 
6134     SDValue SplitLoad = DAG.getExtLoad(
6135         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6136         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6137         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6138 
6139     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6140                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6141 
6142     Loads.push_back(SplitLoad.getValue(0));
6143     Chains.push_back(SplitLoad.getValue(1));
6144   }
6145 
6146   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6147   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6148 
6149   CombineTo(N, NewValue);
6150 
6151   // Replace uses of the original load (before extension)
6152   // with a truncate of the concatenated sextloaded vectors.
6153   SDValue Trunc =
6154       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6155   CombineTo(N0.getNode(), Trunc, NewChain);
6156   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6157                   (ISD::NodeType)N->getOpcode());
6158   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6159 }
6160 
6161 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6162   SDValue N0 = N->getOperand(0);
6163   EVT VT = N->getValueType(0);
6164 
6165   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6166                                               LegalOperations))
6167     return SDValue(Res, 0);
6168 
6169   // fold (sext (sext x)) -> (sext x)
6170   // fold (sext (aext x)) -> (sext x)
6171   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6172     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6173                        N0.getOperand(0));
6174 
6175   if (N0.getOpcode() == ISD::TRUNCATE) {
6176     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6177     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6178     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6179       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6180       if (NarrowLoad.getNode() != N0.getNode()) {
6181         CombineTo(N0.getNode(), NarrowLoad);
6182         // CombineTo deleted the truncate, if needed, but not what's under it.
6183         AddToWorklist(oye);
6184       }
6185       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6186     }
6187 
6188     // See if the value being truncated is already sign extended.  If so, just
6189     // eliminate the trunc/sext pair.
6190     SDValue Op = N0.getOperand(0);
6191     unsigned OpBits   = Op.getScalarValueSizeInBits();
6192     unsigned MidBits  = N0.getScalarValueSizeInBits();
6193     unsigned DestBits = VT.getScalarSizeInBits();
6194     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6195 
6196     if (OpBits == DestBits) {
6197       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6198       // bits, it is already ready.
6199       if (NumSignBits > DestBits-MidBits)
6200         return Op;
6201     } else if (OpBits < DestBits) {
6202       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6203       // bits, just sext from i32.
6204       if (NumSignBits > OpBits-MidBits)
6205         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6206     } else {
6207       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6208       // bits, just truncate to i32.
6209       if (NumSignBits > OpBits-MidBits)
6210         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6211     }
6212 
6213     // fold (sext (truncate x)) -> (sextinreg x).
6214     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6215                                                  N0.getValueType())) {
6216       if (OpBits < DestBits)
6217         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6218       else if (OpBits > DestBits)
6219         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6220       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6221                          DAG.getValueType(N0.getValueType()));
6222     }
6223   }
6224 
6225   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6226   // Only generate vector extloads when 1) they're legal, and 2) they are
6227   // deemed desirable by the target.
6228   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6229       ((!LegalOperations && !VT.isVector() &&
6230         !cast<LoadSDNode>(N0)->isVolatile()) ||
6231        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6232     bool DoXform = true;
6233     SmallVector<SDNode*, 4> SetCCs;
6234     if (!N0.hasOneUse())
6235       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6236     if (VT.isVector())
6237       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6238     if (DoXform) {
6239       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6240       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6241                                        LN0->getChain(),
6242                                        LN0->getBasePtr(), N0.getValueType(),
6243                                        LN0->getMemOperand());
6244       CombineTo(N, ExtLoad);
6245       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6246                                   N0.getValueType(), ExtLoad);
6247       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6248       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6249                       ISD::SIGN_EXTEND);
6250       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6251     }
6252   }
6253 
6254   // fold (sext (load x)) to multiple smaller sextloads.
6255   // Only on illegal but splittable vectors.
6256   if (SDValue ExtLoad = CombineExtLoad(N))
6257     return ExtLoad;
6258 
6259   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6260   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6261   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6262       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6263     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6264     EVT MemVT = LN0->getMemoryVT();
6265     if ((!LegalOperations && !LN0->isVolatile()) ||
6266         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6267       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6268                                        LN0->getChain(),
6269                                        LN0->getBasePtr(), MemVT,
6270                                        LN0->getMemOperand());
6271       CombineTo(N, ExtLoad);
6272       CombineTo(N0.getNode(),
6273                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6274                             N0.getValueType(), ExtLoad),
6275                 ExtLoad.getValue(1));
6276       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6277     }
6278   }
6279 
6280   // fold (sext (and/or/xor (load x), cst)) ->
6281   //      (and/or/xor (sextload x), (sext cst))
6282   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6283        N0.getOpcode() == ISD::XOR) &&
6284       isa<LoadSDNode>(N0.getOperand(0)) &&
6285       N0.getOperand(1).getOpcode() == ISD::Constant &&
6286       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6287       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6288     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6289     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6290       bool DoXform = true;
6291       SmallVector<SDNode*, 4> SetCCs;
6292       if (!N0.hasOneUse())
6293         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6294                                           SetCCs, TLI);
6295       if (DoXform) {
6296         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6297                                          LN0->getChain(), LN0->getBasePtr(),
6298                                          LN0->getMemoryVT(),
6299                                          LN0->getMemOperand());
6300         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6301         Mask = Mask.sext(VT.getSizeInBits());
6302         SDLoc DL(N);
6303         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6304                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6305         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6306                                     SDLoc(N0.getOperand(0)),
6307                                     N0.getOperand(0).getValueType(), ExtLoad);
6308         CombineTo(N, And);
6309         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6310         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6311                         ISD::SIGN_EXTEND);
6312         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6313       }
6314     }
6315   }
6316 
6317   if (N0.getOpcode() == ISD::SETCC) {
6318     EVT N0VT = N0.getOperand(0).getValueType();
6319     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6320     // Only do this before legalize for now.
6321     if (VT.isVector() && !LegalOperations &&
6322         TLI.getBooleanContents(N0VT) ==
6323             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6324       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6325       // of the same size as the compared operands. Only optimize sext(setcc())
6326       // if this is the case.
6327       EVT SVT = getSetCCResultType(N0VT);
6328 
6329       // We know that the # elements of the results is the same as the
6330       // # elements of the compare (and the # elements of the compare result
6331       // for that matter).  Check to see that they are the same size.  If so,
6332       // we know that the element size of the sext'd result matches the
6333       // element size of the compare operands.
6334       if (VT.getSizeInBits() == SVT.getSizeInBits())
6335         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6336                              N0.getOperand(1),
6337                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6338 
6339       // If the desired elements are smaller or larger than the source
6340       // elements we can use a matching integer vector type and then
6341       // truncate/sign extend
6342       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6343       if (SVT == MatchingVectorType) {
6344         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6345                                N0.getOperand(0), N0.getOperand(1),
6346                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6347         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6348       }
6349     }
6350 
6351     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
6352     // Here, T can be 1 or -1, depending on the type of the setcc and
6353     // getBooleanContents().
6354     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
6355 
6356     SDLoc DL(N);
6357     // To determine the "true" side of the select, we need to know the high bit
6358     // of the value returned by the setcc if it evaluates to true.
6359     // If the type of the setcc is i1, then the true case of the select is just
6360     // sext(i1 1), that is, -1.
6361     // If the type of the setcc is larger (say, i8) then the value of the high
6362     // bit depends on getBooleanContents(). So, ask TLI for a real "true" value
6363     // of the appropriate width.
6364     SDValue ExtTrueVal =
6365         (SetCCWidth == 1)
6366             ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()),
6367                               DL, VT)
6368             : TLI.getConstTrueVal(DAG, VT, DL);
6369 
6370     if (SDValue SCC = SimplifySelectCC(
6371             DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal,
6372             DAG.getConstant(0, DL, VT),
6373             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6374       return SCC;
6375 
6376     if (!VT.isVector()) {
6377       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6378       if (!LegalOperations ||
6379           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6380         SDLoc DL(N);
6381         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6382         SDValue SetCC =
6383             DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC);
6384         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal,
6385                              DAG.getConstant(0, DL, VT));
6386       }
6387     }
6388   }
6389 
6390   // fold (sext x) -> (zext x) if the sign bit is known zero.
6391   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6392       DAG.SignBitIsZero(N0))
6393     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6394 
6395   return SDValue();
6396 }
6397 
6398 // isTruncateOf - If N is a truncate of some other value, return true, record
6399 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6400 // This function computes KnownZero to avoid a duplicated call to
6401 // computeKnownBits in the caller.
6402 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6403                          APInt &KnownZero) {
6404   APInt KnownOne;
6405   if (N->getOpcode() == ISD::TRUNCATE) {
6406     Op = N->getOperand(0);
6407     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6408     return true;
6409   }
6410 
6411   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6412       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6413     return false;
6414 
6415   SDValue Op0 = N->getOperand(0);
6416   SDValue Op1 = N->getOperand(1);
6417   assert(Op0.getValueType() == Op1.getValueType());
6418 
6419   if (isNullConstant(Op0))
6420     Op = Op1;
6421   else if (isNullConstant(Op1))
6422     Op = Op0;
6423   else
6424     return false;
6425 
6426   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6427 
6428   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6429     return false;
6430 
6431   return true;
6432 }
6433 
6434 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6435   SDValue N0 = N->getOperand(0);
6436   EVT VT = N->getValueType(0);
6437 
6438   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6439                                               LegalOperations))
6440     return SDValue(Res, 0);
6441 
6442   // fold (zext (zext x)) -> (zext x)
6443   // fold (zext (aext x)) -> (zext x)
6444   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6445     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6446                        N0.getOperand(0));
6447 
6448   // fold (zext (truncate x)) -> (zext x) or
6449   //      (zext (truncate x)) -> (truncate x)
6450   // This is valid when the truncated bits of x are already zero.
6451   // FIXME: We should extend this to work for vectors too.
6452   SDValue Op;
6453   APInt KnownZero;
6454   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6455     APInt TruncatedBits =
6456       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6457       APInt(Op.getValueSizeInBits(), 0) :
6458       APInt::getBitsSet(Op.getValueSizeInBits(),
6459                         N0.getValueSizeInBits(),
6460                         std::min(Op.getValueSizeInBits(),
6461                                  VT.getSizeInBits()));
6462     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6463       if (VT.bitsGT(Op.getValueType()))
6464         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6465       if (VT.bitsLT(Op.getValueType()))
6466         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6467 
6468       return Op;
6469     }
6470   }
6471 
6472   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6473   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6474   if (N0.getOpcode() == ISD::TRUNCATE) {
6475     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6476       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6477       if (NarrowLoad.getNode() != N0.getNode()) {
6478         CombineTo(N0.getNode(), NarrowLoad);
6479         // CombineTo deleted the truncate, if needed, but not what's under it.
6480         AddToWorklist(oye);
6481       }
6482       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6483     }
6484   }
6485 
6486   // fold (zext (truncate x)) -> (and x, mask)
6487   if (N0.getOpcode() == ISD::TRUNCATE) {
6488     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6489     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6490     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6491       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6492       if (NarrowLoad.getNode() != N0.getNode()) {
6493         CombineTo(N0.getNode(), NarrowLoad);
6494         // CombineTo deleted the truncate, if needed, but not what's under it.
6495         AddToWorklist(oye);
6496       }
6497       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6498     }
6499 
6500     EVT SrcVT = N0.getOperand(0).getValueType();
6501     EVT MinVT = N0.getValueType();
6502 
6503     // Try to mask before the extension to avoid having to generate a larger mask,
6504     // possibly over several sub-vectors.
6505     if (SrcVT.bitsLT(VT)) {
6506       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6507                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6508         SDValue Op = N0.getOperand(0);
6509         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6510         AddToWorklist(Op.getNode());
6511         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6512       }
6513     }
6514 
6515     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6516       SDValue Op = N0.getOperand(0);
6517       if (SrcVT.bitsLT(VT)) {
6518         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6519         AddToWorklist(Op.getNode());
6520       } else if (SrcVT.bitsGT(VT)) {
6521         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6522         AddToWorklist(Op.getNode());
6523       }
6524       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6525     }
6526   }
6527 
6528   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6529   // if either of the casts is not free.
6530   if (N0.getOpcode() == ISD::AND &&
6531       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6532       N0.getOperand(1).getOpcode() == ISD::Constant &&
6533       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6534                            N0.getValueType()) ||
6535        !TLI.isZExtFree(N0.getValueType(), VT))) {
6536     SDValue X = N0.getOperand(0).getOperand(0);
6537     if (X.getValueType().bitsLT(VT)) {
6538       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6539     } else if (X.getValueType().bitsGT(VT)) {
6540       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6541     }
6542     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6543     Mask = Mask.zext(VT.getSizeInBits());
6544     SDLoc DL(N);
6545     return DAG.getNode(ISD::AND, DL, VT,
6546                        X, DAG.getConstant(Mask, DL, VT));
6547   }
6548 
6549   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6550   // Only generate vector extloads when 1) they're legal, and 2) they are
6551   // deemed desirable by the target.
6552   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6553       ((!LegalOperations && !VT.isVector() &&
6554         !cast<LoadSDNode>(N0)->isVolatile()) ||
6555        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6556     bool DoXform = true;
6557     SmallVector<SDNode*, 4> SetCCs;
6558     if (!N0.hasOneUse())
6559       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6560     if (VT.isVector())
6561       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6562     if (DoXform) {
6563       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6564       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6565                                        LN0->getChain(),
6566                                        LN0->getBasePtr(), N0.getValueType(),
6567                                        LN0->getMemOperand());
6568       CombineTo(N, ExtLoad);
6569       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6570                                   N0.getValueType(), ExtLoad);
6571       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6572 
6573       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6574                       ISD::ZERO_EXTEND);
6575       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6576     }
6577   }
6578 
6579   // fold (zext (load x)) to multiple smaller zextloads.
6580   // Only on illegal but splittable vectors.
6581   if (SDValue ExtLoad = CombineExtLoad(N))
6582     return ExtLoad;
6583 
6584   // fold (zext (and/or/xor (load x), cst)) ->
6585   //      (and/or/xor (zextload x), (zext cst))
6586   // Unless (and (load x) cst) will match as a zextload already and has
6587   // additional users.
6588   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6589        N0.getOpcode() == ISD::XOR) &&
6590       isa<LoadSDNode>(N0.getOperand(0)) &&
6591       N0.getOperand(1).getOpcode() == ISD::Constant &&
6592       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6593       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6594     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6595     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6596       bool DoXform = true;
6597       SmallVector<SDNode*, 4> SetCCs;
6598       if (!N0.hasOneUse()) {
6599         if (N0.getOpcode() == ISD::AND) {
6600           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6601           auto NarrowLoad = false;
6602           EVT LoadResultTy = AndC->getValueType(0);
6603           EVT ExtVT, LoadedVT;
6604           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6605                                NarrowLoad))
6606             DoXform = false;
6607         }
6608         if (DoXform)
6609           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6610                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6611       }
6612       if (DoXform) {
6613         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6614                                          LN0->getChain(), LN0->getBasePtr(),
6615                                          LN0->getMemoryVT(),
6616                                          LN0->getMemOperand());
6617         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6618         Mask = Mask.zext(VT.getSizeInBits());
6619         SDLoc DL(N);
6620         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6621                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6622         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6623                                     SDLoc(N0.getOperand(0)),
6624                                     N0.getOperand(0).getValueType(), ExtLoad);
6625         CombineTo(N, And);
6626         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6627         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6628                         ISD::ZERO_EXTEND);
6629         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6630       }
6631     }
6632   }
6633 
6634   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6635   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6636   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6637       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6638     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6639     EVT MemVT = LN0->getMemoryVT();
6640     if ((!LegalOperations && !LN0->isVolatile()) ||
6641         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6642       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6643                                        LN0->getChain(),
6644                                        LN0->getBasePtr(), MemVT,
6645                                        LN0->getMemOperand());
6646       CombineTo(N, ExtLoad);
6647       CombineTo(N0.getNode(),
6648                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6649                             ExtLoad),
6650                 ExtLoad.getValue(1));
6651       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6652     }
6653   }
6654 
6655   if (N0.getOpcode() == ISD::SETCC) {
6656     // Only do this before legalize for now.
6657     if (!LegalOperations && VT.isVector() &&
6658         N0.getValueType().getVectorElementType() == MVT::i1) {
6659       EVT N00VT = N0.getOperand(0).getValueType();
6660       if (getSetCCResultType(N00VT) == N0.getValueType())
6661         return SDValue();
6662 
6663       // We know that the # elements of the results is the same as the #
6664       // elements of the compare (and the # elements of the compare result for
6665       // that matter). Check to see that they are the same size. If so, we know
6666       // that the element size of the sext'd result matches the element size of
6667       // the compare operands.
6668       SDLoc DL(N);
6669       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6670       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
6671         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6672         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
6673                                      N0.getOperand(1), N0.getOperand(2));
6674         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
6675       }
6676 
6677       // If the desired elements are smaller or larger than the source
6678       // elements we can use a matching integer vector type and then
6679       // truncate/sign extend.
6680       EVT MatchingElementType = EVT::getIntegerVT(
6681           *DAG.getContext(), N00VT.getScalarSizeInBits());
6682       EVT MatchingVectorType = EVT::getVectorVT(
6683           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
6684       SDValue VsetCC =
6685           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
6686                       N0.getOperand(1), N0.getOperand(2));
6687       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
6688                          VecOnes);
6689     }
6690 
6691     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6692     SDLoc DL(N);
6693     if (SDValue SCC = SimplifySelectCC(
6694             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6695             DAG.getConstant(0, DL, VT),
6696             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6697       return SCC;
6698   }
6699 
6700   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6701   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6702       isa<ConstantSDNode>(N0.getOperand(1)) &&
6703       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6704       N0.hasOneUse()) {
6705     SDValue ShAmt = N0.getOperand(1);
6706     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6707     if (N0.getOpcode() == ISD::SHL) {
6708       SDValue InnerZExt = N0.getOperand(0);
6709       // If the original shl may be shifting out bits, do not perform this
6710       // transformation.
6711       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
6712         InnerZExt.getOperand(0).getValueSizeInBits();
6713       if (ShAmtVal > KnownZeroBits)
6714         return SDValue();
6715     }
6716 
6717     SDLoc DL(N);
6718 
6719     // Ensure that the shift amount is wide enough for the shifted value.
6720     if (VT.getSizeInBits() >= 256)
6721       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6722 
6723     return DAG.getNode(N0.getOpcode(), DL, VT,
6724                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6725                        ShAmt);
6726   }
6727 
6728   return SDValue();
6729 }
6730 
6731 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6732   SDValue N0 = N->getOperand(0);
6733   EVT VT = N->getValueType(0);
6734 
6735   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6736                                               LegalOperations))
6737     return SDValue(Res, 0);
6738 
6739   // fold (aext (aext x)) -> (aext x)
6740   // fold (aext (zext x)) -> (zext x)
6741   // fold (aext (sext x)) -> (sext x)
6742   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6743       N0.getOpcode() == ISD::ZERO_EXTEND ||
6744       N0.getOpcode() == ISD::SIGN_EXTEND)
6745     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6746 
6747   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6748   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6749   if (N0.getOpcode() == ISD::TRUNCATE) {
6750     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6751       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6752       if (NarrowLoad.getNode() != N0.getNode()) {
6753         CombineTo(N0.getNode(), NarrowLoad);
6754         // CombineTo deleted the truncate, if needed, but not what's under it.
6755         AddToWorklist(oye);
6756       }
6757       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6758     }
6759   }
6760 
6761   // fold (aext (truncate x))
6762   if (N0.getOpcode() == ISD::TRUNCATE) {
6763     SDValue TruncOp = N0.getOperand(0);
6764     if (TruncOp.getValueType() == VT)
6765       return TruncOp; // x iff x size == zext size.
6766     if (TruncOp.getValueType().bitsGT(VT))
6767       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6768     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6769   }
6770 
6771   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6772   // if the trunc is not free.
6773   if (N0.getOpcode() == ISD::AND &&
6774       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6775       N0.getOperand(1).getOpcode() == ISD::Constant &&
6776       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6777                           N0.getValueType())) {
6778     SDValue X = N0.getOperand(0).getOperand(0);
6779     if (X.getValueType().bitsLT(VT)) {
6780       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6781     } else if (X.getValueType().bitsGT(VT)) {
6782       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6783     }
6784     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6785     Mask = Mask.zext(VT.getSizeInBits());
6786     SDLoc DL(N);
6787     return DAG.getNode(ISD::AND, DL, VT,
6788                        X, DAG.getConstant(Mask, DL, VT));
6789   }
6790 
6791   // fold (aext (load x)) -> (aext (truncate (extload x)))
6792   // None of the supported targets knows how to perform load and any_ext
6793   // on vectors in one instruction.  We only perform this transformation on
6794   // scalars.
6795   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6796       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6797       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6798     bool DoXform = true;
6799     SmallVector<SDNode*, 4> SetCCs;
6800     if (!N0.hasOneUse())
6801       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6802     if (DoXform) {
6803       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6804       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6805                                        LN0->getChain(),
6806                                        LN0->getBasePtr(), N0.getValueType(),
6807                                        LN0->getMemOperand());
6808       CombineTo(N, ExtLoad);
6809       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6810                                   N0.getValueType(), ExtLoad);
6811       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6812       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6813                       ISD::ANY_EXTEND);
6814       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6815     }
6816   }
6817 
6818   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6819   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6820   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6821   if (N0.getOpcode() == ISD::LOAD &&
6822       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6823       N0.hasOneUse()) {
6824     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6825     ISD::LoadExtType ExtType = LN0->getExtensionType();
6826     EVT MemVT = LN0->getMemoryVT();
6827     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6828       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6829                                        VT, LN0->getChain(), LN0->getBasePtr(),
6830                                        MemVT, LN0->getMemOperand());
6831       CombineTo(N, ExtLoad);
6832       CombineTo(N0.getNode(),
6833                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6834                             N0.getValueType(), ExtLoad),
6835                 ExtLoad.getValue(1));
6836       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6837     }
6838   }
6839 
6840   if (N0.getOpcode() == ISD::SETCC) {
6841     // For vectors:
6842     // aext(setcc) -> vsetcc
6843     // aext(setcc) -> truncate(vsetcc)
6844     // aext(setcc) -> aext(vsetcc)
6845     // Only do this before legalize for now.
6846     if (VT.isVector() && !LegalOperations) {
6847       EVT N0VT = N0.getOperand(0).getValueType();
6848         // We know that the # elements of the results is the same as the
6849         // # elements of the compare (and the # elements of the compare result
6850         // for that matter).  Check to see that they are the same size.  If so,
6851         // we know that the element size of the sext'd result matches the
6852         // element size of the compare operands.
6853       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6854         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6855                              N0.getOperand(1),
6856                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6857       // If the desired elements are smaller or larger than the source
6858       // elements we can use a matching integer vector type and then
6859       // truncate/any extend
6860       else {
6861         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6862         SDValue VsetCC =
6863           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6864                         N0.getOperand(1),
6865                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6866         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6867       }
6868     }
6869 
6870     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6871     SDLoc DL(N);
6872     if (SDValue SCC = SimplifySelectCC(
6873             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6874             DAG.getConstant(0, DL, VT),
6875             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6876       return SCC;
6877   }
6878 
6879   return SDValue();
6880 }
6881 
6882 /// See if the specified operand can be simplified with the knowledge that only
6883 /// the bits specified by Mask are used.  If so, return the simpler operand,
6884 /// otherwise return a null SDValue.
6885 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6886   switch (V.getOpcode()) {
6887   default: break;
6888   case ISD::Constant: {
6889     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6890     assert(CV && "Const value should be ConstSDNode.");
6891     const APInt &CVal = CV->getAPIntValue();
6892     APInt NewVal = CVal & Mask;
6893     if (NewVal != CVal)
6894       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6895     break;
6896   }
6897   case ISD::OR:
6898   case ISD::XOR:
6899     // If the LHS or RHS don't contribute bits to the or, drop them.
6900     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6901       return V.getOperand(1);
6902     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6903       return V.getOperand(0);
6904     break;
6905   case ISD::SRL:
6906     // Only look at single-use SRLs.
6907     if (!V.getNode()->hasOneUse())
6908       break;
6909     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6910       // See if we can recursively simplify the LHS.
6911       unsigned Amt = RHSC->getZExtValue();
6912 
6913       // Watch out for shift count overflow though.
6914       if (Amt >= Mask.getBitWidth()) break;
6915       APInt NewMask = Mask << Amt;
6916       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6917         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6918                            SimplifyLHS, V.getOperand(1));
6919     }
6920   }
6921   return SDValue();
6922 }
6923 
6924 /// If the result of a wider load is shifted to right of N  bits and then
6925 /// truncated to a narrower type and where N is a multiple of number of bits of
6926 /// the narrower type, transform it to a narrower load from address + N / num of
6927 /// bits of new type. If the result is to be extended, also fold the extension
6928 /// to form a extending load.
6929 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6930   unsigned Opc = N->getOpcode();
6931 
6932   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6933   SDValue N0 = N->getOperand(0);
6934   EVT VT = N->getValueType(0);
6935   EVT ExtVT = VT;
6936 
6937   // This transformation isn't valid for vector loads.
6938   if (VT.isVector())
6939     return SDValue();
6940 
6941   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6942   // extended to VT.
6943   if (Opc == ISD::SIGN_EXTEND_INREG) {
6944     ExtType = ISD::SEXTLOAD;
6945     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6946   } else if (Opc == ISD::SRL) {
6947     // Another special-case: SRL is basically zero-extending a narrower value.
6948     ExtType = ISD::ZEXTLOAD;
6949     N0 = SDValue(N, 0);
6950     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6951     if (!N01) return SDValue();
6952     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6953                               VT.getSizeInBits() - N01->getZExtValue());
6954   }
6955   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6956     return SDValue();
6957 
6958   unsigned EVTBits = ExtVT.getSizeInBits();
6959 
6960   // Do not generate loads of non-round integer types since these can
6961   // be expensive (and would be wrong if the type is not byte sized).
6962   if (!ExtVT.isRound())
6963     return SDValue();
6964 
6965   unsigned ShAmt = 0;
6966   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6967     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6968       ShAmt = N01->getZExtValue();
6969       // Is the shift amount a multiple of size of VT?
6970       if ((ShAmt & (EVTBits-1)) == 0) {
6971         N0 = N0.getOperand(0);
6972         // Is the load width a multiple of size of VT?
6973         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
6974           return SDValue();
6975       }
6976 
6977       // At this point, we must have a load or else we can't do the transform.
6978       if (!isa<LoadSDNode>(N0)) return SDValue();
6979 
6980       // Because a SRL must be assumed to *need* to zero-extend the high bits
6981       // (as opposed to anyext the high bits), we can't combine the zextload
6982       // lowering of SRL and an sextload.
6983       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6984         return SDValue();
6985 
6986       // If the shift amount is larger than the input type then we're not
6987       // accessing any of the loaded bytes.  If the load was a zextload/extload
6988       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6989       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6990         return SDValue();
6991     }
6992   }
6993 
6994   // If the load is shifted left (and the result isn't shifted back right),
6995   // we can fold the truncate through the shift.
6996   unsigned ShLeftAmt = 0;
6997   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6998       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6999     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7000       ShLeftAmt = N01->getZExtValue();
7001       N0 = N0.getOperand(0);
7002     }
7003   }
7004 
7005   // If we haven't found a load, we can't narrow it.  Don't transform one with
7006   // multiple uses, this would require adding a new load.
7007   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7008     return SDValue();
7009 
7010   // Don't change the width of a volatile load.
7011   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7012   if (LN0->isVolatile())
7013     return SDValue();
7014 
7015   // Verify that we are actually reducing a load width here.
7016   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7017     return SDValue();
7018 
7019   // For the transform to be legal, the load must produce only two values
7020   // (the value loaded and the chain).  Don't transform a pre-increment
7021   // load, for example, which produces an extra value.  Otherwise the
7022   // transformation is not equivalent, and the downstream logic to replace
7023   // uses gets things wrong.
7024   if (LN0->getNumValues() > 2)
7025     return SDValue();
7026 
7027   // If the load that we're shrinking is an extload and we're not just
7028   // discarding the extension we can't simply shrink the load. Bail.
7029   // TODO: It would be possible to merge the extensions in some cases.
7030   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7031       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7032     return SDValue();
7033 
7034   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7035     return SDValue();
7036 
7037   EVT PtrType = N0.getOperand(1).getValueType();
7038 
7039   if (PtrType == MVT::Untyped || PtrType.isExtended())
7040     // It's not possible to generate a constant of extended or untyped type.
7041     return SDValue();
7042 
7043   // For big endian targets, we need to adjust the offset to the pointer to
7044   // load the correct bytes.
7045   if (DAG.getDataLayout().isBigEndian()) {
7046     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7047     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7048     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7049   }
7050 
7051   uint64_t PtrOff = ShAmt / 8;
7052   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7053   SDLoc DL(LN0);
7054   // The original load itself didn't wrap, so an offset within it doesn't.
7055   SDNodeFlags Flags;
7056   Flags.setNoUnsignedWrap(true);
7057   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7058                                PtrType, LN0->getBasePtr(),
7059                                DAG.getConstant(PtrOff, DL, PtrType),
7060                                &Flags);
7061   AddToWorklist(NewPtr.getNode());
7062 
7063   SDValue Load;
7064   if (ExtType == ISD::NON_EXTLOAD)
7065     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7066                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7067                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7068   else
7069     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7070                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7071                           NewAlign, LN0->getMemOperand()->getFlags(),
7072                           LN0->getAAInfo());
7073 
7074   // Replace the old load's chain with the new load's chain.
7075   WorklistRemover DeadNodes(*this);
7076   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7077 
7078   // Shift the result left, if we've swallowed a left shift.
7079   SDValue Result = Load;
7080   if (ShLeftAmt != 0) {
7081     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7082     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7083       ShImmTy = VT;
7084     // If the shift amount is as large as the result size (but, presumably,
7085     // no larger than the source) then the useful bits of the result are
7086     // zero; we can't simply return the shortened shift, because the result
7087     // of that operation is undefined.
7088     SDLoc DL(N0);
7089     if (ShLeftAmt >= VT.getSizeInBits())
7090       Result = DAG.getConstant(0, DL, VT);
7091     else
7092       Result = DAG.getNode(ISD::SHL, DL, VT,
7093                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7094   }
7095 
7096   // Return the new loaded value.
7097   return Result;
7098 }
7099 
7100 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7101   SDValue N0 = N->getOperand(0);
7102   SDValue N1 = N->getOperand(1);
7103   EVT VT = N->getValueType(0);
7104   EVT EVT = cast<VTSDNode>(N1)->getVT();
7105   unsigned VTBits = VT.getScalarSizeInBits();
7106   unsigned EVTBits = EVT.getScalarSizeInBits();
7107 
7108   if (N0.isUndef())
7109     return DAG.getUNDEF(VT);
7110 
7111   // fold (sext_in_reg c1) -> c1
7112   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7113     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7114 
7115   // If the input is already sign extended, just drop the extension.
7116   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7117     return N0;
7118 
7119   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7120   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7121       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7122     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7123                        N0.getOperand(0), N1);
7124 
7125   // fold (sext_in_reg (sext x)) -> (sext x)
7126   // fold (sext_in_reg (aext x)) -> (sext x)
7127   // if x is small enough.
7128   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7129     SDValue N00 = N0.getOperand(0);
7130     if (N00.getScalarValueSizeInBits() <= EVTBits &&
7131         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7132       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7133   }
7134 
7135   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7136   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7137     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7138 
7139   // fold operands of sext_in_reg based on knowledge that the top bits are not
7140   // demanded.
7141   if (SimplifyDemandedBits(SDValue(N, 0)))
7142     return SDValue(N, 0);
7143 
7144   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7145   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7146   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7147     return NarrowLoad;
7148 
7149   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7150   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7151   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7152   if (N0.getOpcode() == ISD::SRL) {
7153     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7154       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7155         // We can turn this into an SRA iff the input to the SRL is already sign
7156         // extended enough.
7157         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7158         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7159           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7160                              N0.getOperand(0), N0.getOperand(1));
7161       }
7162   }
7163 
7164   // fold (sext_inreg (extload x)) -> (sextload x)
7165   if (ISD::isEXTLoad(N0.getNode()) &&
7166       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7167       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7168       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7169        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7170     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7171     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7172                                      LN0->getChain(),
7173                                      LN0->getBasePtr(), EVT,
7174                                      LN0->getMemOperand());
7175     CombineTo(N, ExtLoad);
7176     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7177     AddToWorklist(ExtLoad.getNode());
7178     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7179   }
7180   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7181   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7182       N0.hasOneUse() &&
7183       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7184       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7185        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7186     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7187     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7188                                      LN0->getChain(),
7189                                      LN0->getBasePtr(), EVT,
7190                                      LN0->getMemOperand());
7191     CombineTo(N, ExtLoad);
7192     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7193     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7194   }
7195 
7196   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7197   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7198     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7199                                            N0.getOperand(1), false))
7200       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7201                          BSwap, N1);
7202   }
7203 
7204   return SDValue();
7205 }
7206 
7207 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7208   SDValue N0 = N->getOperand(0);
7209   EVT VT = N->getValueType(0);
7210 
7211   if (N0.isUndef())
7212     return DAG.getUNDEF(VT);
7213 
7214   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7215                                               LegalOperations))
7216     return SDValue(Res, 0);
7217 
7218   return SDValue();
7219 }
7220 
7221 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7222   SDValue N0 = N->getOperand(0);
7223   EVT VT = N->getValueType(0);
7224 
7225   if (N0.isUndef())
7226     return DAG.getUNDEF(VT);
7227 
7228   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7229                                               LegalOperations))
7230     return SDValue(Res, 0);
7231 
7232   return SDValue();
7233 }
7234 
7235 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7236   SDValue N0 = N->getOperand(0);
7237   EVT VT = N->getValueType(0);
7238   bool isLE = DAG.getDataLayout().isLittleEndian();
7239 
7240   // noop truncate
7241   if (N0.getValueType() == N->getValueType(0))
7242     return N0;
7243   // fold (truncate c1) -> c1
7244   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7245     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7246   // fold (truncate (truncate x)) -> (truncate x)
7247   if (N0.getOpcode() == ISD::TRUNCATE)
7248     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7249   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7250   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7251       N0.getOpcode() == ISD::SIGN_EXTEND ||
7252       N0.getOpcode() == ISD::ANY_EXTEND) {
7253     // if the source is smaller than the dest, we still need an extend.
7254     if (N0.getOperand(0).getValueType().bitsLT(VT))
7255       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7256     // if the source is larger than the dest, than we just need the truncate.
7257     if (N0.getOperand(0).getValueType().bitsGT(VT))
7258       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7259     // if the source and dest are the same type, we can drop both the extend
7260     // and the truncate.
7261     return N0.getOperand(0);
7262   }
7263 
7264   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
7265   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
7266     return SDValue();
7267 
7268   // Fold extract-and-trunc into a narrow extract. For example:
7269   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7270   //   i32 y = TRUNCATE(i64 x)
7271   //        -- becomes --
7272   //   v16i8 b = BITCAST (v2i64 val)
7273   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7274   //
7275   // Note: We only run this optimization after type legalization (which often
7276   // creates this pattern) and before operation legalization after which
7277   // we need to be more careful about the vector instructions that we generate.
7278   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7279       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7280 
7281     EVT VecTy = N0.getOperand(0).getValueType();
7282     EVT ExTy = N0.getValueType();
7283     EVT TrTy = N->getValueType(0);
7284 
7285     unsigned NumElem = VecTy.getVectorNumElements();
7286     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7287 
7288     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7289     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7290 
7291     SDValue EltNo = N0->getOperand(1);
7292     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7293       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7294       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7295       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7296 
7297       SDLoc DL(N);
7298       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7299                          DAG.getBitcast(NVT, N0.getOperand(0)),
7300                          DAG.getConstant(Index, DL, IndexTy));
7301     }
7302   }
7303 
7304   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7305   if (N0.getOpcode() == ISD::SELECT) {
7306     EVT SrcVT = N0.getValueType();
7307     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7308         TLI.isTruncateFree(SrcVT, VT)) {
7309       SDLoc SL(N0);
7310       SDValue Cond = N0.getOperand(0);
7311       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7312       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7313       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7314     }
7315   }
7316 
7317   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
7318   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7319       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7320       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7321     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7322       uint64_t Amt = CAmt->getZExtValue();
7323       unsigned Size = VT.getScalarSizeInBits();
7324 
7325       if (Amt < Size) {
7326         SDLoc SL(N);
7327         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7328 
7329         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7330         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7331                            DAG.getConstant(Amt, SL, AmtVT));
7332       }
7333     }
7334   }
7335 
7336   // Fold a series of buildvector, bitcast, and truncate if possible.
7337   // For example fold
7338   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7339   //   (2xi32 (buildvector x, y)).
7340   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7341       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7342       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7343       N0.getOperand(0).hasOneUse()) {
7344 
7345     SDValue BuildVect = N0.getOperand(0);
7346     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7347     EVT TruncVecEltTy = VT.getVectorElementType();
7348 
7349     // Check that the element types match.
7350     if (BuildVectEltTy == TruncVecEltTy) {
7351       // Now we only need to compute the offset of the truncated elements.
7352       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7353       unsigned TruncVecNumElts = VT.getVectorNumElements();
7354       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7355 
7356       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7357              "Invalid number of elements");
7358 
7359       SmallVector<SDValue, 8> Opnds;
7360       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7361         Opnds.push_back(BuildVect.getOperand(i));
7362 
7363       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7364     }
7365   }
7366 
7367   // See if we can simplify the input to this truncate through knowledge that
7368   // only the low bits are being used.
7369   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7370   // Currently we only perform this optimization on scalars because vectors
7371   // may have different active low bits.
7372   if (!VT.isVector()) {
7373     if (SDValue Shorter =
7374             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7375                                                      VT.getSizeInBits())))
7376       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7377   }
7378   // fold (truncate (load x)) -> (smaller load x)
7379   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7380   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7381     if (SDValue Reduced = ReduceLoadWidth(N))
7382       return Reduced;
7383 
7384     // Handle the case where the load remains an extending load even
7385     // after truncation.
7386     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7387       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7388       if (!LN0->isVolatile() &&
7389           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7390         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7391                                          VT, LN0->getChain(), LN0->getBasePtr(),
7392                                          LN0->getMemoryVT(),
7393                                          LN0->getMemOperand());
7394         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7395         return NewLoad;
7396       }
7397     }
7398   }
7399   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7400   // where ... are all 'undef'.
7401   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7402     SmallVector<EVT, 8> VTs;
7403     SDValue V;
7404     unsigned Idx = 0;
7405     unsigned NumDefs = 0;
7406 
7407     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7408       SDValue X = N0.getOperand(i);
7409       if (!X.isUndef()) {
7410         V = X;
7411         Idx = i;
7412         NumDefs++;
7413       }
7414       // Stop if more than one members are non-undef.
7415       if (NumDefs > 1)
7416         break;
7417       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7418                                      VT.getVectorElementType(),
7419                                      X.getValueType().getVectorNumElements()));
7420     }
7421 
7422     if (NumDefs == 0)
7423       return DAG.getUNDEF(VT);
7424 
7425     if (NumDefs == 1) {
7426       assert(V.getNode() && "The single defined operand is empty!");
7427       SmallVector<SDValue, 8> Opnds;
7428       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7429         if (i != Idx) {
7430           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7431           continue;
7432         }
7433         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7434         AddToWorklist(NV.getNode());
7435         Opnds.push_back(NV);
7436       }
7437       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7438     }
7439   }
7440 
7441   // Fold truncate of a bitcast of a vector to an extract of the low vector
7442   // element.
7443   //
7444   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7445   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7446     SDValue VecSrc = N0.getOperand(0);
7447     EVT SrcVT = VecSrc.getValueType();
7448     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7449         (!LegalOperations ||
7450          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7451       SDLoc SL(N);
7452 
7453       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7454       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7455                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7456     }
7457   }
7458 
7459   // Simplify the operands using demanded-bits information.
7460   if (!VT.isVector() &&
7461       SimplifyDemandedBits(SDValue(N, 0)))
7462     return SDValue(N, 0);
7463 
7464   return SDValue();
7465 }
7466 
7467 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7468   SDValue Elt = N->getOperand(i);
7469   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7470     return Elt.getNode();
7471   return Elt.getOperand(Elt.getResNo()).getNode();
7472 }
7473 
7474 /// build_pair (load, load) -> load
7475 /// if load locations are consecutive.
7476 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7477   assert(N->getOpcode() == ISD::BUILD_PAIR);
7478 
7479   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7480   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7481   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7482       LD1->getAddressSpace() != LD2->getAddressSpace())
7483     return SDValue();
7484   EVT LD1VT = LD1->getValueType(0);
7485   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7486   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7487       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7488     unsigned Align = LD1->getAlignment();
7489     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7490         VT.getTypeForEVT(*DAG.getContext()));
7491 
7492     if (NewAlign <= Align &&
7493         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7494       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
7495                          LD1->getPointerInfo(), Align);
7496   }
7497 
7498   return SDValue();
7499 }
7500 
7501 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7502   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7503   // and Lo parts; on big-endian machines it doesn't.
7504   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7505 }
7506 
7507 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7508                                     const TargetLowering &TLI) {
7509   // If this is not a bitcast to an FP type or if the target doesn't have
7510   // IEEE754-compliant FP logic, we're done.
7511   EVT VT = N->getValueType(0);
7512   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7513     return SDValue();
7514 
7515   // TODO: Use splat values for the constant-checking below and remove this
7516   // restriction.
7517   SDValue N0 = N->getOperand(0);
7518   EVT SourceVT = N0.getValueType();
7519   if (SourceVT.isVector())
7520     return SDValue();
7521 
7522   unsigned FPOpcode;
7523   APInt SignMask;
7524   switch (N0.getOpcode()) {
7525   case ISD::AND:
7526     FPOpcode = ISD::FABS;
7527     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7528     break;
7529   case ISD::XOR:
7530     FPOpcode = ISD::FNEG;
7531     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7532     break;
7533   // TODO: ISD::OR --> ISD::FNABS?
7534   default:
7535     return SDValue();
7536   }
7537 
7538   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7539   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7540   SDValue LogicOp0 = N0.getOperand(0);
7541   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7542   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7543       LogicOp0.getOpcode() == ISD::BITCAST &&
7544       LogicOp0->getOperand(0).getValueType() == VT)
7545     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7546 
7547   return SDValue();
7548 }
7549 
7550 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7551   SDValue N0 = N->getOperand(0);
7552   EVT VT = N->getValueType(0);
7553 
7554   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7555   // Only do this before legalize, since afterward the target may be depending
7556   // on the bitconvert.
7557   // First check to see if this is all constant.
7558   if (!LegalTypes &&
7559       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7560       VT.isVector()) {
7561     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7562 
7563     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7564     assert(!DestEltVT.isVector() &&
7565            "Element type of vector ValueType must not be vector!");
7566     if (isSimple)
7567       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7568   }
7569 
7570   // If the input is a constant, let getNode fold it.
7571   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7572     // If we can't allow illegal operations, we need to check that this is just
7573     // a fp -> int or int -> conversion and that the resulting operation will
7574     // be legal.
7575     if (!LegalOperations ||
7576         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7577          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7578         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7579          TLI.isOperationLegal(ISD::Constant, VT)))
7580       return DAG.getBitcast(VT, N0);
7581   }
7582 
7583   // (conv (conv x, t1), t2) -> (conv x, t2)
7584   if (N0.getOpcode() == ISD::BITCAST)
7585     return DAG.getBitcast(VT, N0.getOperand(0));
7586 
7587   // fold (conv (load x)) -> (load (conv*)x)
7588   // If the resultant load doesn't need a higher alignment than the original!
7589   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7590       // Do not change the width of a volatile load.
7591       !cast<LoadSDNode>(N0)->isVolatile() &&
7592       // Do not remove the cast if the types differ in endian layout.
7593       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7594           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7595       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7596       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7597     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7598     unsigned OrigAlign = LN0->getAlignment();
7599 
7600     bool Fast = false;
7601     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7602                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7603         Fast) {
7604       SDValue Load =
7605           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7606                       LN0->getPointerInfo(), OrigAlign,
7607                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7608       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7609       return Load;
7610     }
7611   }
7612 
7613   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7614     return V;
7615 
7616   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7617   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7618   //
7619   // For ppc_fp128:
7620   // fold (bitcast (fneg x)) ->
7621   //     flipbit = signbit
7622   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7623   //
7624   // fold (bitcast (fabs x)) ->
7625   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7626   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7627   // This often reduces constant pool loads.
7628   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7629        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7630       N0.getNode()->hasOneUse() && VT.isInteger() &&
7631       !VT.isVector() && !N0.getValueType().isVector()) {
7632     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7633     AddToWorklist(NewConv.getNode());
7634 
7635     SDLoc DL(N);
7636     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7637       assert(VT.getSizeInBits() == 128);
7638       SDValue SignBit = DAG.getConstant(
7639           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7640       SDValue FlipBit;
7641       if (N0.getOpcode() == ISD::FNEG) {
7642         FlipBit = SignBit;
7643         AddToWorklist(FlipBit.getNode());
7644       } else {
7645         assert(N0.getOpcode() == ISD::FABS);
7646         SDValue Hi =
7647             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7648                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7649                                               SDLoc(NewConv)));
7650         AddToWorklist(Hi.getNode());
7651         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7652         AddToWorklist(FlipBit.getNode());
7653       }
7654       SDValue FlipBits =
7655           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7656       AddToWorklist(FlipBits.getNode());
7657       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7658     }
7659     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7660     if (N0.getOpcode() == ISD::FNEG)
7661       return DAG.getNode(ISD::XOR, DL, VT,
7662                          NewConv, DAG.getConstant(SignBit, DL, VT));
7663     assert(N0.getOpcode() == ISD::FABS);
7664     return DAG.getNode(ISD::AND, DL, VT,
7665                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7666   }
7667 
7668   // fold (bitconvert (fcopysign cst, x)) ->
7669   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7670   // Note that we don't handle (copysign x, cst) because this can always be
7671   // folded to an fneg or fabs.
7672   //
7673   // For ppc_fp128:
7674   // fold (bitcast (fcopysign cst, x)) ->
7675   //     flipbit = (and (extract_element
7676   //                     (xor (bitcast cst), (bitcast x)), 0),
7677   //                    signbit)
7678   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7679   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7680       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7681       VT.isInteger() && !VT.isVector()) {
7682     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
7683     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7684     if (isTypeLegal(IntXVT)) {
7685       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7686       AddToWorklist(X.getNode());
7687 
7688       // If X has a different width than the result/lhs, sext it or truncate it.
7689       unsigned VTWidth = VT.getSizeInBits();
7690       if (OrigXWidth < VTWidth) {
7691         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7692         AddToWorklist(X.getNode());
7693       } else if (OrigXWidth > VTWidth) {
7694         // To get the sign bit in the right place, we have to shift it right
7695         // before truncating.
7696         SDLoc DL(X);
7697         X = DAG.getNode(ISD::SRL, DL,
7698                         X.getValueType(), X,
7699                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7700                                         X.getValueType()));
7701         AddToWorklist(X.getNode());
7702         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7703         AddToWorklist(X.getNode());
7704       }
7705 
7706       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7707         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7708         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7709         AddToWorklist(Cst.getNode());
7710         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7711         AddToWorklist(X.getNode());
7712         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7713         AddToWorklist(XorResult.getNode());
7714         SDValue XorResult64 = DAG.getNode(
7715             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7716             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7717                                   SDLoc(XorResult)));
7718         AddToWorklist(XorResult64.getNode());
7719         SDValue FlipBit =
7720             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7721                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7722         AddToWorklist(FlipBit.getNode());
7723         SDValue FlipBits =
7724             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7725         AddToWorklist(FlipBits.getNode());
7726         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7727       }
7728       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7729       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7730                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7731       AddToWorklist(X.getNode());
7732 
7733       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7734       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7735                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7736       AddToWorklist(Cst.getNode());
7737 
7738       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7739     }
7740   }
7741 
7742   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7743   if (N0.getOpcode() == ISD::BUILD_PAIR)
7744     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7745       return CombineLD;
7746 
7747   // Remove double bitcasts from shuffles - this is often a legacy of
7748   // XformToShuffleWithZero being used to combine bitmaskings (of
7749   // float vectors bitcast to integer vectors) into shuffles.
7750   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7751   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7752       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7753       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7754       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7755     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7756 
7757     // If operands are a bitcast, peek through if it casts the original VT.
7758     // If operands are a constant, just bitcast back to original VT.
7759     auto PeekThroughBitcast = [&](SDValue Op) {
7760       if (Op.getOpcode() == ISD::BITCAST &&
7761           Op.getOperand(0).getValueType() == VT)
7762         return SDValue(Op.getOperand(0));
7763       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7764           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7765         return DAG.getBitcast(VT, Op);
7766       return SDValue();
7767     };
7768 
7769     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7770     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7771     if (!(SV0 && SV1))
7772       return SDValue();
7773 
7774     int MaskScale =
7775         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7776     SmallVector<int, 8> NewMask;
7777     for (int M : SVN->getMask())
7778       for (int i = 0; i != MaskScale; ++i)
7779         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7780 
7781     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7782     if (!LegalMask) {
7783       std::swap(SV0, SV1);
7784       ShuffleVectorSDNode::commuteMask(NewMask);
7785       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7786     }
7787 
7788     if (LegalMask)
7789       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7790   }
7791 
7792   return SDValue();
7793 }
7794 
7795 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7796   EVT VT = N->getValueType(0);
7797   return CombineConsecutiveLoads(N, VT);
7798 }
7799 
7800 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7801 /// operands. DstEltVT indicates the destination element value type.
7802 SDValue DAGCombiner::
7803 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7804   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7805 
7806   // If this is already the right type, we're done.
7807   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7808 
7809   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7810   unsigned DstBitSize = DstEltVT.getSizeInBits();
7811 
7812   // If this is a conversion of N elements of one type to N elements of another
7813   // type, convert each element.  This handles FP<->INT cases.
7814   if (SrcBitSize == DstBitSize) {
7815     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7816                               BV->getValueType(0).getVectorNumElements());
7817 
7818     // Due to the FP element handling below calling this routine recursively,
7819     // we can end up with a scalar-to-vector node here.
7820     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7821       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7822                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7823 
7824     SmallVector<SDValue, 8> Ops;
7825     for (SDValue Op : BV->op_values()) {
7826       // If the vector element type is not legal, the BUILD_VECTOR operands
7827       // are promoted and implicitly truncated.  Make that explicit here.
7828       if (Op.getValueType() != SrcEltVT)
7829         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7830       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7831       AddToWorklist(Ops.back().getNode());
7832     }
7833     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7834   }
7835 
7836   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7837   // handle annoying details of growing/shrinking FP values, we convert them to
7838   // int first.
7839   if (SrcEltVT.isFloatingPoint()) {
7840     // Convert the input float vector to a int vector where the elements are the
7841     // same sizes.
7842     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7843     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7844     SrcEltVT = IntVT;
7845   }
7846 
7847   // Now we know the input is an integer vector.  If the output is a FP type,
7848   // convert to integer first, then to FP of the right size.
7849   if (DstEltVT.isFloatingPoint()) {
7850     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7851     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7852 
7853     // Next, convert to FP elements of the same size.
7854     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7855   }
7856 
7857   SDLoc DL(BV);
7858 
7859   // Okay, we know the src/dst types are both integers of differing types.
7860   // Handling growing first.
7861   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7862   if (SrcBitSize < DstBitSize) {
7863     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7864 
7865     SmallVector<SDValue, 8> Ops;
7866     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7867          i += NumInputsPerOutput) {
7868       bool isLE = DAG.getDataLayout().isLittleEndian();
7869       APInt NewBits = APInt(DstBitSize, 0);
7870       bool EltIsUndef = true;
7871       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7872         // Shift the previously computed bits over.
7873         NewBits <<= SrcBitSize;
7874         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7875         if (Op.isUndef()) continue;
7876         EltIsUndef = false;
7877 
7878         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7879                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7880       }
7881 
7882       if (EltIsUndef)
7883         Ops.push_back(DAG.getUNDEF(DstEltVT));
7884       else
7885         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7886     }
7887 
7888     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7889     return DAG.getBuildVector(VT, DL, Ops);
7890   }
7891 
7892   // Finally, this must be the case where we are shrinking elements: each input
7893   // turns into multiple outputs.
7894   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7895   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7896                             NumOutputsPerInput*BV->getNumOperands());
7897   SmallVector<SDValue, 8> Ops;
7898 
7899   for (const SDValue &Op : BV->op_values()) {
7900     if (Op.isUndef()) {
7901       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7902       continue;
7903     }
7904 
7905     APInt OpVal = cast<ConstantSDNode>(Op)->
7906                   getAPIntValue().zextOrTrunc(SrcBitSize);
7907 
7908     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7909       APInt ThisVal = OpVal.trunc(DstBitSize);
7910       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7911       OpVal = OpVal.lshr(DstBitSize);
7912     }
7913 
7914     // For big endian targets, swap the order of the pieces of each element.
7915     if (DAG.getDataLayout().isBigEndian())
7916       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7917   }
7918 
7919   return DAG.getBuildVector(VT, DL, Ops);
7920 }
7921 
7922 /// Try to perform FMA combining on a given FADD node.
7923 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7924   SDValue N0 = N->getOperand(0);
7925   SDValue N1 = N->getOperand(1);
7926   EVT VT = N->getValueType(0);
7927   SDLoc SL(N);
7928 
7929   const TargetOptions &Options = DAG.getTarget().Options;
7930   bool AllowFusion =
7931       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7932 
7933   // Floating-point multiply-add with intermediate rounding.
7934   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7935 
7936   // Floating-point multiply-add without intermediate rounding.
7937   bool HasFMA =
7938       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7939       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7940 
7941   // No valid opcode, do not combine.
7942   if (!HasFMAD && !HasFMA)
7943     return SDValue();
7944 
7945   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7946   ;
7947   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7948     return SDValue();
7949 
7950   // Always prefer FMAD to FMA for precision.
7951   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7952   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7953   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7954 
7955   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7956   // prefer to fold the multiply with fewer uses.
7957   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7958       N1.getOpcode() == ISD::FMUL) {
7959     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7960       std::swap(N0, N1);
7961   }
7962 
7963   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7964   if (N0.getOpcode() == ISD::FMUL &&
7965       (Aggressive || N0->hasOneUse())) {
7966     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7967                        N0.getOperand(0), N0.getOperand(1), N1);
7968   }
7969 
7970   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7971   // Note: Commutes FADD operands.
7972   if (N1.getOpcode() == ISD::FMUL &&
7973       (Aggressive || N1->hasOneUse())) {
7974     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7975                        N1.getOperand(0), N1.getOperand(1), N0);
7976   }
7977 
7978   // Look through FP_EXTEND nodes to do more combining.
7979   if (AllowFusion && LookThroughFPExt) {
7980     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7981     if (N0.getOpcode() == ISD::FP_EXTEND) {
7982       SDValue N00 = N0.getOperand(0);
7983       if (N00.getOpcode() == ISD::FMUL)
7984         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7985                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7986                                        N00.getOperand(0)),
7987                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7988                                        N00.getOperand(1)), N1);
7989     }
7990 
7991     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7992     // Note: Commutes FADD operands.
7993     if (N1.getOpcode() == ISD::FP_EXTEND) {
7994       SDValue N10 = N1.getOperand(0);
7995       if (N10.getOpcode() == ISD::FMUL)
7996         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7997                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7998                                        N10.getOperand(0)),
7999                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8000                                        N10.getOperand(1)), N0);
8001     }
8002   }
8003 
8004   // More folding opportunities when target permits.
8005   if ((AllowFusion || HasFMAD)  && Aggressive) {
8006     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8007     if (N0.getOpcode() == PreferredFusedOpcode &&
8008         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8009       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8010                          N0.getOperand(0), N0.getOperand(1),
8011                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8012                                      N0.getOperand(2).getOperand(0),
8013                                      N0.getOperand(2).getOperand(1),
8014                                      N1));
8015     }
8016 
8017     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8018     if (N1->getOpcode() == PreferredFusedOpcode &&
8019         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8020       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8021                          N1.getOperand(0), N1.getOperand(1),
8022                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8023                                      N1.getOperand(2).getOperand(0),
8024                                      N1.getOperand(2).getOperand(1),
8025                                      N0));
8026     }
8027 
8028     if (AllowFusion && LookThroughFPExt) {
8029       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8030       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
8031       auto FoldFAddFMAFPExtFMul = [&] (
8032           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8033         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8034                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8035                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8036                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8037                                        Z));
8038       };
8039       if (N0.getOpcode() == PreferredFusedOpcode) {
8040         SDValue N02 = N0.getOperand(2);
8041         if (N02.getOpcode() == ISD::FP_EXTEND) {
8042           SDValue N020 = N02.getOperand(0);
8043           if (N020.getOpcode() == ISD::FMUL)
8044             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8045                                         N020.getOperand(0), N020.getOperand(1),
8046                                         N1);
8047         }
8048       }
8049 
8050       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8051       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8052       // FIXME: This turns two single-precision and one double-precision
8053       // operation into two double-precision operations, which might not be
8054       // interesting for all targets, especially GPUs.
8055       auto FoldFAddFPExtFMAFMul = [&] (
8056           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8057         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8058                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8059                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8060                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8061                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8062                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8063                                        Z));
8064       };
8065       if (N0.getOpcode() == ISD::FP_EXTEND) {
8066         SDValue N00 = N0.getOperand(0);
8067         if (N00.getOpcode() == PreferredFusedOpcode) {
8068           SDValue N002 = N00.getOperand(2);
8069           if (N002.getOpcode() == ISD::FMUL)
8070             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8071                                         N002.getOperand(0), N002.getOperand(1),
8072                                         N1);
8073         }
8074       }
8075 
8076       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
8077       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
8078       if (N1.getOpcode() == PreferredFusedOpcode) {
8079         SDValue N12 = N1.getOperand(2);
8080         if (N12.getOpcode() == ISD::FP_EXTEND) {
8081           SDValue N120 = N12.getOperand(0);
8082           if (N120.getOpcode() == ISD::FMUL)
8083             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8084                                         N120.getOperand(0), N120.getOperand(1),
8085                                         N0);
8086         }
8087       }
8088 
8089       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8090       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8091       // FIXME: This turns two single-precision and one double-precision
8092       // operation into two double-precision operations, which might not be
8093       // interesting for all targets, especially GPUs.
8094       if (N1.getOpcode() == ISD::FP_EXTEND) {
8095         SDValue N10 = N1.getOperand(0);
8096         if (N10.getOpcode() == PreferredFusedOpcode) {
8097           SDValue N102 = N10.getOperand(2);
8098           if (N102.getOpcode() == ISD::FMUL)
8099             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8100                                         N102.getOperand(0), N102.getOperand(1),
8101                                         N0);
8102         }
8103       }
8104     }
8105   }
8106 
8107   return SDValue();
8108 }
8109 
8110 /// Try to perform FMA combining on a given FSUB node.
8111 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8112   SDValue N0 = N->getOperand(0);
8113   SDValue N1 = N->getOperand(1);
8114   EVT VT = N->getValueType(0);
8115   SDLoc SL(N);
8116 
8117   const TargetOptions &Options = DAG.getTarget().Options;
8118   bool AllowFusion =
8119       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8120 
8121   // Floating-point multiply-add with intermediate rounding.
8122   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8123 
8124   // Floating-point multiply-add without intermediate rounding.
8125   bool HasFMA =
8126       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8127       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8128 
8129   // No valid opcode, do not combine.
8130   if (!HasFMAD && !HasFMA)
8131     return SDValue();
8132 
8133   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8134   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8135     return SDValue();
8136 
8137   // Always prefer FMAD to FMA for precision.
8138   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8139   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8140   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8141 
8142   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8143   if (N0.getOpcode() == ISD::FMUL &&
8144       (Aggressive || N0->hasOneUse())) {
8145     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8146                        N0.getOperand(0), N0.getOperand(1),
8147                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8148   }
8149 
8150   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8151   // Note: Commutes FSUB operands.
8152   if (N1.getOpcode() == ISD::FMUL &&
8153       (Aggressive || N1->hasOneUse()))
8154     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8155                        DAG.getNode(ISD::FNEG, SL, VT,
8156                                    N1.getOperand(0)),
8157                        N1.getOperand(1), N0);
8158 
8159   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8160   if (N0.getOpcode() == ISD::FNEG &&
8161       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8162       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8163     SDValue N00 = N0.getOperand(0).getOperand(0);
8164     SDValue N01 = N0.getOperand(0).getOperand(1);
8165     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8166                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8167                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8168   }
8169 
8170   // Look through FP_EXTEND nodes to do more combining.
8171   if (AllowFusion && LookThroughFPExt) {
8172     // fold (fsub (fpext (fmul x, y)), z)
8173     //   -> (fma (fpext x), (fpext y), (fneg z))
8174     if (N0.getOpcode() == ISD::FP_EXTEND) {
8175       SDValue N00 = N0.getOperand(0);
8176       if (N00.getOpcode() == ISD::FMUL)
8177         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8178                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8179                                        N00.getOperand(0)),
8180                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8181                                        N00.getOperand(1)),
8182                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8183     }
8184 
8185     // fold (fsub x, (fpext (fmul y, z)))
8186     //   -> (fma (fneg (fpext y)), (fpext z), x)
8187     // Note: Commutes FSUB operands.
8188     if (N1.getOpcode() == ISD::FP_EXTEND) {
8189       SDValue N10 = N1.getOperand(0);
8190       if (N10.getOpcode() == ISD::FMUL)
8191         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8192                            DAG.getNode(ISD::FNEG, SL, VT,
8193                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8194                                                    N10.getOperand(0))),
8195                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8196                                        N10.getOperand(1)),
8197                            N0);
8198     }
8199 
8200     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8201     //   -> (fneg (fma (fpext x), (fpext y), z))
8202     // Note: This could be removed with appropriate canonicalization of the
8203     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8204     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8205     // from implementing the canonicalization in visitFSUB.
8206     if (N0.getOpcode() == ISD::FP_EXTEND) {
8207       SDValue N00 = N0.getOperand(0);
8208       if (N00.getOpcode() == ISD::FNEG) {
8209         SDValue N000 = N00.getOperand(0);
8210         if (N000.getOpcode() == ISD::FMUL) {
8211           return DAG.getNode(ISD::FNEG, SL, VT,
8212                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8213                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8214                                                      N000.getOperand(0)),
8215                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8216                                                      N000.getOperand(1)),
8217                                          N1));
8218         }
8219       }
8220     }
8221 
8222     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8223     //   -> (fneg (fma (fpext x)), (fpext y), z)
8224     // Note: This could be removed with appropriate canonicalization of the
8225     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8226     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8227     // from implementing the canonicalization in visitFSUB.
8228     if (N0.getOpcode() == ISD::FNEG) {
8229       SDValue N00 = N0.getOperand(0);
8230       if (N00.getOpcode() == ISD::FP_EXTEND) {
8231         SDValue N000 = N00.getOperand(0);
8232         if (N000.getOpcode() == ISD::FMUL) {
8233           return DAG.getNode(ISD::FNEG, SL, VT,
8234                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8235                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8236                                                      N000.getOperand(0)),
8237                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8238                                                      N000.getOperand(1)),
8239                                          N1));
8240         }
8241       }
8242     }
8243 
8244   }
8245 
8246   // More folding opportunities when target permits.
8247   if ((AllowFusion || HasFMAD) && Aggressive) {
8248     // fold (fsub (fma x, y, (fmul u, v)), z)
8249     //   -> (fma x, y (fma u, v, (fneg z)))
8250     if (N0.getOpcode() == PreferredFusedOpcode &&
8251         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8252       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8253                          N0.getOperand(0), N0.getOperand(1),
8254                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8255                                      N0.getOperand(2).getOperand(0),
8256                                      N0.getOperand(2).getOperand(1),
8257                                      DAG.getNode(ISD::FNEG, SL, VT,
8258                                                  N1)));
8259     }
8260 
8261     // fold (fsub x, (fma y, z, (fmul u, v)))
8262     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8263     if (N1.getOpcode() == PreferredFusedOpcode &&
8264         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8265       SDValue N20 = N1.getOperand(2).getOperand(0);
8266       SDValue N21 = N1.getOperand(2).getOperand(1);
8267       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8268                          DAG.getNode(ISD::FNEG, SL, VT,
8269                                      N1.getOperand(0)),
8270                          N1.getOperand(1),
8271                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8272                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8273 
8274                                      N21, N0));
8275     }
8276 
8277     if (AllowFusion && LookThroughFPExt) {
8278       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8279       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8280       if (N0.getOpcode() == PreferredFusedOpcode) {
8281         SDValue N02 = N0.getOperand(2);
8282         if (N02.getOpcode() == ISD::FP_EXTEND) {
8283           SDValue N020 = N02.getOperand(0);
8284           if (N020.getOpcode() == ISD::FMUL)
8285             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8286                                N0.getOperand(0), N0.getOperand(1),
8287                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8288                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8289                                                        N020.getOperand(0)),
8290                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8291                                                        N020.getOperand(1)),
8292                                            DAG.getNode(ISD::FNEG, SL, VT,
8293                                                        N1)));
8294         }
8295       }
8296 
8297       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8298       //   -> (fma (fpext x), (fpext y),
8299       //           (fma (fpext u), (fpext v), (fneg z)))
8300       // FIXME: This turns two single-precision and one double-precision
8301       // operation into two double-precision operations, which might not be
8302       // interesting for all targets, especially GPUs.
8303       if (N0.getOpcode() == ISD::FP_EXTEND) {
8304         SDValue N00 = N0.getOperand(0);
8305         if (N00.getOpcode() == PreferredFusedOpcode) {
8306           SDValue N002 = N00.getOperand(2);
8307           if (N002.getOpcode() == ISD::FMUL)
8308             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8309                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8310                                            N00.getOperand(0)),
8311                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8312                                            N00.getOperand(1)),
8313                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8314                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8315                                                        N002.getOperand(0)),
8316                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8317                                                        N002.getOperand(1)),
8318                                            DAG.getNode(ISD::FNEG, SL, VT,
8319                                                        N1)));
8320         }
8321       }
8322 
8323       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8324       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8325       if (N1.getOpcode() == PreferredFusedOpcode &&
8326         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8327         SDValue N120 = N1.getOperand(2).getOperand(0);
8328         if (N120.getOpcode() == ISD::FMUL) {
8329           SDValue N1200 = N120.getOperand(0);
8330           SDValue N1201 = N120.getOperand(1);
8331           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8332                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8333                              N1.getOperand(1),
8334                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8335                                          DAG.getNode(ISD::FNEG, SL, VT,
8336                                              DAG.getNode(ISD::FP_EXTEND, SL,
8337                                                          VT, N1200)),
8338                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8339                                                      N1201),
8340                                          N0));
8341         }
8342       }
8343 
8344       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8345       //   -> (fma (fneg (fpext y)), (fpext z),
8346       //           (fma (fneg (fpext u)), (fpext v), x))
8347       // FIXME: This turns two single-precision and one double-precision
8348       // operation into two double-precision operations, which might not be
8349       // interesting for all targets, especially GPUs.
8350       if (N1.getOpcode() == ISD::FP_EXTEND &&
8351         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8352         SDValue N100 = N1.getOperand(0).getOperand(0);
8353         SDValue N101 = N1.getOperand(0).getOperand(1);
8354         SDValue N102 = N1.getOperand(0).getOperand(2);
8355         if (N102.getOpcode() == ISD::FMUL) {
8356           SDValue N1020 = N102.getOperand(0);
8357           SDValue N1021 = N102.getOperand(1);
8358           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8359                              DAG.getNode(ISD::FNEG, SL, VT,
8360                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8361                                                      N100)),
8362                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8363                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8364                                          DAG.getNode(ISD::FNEG, SL, VT,
8365                                              DAG.getNode(ISD::FP_EXTEND, SL,
8366                                                          VT, N1020)),
8367                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8368                                                      N1021),
8369                                          N0));
8370         }
8371       }
8372     }
8373   }
8374 
8375   return SDValue();
8376 }
8377 
8378 /// Try to perform FMA combining on a given FMUL node.
8379 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8380   SDValue N0 = N->getOperand(0);
8381   SDValue N1 = N->getOperand(1);
8382   EVT VT = N->getValueType(0);
8383   SDLoc SL(N);
8384 
8385   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8386 
8387   const TargetOptions &Options = DAG.getTarget().Options;
8388   bool AllowFusion =
8389       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8390 
8391   // Floating-point multiply-add with intermediate rounding.
8392   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8393 
8394   // Floating-point multiply-add without intermediate rounding.
8395   bool HasFMA =
8396       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8397       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8398 
8399   // No valid opcode, do not combine.
8400   if (!HasFMAD && !HasFMA)
8401     return SDValue();
8402 
8403   // Always prefer FMAD to FMA for precision.
8404   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8405   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8406 
8407   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8408   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8409   auto FuseFADD = [&](SDValue X, SDValue Y) {
8410     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8411       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8412       if (XC1 && XC1->isExactlyValue(+1.0))
8413         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8414       if (XC1 && XC1->isExactlyValue(-1.0))
8415         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8416                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8417     }
8418     return SDValue();
8419   };
8420 
8421   if (SDValue FMA = FuseFADD(N0, N1))
8422     return FMA;
8423   if (SDValue FMA = FuseFADD(N1, N0))
8424     return FMA;
8425 
8426   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8427   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8428   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8429   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8430   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8431     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8432       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8433       if (XC0 && XC0->isExactlyValue(+1.0))
8434         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8435                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8436                            Y);
8437       if (XC0 && XC0->isExactlyValue(-1.0))
8438         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8439                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8440                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8441 
8442       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8443       if (XC1 && XC1->isExactlyValue(+1.0))
8444         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8445                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8446       if (XC1 && XC1->isExactlyValue(-1.0))
8447         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8448     }
8449     return SDValue();
8450   };
8451 
8452   if (SDValue FMA = FuseFSUB(N0, N1))
8453     return FMA;
8454   if (SDValue FMA = FuseFSUB(N1, N0))
8455     return FMA;
8456 
8457   return SDValue();
8458 }
8459 
8460 SDValue DAGCombiner::visitFADD(SDNode *N) {
8461   SDValue N0 = N->getOperand(0);
8462   SDValue N1 = N->getOperand(1);
8463   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8464   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8465   EVT VT = N->getValueType(0);
8466   SDLoc DL(N);
8467   const TargetOptions &Options = DAG.getTarget().Options;
8468   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8469 
8470   // fold vector ops
8471   if (VT.isVector())
8472     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8473       return FoldedVOp;
8474 
8475   // fold (fadd c1, c2) -> c1 + c2
8476   if (N0CFP && N1CFP)
8477     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8478 
8479   // canonicalize constant to RHS
8480   if (N0CFP && !N1CFP)
8481     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8482 
8483   // fold (fadd A, (fneg B)) -> (fsub A, B)
8484   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8485       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8486     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8487                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8488 
8489   // fold (fadd (fneg A), B) -> (fsub B, A)
8490   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8491       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8492     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8493                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8494 
8495   // FIXME: Auto-upgrade the target/function-level option.
8496   if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8497     // fold (fadd A, 0) -> A
8498     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8499       if (N1C->isZero())
8500         return N0;
8501   }
8502 
8503   // If 'unsafe math' is enabled, fold lots of things.
8504   if (Options.UnsafeFPMath) {
8505     // No FP constant should be created after legalization as Instruction
8506     // Selection pass has a hard time dealing with FP constants.
8507     bool AllowNewConst = (Level < AfterLegalizeDAG);
8508 
8509     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8510     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8511         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8512       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8513                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8514                                      Flags),
8515                          Flags);
8516 
8517     // If allowed, fold (fadd (fneg x), x) -> 0.0
8518     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8519       return DAG.getConstantFP(0.0, DL, VT);
8520 
8521     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8522     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8523       return DAG.getConstantFP(0.0, DL, VT);
8524 
8525     // We can fold chains of FADD's of the same value into multiplications.
8526     // This transform is not safe in general because we are reducing the number
8527     // of rounding steps.
8528     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8529       if (N0.getOpcode() == ISD::FMUL) {
8530         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8531         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8532 
8533         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8534         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8535           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8536                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8537           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8538         }
8539 
8540         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8541         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8542             N1.getOperand(0) == N1.getOperand(1) &&
8543             N0.getOperand(0) == N1.getOperand(0)) {
8544           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8545                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8546           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8547         }
8548       }
8549 
8550       if (N1.getOpcode() == ISD::FMUL) {
8551         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8552         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8553 
8554         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8555         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8556           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8557                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8558           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8559         }
8560 
8561         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8562         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8563             N0.getOperand(0) == N0.getOperand(1) &&
8564             N1.getOperand(0) == N0.getOperand(0)) {
8565           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8566                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8567           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8568         }
8569       }
8570 
8571       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8572         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8573         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8574         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8575             (N0.getOperand(0) == N1)) {
8576           return DAG.getNode(ISD::FMUL, DL, VT,
8577                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8578         }
8579       }
8580 
8581       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8582         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8583         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8584         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8585             N1.getOperand(0) == N0) {
8586           return DAG.getNode(ISD::FMUL, DL, VT,
8587                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8588         }
8589       }
8590 
8591       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8592       if (AllowNewConst &&
8593           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8594           N0.getOperand(0) == N0.getOperand(1) &&
8595           N1.getOperand(0) == N1.getOperand(1) &&
8596           N0.getOperand(0) == N1.getOperand(0)) {
8597         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8598                            DAG.getConstantFP(4.0, DL, VT), Flags);
8599       }
8600     }
8601   } // enable-unsafe-fp-math
8602 
8603   // FADD -> FMA combines:
8604   if (SDValue Fused = visitFADDForFMACombine(N)) {
8605     AddToWorklist(Fused.getNode());
8606     return Fused;
8607   }
8608   return SDValue();
8609 }
8610 
8611 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8612   SDValue N0 = N->getOperand(0);
8613   SDValue N1 = N->getOperand(1);
8614   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8615   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8616   EVT VT = N->getValueType(0);
8617   SDLoc DL(N);
8618   const TargetOptions &Options = DAG.getTarget().Options;
8619   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8620 
8621   // fold vector ops
8622   if (VT.isVector())
8623     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8624       return FoldedVOp;
8625 
8626   // fold (fsub c1, c2) -> c1-c2
8627   if (N0CFP && N1CFP)
8628     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
8629 
8630   // fold (fsub A, (fneg B)) -> (fadd A, B)
8631   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8632     return DAG.getNode(ISD::FADD, DL, VT, N0,
8633                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8634 
8635   // FIXME: Auto-upgrade the target/function-level option.
8636   if (Options.UnsafeFPMath || N->getFlags()->hasNoSignedZeros()) {
8637     // (fsub 0, B) -> -B
8638     if (N0CFP && N0CFP->isZero()) {
8639       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8640         return GetNegatedExpression(N1, DAG, LegalOperations);
8641       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8642         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
8643     }
8644   }
8645 
8646   // If 'unsafe math' is enabled, fold lots of things.
8647   if (Options.UnsafeFPMath) {
8648     // (fsub A, 0) -> A
8649     if (N1CFP && N1CFP->isZero())
8650       return N0;
8651 
8652     // (fsub x, x) -> 0.0
8653     if (N0 == N1)
8654       return DAG.getConstantFP(0.0f, DL, VT);
8655 
8656     // (fsub x, (fadd x, y)) -> (fneg y)
8657     // (fsub x, (fadd y, x)) -> (fneg y)
8658     if (N1.getOpcode() == ISD::FADD) {
8659       SDValue N10 = N1->getOperand(0);
8660       SDValue N11 = N1->getOperand(1);
8661 
8662       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8663         return GetNegatedExpression(N11, DAG, LegalOperations);
8664 
8665       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8666         return GetNegatedExpression(N10, DAG, LegalOperations);
8667     }
8668   }
8669 
8670   // FSUB -> FMA combines:
8671   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8672     AddToWorklist(Fused.getNode());
8673     return Fused;
8674   }
8675 
8676   return SDValue();
8677 }
8678 
8679 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8680   SDValue N0 = N->getOperand(0);
8681   SDValue N1 = N->getOperand(1);
8682   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8683   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8684   EVT VT = N->getValueType(0);
8685   SDLoc DL(N);
8686   const TargetOptions &Options = DAG.getTarget().Options;
8687   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8688 
8689   // fold vector ops
8690   if (VT.isVector()) {
8691     // This just handles C1 * C2 for vectors. Other vector folds are below.
8692     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8693       return FoldedVOp;
8694   }
8695 
8696   // fold (fmul c1, c2) -> c1*c2
8697   if (N0CFP && N1CFP)
8698     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8699 
8700   // canonicalize constant to RHS
8701   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8702      !isConstantFPBuildVectorOrConstantFP(N1))
8703     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8704 
8705   // fold (fmul A, 1.0) -> A
8706   if (N1CFP && N1CFP->isExactlyValue(1.0))
8707     return N0;
8708 
8709   if (Options.UnsafeFPMath) {
8710     // fold (fmul A, 0) -> 0
8711     if (N1CFP && N1CFP->isZero())
8712       return N1;
8713 
8714     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8715     if (N0.getOpcode() == ISD::FMUL) {
8716       // Fold scalars or any vector constants (not just splats).
8717       // This fold is done in general by InstCombine, but extra fmul insts
8718       // may have been generated during lowering.
8719       SDValue N00 = N0.getOperand(0);
8720       SDValue N01 = N0.getOperand(1);
8721       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8722       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8723       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8724 
8725       // Check 1: Make sure that the first operand of the inner multiply is NOT
8726       // a constant. Otherwise, we may induce infinite looping.
8727       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8728         // Check 2: Make sure that the second operand of the inner multiply and
8729         // the second operand of the outer multiply are constants.
8730         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8731             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8732           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8733           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8734         }
8735       }
8736     }
8737 
8738     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8739     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8740     // during an early run of DAGCombiner can prevent folding with fmuls
8741     // inserted during lowering.
8742     if (N0.getOpcode() == ISD::FADD &&
8743         (N0.getOperand(0) == N0.getOperand(1)) &&
8744         N0.hasOneUse()) {
8745       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8746       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8747       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8748     }
8749   }
8750 
8751   // fold (fmul X, 2.0) -> (fadd X, X)
8752   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8753     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8754 
8755   // fold (fmul X, -1.0) -> (fneg X)
8756   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8757     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8758       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8759 
8760   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8761   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8762     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8763       // Both can be negated for free, check to see if at least one is cheaper
8764       // negated.
8765       if (LHSNeg == 2 || RHSNeg == 2)
8766         return DAG.getNode(ISD::FMUL, DL, VT,
8767                            GetNegatedExpression(N0, DAG, LegalOperations),
8768                            GetNegatedExpression(N1, DAG, LegalOperations),
8769                            Flags);
8770     }
8771   }
8772 
8773   // FMUL -> FMA combines:
8774   if (SDValue Fused = visitFMULForFMACombine(N)) {
8775     AddToWorklist(Fused.getNode());
8776     return Fused;
8777   }
8778 
8779   return SDValue();
8780 }
8781 
8782 SDValue DAGCombiner::visitFMA(SDNode *N) {
8783   SDValue N0 = N->getOperand(0);
8784   SDValue N1 = N->getOperand(1);
8785   SDValue N2 = N->getOperand(2);
8786   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8787   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8788   EVT VT = N->getValueType(0);
8789   SDLoc DL(N);
8790   const TargetOptions &Options = DAG.getTarget().Options;
8791 
8792   // Constant fold FMA.
8793   if (isa<ConstantFPSDNode>(N0) &&
8794       isa<ConstantFPSDNode>(N1) &&
8795       isa<ConstantFPSDNode>(N2)) {
8796     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
8797   }
8798 
8799   if (Options.UnsafeFPMath) {
8800     if (N0CFP && N0CFP->isZero())
8801       return N2;
8802     if (N1CFP && N1CFP->isZero())
8803       return N2;
8804   }
8805   // TODO: The FMA node should have flags that propagate to these nodes.
8806   if (N0CFP && N0CFP->isExactlyValue(1.0))
8807     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8808   if (N1CFP && N1CFP->isExactlyValue(1.0))
8809     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8810 
8811   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8812   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8813      !isConstantFPBuildVectorOrConstantFP(N1))
8814     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8815 
8816   // TODO: FMA nodes should have flags that propagate to the created nodes.
8817   // For now, create a Flags object for use with all unsafe math transforms.
8818   SDNodeFlags Flags;
8819   Flags.setUnsafeAlgebra(true);
8820 
8821   if (Options.UnsafeFPMath) {
8822     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8823     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8824         isConstantFPBuildVectorOrConstantFP(N1) &&
8825         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8826       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8827                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
8828                                      &Flags), &Flags);
8829     }
8830 
8831     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8832     if (N0.getOpcode() == ISD::FMUL &&
8833         isConstantFPBuildVectorOrConstantFP(N1) &&
8834         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8835       return DAG.getNode(ISD::FMA, DL, VT,
8836                          N0.getOperand(0),
8837                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
8838                                      &Flags),
8839                          N2);
8840     }
8841   }
8842 
8843   // (fma x, 1, y) -> (fadd x, y)
8844   // (fma x, -1, y) -> (fadd (fneg x), y)
8845   if (N1CFP) {
8846     if (N1CFP->isExactlyValue(1.0))
8847       // TODO: The FMA node should have flags that propagate to this node.
8848       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
8849 
8850     if (N1CFP->isExactlyValue(-1.0) &&
8851         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8852       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
8853       AddToWorklist(RHSNeg.getNode());
8854       // TODO: The FMA node should have flags that propagate to this node.
8855       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
8856     }
8857   }
8858 
8859   if (Options.UnsafeFPMath) {
8860     // (fma x, c, x) -> (fmul x, (c+1))
8861     if (N1CFP && N0 == N2) {
8862       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8863                          DAG.getNode(ISD::FADD, DL, VT, N1,
8864                                      DAG.getConstantFP(1.0, DL, VT), &Flags),
8865                          &Flags);
8866     }
8867 
8868     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8869     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8870       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8871                          DAG.getNode(ISD::FADD, DL, VT, N1,
8872                                      DAG.getConstantFP(-1.0, DL, VT), &Flags),
8873                          &Flags);
8874     }
8875   }
8876 
8877   return SDValue();
8878 }
8879 
8880 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8881 // reciprocal.
8882 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8883 // Notice that this is not always beneficial. One reason is different target
8884 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8885 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8886 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8887 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8888   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8889   const SDNodeFlags *Flags = N->getFlags();
8890   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8891     return SDValue();
8892 
8893   // Skip if current node is a reciprocal.
8894   SDValue N0 = N->getOperand(0);
8895   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8896   if (N0CFP && N0CFP->isExactlyValue(1.0))
8897     return SDValue();
8898 
8899   // Exit early if the target does not want this transform or if there can't
8900   // possibly be enough uses of the divisor to make the transform worthwhile.
8901   SDValue N1 = N->getOperand(1);
8902   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8903   if (!MinUses || N1->use_size() < MinUses)
8904     return SDValue();
8905 
8906   // Find all FDIV users of the same divisor.
8907   // Use a set because duplicates may be present in the user list.
8908   SetVector<SDNode *> Users;
8909   for (auto *U : N1->uses()) {
8910     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8911       // This division is eligible for optimization only if global unsafe math
8912       // is enabled or if this division allows reciprocal formation.
8913       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8914         Users.insert(U);
8915     }
8916   }
8917 
8918   // Now that we have the actual number of divisor uses, make sure it meets
8919   // the minimum threshold specified by the target.
8920   if (Users.size() < MinUses)
8921     return SDValue();
8922 
8923   EVT VT = N->getValueType(0);
8924   SDLoc DL(N);
8925   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8926   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8927 
8928   // Dividend / Divisor -> Dividend * Reciprocal
8929   for (auto *U : Users) {
8930     SDValue Dividend = U->getOperand(0);
8931     if (Dividend != FPOne) {
8932       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8933                                     Reciprocal, Flags);
8934       CombineTo(U, NewNode);
8935     } else if (U != Reciprocal.getNode()) {
8936       // In the absence of fast-math-flags, this user node is always the
8937       // same node as Reciprocal, but with FMF they may be different nodes.
8938       CombineTo(U, Reciprocal);
8939     }
8940   }
8941   return SDValue(N, 0);  // N was replaced.
8942 }
8943 
8944 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8945   SDValue N0 = N->getOperand(0);
8946   SDValue N1 = N->getOperand(1);
8947   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8948   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8949   EVT VT = N->getValueType(0);
8950   SDLoc DL(N);
8951   const TargetOptions &Options = DAG.getTarget().Options;
8952   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8953 
8954   // fold vector ops
8955   if (VT.isVector())
8956     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8957       return FoldedVOp;
8958 
8959   // fold (fdiv c1, c2) -> c1/c2
8960   if (N0CFP && N1CFP)
8961     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8962 
8963   if (Options.UnsafeFPMath) {
8964     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8965     if (N1CFP) {
8966       // Compute the reciprocal 1.0 / c2.
8967       const APFloat &N1APF = N1CFP->getValueAPF();
8968       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8969       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8970       // Only do the transform if the reciprocal is a legal fp immediate that
8971       // isn't too nasty (eg NaN, denormal, ...).
8972       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8973           (!LegalOperations ||
8974            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8975            // backend)... we should handle this gracefully after Legalize.
8976            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8977            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8978            TLI.isFPImmLegal(Recip, VT)))
8979         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8980                            DAG.getConstantFP(Recip, DL, VT), Flags);
8981     }
8982 
8983     // If this FDIV is part of a reciprocal square root, it may be folded
8984     // into a target-specific square root estimate instruction.
8985     if (N1.getOpcode() == ISD::FSQRT) {
8986       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
8987         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8988       }
8989     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8990                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8991       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8992                                           Flags)) {
8993         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8994         AddToWorklist(RV.getNode());
8995         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8996       }
8997     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8998                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8999       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9000                                           Flags)) {
9001         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9002         AddToWorklist(RV.getNode());
9003         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9004       }
9005     } else if (N1.getOpcode() == ISD::FMUL) {
9006       // Look through an FMUL. Even though this won't remove the FDIV directly,
9007       // it's still worthwhile to get rid of the FSQRT if possible.
9008       SDValue SqrtOp;
9009       SDValue OtherOp;
9010       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9011         SqrtOp = N1.getOperand(0);
9012         OtherOp = N1.getOperand(1);
9013       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
9014         SqrtOp = N1.getOperand(1);
9015         OtherOp = N1.getOperand(0);
9016       }
9017       if (SqrtOp.getNode()) {
9018         // We found a FSQRT, so try to make this fold:
9019         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9020         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9021           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9022           AddToWorklist(RV.getNode());
9023           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9024         }
9025       }
9026     }
9027 
9028     // Fold into a reciprocal estimate and multiply instead of a real divide.
9029     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
9030       AddToWorklist(RV.getNode());
9031       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9032     }
9033   }
9034 
9035   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
9036   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9037     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9038       // Both can be negated for free, check to see if at least one is cheaper
9039       // negated.
9040       if (LHSNeg == 2 || RHSNeg == 2)
9041         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
9042                            GetNegatedExpression(N0, DAG, LegalOperations),
9043                            GetNegatedExpression(N1, DAG, LegalOperations),
9044                            Flags);
9045     }
9046   }
9047 
9048   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
9049     return CombineRepeatedDivisors;
9050 
9051   return SDValue();
9052 }
9053 
9054 SDValue DAGCombiner::visitFREM(SDNode *N) {
9055   SDValue N0 = N->getOperand(0);
9056   SDValue N1 = N->getOperand(1);
9057   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9058   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9059   EVT VT = N->getValueType(0);
9060 
9061   // fold (frem c1, c2) -> fmod(c1,c2)
9062   if (N0CFP && N1CFP)
9063     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
9064                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
9065 
9066   return SDValue();
9067 }
9068 
9069 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
9070   if (!DAG.getTarget().Options.UnsafeFPMath)
9071     return SDValue();
9072 
9073   SDValue N0 = N->getOperand(0);
9074   if (TLI.isFsqrtCheap(N0, DAG))
9075     return SDValue();
9076 
9077   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
9078   // For now, create a Flags object for use with all unsafe math transforms.
9079   SDNodeFlags Flags;
9080   Flags.setUnsafeAlgebra(true);
9081   return buildSqrtEstimate(N0, &Flags);
9082 }
9083 
9084 /// copysign(x, fp_extend(y)) -> copysign(x, y)
9085 /// copysign(x, fp_round(y)) -> copysign(x, y)
9086 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9087   SDValue N1 = N->getOperand(1);
9088   if ((N1.getOpcode() == ISD::FP_EXTEND ||
9089        N1.getOpcode() == ISD::FP_ROUND)) {
9090     // Do not optimize out type conversion of f128 type yet.
9091     // For some targets like x86_64, configuration is changed to keep one f128
9092     // value in one SSE register, but instruction selection cannot handle
9093     // FCOPYSIGN on SSE registers yet.
9094     EVT N1VT = N1->getValueType(0);
9095     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9096     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9097   }
9098   return false;
9099 }
9100 
9101 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9102   SDValue N0 = N->getOperand(0);
9103   SDValue N1 = N->getOperand(1);
9104   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9105   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9106   EVT VT = N->getValueType(0);
9107 
9108   if (N0CFP && N1CFP) // Constant fold
9109     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9110 
9111   if (N1CFP) {
9112     const APFloat &V = N1CFP->getValueAPF();
9113     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
9114     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9115     if (!V.isNegative()) {
9116       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9117         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9118     } else {
9119       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9120         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9121                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9122     }
9123   }
9124 
9125   // copysign(fabs(x), y) -> copysign(x, y)
9126   // copysign(fneg(x), y) -> copysign(x, y)
9127   // copysign(copysign(x,z), y) -> copysign(x, y)
9128   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9129       N0.getOpcode() == ISD::FCOPYSIGN)
9130     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9131 
9132   // copysign(x, abs(y)) -> abs(x)
9133   if (N1.getOpcode() == ISD::FABS)
9134     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9135 
9136   // copysign(x, copysign(y,z)) -> copysign(x, z)
9137   if (N1.getOpcode() == ISD::FCOPYSIGN)
9138     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9139 
9140   // copysign(x, fp_extend(y)) -> copysign(x, y)
9141   // copysign(x, fp_round(y)) -> copysign(x, y)
9142   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9143     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9144 
9145   return SDValue();
9146 }
9147 
9148 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9149   SDValue N0 = N->getOperand(0);
9150   EVT VT = N->getValueType(0);
9151   EVT OpVT = N0.getValueType();
9152 
9153   // fold (sint_to_fp c1) -> c1fp
9154   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9155       // ...but only if the target supports immediate floating-point values
9156       (!LegalOperations ||
9157        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9158     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9159 
9160   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9161   // but UINT_TO_FP is legal on this target, try to convert.
9162   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9163       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9164     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9165     if (DAG.SignBitIsZero(N0))
9166       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9167   }
9168 
9169   // The next optimizations are desirable only if SELECT_CC can be lowered.
9170   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9171     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9172     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9173         !VT.isVector() &&
9174         (!LegalOperations ||
9175          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9176       SDLoc DL(N);
9177       SDValue Ops[] =
9178         { N0.getOperand(0), N0.getOperand(1),
9179           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9180           N0.getOperand(2) };
9181       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9182     }
9183 
9184     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9185     //      (select_cc x, y, 1.0, 0.0,, cc)
9186     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9187         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9188         (!LegalOperations ||
9189          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9190       SDLoc DL(N);
9191       SDValue Ops[] =
9192         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9193           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9194           N0.getOperand(0).getOperand(2) };
9195       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9196     }
9197   }
9198 
9199   return SDValue();
9200 }
9201 
9202 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9203   SDValue N0 = N->getOperand(0);
9204   EVT VT = N->getValueType(0);
9205   EVT OpVT = N0.getValueType();
9206 
9207   // fold (uint_to_fp c1) -> c1fp
9208   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9209       // ...but only if the target supports immediate floating-point values
9210       (!LegalOperations ||
9211        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9212     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9213 
9214   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9215   // but SINT_TO_FP is legal on this target, try to convert.
9216   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9217       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9218     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9219     if (DAG.SignBitIsZero(N0))
9220       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9221   }
9222 
9223   // The next optimizations are desirable only if SELECT_CC can be lowered.
9224   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9225     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9226 
9227     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9228         (!LegalOperations ||
9229          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9230       SDLoc DL(N);
9231       SDValue Ops[] =
9232         { N0.getOperand(0), N0.getOperand(1),
9233           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9234           N0.getOperand(2) };
9235       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9236     }
9237   }
9238 
9239   return SDValue();
9240 }
9241 
9242 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9243 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9244   SDValue N0 = N->getOperand(0);
9245   EVT VT = N->getValueType(0);
9246 
9247   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9248     return SDValue();
9249 
9250   SDValue Src = N0.getOperand(0);
9251   EVT SrcVT = Src.getValueType();
9252   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9253   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9254 
9255   // We can safely assume the conversion won't overflow the output range,
9256   // because (for example) (uint8_t)18293.f is undefined behavior.
9257 
9258   // Since we can assume the conversion won't overflow, our decision as to
9259   // whether the input will fit in the float should depend on the minimum
9260   // of the input range and output range.
9261 
9262   // This means this is also safe for a signed input and unsigned output, since
9263   // a negative input would lead to undefined behavior.
9264   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9265   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9266   unsigned ActualSize = std::min(InputSize, OutputSize);
9267   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9268 
9269   // We can only fold away the float conversion if the input range can be
9270   // represented exactly in the float range.
9271   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9272     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9273       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9274                                                        : ISD::ZERO_EXTEND;
9275       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9276     }
9277     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9278       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9279     return DAG.getBitcast(VT, Src);
9280   }
9281   return SDValue();
9282 }
9283 
9284 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9285   SDValue N0 = N->getOperand(0);
9286   EVT VT = N->getValueType(0);
9287 
9288   // fold (fp_to_sint c1fp) -> c1
9289   if (isConstantFPBuildVectorOrConstantFP(N0))
9290     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9291 
9292   return FoldIntToFPToInt(N, DAG);
9293 }
9294 
9295 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9296   SDValue N0 = N->getOperand(0);
9297   EVT VT = N->getValueType(0);
9298 
9299   // fold (fp_to_uint c1fp) -> c1
9300   if (isConstantFPBuildVectorOrConstantFP(N0))
9301     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9302 
9303   return FoldIntToFPToInt(N, DAG);
9304 }
9305 
9306 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9307   SDValue N0 = N->getOperand(0);
9308   SDValue N1 = N->getOperand(1);
9309   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9310   EVT VT = N->getValueType(0);
9311 
9312   // fold (fp_round c1fp) -> c1fp
9313   if (N0CFP)
9314     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9315 
9316   // fold (fp_round (fp_extend x)) -> x
9317   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9318     return N0.getOperand(0);
9319 
9320   // fold (fp_round (fp_round x)) -> (fp_round x)
9321   if (N0.getOpcode() == ISD::FP_ROUND) {
9322     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9323     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9324 
9325     // Skip this folding if it results in an fp_round from f80 to f16.
9326     //
9327     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9328     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9329     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9330     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9331     // x86.
9332     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9333       return SDValue();
9334 
9335     // If the first fp_round isn't a value preserving truncation, it might
9336     // introduce a tie in the second fp_round, that wouldn't occur in the
9337     // single-step fp_round we want to fold to.
9338     // In other words, double rounding isn't the same as rounding.
9339     // Also, this is a value preserving truncation iff both fp_round's are.
9340     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9341       SDLoc DL(N);
9342       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9343                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9344     }
9345   }
9346 
9347   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9348   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9349     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9350                               N0.getOperand(0), N1);
9351     AddToWorklist(Tmp.getNode());
9352     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9353                        Tmp, N0.getOperand(1));
9354   }
9355 
9356   return SDValue();
9357 }
9358 
9359 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9360   SDValue N0 = N->getOperand(0);
9361   EVT VT = N->getValueType(0);
9362   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9363   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9364 
9365   // fold (fp_round_inreg c1fp) -> c1fp
9366   if (N0CFP && isTypeLegal(EVT)) {
9367     SDLoc DL(N);
9368     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9369     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9370   }
9371 
9372   return SDValue();
9373 }
9374 
9375 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9376   SDValue N0 = N->getOperand(0);
9377   EVT VT = N->getValueType(0);
9378 
9379   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9380   if (N->hasOneUse() &&
9381       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9382     return SDValue();
9383 
9384   // fold (fp_extend c1fp) -> c1fp
9385   if (isConstantFPBuildVectorOrConstantFP(N0))
9386     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9387 
9388   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9389   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9390       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9391     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9392 
9393   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9394   // value of X.
9395   if (N0.getOpcode() == ISD::FP_ROUND
9396       && N0.getNode()->getConstantOperandVal(1) == 1) {
9397     SDValue In = N0.getOperand(0);
9398     if (In.getValueType() == VT) return In;
9399     if (VT.bitsLT(In.getValueType()))
9400       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9401                          In, N0.getOperand(1));
9402     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9403   }
9404 
9405   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9406   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9407        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9408     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9409     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9410                                      LN0->getChain(),
9411                                      LN0->getBasePtr(), N0.getValueType(),
9412                                      LN0->getMemOperand());
9413     CombineTo(N, ExtLoad);
9414     CombineTo(N0.getNode(),
9415               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9416                           N0.getValueType(), ExtLoad,
9417                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9418               ExtLoad.getValue(1));
9419     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9420   }
9421 
9422   return SDValue();
9423 }
9424 
9425 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9426   SDValue N0 = N->getOperand(0);
9427   EVT VT = N->getValueType(0);
9428 
9429   // fold (fceil c1) -> fceil(c1)
9430   if (isConstantFPBuildVectorOrConstantFP(N0))
9431     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9432 
9433   return SDValue();
9434 }
9435 
9436 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9437   SDValue N0 = N->getOperand(0);
9438   EVT VT = N->getValueType(0);
9439 
9440   // fold (ftrunc c1) -> ftrunc(c1)
9441   if (isConstantFPBuildVectorOrConstantFP(N0))
9442     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9443 
9444   return SDValue();
9445 }
9446 
9447 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9448   SDValue N0 = N->getOperand(0);
9449   EVT VT = N->getValueType(0);
9450 
9451   // fold (ffloor c1) -> ffloor(c1)
9452   if (isConstantFPBuildVectorOrConstantFP(N0))
9453     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9454 
9455   return SDValue();
9456 }
9457 
9458 // FIXME: FNEG and FABS have a lot in common; refactor.
9459 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9460   SDValue N0 = N->getOperand(0);
9461   EVT VT = N->getValueType(0);
9462 
9463   // Constant fold FNEG.
9464   if (isConstantFPBuildVectorOrConstantFP(N0))
9465     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9466 
9467   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9468                          &DAG.getTarget().Options))
9469     return GetNegatedExpression(N0, DAG, LegalOperations);
9470 
9471   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9472   // constant pool values.
9473   if (!TLI.isFNegFree(VT) &&
9474       N0.getOpcode() == ISD::BITCAST &&
9475       N0.getNode()->hasOneUse()) {
9476     SDValue Int = N0.getOperand(0);
9477     EVT IntVT = Int.getValueType();
9478     if (IntVT.isInteger() && !IntVT.isVector()) {
9479       APInt SignMask;
9480       if (N0.getValueType().isVector()) {
9481         // For a vector, get a mask such as 0x80... per scalar element
9482         // and splat it.
9483         SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits());
9484         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9485       } else {
9486         // For a scalar, just generate 0x80...
9487         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9488       }
9489       SDLoc DL0(N0);
9490       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9491                         DAG.getConstant(SignMask, DL0, IntVT));
9492       AddToWorklist(Int.getNode());
9493       return DAG.getBitcast(VT, Int);
9494     }
9495   }
9496 
9497   // (fneg (fmul c, x)) -> (fmul -c, x)
9498   if (N0.getOpcode() == ISD::FMUL &&
9499       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9500     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9501     if (CFP1) {
9502       APFloat CVal = CFP1->getValueAPF();
9503       CVal.changeSign();
9504       if (Level >= AfterLegalizeDAG &&
9505           (TLI.isFPImmLegal(CVal, VT) ||
9506            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9507         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9508                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9509                                        N0.getOperand(1)),
9510                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9511     }
9512   }
9513 
9514   return SDValue();
9515 }
9516 
9517 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9518   SDValue N0 = N->getOperand(0);
9519   SDValue N1 = N->getOperand(1);
9520   EVT VT = N->getValueType(0);
9521   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9522   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9523 
9524   if (N0CFP && N1CFP) {
9525     const APFloat &C0 = N0CFP->getValueAPF();
9526     const APFloat &C1 = N1CFP->getValueAPF();
9527     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9528   }
9529 
9530   // Canonicalize to constant on RHS.
9531   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9532      !isConstantFPBuildVectorOrConstantFP(N1))
9533     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9534 
9535   return SDValue();
9536 }
9537 
9538 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9539   SDValue N0 = N->getOperand(0);
9540   SDValue N1 = N->getOperand(1);
9541   EVT VT = N->getValueType(0);
9542   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9543   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9544 
9545   if (N0CFP && N1CFP) {
9546     const APFloat &C0 = N0CFP->getValueAPF();
9547     const APFloat &C1 = N1CFP->getValueAPF();
9548     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9549   }
9550 
9551   // Canonicalize to constant on RHS.
9552   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9553      !isConstantFPBuildVectorOrConstantFP(N1))
9554     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9555 
9556   return SDValue();
9557 }
9558 
9559 SDValue DAGCombiner::visitFABS(SDNode *N) {
9560   SDValue N0 = N->getOperand(0);
9561   EVT VT = N->getValueType(0);
9562 
9563   // fold (fabs c1) -> fabs(c1)
9564   if (isConstantFPBuildVectorOrConstantFP(N0))
9565     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9566 
9567   // fold (fabs (fabs x)) -> (fabs x)
9568   if (N0.getOpcode() == ISD::FABS)
9569     return N->getOperand(0);
9570 
9571   // fold (fabs (fneg x)) -> (fabs x)
9572   // fold (fabs (fcopysign x, y)) -> (fabs x)
9573   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9574     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9575 
9576   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9577   // constant pool values.
9578   if (!TLI.isFAbsFree(VT) &&
9579       N0.getOpcode() == ISD::BITCAST &&
9580       N0.getNode()->hasOneUse()) {
9581     SDValue Int = N0.getOperand(0);
9582     EVT IntVT = Int.getValueType();
9583     if (IntVT.isInteger() && !IntVT.isVector()) {
9584       APInt SignMask;
9585       if (N0.getValueType().isVector()) {
9586         // For a vector, get a mask such as 0x7f... per scalar element
9587         // and splat it.
9588         SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits());
9589         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9590       } else {
9591         // For a scalar, just generate 0x7f...
9592         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9593       }
9594       SDLoc DL(N0);
9595       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9596                         DAG.getConstant(SignMask, DL, IntVT));
9597       AddToWorklist(Int.getNode());
9598       return DAG.getBitcast(N->getValueType(0), Int);
9599     }
9600   }
9601 
9602   return SDValue();
9603 }
9604 
9605 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9606   SDValue Chain = N->getOperand(0);
9607   SDValue N1 = N->getOperand(1);
9608   SDValue N2 = N->getOperand(2);
9609 
9610   // If N is a constant we could fold this into a fallthrough or unconditional
9611   // branch. However that doesn't happen very often in normal code, because
9612   // Instcombine/SimplifyCFG should have handled the available opportunities.
9613   // If we did this folding here, it would be necessary to update the
9614   // MachineBasicBlock CFG, which is awkward.
9615 
9616   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9617   // on the target.
9618   if (N1.getOpcode() == ISD::SETCC &&
9619       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9620                                    N1.getOperand(0).getValueType())) {
9621     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9622                        Chain, N1.getOperand(2),
9623                        N1.getOperand(0), N1.getOperand(1), N2);
9624   }
9625 
9626   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9627       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9628        (N1.getOperand(0).hasOneUse() &&
9629         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9630     SDNode *Trunc = nullptr;
9631     if (N1.getOpcode() == ISD::TRUNCATE) {
9632       // Look pass the truncate.
9633       Trunc = N1.getNode();
9634       N1 = N1.getOperand(0);
9635     }
9636 
9637     // Match this pattern so that we can generate simpler code:
9638     //
9639     //   %a = ...
9640     //   %b = and i32 %a, 2
9641     //   %c = srl i32 %b, 1
9642     //   brcond i32 %c ...
9643     //
9644     // into
9645     //
9646     //   %a = ...
9647     //   %b = and i32 %a, 2
9648     //   %c = setcc eq %b, 0
9649     //   brcond %c ...
9650     //
9651     // This applies only when the AND constant value has one bit set and the
9652     // SRL constant is equal to the log2 of the AND constant. The back-end is
9653     // smart enough to convert the result into a TEST/JMP sequence.
9654     SDValue Op0 = N1.getOperand(0);
9655     SDValue Op1 = N1.getOperand(1);
9656 
9657     if (Op0.getOpcode() == ISD::AND &&
9658         Op1.getOpcode() == ISD::Constant) {
9659       SDValue AndOp1 = Op0.getOperand(1);
9660 
9661       if (AndOp1.getOpcode() == ISD::Constant) {
9662         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9663 
9664         if (AndConst.isPowerOf2() &&
9665             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9666           SDLoc DL(N);
9667           SDValue SetCC =
9668             DAG.getSetCC(DL,
9669                          getSetCCResultType(Op0.getValueType()),
9670                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9671                          ISD::SETNE);
9672 
9673           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9674                                           MVT::Other, Chain, SetCC, N2);
9675           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9676           // will convert it back to (X & C1) >> C2.
9677           CombineTo(N, NewBRCond, false);
9678           // Truncate is dead.
9679           if (Trunc)
9680             deleteAndRecombine(Trunc);
9681           // Replace the uses of SRL with SETCC
9682           WorklistRemover DeadNodes(*this);
9683           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9684           deleteAndRecombine(N1.getNode());
9685           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9686         }
9687       }
9688     }
9689 
9690     if (Trunc)
9691       // Restore N1 if the above transformation doesn't match.
9692       N1 = N->getOperand(1);
9693   }
9694 
9695   // Transform br(xor(x, y)) -> br(x != y)
9696   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9697   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9698     SDNode *TheXor = N1.getNode();
9699     SDValue Op0 = TheXor->getOperand(0);
9700     SDValue Op1 = TheXor->getOperand(1);
9701     if (Op0.getOpcode() == Op1.getOpcode()) {
9702       // Avoid missing important xor optimizations.
9703       if (SDValue Tmp = visitXOR(TheXor)) {
9704         if (Tmp.getNode() != TheXor) {
9705           DEBUG(dbgs() << "\nReplacing.8 ";
9706                 TheXor->dump(&DAG);
9707                 dbgs() << "\nWith: ";
9708                 Tmp.getNode()->dump(&DAG);
9709                 dbgs() << '\n');
9710           WorklistRemover DeadNodes(*this);
9711           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9712           deleteAndRecombine(TheXor);
9713           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9714                              MVT::Other, Chain, Tmp, N2);
9715         }
9716 
9717         // visitXOR has changed XOR's operands or replaced the XOR completely,
9718         // bail out.
9719         return SDValue(N, 0);
9720       }
9721     }
9722 
9723     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9724       bool Equal = false;
9725       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9726           Op0.getOpcode() == ISD::XOR) {
9727         TheXor = Op0.getNode();
9728         Equal = true;
9729       }
9730 
9731       EVT SetCCVT = N1.getValueType();
9732       if (LegalTypes)
9733         SetCCVT = getSetCCResultType(SetCCVT);
9734       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9735                                    SetCCVT,
9736                                    Op0, Op1,
9737                                    Equal ? ISD::SETEQ : ISD::SETNE);
9738       // Replace the uses of XOR with SETCC
9739       WorklistRemover DeadNodes(*this);
9740       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9741       deleteAndRecombine(N1.getNode());
9742       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9743                          MVT::Other, Chain, SetCC, N2);
9744     }
9745   }
9746 
9747   return SDValue();
9748 }
9749 
9750 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9751 //
9752 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9753   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9754   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9755 
9756   // If N is a constant we could fold this into a fallthrough or unconditional
9757   // branch. However that doesn't happen very often in normal code, because
9758   // Instcombine/SimplifyCFG should have handled the available opportunities.
9759   // If we did this folding here, it would be necessary to update the
9760   // MachineBasicBlock CFG, which is awkward.
9761 
9762   // Use SimplifySetCC to simplify SETCC's.
9763   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9764                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9765                                false);
9766   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9767 
9768   // fold to a simpler setcc
9769   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9770     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9771                        N->getOperand(0), Simp.getOperand(2),
9772                        Simp.getOperand(0), Simp.getOperand(1),
9773                        N->getOperand(4));
9774 
9775   return SDValue();
9776 }
9777 
9778 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9779 /// and that N may be folded in the load / store addressing mode.
9780 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9781                                     SelectionDAG &DAG,
9782                                     const TargetLowering &TLI) {
9783   EVT VT;
9784   unsigned AS;
9785 
9786   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9787     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9788       return false;
9789     VT = LD->getMemoryVT();
9790     AS = LD->getAddressSpace();
9791   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9792     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9793       return false;
9794     VT = ST->getMemoryVT();
9795     AS = ST->getAddressSpace();
9796   } else
9797     return false;
9798 
9799   TargetLowering::AddrMode AM;
9800   if (N->getOpcode() == ISD::ADD) {
9801     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9802     if (Offset)
9803       // [reg +/- imm]
9804       AM.BaseOffs = Offset->getSExtValue();
9805     else
9806       // [reg +/- reg]
9807       AM.Scale = 1;
9808   } else if (N->getOpcode() == ISD::SUB) {
9809     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9810     if (Offset)
9811       // [reg +/- imm]
9812       AM.BaseOffs = -Offset->getSExtValue();
9813     else
9814       // [reg +/- reg]
9815       AM.Scale = 1;
9816   } else
9817     return false;
9818 
9819   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9820                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9821 }
9822 
9823 /// Try turning a load/store into a pre-indexed load/store when the base
9824 /// pointer is an add or subtract and it has other uses besides the load/store.
9825 /// After the transformation, the new indexed load/store has effectively folded
9826 /// the add/subtract in and all of its other uses are redirected to the
9827 /// new load/store.
9828 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9829   if (Level < AfterLegalizeDAG)
9830     return false;
9831 
9832   bool isLoad = true;
9833   SDValue Ptr;
9834   EVT VT;
9835   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9836     if (LD->isIndexed())
9837       return false;
9838     VT = LD->getMemoryVT();
9839     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9840         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9841       return false;
9842     Ptr = LD->getBasePtr();
9843   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9844     if (ST->isIndexed())
9845       return false;
9846     VT = ST->getMemoryVT();
9847     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9848         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9849       return false;
9850     Ptr = ST->getBasePtr();
9851     isLoad = false;
9852   } else {
9853     return false;
9854   }
9855 
9856   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9857   // out.  There is no reason to make this a preinc/predec.
9858   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9859       Ptr.getNode()->hasOneUse())
9860     return false;
9861 
9862   // Ask the target to do addressing mode selection.
9863   SDValue BasePtr;
9864   SDValue Offset;
9865   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9866   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9867     return false;
9868 
9869   // Backends without true r+i pre-indexed forms may need to pass a
9870   // constant base with a variable offset so that constant coercion
9871   // will work with the patterns in canonical form.
9872   bool Swapped = false;
9873   if (isa<ConstantSDNode>(BasePtr)) {
9874     std::swap(BasePtr, Offset);
9875     Swapped = true;
9876   }
9877 
9878   // Don't create a indexed load / store with zero offset.
9879   if (isNullConstant(Offset))
9880     return false;
9881 
9882   // Try turning it into a pre-indexed load / store except when:
9883   // 1) The new base ptr is a frame index.
9884   // 2) If N is a store and the new base ptr is either the same as or is a
9885   //    predecessor of the value being stored.
9886   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9887   //    that would create a cycle.
9888   // 4) All uses are load / store ops that use it as old base ptr.
9889 
9890   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9891   // (plus the implicit offset) to a register to preinc anyway.
9892   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9893     return false;
9894 
9895   // Check #2.
9896   if (!isLoad) {
9897     SDValue Val = cast<StoreSDNode>(N)->getValue();
9898     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9899       return false;
9900   }
9901 
9902   // Caches for hasPredecessorHelper.
9903   SmallPtrSet<const SDNode *, 32> Visited;
9904   SmallVector<const SDNode *, 16> Worklist;
9905   Worklist.push_back(N);
9906 
9907   // If the offset is a constant, there may be other adds of constants that
9908   // can be folded with this one. We should do this to avoid having to keep
9909   // a copy of the original base pointer.
9910   SmallVector<SDNode *, 16> OtherUses;
9911   if (isa<ConstantSDNode>(Offset))
9912     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9913                               UE = BasePtr.getNode()->use_end();
9914          UI != UE; ++UI) {
9915       SDUse &Use = UI.getUse();
9916       // Skip the use that is Ptr and uses of other results from BasePtr's
9917       // node (important for nodes that return multiple results).
9918       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9919         continue;
9920 
9921       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9922         continue;
9923 
9924       if (Use.getUser()->getOpcode() != ISD::ADD &&
9925           Use.getUser()->getOpcode() != ISD::SUB) {
9926         OtherUses.clear();
9927         break;
9928       }
9929 
9930       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9931       if (!isa<ConstantSDNode>(Op1)) {
9932         OtherUses.clear();
9933         break;
9934       }
9935 
9936       // FIXME: In some cases, we can be smarter about this.
9937       if (Op1.getValueType() != Offset.getValueType()) {
9938         OtherUses.clear();
9939         break;
9940       }
9941 
9942       OtherUses.push_back(Use.getUser());
9943     }
9944 
9945   if (Swapped)
9946     std::swap(BasePtr, Offset);
9947 
9948   // Now check for #3 and #4.
9949   bool RealUse = false;
9950 
9951   for (SDNode *Use : Ptr.getNode()->uses()) {
9952     if (Use == N)
9953       continue;
9954     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9955       return false;
9956 
9957     // If Ptr may be folded in addressing mode of other use, then it's
9958     // not profitable to do this transformation.
9959     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9960       RealUse = true;
9961   }
9962 
9963   if (!RealUse)
9964     return false;
9965 
9966   SDValue Result;
9967   if (isLoad)
9968     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9969                                 BasePtr, Offset, AM);
9970   else
9971     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9972                                  BasePtr, Offset, AM);
9973   ++PreIndexedNodes;
9974   ++NodesCombined;
9975   DEBUG(dbgs() << "\nReplacing.4 ";
9976         N->dump(&DAG);
9977         dbgs() << "\nWith: ";
9978         Result.getNode()->dump(&DAG);
9979         dbgs() << '\n');
9980   WorklistRemover DeadNodes(*this);
9981   if (isLoad) {
9982     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9983     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9984   } else {
9985     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9986   }
9987 
9988   // Finally, since the node is now dead, remove it from the graph.
9989   deleteAndRecombine(N);
9990 
9991   if (Swapped)
9992     std::swap(BasePtr, Offset);
9993 
9994   // Replace other uses of BasePtr that can be updated to use Ptr
9995   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9996     unsigned OffsetIdx = 1;
9997     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9998       OffsetIdx = 0;
9999     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
10000            BasePtr.getNode() && "Expected BasePtr operand");
10001 
10002     // We need to replace ptr0 in the following expression:
10003     //   x0 * offset0 + y0 * ptr0 = t0
10004     // knowing that
10005     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
10006     //
10007     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
10008     // indexed load/store and the expresion that needs to be re-written.
10009     //
10010     // Therefore, we have:
10011     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
10012 
10013     ConstantSDNode *CN =
10014       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
10015     int X0, X1, Y0, Y1;
10016     const APInt &Offset0 = CN->getAPIntValue();
10017     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
10018 
10019     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
10020     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
10021     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
10022     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
10023 
10024     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
10025 
10026     APInt CNV = Offset0;
10027     if (X0 < 0) CNV = -CNV;
10028     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
10029     else CNV = CNV - Offset1;
10030 
10031     SDLoc DL(OtherUses[i]);
10032 
10033     // We can now generate the new expression.
10034     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
10035     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
10036 
10037     SDValue NewUse = DAG.getNode(Opcode,
10038                                  DL,
10039                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
10040     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
10041     deleteAndRecombine(OtherUses[i]);
10042   }
10043 
10044   // Replace the uses of Ptr with uses of the updated base value.
10045   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
10046   deleteAndRecombine(Ptr.getNode());
10047 
10048   return true;
10049 }
10050 
10051 /// Try to combine a load/store with a add/sub of the base pointer node into a
10052 /// post-indexed load/store. The transformation folded the add/subtract into the
10053 /// new indexed load/store effectively and all of its uses are redirected to the
10054 /// new load/store.
10055 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
10056   if (Level < AfterLegalizeDAG)
10057     return false;
10058 
10059   bool isLoad = true;
10060   SDValue Ptr;
10061   EVT VT;
10062   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10063     if (LD->isIndexed())
10064       return false;
10065     VT = LD->getMemoryVT();
10066     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
10067         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
10068       return false;
10069     Ptr = LD->getBasePtr();
10070   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10071     if (ST->isIndexed())
10072       return false;
10073     VT = ST->getMemoryVT();
10074     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
10075         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
10076       return false;
10077     Ptr = ST->getBasePtr();
10078     isLoad = false;
10079   } else {
10080     return false;
10081   }
10082 
10083   if (Ptr.getNode()->hasOneUse())
10084     return false;
10085 
10086   for (SDNode *Op : Ptr.getNode()->uses()) {
10087     if (Op == N ||
10088         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10089       continue;
10090 
10091     SDValue BasePtr;
10092     SDValue Offset;
10093     ISD::MemIndexedMode AM = ISD::UNINDEXED;
10094     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10095       // Don't create a indexed load / store with zero offset.
10096       if (isNullConstant(Offset))
10097         continue;
10098 
10099       // Try turning it into a post-indexed load / store except when
10100       // 1) All uses are load / store ops that use it as base ptr (and
10101       //    it may be folded as addressing mmode).
10102       // 2) Op must be independent of N, i.e. Op is neither a predecessor
10103       //    nor a successor of N. Otherwise, if Op is folded that would
10104       //    create a cycle.
10105 
10106       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10107         continue;
10108 
10109       // Check for #1.
10110       bool TryNext = false;
10111       for (SDNode *Use : BasePtr.getNode()->uses()) {
10112         if (Use == Ptr.getNode())
10113           continue;
10114 
10115         // If all the uses are load / store addresses, then don't do the
10116         // transformation.
10117         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10118           bool RealUse = false;
10119           for (SDNode *UseUse : Use->uses()) {
10120             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10121               RealUse = true;
10122           }
10123 
10124           if (!RealUse) {
10125             TryNext = true;
10126             break;
10127           }
10128         }
10129       }
10130 
10131       if (TryNext)
10132         continue;
10133 
10134       // Check for #2
10135       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10136         SDValue Result = isLoad
10137           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10138                                BasePtr, Offset, AM)
10139           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10140                                 BasePtr, Offset, AM);
10141         ++PostIndexedNodes;
10142         ++NodesCombined;
10143         DEBUG(dbgs() << "\nReplacing.5 ";
10144               N->dump(&DAG);
10145               dbgs() << "\nWith: ";
10146               Result.getNode()->dump(&DAG);
10147               dbgs() << '\n');
10148         WorklistRemover DeadNodes(*this);
10149         if (isLoad) {
10150           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10151           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10152         } else {
10153           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10154         }
10155 
10156         // Finally, since the node is now dead, remove it from the graph.
10157         deleteAndRecombine(N);
10158 
10159         // Replace the uses of Use with uses of the updated base value.
10160         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10161                                       Result.getValue(isLoad ? 1 : 0));
10162         deleteAndRecombine(Op);
10163         return true;
10164       }
10165     }
10166   }
10167 
10168   return false;
10169 }
10170 
10171 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10172 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10173   ISD::MemIndexedMode AM = LD->getAddressingMode();
10174   assert(AM != ISD::UNINDEXED);
10175   SDValue BP = LD->getOperand(1);
10176   SDValue Inc = LD->getOperand(2);
10177 
10178   // Some backends use TargetConstants for load offsets, but don't expect
10179   // TargetConstants in general ADD nodes. We can convert these constants into
10180   // regular Constants (if the constant is not opaque).
10181   assert((Inc.getOpcode() != ISD::TargetConstant ||
10182           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10183          "Cannot split out indexing using opaque target constants");
10184   if (Inc.getOpcode() == ISD::TargetConstant) {
10185     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10186     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10187                           ConstInc->getValueType(0));
10188   }
10189 
10190   unsigned Opc =
10191       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10192   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10193 }
10194 
10195 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10196   LoadSDNode *LD  = cast<LoadSDNode>(N);
10197   SDValue Chain = LD->getChain();
10198   SDValue Ptr   = LD->getBasePtr();
10199 
10200   // If load is not volatile and there are no uses of the loaded value (and
10201   // the updated indexed value in case of indexed loads), change uses of the
10202   // chain value into uses of the chain input (i.e. delete the dead load).
10203   if (!LD->isVolatile()) {
10204     if (N->getValueType(1) == MVT::Other) {
10205       // Unindexed loads.
10206       if (!N->hasAnyUseOfValue(0)) {
10207         // It's not safe to use the two value CombineTo variant here. e.g.
10208         // v1, chain2 = load chain1, loc
10209         // v2, chain3 = load chain2, loc
10210         // v3         = add v2, c
10211         // Now we replace use of chain2 with chain1.  This makes the second load
10212         // isomorphic to the one we are deleting, and thus makes this load live.
10213         DEBUG(dbgs() << "\nReplacing.6 ";
10214               N->dump(&DAG);
10215               dbgs() << "\nWith chain: ";
10216               Chain.getNode()->dump(&DAG);
10217               dbgs() << "\n");
10218         WorklistRemover DeadNodes(*this);
10219         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10220 
10221         if (N->use_empty())
10222           deleteAndRecombine(N);
10223 
10224         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10225       }
10226     } else {
10227       // Indexed loads.
10228       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10229 
10230       // If this load has an opaque TargetConstant offset, then we cannot split
10231       // the indexing into an add/sub directly (that TargetConstant may not be
10232       // valid for a different type of node, and we cannot convert an opaque
10233       // target constant into a regular constant).
10234       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10235                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10236 
10237       if (!N->hasAnyUseOfValue(0) &&
10238           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10239         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10240         SDValue Index;
10241         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10242           Index = SplitIndexingFromLoad(LD);
10243           // Try to fold the base pointer arithmetic into subsequent loads and
10244           // stores.
10245           AddUsersToWorklist(N);
10246         } else
10247           Index = DAG.getUNDEF(N->getValueType(1));
10248         DEBUG(dbgs() << "\nReplacing.7 ";
10249               N->dump(&DAG);
10250               dbgs() << "\nWith: ";
10251               Undef.getNode()->dump(&DAG);
10252               dbgs() << " and 2 other values\n");
10253         WorklistRemover DeadNodes(*this);
10254         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10255         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10256         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10257         deleteAndRecombine(N);
10258         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10259       }
10260     }
10261   }
10262 
10263   // If this load is directly stored, replace the load value with the stored
10264   // value.
10265   // TODO: Handle store large -> read small portion.
10266   // TODO: Handle TRUNCSTORE/LOADEXT
10267   if (OptLevel != CodeGenOpt::None &&
10268       ISD::isNormalLoad(N) && !LD->isVolatile()) {
10269     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10270       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10271       if (PrevST->getBasePtr() == Ptr &&
10272           PrevST->getValue().getValueType() == N->getValueType(0))
10273       return CombineTo(N, Chain.getOperand(1), Chain);
10274     }
10275   }
10276 
10277   // Try to infer better alignment information than the load already has.
10278   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10279     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10280       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10281         SDValue NewLoad = DAG.getExtLoad(
10282             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
10283             LD->getPointerInfo(), LD->getMemoryVT(), Align,
10284             LD->getMemOperand()->getFlags(), LD->getAAInfo());
10285         if (NewLoad.getNode() != N)
10286           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10287       }
10288     }
10289   }
10290 
10291   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10292                                                   : DAG.getSubtarget().useAA();
10293 #ifndef NDEBUG
10294   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10295       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10296     UseAA = false;
10297 #endif
10298   if (UseAA && LD->isUnindexed()) {
10299     // Walk up chain skipping non-aliasing memory nodes.
10300     SDValue BetterChain = FindBetterChain(N, Chain);
10301 
10302     // If there is a better chain.
10303     if (Chain != BetterChain) {
10304       SDValue ReplLoad;
10305 
10306       // Replace the chain to void dependency.
10307       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10308         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10309                                BetterChain, Ptr, LD->getMemOperand());
10310       } else {
10311         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10312                                   LD->getValueType(0),
10313                                   BetterChain, Ptr, LD->getMemoryVT(),
10314                                   LD->getMemOperand());
10315       }
10316 
10317       // Create token factor to keep old chain connected.
10318       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10319                                   MVT::Other, Chain, ReplLoad.getValue(1));
10320 
10321       // Make sure the new and old chains are cleaned up.
10322       AddToWorklist(Token.getNode());
10323 
10324       // Replace uses with load result and token factor. Don't add users
10325       // to work list.
10326       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10327     }
10328   }
10329 
10330   // Try transforming N to an indexed load.
10331   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10332     return SDValue(N, 0);
10333 
10334   // Try to slice up N to more direct loads if the slices are mapped to
10335   // different register banks or pairing can take place.
10336   if (SliceUpLoad(N))
10337     return SDValue(N, 0);
10338 
10339   return SDValue();
10340 }
10341 
10342 namespace {
10343 /// \brief Helper structure used to slice a load in smaller loads.
10344 /// Basically a slice is obtained from the following sequence:
10345 /// Origin = load Ty1, Base
10346 /// Shift = srl Ty1 Origin, CstTy Amount
10347 /// Inst = trunc Shift to Ty2
10348 ///
10349 /// Then, it will be rewriten into:
10350 /// Slice = load SliceTy, Base + SliceOffset
10351 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10352 ///
10353 /// SliceTy is deduced from the number of bits that are actually used to
10354 /// build Inst.
10355 struct LoadedSlice {
10356   /// \brief Helper structure used to compute the cost of a slice.
10357   struct Cost {
10358     /// Are we optimizing for code size.
10359     bool ForCodeSize;
10360     /// Various cost.
10361     unsigned Loads;
10362     unsigned Truncates;
10363     unsigned CrossRegisterBanksCopies;
10364     unsigned ZExts;
10365     unsigned Shift;
10366 
10367     Cost(bool ForCodeSize = false)
10368         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10369           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10370 
10371     /// \brief Get the cost of one isolated slice.
10372     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10373         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10374           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10375       EVT TruncType = LS.Inst->getValueType(0);
10376       EVT LoadedType = LS.getLoadedType();
10377       if (TruncType != LoadedType &&
10378           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10379         ZExts = 1;
10380     }
10381 
10382     /// \brief Account for slicing gain in the current cost.
10383     /// Slicing provide a few gains like removing a shift or a
10384     /// truncate. This method allows to grow the cost of the original
10385     /// load with the gain from this slice.
10386     void addSliceGain(const LoadedSlice &LS) {
10387       // Each slice saves a truncate.
10388       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10389       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10390                               LS.Inst->getValueType(0)))
10391         ++Truncates;
10392       // If there is a shift amount, this slice gets rid of it.
10393       if (LS.Shift)
10394         ++Shift;
10395       // If this slice can merge a cross register bank copy, account for it.
10396       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10397         ++CrossRegisterBanksCopies;
10398     }
10399 
10400     Cost &operator+=(const Cost &RHS) {
10401       Loads += RHS.Loads;
10402       Truncates += RHS.Truncates;
10403       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10404       ZExts += RHS.ZExts;
10405       Shift += RHS.Shift;
10406       return *this;
10407     }
10408 
10409     bool operator==(const Cost &RHS) const {
10410       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10411              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10412              ZExts == RHS.ZExts && Shift == RHS.Shift;
10413     }
10414 
10415     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10416 
10417     bool operator<(const Cost &RHS) const {
10418       // Assume cross register banks copies are as expensive as loads.
10419       // FIXME: Do we want some more target hooks?
10420       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10421       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10422       // Unless we are optimizing for code size, consider the
10423       // expensive operation first.
10424       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10425         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10426       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10427              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10428     }
10429 
10430     bool operator>(const Cost &RHS) const { return RHS < *this; }
10431 
10432     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10433 
10434     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10435   };
10436   // The last instruction that represent the slice. This should be a
10437   // truncate instruction.
10438   SDNode *Inst;
10439   // The original load instruction.
10440   LoadSDNode *Origin;
10441   // The right shift amount in bits from the original load.
10442   unsigned Shift;
10443   // The DAG from which Origin came from.
10444   // This is used to get some contextual information about legal types, etc.
10445   SelectionDAG *DAG;
10446 
10447   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10448               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10449       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10450 
10451   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10452   /// \return Result is \p BitWidth and has used bits set to 1 and
10453   ///         not used bits set to 0.
10454   APInt getUsedBits() const {
10455     // Reproduce the trunc(lshr) sequence:
10456     // - Start from the truncated value.
10457     // - Zero extend to the desired bit width.
10458     // - Shift left.
10459     assert(Origin && "No original load to compare against.");
10460     unsigned BitWidth = Origin->getValueSizeInBits(0);
10461     assert(Inst && "This slice is not bound to an instruction");
10462     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10463            "Extracted slice is bigger than the whole type!");
10464     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10465     UsedBits.setAllBits();
10466     UsedBits = UsedBits.zext(BitWidth);
10467     UsedBits <<= Shift;
10468     return UsedBits;
10469   }
10470 
10471   /// \brief Get the size of the slice to be loaded in bytes.
10472   unsigned getLoadedSize() const {
10473     unsigned SliceSize = getUsedBits().countPopulation();
10474     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10475     return SliceSize / 8;
10476   }
10477 
10478   /// \brief Get the type that will be loaded for this slice.
10479   /// Note: This may not be the final type for the slice.
10480   EVT getLoadedType() const {
10481     assert(DAG && "Missing context");
10482     LLVMContext &Ctxt = *DAG->getContext();
10483     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10484   }
10485 
10486   /// \brief Get the alignment of the load used for this slice.
10487   unsigned getAlignment() const {
10488     unsigned Alignment = Origin->getAlignment();
10489     unsigned Offset = getOffsetFromBase();
10490     if (Offset != 0)
10491       Alignment = MinAlign(Alignment, Alignment + Offset);
10492     return Alignment;
10493   }
10494 
10495   /// \brief Check if this slice can be rewritten with legal operations.
10496   bool isLegal() const {
10497     // An invalid slice is not legal.
10498     if (!Origin || !Inst || !DAG)
10499       return false;
10500 
10501     // Offsets are for indexed load only, we do not handle that.
10502     if (!Origin->getOffset().isUndef())
10503       return false;
10504 
10505     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10506 
10507     // Check that the type is legal.
10508     EVT SliceType = getLoadedType();
10509     if (!TLI.isTypeLegal(SliceType))
10510       return false;
10511 
10512     // Check that the load is legal for this type.
10513     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10514       return false;
10515 
10516     // Check that the offset can be computed.
10517     // 1. Check its type.
10518     EVT PtrType = Origin->getBasePtr().getValueType();
10519     if (PtrType == MVT::Untyped || PtrType.isExtended())
10520       return false;
10521 
10522     // 2. Check that it fits in the immediate.
10523     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10524       return false;
10525 
10526     // 3. Check that the computation is legal.
10527     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10528       return false;
10529 
10530     // Check that the zext is legal if it needs one.
10531     EVT TruncateType = Inst->getValueType(0);
10532     if (TruncateType != SliceType &&
10533         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10534       return false;
10535 
10536     return true;
10537   }
10538 
10539   /// \brief Get the offset in bytes of this slice in the original chunk of
10540   /// bits.
10541   /// \pre DAG != nullptr.
10542   uint64_t getOffsetFromBase() const {
10543     assert(DAG && "Missing context.");
10544     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10545     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10546     uint64_t Offset = Shift / 8;
10547     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10548     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10549            "The size of the original loaded type is not a multiple of a"
10550            " byte.");
10551     // If Offset is bigger than TySizeInBytes, it means we are loading all
10552     // zeros. This should have been optimized before in the process.
10553     assert(TySizeInBytes > Offset &&
10554            "Invalid shift amount for given loaded size");
10555     if (IsBigEndian)
10556       Offset = TySizeInBytes - Offset - getLoadedSize();
10557     return Offset;
10558   }
10559 
10560   /// \brief Generate the sequence of instructions to load the slice
10561   /// represented by this object and redirect the uses of this slice to
10562   /// this new sequence of instructions.
10563   /// \pre this->Inst && this->Origin are valid Instructions and this
10564   /// object passed the legal check: LoadedSlice::isLegal returned true.
10565   /// \return The last instruction of the sequence used to load the slice.
10566   SDValue loadSlice() const {
10567     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10568     const SDValue &OldBaseAddr = Origin->getBasePtr();
10569     SDValue BaseAddr = OldBaseAddr;
10570     // Get the offset in that chunk of bytes w.r.t. the endianess.
10571     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10572     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10573     if (Offset) {
10574       // BaseAddr = BaseAddr + Offset.
10575       EVT ArithType = BaseAddr.getValueType();
10576       SDLoc DL(Origin);
10577       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10578                               DAG->getConstant(Offset, DL, ArithType));
10579     }
10580 
10581     // Create the type of the loaded slice according to its size.
10582     EVT SliceType = getLoadedType();
10583 
10584     // Create the load for the slice.
10585     SDValue LastInst =
10586         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10587                      Origin->getPointerInfo().getWithOffset(Offset),
10588                      getAlignment(), Origin->getMemOperand()->getFlags());
10589     // If the final type is not the same as the loaded type, this means that
10590     // we have to pad with zero. Create a zero extend for that.
10591     EVT FinalType = Inst->getValueType(0);
10592     if (SliceType != FinalType)
10593       LastInst =
10594           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10595     return LastInst;
10596   }
10597 
10598   /// \brief Check if this slice can be merged with an expensive cross register
10599   /// bank copy. E.g.,
10600   /// i = load i32
10601   /// f = bitcast i32 i to float
10602   bool canMergeExpensiveCrossRegisterBankCopy() const {
10603     if (!Inst || !Inst->hasOneUse())
10604       return false;
10605     SDNode *Use = *Inst->use_begin();
10606     if (Use->getOpcode() != ISD::BITCAST)
10607       return false;
10608     assert(DAG && "Missing context");
10609     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10610     EVT ResVT = Use->getValueType(0);
10611     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10612     const TargetRegisterClass *ArgRC =
10613         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10614     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10615       return false;
10616 
10617     // At this point, we know that we perform a cross-register-bank copy.
10618     // Check if it is expensive.
10619     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10620     // Assume bitcasts are cheap, unless both register classes do not
10621     // explicitly share a common sub class.
10622     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10623       return false;
10624 
10625     // Check if it will be merged with the load.
10626     // 1. Check the alignment constraint.
10627     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10628         ResVT.getTypeForEVT(*DAG->getContext()));
10629 
10630     if (RequiredAlignment > getAlignment())
10631       return false;
10632 
10633     // 2. Check that the load is a legal operation for that type.
10634     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10635       return false;
10636 
10637     // 3. Check that we do not have a zext in the way.
10638     if (Inst->getValueType(0) != getLoadedType())
10639       return false;
10640 
10641     return true;
10642   }
10643 };
10644 }
10645 
10646 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10647 /// \p UsedBits looks like 0..0 1..1 0..0.
10648 static bool areUsedBitsDense(const APInt &UsedBits) {
10649   // If all the bits are one, this is dense!
10650   if (UsedBits.isAllOnesValue())
10651     return true;
10652 
10653   // Get rid of the unused bits on the right.
10654   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10655   // Get rid of the unused bits on the left.
10656   if (NarrowedUsedBits.countLeadingZeros())
10657     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10658   // Check that the chunk of bits is completely used.
10659   return NarrowedUsedBits.isAllOnesValue();
10660 }
10661 
10662 /// \brief Check whether or not \p First and \p Second are next to each other
10663 /// in memory. This means that there is no hole between the bits loaded
10664 /// by \p First and the bits loaded by \p Second.
10665 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10666                                      const LoadedSlice &Second) {
10667   assert(First.Origin == Second.Origin && First.Origin &&
10668          "Unable to match different memory origins.");
10669   APInt UsedBits = First.getUsedBits();
10670   assert((UsedBits & Second.getUsedBits()) == 0 &&
10671          "Slices are not supposed to overlap.");
10672   UsedBits |= Second.getUsedBits();
10673   return areUsedBitsDense(UsedBits);
10674 }
10675 
10676 /// \brief Adjust the \p GlobalLSCost according to the target
10677 /// paring capabilities and the layout of the slices.
10678 /// \pre \p GlobalLSCost should account for at least as many loads as
10679 /// there is in the slices in \p LoadedSlices.
10680 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10681                                  LoadedSlice::Cost &GlobalLSCost) {
10682   unsigned NumberOfSlices = LoadedSlices.size();
10683   // If there is less than 2 elements, no pairing is possible.
10684   if (NumberOfSlices < 2)
10685     return;
10686 
10687   // Sort the slices so that elements that are likely to be next to each
10688   // other in memory are next to each other in the list.
10689   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10690             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10691     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10692     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10693   });
10694   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10695   // First (resp. Second) is the first (resp. Second) potentially candidate
10696   // to be placed in a paired load.
10697   const LoadedSlice *First = nullptr;
10698   const LoadedSlice *Second = nullptr;
10699   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10700                 // Set the beginning of the pair.
10701                                                            First = Second) {
10702 
10703     Second = &LoadedSlices[CurrSlice];
10704 
10705     // If First is NULL, it means we start a new pair.
10706     // Get to the next slice.
10707     if (!First)
10708       continue;
10709 
10710     EVT LoadedType = First->getLoadedType();
10711 
10712     // If the types of the slices are different, we cannot pair them.
10713     if (LoadedType != Second->getLoadedType())
10714       continue;
10715 
10716     // Check if the target supplies paired loads for this type.
10717     unsigned RequiredAlignment = 0;
10718     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10719       // move to the next pair, this type is hopeless.
10720       Second = nullptr;
10721       continue;
10722     }
10723     // Check if we meet the alignment requirement.
10724     if (RequiredAlignment > First->getAlignment())
10725       continue;
10726 
10727     // Check that both loads are next to each other in memory.
10728     if (!areSlicesNextToEachOther(*First, *Second))
10729       continue;
10730 
10731     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10732     --GlobalLSCost.Loads;
10733     // Move to the next pair.
10734     Second = nullptr;
10735   }
10736 }
10737 
10738 /// \brief Check the profitability of all involved LoadedSlice.
10739 /// Currently, it is considered profitable if there is exactly two
10740 /// involved slices (1) which are (2) next to each other in memory, and
10741 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10742 ///
10743 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10744 /// the elements themselves.
10745 ///
10746 /// FIXME: When the cost model will be mature enough, we can relax
10747 /// constraints (1) and (2).
10748 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10749                                 const APInt &UsedBits, bool ForCodeSize) {
10750   unsigned NumberOfSlices = LoadedSlices.size();
10751   if (StressLoadSlicing)
10752     return NumberOfSlices > 1;
10753 
10754   // Check (1).
10755   if (NumberOfSlices != 2)
10756     return false;
10757 
10758   // Check (2).
10759   if (!areUsedBitsDense(UsedBits))
10760     return false;
10761 
10762   // Check (3).
10763   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10764   // The original code has one big load.
10765   OrigCost.Loads = 1;
10766   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10767     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10768     // Accumulate the cost of all the slices.
10769     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10770     GlobalSlicingCost += SliceCost;
10771 
10772     // Account as cost in the original configuration the gain obtained
10773     // with the current slices.
10774     OrigCost.addSliceGain(LS);
10775   }
10776 
10777   // If the target supports paired load, adjust the cost accordingly.
10778   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10779   return OrigCost > GlobalSlicingCost;
10780 }
10781 
10782 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10783 /// operations, split it in the various pieces being extracted.
10784 ///
10785 /// This sort of thing is introduced by SROA.
10786 /// This slicing takes care not to insert overlapping loads.
10787 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10788 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10789   if (Level < AfterLegalizeDAG)
10790     return false;
10791 
10792   LoadSDNode *LD = cast<LoadSDNode>(N);
10793   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10794       !LD->getValueType(0).isInteger())
10795     return false;
10796 
10797   // Keep track of already used bits to detect overlapping values.
10798   // In that case, we will just abort the transformation.
10799   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10800 
10801   SmallVector<LoadedSlice, 4> LoadedSlices;
10802 
10803   // Check if this load is used as several smaller chunks of bits.
10804   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10805   // of computation for each trunc.
10806   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10807        UI != UIEnd; ++UI) {
10808     // Skip the uses of the chain.
10809     if (UI.getUse().getResNo() != 0)
10810       continue;
10811 
10812     SDNode *User = *UI;
10813     unsigned Shift = 0;
10814 
10815     // Check if this is a trunc(lshr).
10816     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10817         isa<ConstantSDNode>(User->getOperand(1))) {
10818       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10819       User = *User->use_begin();
10820     }
10821 
10822     // At this point, User is a Truncate, iff we encountered, trunc or
10823     // trunc(lshr).
10824     if (User->getOpcode() != ISD::TRUNCATE)
10825       return false;
10826 
10827     // The width of the type must be a power of 2 and greater than 8-bits.
10828     // Otherwise the load cannot be represented in LLVM IR.
10829     // Moreover, if we shifted with a non-8-bits multiple, the slice
10830     // will be across several bytes. We do not support that.
10831     unsigned Width = User->getValueSizeInBits(0);
10832     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10833       return 0;
10834 
10835     // Build the slice for this chain of computations.
10836     LoadedSlice LS(User, LD, Shift, &DAG);
10837     APInt CurrentUsedBits = LS.getUsedBits();
10838 
10839     // Check if this slice overlaps with another.
10840     if ((CurrentUsedBits & UsedBits) != 0)
10841       return false;
10842     // Update the bits used globally.
10843     UsedBits |= CurrentUsedBits;
10844 
10845     // Check if the new slice would be legal.
10846     if (!LS.isLegal())
10847       return false;
10848 
10849     // Record the slice.
10850     LoadedSlices.push_back(LS);
10851   }
10852 
10853   // Abort slicing if it does not seem to be profitable.
10854   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10855     return false;
10856 
10857   ++SlicedLoads;
10858 
10859   // Rewrite each chain to use an independent load.
10860   // By construction, each chain can be represented by a unique load.
10861 
10862   // Prepare the argument for the new token factor for all the slices.
10863   SmallVector<SDValue, 8> ArgChains;
10864   for (SmallVectorImpl<LoadedSlice>::const_iterator
10865            LSIt = LoadedSlices.begin(),
10866            LSItEnd = LoadedSlices.end();
10867        LSIt != LSItEnd; ++LSIt) {
10868     SDValue SliceInst = LSIt->loadSlice();
10869     CombineTo(LSIt->Inst, SliceInst, true);
10870     if (SliceInst.getOpcode() != ISD::LOAD)
10871       SliceInst = SliceInst.getOperand(0);
10872     assert(SliceInst->getOpcode() == ISD::LOAD &&
10873            "It takes more than a zext to get to the loaded slice!!");
10874     ArgChains.push_back(SliceInst.getValue(1));
10875   }
10876 
10877   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10878                               ArgChains);
10879   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10880   return true;
10881 }
10882 
10883 /// Check to see if V is (and load (ptr), imm), where the load is having
10884 /// specific bytes cleared out.  If so, return the byte size being masked out
10885 /// and the shift amount.
10886 static std::pair<unsigned, unsigned>
10887 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10888   std::pair<unsigned, unsigned> Result(0, 0);
10889 
10890   // Check for the structure we're looking for.
10891   if (V->getOpcode() != ISD::AND ||
10892       !isa<ConstantSDNode>(V->getOperand(1)) ||
10893       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10894     return Result;
10895 
10896   // Check the chain and pointer.
10897   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10898   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10899 
10900   // The store should be chained directly to the load or be an operand of a
10901   // tokenfactor.
10902   if (LD == Chain.getNode())
10903     ; // ok.
10904   else if (Chain->getOpcode() != ISD::TokenFactor)
10905     return Result; // Fail.
10906   else {
10907     bool isOk = false;
10908     for (const SDValue &ChainOp : Chain->op_values())
10909       if (ChainOp.getNode() == LD) {
10910         isOk = true;
10911         break;
10912       }
10913     if (!isOk) return Result;
10914   }
10915 
10916   // This only handles simple types.
10917   if (V.getValueType() != MVT::i16 &&
10918       V.getValueType() != MVT::i32 &&
10919       V.getValueType() != MVT::i64)
10920     return Result;
10921 
10922   // Check the constant mask.  Invert it so that the bits being masked out are
10923   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10924   // follow the sign bit for uniformity.
10925   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10926   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10927   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10928   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10929   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10930   if (NotMaskLZ == 64) return Result;  // All zero mask.
10931 
10932   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10933   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10934     return Result;
10935 
10936   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10937   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10938     NotMaskLZ -= 64-V.getValueSizeInBits();
10939 
10940   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10941   switch (MaskedBytes) {
10942   case 1:
10943   case 2:
10944   case 4: break;
10945   default: return Result; // All one mask, or 5-byte mask.
10946   }
10947 
10948   // Verify that the first bit starts at a multiple of mask so that the access
10949   // is aligned the same as the access width.
10950   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10951 
10952   Result.first = MaskedBytes;
10953   Result.second = NotMaskTZ/8;
10954   return Result;
10955 }
10956 
10957 
10958 /// Check to see if IVal is something that provides a value as specified by
10959 /// MaskInfo. If so, replace the specified store with a narrower store of
10960 /// truncated IVal.
10961 static SDNode *
10962 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10963                                 SDValue IVal, StoreSDNode *St,
10964                                 DAGCombiner *DC) {
10965   unsigned NumBytes = MaskInfo.first;
10966   unsigned ByteShift = MaskInfo.second;
10967   SelectionDAG &DAG = DC->getDAG();
10968 
10969   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10970   // that uses this.  If not, this is not a replacement.
10971   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10972                                   ByteShift*8, (ByteShift+NumBytes)*8);
10973   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10974 
10975   // Check that it is legal on the target to do this.  It is legal if the new
10976   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10977   // legalization.
10978   MVT VT = MVT::getIntegerVT(NumBytes*8);
10979   if (!DC->isTypeLegal(VT))
10980     return nullptr;
10981 
10982   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10983   // shifted by ByteShift and truncated down to NumBytes.
10984   if (ByteShift) {
10985     SDLoc DL(IVal);
10986     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10987                        DAG.getConstant(ByteShift*8, DL,
10988                                     DC->getShiftAmountTy(IVal.getValueType())));
10989   }
10990 
10991   // Figure out the offset for the store and the alignment of the access.
10992   unsigned StOffset;
10993   unsigned NewAlign = St->getAlignment();
10994 
10995   if (DAG.getDataLayout().isLittleEndian())
10996     StOffset = ByteShift;
10997   else
10998     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10999 
11000   SDValue Ptr = St->getBasePtr();
11001   if (StOffset) {
11002     SDLoc DL(IVal);
11003     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11004                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11005     NewAlign = MinAlign(NewAlign, StOffset);
11006   }
11007 
11008   // Truncate down to the new size.
11009   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
11010 
11011   ++OpsNarrowed;
11012   return DAG
11013       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
11014                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
11015       .getNode();
11016 }
11017 
11018 
11019 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11020 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
11021 /// narrowing the load and store if it would end up being a win for performance
11022 /// or code size.
11023 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
11024   StoreSDNode *ST  = cast<StoreSDNode>(N);
11025   if (ST->isVolatile())
11026     return SDValue();
11027 
11028   SDValue Chain = ST->getChain();
11029   SDValue Value = ST->getValue();
11030   SDValue Ptr   = ST->getBasePtr();
11031   EVT VT = Value.getValueType();
11032 
11033   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
11034     return SDValue();
11035 
11036   unsigned Opc = Value.getOpcode();
11037 
11038   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
11039   // is a byte mask indicating a consecutive number of bytes, check to see if
11040   // Y is known to provide just those bytes.  If so, we try to replace the
11041   // load + replace + store sequence with a single (narrower) store, which makes
11042   // the load dead.
11043   if (Opc == ISD::OR) {
11044     std::pair<unsigned, unsigned> MaskedLoad;
11045     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
11046     if (MaskedLoad.first)
11047       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11048                                                   Value.getOperand(1), ST,this))
11049         return SDValue(NewST, 0);
11050 
11051     // Or is commutative, so try swapping X and Y.
11052     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
11053     if (MaskedLoad.first)
11054       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11055                                                   Value.getOperand(0), ST,this))
11056         return SDValue(NewST, 0);
11057   }
11058 
11059   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
11060       Value.getOperand(1).getOpcode() != ISD::Constant)
11061     return SDValue();
11062 
11063   SDValue N0 = Value.getOperand(0);
11064   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11065       Chain == SDValue(N0.getNode(), 1)) {
11066     LoadSDNode *LD = cast<LoadSDNode>(N0);
11067     if (LD->getBasePtr() != Ptr ||
11068         LD->getPointerInfo().getAddrSpace() !=
11069         ST->getPointerInfo().getAddrSpace())
11070       return SDValue();
11071 
11072     // Find the type to narrow it the load / op / store to.
11073     SDValue N1 = Value.getOperand(1);
11074     unsigned BitWidth = N1.getValueSizeInBits();
11075     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
11076     if (Opc == ISD::AND)
11077       Imm ^= APInt::getAllOnesValue(BitWidth);
11078     if (Imm == 0 || Imm.isAllOnesValue())
11079       return SDValue();
11080     unsigned ShAmt = Imm.countTrailingZeros();
11081     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
11082     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
11083     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11084     // The narrowing should be profitable, the load/store operation should be
11085     // legal (or custom) and the store size should be equal to the NewVT width.
11086     while (NewBW < BitWidth &&
11087            (NewVT.getStoreSizeInBits() != NewBW ||
11088             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11089             !TLI.isNarrowingProfitable(VT, NewVT))) {
11090       NewBW = NextPowerOf2(NewBW);
11091       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11092     }
11093     if (NewBW >= BitWidth)
11094       return SDValue();
11095 
11096     // If the lsb changed does not start at the type bitwidth boundary,
11097     // start at the previous one.
11098     if (ShAmt % NewBW)
11099       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11100     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11101                                    std::min(BitWidth, ShAmt + NewBW));
11102     if ((Imm & Mask) == Imm) {
11103       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11104       if (Opc == ISD::AND)
11105         NewImm ^= APInt::getAllOnesValue(NewBW);
11106       uint64_t PtrOff = ShAmt / 8;
11107       // For big endian targets, we need to adjust the offset to the pointer to
11108       // load the correct bytes.
11109       if (DAG.getDataLayout().isBigEndian())
11110         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11111 
11112       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11113       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11114       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11115         return SDValue();
11116 
11117       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11118                                    Ptr.getValueType(), Ptr,
11119                                    DAG.getConstant(PtrOff, SDLoc(LD),
11120                                                    Ptr.getValueType()));
11121       SDValue NewLD =
11122           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11123                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11124                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
11125       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11126                                    DAG.getConstant(NewImm, SDLoc(Value),
11127                                                    NewVT));
11128       SDValue NewST =
11129           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11130                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11131 
11132       AddToWorklist(NewPtr.getNode());
11133       AddToWorklist(NewLD.getNode());
11134       AddToWorklist(NewVal.getNode());
11135       WorklistRemover DeadNodes(*this);
11136       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11137       ++OpsNarrowed;
11138       return NewST;
11139     }
11140   }
11141 
11142   return SDValue();
11143 }
11144 
11145 /// For a given floating point load / store pair, if the load value isn't used
11146 /// by any other operations, then consider transforming the pair to integer
11147 /// load / store operations if the target deems the transformation profitable.
11148 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11149   StoreSDNode *ST  = cast<StoreSDNode>(N);
11150   SDValue Chain = ST->getChain();
11151   SDValue Value = ST->getValue();
11152   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11153       Value.hasOneUse() &&
11154       Chain == SDValue(Value.getNode(), 1)) {
11155     LoadSDNode *LD = cast<LoadSDNode>(Value);
11156     EVT VT = LD->getMemoryVT();
11157     if (!VT.isFloatingPoint() ||
11158         VT != ST->getMemoryVT() ||
11159         LD->isNonTemporal() ||
11160         ST->isNonTemporal() ||
11161         LD->getPointerInfo().getAddrSpace() != 0 ||
11162         ST->getPointerInfo().getAddrSpace() != 0)
11163       return SDValue();
11164 
11165     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11166     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11167         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11168         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11169         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11170       return SDValue();
11171 
11172     unsigned LDAlign = LD->getAlignment();
11173     unsigned STAlign = ST->getAlignment();
11174     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11175     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11176     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11177       return SDValue();
11178 
11179     SDValue NewLD =
11180         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
11181                     LD->getPointerInfo(), LDAlign);
11182 
11183     SDValue NewST =
11184         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
11185                      ST->getPointerInfo(), STAlign);
11186 
11187     AddToWorklist(NewLD.getNode());
11188     AddToWorklist(NewST.getNode());
11189     WorklistRemover DeadNodes(*this);
11190     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11191     ++LdStFP2Int;
11192     return NewST;
11193   }
11194 
11195   return SDValue();
11196 }
11197 
11198 namespace {
11199 /// Helper struct to parse and store a memory address as base + index + offset.
11200 /// We ignore sign extensions when it is safe to do so.
11201 /// The following two expressions are not equivalent. To differentiate we need
11202 /// to store whether there was a sign extension involved in the index
11203 /// computation.
11204 ///  (load (i64 add (i64 copyfromreg %c)
11205 ///                 (i64 signextend (add (i8 load %index)
11206 ///                                      (i8 1))))
11207 /// vs
11208 ///
11209 /// (load (i64 add (i64 copyfromreg %c)
11210 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11211 ///                                         (i32 1)))))
11212 struct BaseIndexOffset {
11213   SDValue Base;
11214   SDValue Index;
11215   int64_t Offset;
11216   bool IsIndexSignExt;
11217 
11218   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11219 
11220   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11221                   bool IsIndexSignExt) :
11222     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11223 
11224   bool equalBaseIndex(const BaseIndexOffset &Other) {
11225     return Other.Base == Base && Other.Index == Index &&
11226       Other.IsIndexSignExt == IsIndexSignExt;
11227   }
11228 
11229   /// Parses tree in Ptr for base, index, offset addresses.
11230   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11231     bool IsIndexSignExt = false;
11232 
11233     // Split up a folded GlobalAddress+Offset into its component parts.
11234     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11235       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11236         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11237                                                     SDLoc(GA),
11238                                                     GA->getValueType(0),
11239                                                     /*Offset=*/0,
11240                                                     /*isTargetGA=*/false,
11241                                                     GA->getTargetFlags()),
11242                                SDValue(),
11243                                GA->getOffset(),
11244                                IsIndexSignExt);
11245       }
11246 
11247     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11248     // instruction, then it could be just the BASE or everything else we don't
11249     // know how to handle. Just use Ptr as BASE and give up.
11250     if (Ptr->getOpcode() != ISD::ADD)
11251       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11252 
11253     // We know that we have at least an ADD instruction. Try to pattern match
11254     // the simple case of BASE + OFFSET.
11255     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11256       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11257       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11258                               IsIndexSignExt);
11259     }
11260 
11261     // Inside a loop the current BASE pointer is calculated using an ADD and a
11262     // MUL instruction. In this case Ptr is the actual BASE pointer.
11263     // (i64 add (i64 %array_ptr)
11264     //          (i64 mul (i64 %induction_var)
11265     //                   (i64 %element_size)))
11266     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11267       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11268 
11269     // Look at Base + Index + Offset cases.
11270     SDValue Base = Ptr->getOperand(0);
11271     SDValue IndexOffset = Ptr->getOperand(1);
11272 
11273     // Skip signextends.
11274     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11275       IndexOffset = IndexOffset->getOperand(0);
11276       IsIndexSignExt = true;
11277     }
11278 
11279     // Either the case of Base + Index (no offset) or something else.
11280     if (IndexOffset->getOpcode() != ISD::ADD)
11281       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11282 
11283     // Now we have the case of Base + Index + offset.
11284     SDValue Index = IndexOffset->getOperand(0);
11285     SDValue Offset = IndexOffset->getOperand(1);
11286 
11287     if (!isa<ConstantSDNode>(Offset))
11288       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11289 
11290     // Ignore signextends.
11291     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11292       Index = Index->getOperand(0);
11293       IsIndexSignExt = true;
11294     } else IsIndexSignExt = false;
11295 
11296     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11297     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11298   }
11299 };
11300 } // namespace
11301 
11302 // This is a helper function for visitMUL to check the profitability
11303 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11304 // MulNode is the original multiply, AddNode is (add x, c1),
11305 // and ConstNode is c2.
11306 //
11307 // If the (add x, c1) has multiple uses, we could increase
11308 // the number of adds if we make this transformation.
11309 // It would only be worth doing this if we can remove a
11310 // multiply in the process. Check for that here.
11311 // To illustrate:
11312 //     (A + c1) * c3
11313 //     (A + c2) * c3
11314 // We're checking for cases where we have common "c3 * A" expressions.
11315 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11316                                               SDValue &AddNode,
11317                                               SDValue &ConstNode) {
11318   APInt Val;
11319 
11320   // If the add only has one use, this would be OK to do.
11321   if (AddNode.getNode()->hasOneUse())
11322     return true;
11323 
11324   // Walk all the users of the constant with which we're multiplying.
11325   for (SDNode *Use : ConstNode->uses()) {
11326 
11327     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11328       continue;
11329 
11330     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11331       SDNode *OtherOp;
11332       SDNode *MulVar = AddNode.getOperand(0).getNode();
11333 
11334       // OtherOp is what we're multiplying against the constant.
11335       if (Use->getOperand(0) == ConstNode)
11336         OtherOp = Use->getOperand(1).getNode();
11337       else
11338         OtherOp = Use->getOperand(0).getNode();
11339 
11340       // Check to see if multiply is with the same operand of our "add".
11341       //
11342       //     ConstNode  = CONST
11343       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11344       //     ...
11345       //     AddNode  = (A + c1)  <-- MulVar is A.
11346       //         = AddNode * ConstNode   <-- current visiting instruction.
11347       //
11348       // If we make this transformation, we will have a common
11349       // multiply (ConstNode * A) that we can save.
11350       if (OtherOp == MulVar)
11351         return true;
11352 
11353       // Now check to see if a future expansion will give us a common
11354       // multiply.
11355       //
11356       //     ConstNode  = CONST
11357       //     AddNode    = (A + c1)
11358       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11359       //     ...
11360       //     OtherOp = (A + c2)
11361       //     Use     = OtherOp * ConstNode <-- visiting Use.
11362       //
11363       // If we make this transformation, we will have a common
11364       // multiply (CONST * A) after we also do the same transformation
11365       // to the "t2" instruction.
11366       if (OtherOp->getOpcode() == ISD::ADD &&
11367           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11368           OtherOp->getOperand(0).getNode() == MulVar)
11369         return true;
11370     }
11371   }
11372 
11373   // Didn't find a case where this would be profitable.
11374   return false;
11375 }
11376 
11377 SDValue DAGCombiner::getMergedConstantVectorStore(
11378     SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11379     SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11380   SmallVector<SDValue, 8> BuildVector;
11381 
11382   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11383     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11384     Chains.push_back(St->getChain());
11385     BuildVector.push_back(St->getValue());
11386   }
11387 
11388   return DAG.getBuildVector(Ty, SL, BuildVector);
11389 }
11390 
11391 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11392                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11393                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11394   // Make sure we have something to merge.
11395   if (NumStores < 2)
11396     return false;
11397 
11398   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11399   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11400   unsigned LatestNodeUsed = 0;
11401 
11402   for (unsigned i=0; i < NumStores; ++i) {
11403     // Find a chain for the new wide-store operand. Notice that some
11404     // of the store nodes that we found may not be selected for inclusion
11405     // in the wide store. The chain we use needs to be the chain of the
11406     // latest store node which is *used* and replaced by the wide store.
11407     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11408       LatestNodeUsed = i;
11409   }
11410 
11411   SmallVector<SDValue, 8> Chains;
11412 
11413   // The latest Node in the DAG.
11414   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11415   SDLoc DL(StoreNodes[0].MemNode);
11416 
11417   SDValue StoredVal;
11418   if (UseVector) {
11419     bool IsVec = MemVT.isVector();
11420     unsigned Elts = NumStores;
11421     if (IsVec) {
11422       // When merging vector stores, get the total number of elements.
11423       Elts *= MemVT.getVectorNumElements();
11424     }
11425     // Get the type for the merged vector store.
11426     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11427     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11428 
11429     if (IsConstantSrc) {
11430       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11431     } else {
11432       SmallVector<SDValue, 8> Ops;
11433       for (unsigned i = 0; i < NumStores; ++i) {
11434         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11435         SDValue Val = St->getValue();
11436         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11437         if (Val.getValueType() != MemVT)
11438           return false;
11439         Ops.push_back(Val);
11440         Chains.push_back(St->getChain());
11441       }
11442 
11443       // Build the extracted vector elements back into a vector.
11444       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11445                               DL, Ty, Ops);    }
11446   } else {
11447     // We should always use a vector store when merging extracted vector
11448     // elements, so this path implies a store of constants.
11449     assert(IsConstantSrc && "Merged vector elements should use vector store");
11450 
11451     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11452     APInt StoreInt(SizeInBits, 0);
11453 
11454     // Construct a single integer constant which is made of the smaller
11455     // constant inputs.
11456     bool IsLE = DAG.getDataLayout().isLittleEndian();
11457     for (unsigned i = 0; i < NumStores; ++i) {
11458       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11459       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11460       Chains.push_back(St->getChain());
11461 
11462       SDValue Val = St->getValue();
11463       StoreInt <<= ElementSizeBytes * 8;
11464       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11465         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11466       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11467         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11468       } else {
11469         llvm_unreachable("Invalid constant element type");
11470       }
11471     }
11472 
11473     // Create the new Load and Store operations.
11474     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11475     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11476   }
11477 
11478   assert(!Chains.empty());
11479 
11480   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11481   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11482                                   FirstInChain->getBasePtr(),
11483                                   FirstInChain->getPointerInfo(),
11484                                   FirstInChain->getAlignment());
11485 
11486   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11487                                                   : DAG.getSubtarget().useAA();
11488   if (UseAA) {
11489     // Replace all merged stores with the new store.
11490     for (unsigned i = 0; i < NumStores; ++i)
11491       CombineTo(StoreNodes[i].MemNode, NewStore);
11492   } else {
11493     // Replace the last store with the new store.
11494     CombineTo(LatestOp, NewStore);
11495     // Erase all other stores.
11496     for (unsigned i = 0; i < NumStores; ++i) {
11497       if (StoreNodes[i].MemNode == LatestOp)
11498         continue;
11499       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11500       // ReplaceAllUsesWith will replace all uses that existed when it was
11501       // called, but graph optimizations may cause new ones to appear. For
11502       // example, the case in pr14333 looks like
11503       //
11504       //  St's chain -> St -> another store -> X
11505       //
11506       // And the only difference from St to the other store is the chain.
11507       // When we change it's chain to be St's chain they become identical,
11508       // get CSEed and the net result is that X is now a use of St.
11509       // Since we know that St is redundant, just iterate.
11510       while (!St->use_empty())
11511         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11512       deleteAndRecombine(St);
11513     }
11514   }
11515 
11516   return true;
11517 }
11518 
11519 void DAGCombiner::getStoreMergeAndAliasCandidates(
11520     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11521     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11522   // This holds the base pointer, index, and the offset in bytes from the base
11523   // pointer.
11524   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11525 
11526   // We must have a base and an offset.
11527   if (!BasePtr.Base.getNode())
11528     return;
11529 
11530   // Do not handle stores to undef base pointers.
11531   if (BasePtr.Base.isUndef())
11532     return;
11533 
11534   // Walk up the chain and look for nodes with offsets from the same
11535   // base pointer. Stop when reaching an instruction with a different kind
11536   // or instruction which has a different base pointer.
11537   EVT MemVT = St->getMemoryVT();
11538   unsigned Seq = 0;
11539   StoreSDNode *Index = St;
11540 
11541 
11542   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11543                                                   : DAG.getSubtarget().useAA();
11544 
11545   if (UseAA) {
11546     // Look at other users of the same chain. Stores on the same chain do not
11547     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11548     // to be on the same chain, so don't bother looking at adjacent chains.
11549 
11550     SDValue Chain = St->getChain();
11551     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11552       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11553         if (I.getOperandNo() != 0)
11554           continue;
11555 
11556         if (OtherST->isVolatile() || OtherST->isIndexed())
11557           continue;
11558 
11559         if (OtherST->getMemoryVT() != MemVT)
11560           continue;
11561 
11562         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11563 
11564         if (Ptr.equalBaseIndex(BasePtr))
11565           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11566       }
11567     }
11568 
11569     return;
11570   }
11571 
11572   while (Index) {
11573     // If the chain has more than one use, then we can't reorder the mem ops.
11574     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11575       break;
11576 
11577     // Find the base pointer and offset for this memory node.
11578     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11579 
11580     // Check that the base pointer is the same as the original one.
11581     if (!Ptr.equalBaseIndex(BasePtr))
11582       break;
11583 
11584     // The memory operands must not be volatile.
11585     if (Index->isVolatile() || Index->isIndexed())
11586       break;
11587 
11588     // No truncation.
11589     if (Index->isTruncatingStore())
11590       break;
11591 
11592     // The stored memory type must be the same.
11593     if (Index->getMemoryVT() != MemVT)
11594       break;
11595 
11596     // We do not allow under-aligned stores in order to prevent
11597     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11598     // be irrelevant here; what MATTERS is that we not move memory
11599     // operations that potentially overlap past each-other.
11600     if (Index->getAlignment() < MemVT.getStoreSize())
11601       break;
11602 
11603     // We found a potential memory operand to merge.
11604     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11605 
11606     // Find the next memory operand in the chain. If the next operand in the
11607     // chain is a store then move up and continue the scan with the next
11608     // memory operand. If the next operand is a load save it and use alias
11609     // information to check if it interferes with anything.
11610     SDNode *NextInChain = Index->getChain().getNode();
11611     while (1) {
11612       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11613         // We found a store node. Use it for the next iteration.
11614         Index = STn;
11615         break;
11616       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11617         if (Ldn->isVolatile()) {
11618           Index = nullptr;
11619           break;
11620         }
11621 
11622         // Save the load node for later. Continue the scan.
11623         AliasLoadNodes.push_back(Ldn);
11624         NextInChain = Ldn->getChain().getNode();
11625         continue;
11626       } else {
11627         Index = nullptr;
11628         break;
11629       }
11630     }
11631   }
11632 }
11633 
11634 // We need to check that merging these stores does not cause a loop
11635 // in the DAG. Any store candidate may depend on another candidate
11636 // indirectly through its operand (we already consider dependencies
11637 // through the chain). Check in parallel by searching up from
11638 // non-chain operands of candidates.
11639 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11640     SmallVectorImpl<MemOpLink> &StoreNodes) {
11641   SmallPtrSet<const SDNode *, 16> Visited;
11642   SmallVector<const SDNode *, 8> Worklist;
11643   // search ops of store candidates
11644   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11645     SDNode *n = StoreNodes[i].MemNode;
11646     // Potential loops may happen only through non-chain operands
11647     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11648       Worklist.push_back(n->getOperand(j).getNode());
11649   }
11650   // search through DAG. We can stop early if we find a storenode
11651   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11652     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11653       return false;
11654   }
11655   return true;
11656 }
11657 
11658 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11659   if (OptLevel == CodeGenOpt::None)
11660     return false;
11661 
11662   EVT MemVT = St->getMemoryVT();
11663   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11664   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11665       Attribute::NoImplicitFloat);
11666 
11667   // This function cannot currently deal with non-byte-sized memory sizes.
11668   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11669     return false;
11670 
11671   if (!MemVT.isSimple())
11672     return false;
11673 
11674   // Perform an early exit check. Do not bother looking at stored values that
11675   // are not constants, loads, or extracted vector elements.
11676   SDValue StoredVal = St->getValue();
11677   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11678   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11679                        isa<ConstantFPSDNode>(StoredVal);
11680   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11681                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11682 
11683   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11684     return false;
11685 
11686   // Don't merge vectors into wider vectors if the source data comes from loads.
11687   // TODO: This restriction can be lifted by using logic similar to the
11688   // ExtractVecSrc case.
11689   if (MemVT.isVector() && IsLoadSrc)
11690     return false;
11691 
11692   // Only look at ends of store sequences.
11693   SDValue Chain = SDValue(St, 0);
11694   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11695     return false;
11696 
11697   // Save the LoadSDNodes that we find in the chain.
11698   // We need to make sure that these nodes do not interfere with
11699   // any of the store nodes.
11700   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11701 
11702   // Save the StoreSDNodes that we find in the chain.
11703   SmallVector<MemOpLink, 8> StoreNodes;
11704 
11705   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11706 
11707   // Check if there is anything to merge.
11708   if (StoreNodes.size() < 2)
11709     return false;
11710 
11711   // only do dependence check in AA case
11712   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11713                                                   : DAG.getSubtarget().useAA();
11714   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11715     return false;
11716 
11717   // Sort the memory operands according to their distance from the
11718   // base pointer.  As a secondary criteria: make sure stores coming
11719   // later in the code come first in the list. This is important for
11720   // the non-UseAA case, because we're merging stores into the FINAL
11721   // store along a chain which potentially contains aliasing stores.
11722   // Thus, if there are multiple stores to the same address, the last
11723   // one can be considered for merging but not the others.
11724   std::sort(StoreNodes.begin(), StoreNodes.end(),
11725             [](MemOpLink LHS, MemOpLink RHS) {
11726     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11727            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11728             LHS.SequenceNum < RHS.SequenceNum);
11729   });
11730 
11731   // Scan the memory operations on the chain and find the first non-consecutive
11732   // store memory address.
11733   unsigned LastConsecutiveStore = 0;
11734   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11735   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11736 
11737     // Check that the addresses are consecutive starting from the second
11738     // element in the list of stores.
11739     if (i > 0) {
11740       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11741       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11742         break;
11743     }
11744 
11745     // Check if this store interferes with any of the loads that we found.
11746     // If we find a load that alias with this store. Stop the sequence.
11747     if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) {
11748           return isAlias(Ldn, StoreNodes[i].MemNode);
11749         }))
11750       break;
11751 
11752     // Mark this node as useful.
11753     LastConsecutiveStore = i;
11754   }
11755 
11756   // The node with the lowest store address.
11757   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11758   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11759   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11760   LLVMContext &Context = *DAG.getContext();
11761   const DataLayout &DL = DAG.getDataLayout();
11762 
11763   // Store the constants into memory as one consecutive store.
11764   if (IsConstantSrc) {
11765     unsigned LastLegalType = 0;
11766     unsigned LastLegalVectorType = 0;
11767     bool NonZero = false;
11768     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11769       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11770       SDValue StoredVal = St->getValue();
11771 
11772       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11773         NonZero |= !C->isNullValue();
11774       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11775         NonZero |= !C->getConstantFPValue()->isNullValue();
11776       } else {
11777         // Non-constant.
11778         break;
11779       }
11780 
11781       // Find a legal type for the constant store.
11782       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11783       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11784       bool IsFast;
11785       if (TLI.isTypeLegal(StoreTy) &&
11786           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11787                                  FirstStoreAlign, &IsFast) && IsFast) {
11788         LastLegalType = i+1;
11789       // Or check whether a truncstore is legal.
11790       } else if (TLI.getTypeAction(Context, StoreTy) ==
11791                  TargetLowering::TypePromoteInteger) {
11792         EVT LegalizedStoredValueTy =
11793           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11794         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11795             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11796                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11797             IsFast) {
11798           LastLegalType = i + 1;
11799         }
11800       }
11801 
11802       // We only use vectors if the constant is known to be zero or the target
11803       // allows it and the function is not marked with the noimplicitfloat
11804       // attribute.
11805       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11806                                                         FirstStoreAS)) &&
11807           !NoVectors) {
11808         // Find a legal type for the vector store.
11809         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11810         if (TLI.isTypeLegal(Ty) &&
11811             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11812                                    FirstStoreAlign, &IsFast) && IsFast)
11813           LastLegalVectorType = i + 1;
11814       }
11815     }
11816 
11817     // Check if we found a legal integer type to store.
11818     if (LastLegalType == 0 && LastLegalVectorType == 0)
11819       return false;
11820 
11821     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11822     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11823 
11824     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11825                                            true, UseVector);
11826   }
11827 
11828   // When extracting multiple vector elements, try to store them
11829   // in one vector store rather than a sequence of scalar stores.
11830   if (IsExtractVecSrc) {
11831     unsigned NumStoresToMerge = 0;
11832     bool IsVec = MemVT.isVector();
11833     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11834       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11835       unsigned StoreValOpcode = St->getValue().getOpcode();
11836       // This restriction could be loosened.
11837       // Bail out if any stored values are not elements extracted from a vector.
11838       // It should be possible to handle mixed sources, but load sources need
11839       // more careful handling (see the block of code below that handles
11840       // consecutive loads).
11841       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11842           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11843         return false;
11844 
11845       // Find a legal type for the vector store.
11846       unsigned Elts = i + 1;
11847       if (IsVec) {
11848         // When merging vector stores, get the total number of elements.
11849         Elts *= MemVT.getVectorNumElements();
11850       }
11851       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11852       bool IsFast;
11853       if (TLI.isTypeLegal(Ty) &&
11854           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11855                                  FirstStoreAlign, &IsFast) && IsFast)
11856         NumStoresToMerge = i + 1;
11857     }
11858 
11859     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11860                                            false, true);
11861   }
11862 
11863   // Below we handle the case of multiple consecutive stores that
11864   // come from multiple consecutive loads. We merge them into a single
11865   // wide load and a single wide store.
11866 
11867   // Look for load nodes which are used by the stored values.
11868   SmallVector<MemOpLink, 8> LoadNodes;
11869 
11870   // Find acceptable loads. Loads need to have the same chain (token factor),
11871   // must not be zext, volatile, indexed, and they must be consecutive.
11872   BaseIndexOffset LdBasePtr;
11873   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11874     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11875     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11876     if (!Ld) break;
11877 
11878     // Loads must only have one use.
11879     if (!Ld->hasNUsesOfValue(1, 0))
11880       break;
11881 
11882     // The memory operands must not be volatile.
11883     if (Ld->isVolatile() || Ld->isIndexed())
11884       break;
11885 
11886     // We do not accept ext loads.
11887     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11888       break;
11889 
11890     // The stored memory type must be the same.
11891     if (Ld->getMemoryVT() != MemVT)
11892       break;
11893 
11894     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11895     // If this is not the first ptr that we check.
11896     if (LdBasePtr.Base.getNode()) {
11897       // The base ptr must be the same.
11898       if (!LdPtr.equalBaseIndex(LdBasePtr))
11899         break;
11900     } else {
11901       // Check that all other base pointers are the same as this one.
11902       LdBasePtr = LdPtr;
11903     }
11904 
11905     // We found a potential memory operand to merge.
11906     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11907   }
11908 
11909   if (LoadNodes.size() < 2)
11910     return false;
11911 
11912   // If we have load/store pair instructions and we only have two values,
11913   // don't bother.
11914   unsigned RequiredAlignment;
11915   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11916       St->getAlignment() >= RequiredAlignment)
11917     return false;
11918 
11919   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11920   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11921   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11922 
11923   // Scan the memory operations on the chain and find the first non-consecutive
11924   // load memory address. These variables hold the index in the store node
11925   // array.
11926   unsigned LastConsecutiveLoad = 0;
11927   // This variable refers to the size and not index in the array.
11928   unsigned LastLegalVectorType = 0;
11929   unsigned LastLegalIntegerType = 0;
11930   StartAddress = LoadNodes[0].OffsetFromBase;
11931   SDValue FirstChain = FirstLoad->getChain();
11932   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11933     // All loads must share the same chain.
11934     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11935       break;
11936 
11937     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11938     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11939       break;
11940     LastConsecutiveLoad = i;
11941     // Find a legal type for the vector store.
11942     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11943     bool IsFastSt, IsFastLd;
11944     if (TLI.isTypeLegal(StoreTy) &&
11945         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11946                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11947         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11948                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11949       LastLegalVectorType = i + 1;
11950     }
11951 
11952     // Find a legal type for the integer store.
11953     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11954     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11955     if (TLI.isTypeLegal(StoreTy) &&
11956         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11957                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11958         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11959                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11960       LastLegalIntegerType = i + 1;
11961     // Or check whether a truncstore and extload is legal.
11962     else if (TLI.getTypeAction(Context, StoreTy) ==
11963              TargetLowering::TypePromoteInteger) {
11964       EVT LegalizedStoredValueTy =
11965         TLI.getTypeToTransformTo(Context, StoreTy);
11966       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11967           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11968           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11969           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11970           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11971                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11972           IsFastSt &&
11973           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11974                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11975           IsFastLd)
11976         LastLegalIntegerType = i+1;
11977     }
11978   }
11979 
11980   // Only use vector types if the vector type is larger than the integer type.
11981   // If they are the same, use integers.
11982   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11983   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11984 
11985   // We add +1 here because the LastXXX variables refer to location while
11986   // the NumElem refers to array/index size.
11987   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11988   NumElem = std::min(LastLegalType, NumElem);
11989 
11990   if (NumElem < 2)
11991     return false;
11992 
11993   // Collect the chains from all merged stores.
11994   SmallVector<SDValue, 8> MergeStoreChains;
11995   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11996 
11997   // The latest Node in the DAG.
11998   unsigned LatestNodeUsed = 0;
11999   for (unsigned i=1; i<NumElem; ++i) {
12000     // Find a chain for the new wide-store operand. Notice that some
12001     // of the store nodes that we found may not be selected for inclusion
12002     // in the wide store. The chain we use needs to be the chain of the
12003     // latest store node which is *used* and replaced by the wide store.
12004     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
12005       LatestNodeUsed = i;
12006 
12007     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
12008   }
12009 
12010   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
12011 
12012   // Find if it is better to use vectors or integers to load and store
12013   // to memory.
12014   EVT JointMemOpVT;
12015   if (UseVectorTy) {
12016     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12017   } else {
12018     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12019     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12020   }
12021 
12022   SDLoc LoadDL(LoadNodes[0].MemNode);
12023   SDLoc StoreDL(StoreNodes[0].MemNode);
12024 
12025   // The merged loads are required to have the same incoming chain, so
12026   // using the first's chain is acceptable.
12027   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12028                                 FirstLoad->getBasePtr(),
12029                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
12030 
12031   SDValue NewStoreChain =
12032     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
12033 
12034   SDValue NewStore =
12035       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12036                    FirstInChain->getPointerInfo(), FirstStoreAlign);
12037 
12038   // Transfer chain users from old loads to the new load.
12039   for (unsigned i = 0; i < NumElem; ++i) {
12040     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12041     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12042                                   SDValue(NewLoad.getNode(), 1));
12043   }
12044 
12045   if (UseAA) {
12046     // Replace the all stores with the new store.
12047     for (unsigned i = 0; i < NumElem; ++i)
12048       CombineTo(StoreNodes[i].MemNode, NewStore);
12049   } else {
12050     // Replace the last store with the new store.
12051     CombineTo(LatestOp, NewStore);
12052     // Erase all other stores.
12053     for (unsigned i = 0; i < NumElem; ++i) {
12054       // Remove all Store nodes.
12055       if (StoreNodes[i].MemNode == LatestOp)
12056         continue;
12057       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12058       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
12059       deleteAndRecombine(St);
12060     }
12061   }
12062 
12063   return true;
12064 }
12065 
12066 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12067   SDLoc SL(ST);
12068   SDValue ReplStore;
12069 
12070   // Replace the chain to avoid dependency.
12071   if (ST->isTruncatingStore()) {
12072     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12073                                   ST->getBasePtr(), ST->getMemoryVT(),
12074                                   ST->getMemOperand());
12075   } else {
12076     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12077                              ST->getMemOperand());
12078   }
12079 
12080   // Create token to keep both nodes around.
12081   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12082                               MVT::Other, ST->getChain(), ReplStore);
12083 
12084   // Make sure the new and old chains are cleaned up.
12085   AddToWorklist(Token.getNode());
12086 
12087   // Don't add users to work list.
12088   return CombineTo(ST, Token, false);
12089 }
12090 
12091 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12092   SDValue Value = ST->getValue();
12093   if (Value.getOpcode() == ISD::TargetConstantFP)
12094     return SDValue();
12095 
12096   SDLoc DL(ST);
12097 
12098   SDValue Chain = ST->getChain();
12099   SDValue Ptr = ST->getBasePtr();
12100 
12101   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12102 
12103   // NOTE: If the original store is volatile, this transform must not increase
12104   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12105   // processor operation but an i64 (which is not legal) requires two.  So the
12106   // transform should not be done in this case.
12107 
12108   SDValue Tmp;
12109   switch (CFP->getSimpleValueType(0).SimpleTy) {
12110   default:
12111     llvm_unreachable("Unknown FP type");
12112   case MVT::f16:    // We don't do this for these yet.
12113   case MVT::f80:
12114   case MVT::f128:
12115   case MVT::ppcf128:
12116     return SDValue();
12117   case MVT::f32:
12118     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12119         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12120       ;
12121       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12122                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12123                             MVT::i32);
12124       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12125     }
12126 
12127     return SDValue();
12128   case MVT::f64:
12129     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12130          !ST->isVolatile()) ||
12131         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12132       ;
12133       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12134                             getZExtValue(), SDLoc(CFP), MVT::i64);
12135       return DAG.getStore(Chain, DL, Tmp,
12136                           Ptr, ST->getMemOperand());
12137     }
12138 
12139     if (!ST->isVolatile() &&
12140         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12141       // Many FP stores are not made apparent until after legalize, e.g. for
12142       // argument passing.  Since this is so common, custom legalize the
12143       // 64-bit integer store into two 32-bit stores.
12144       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12145       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12146       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12147       if (DAG.getDataLayout().isBigEndian())
12148         std::swap(Lo, Hi);
12149 
12150       unsigned Alignment = ST->getAlignment();
12151       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12152       AAMDNodes AAInfo = ST->getAAInfo();
12153 
12154       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12155                                  ST->getAlignment(), MMOFlags, AAInfo);
12156       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12157                         DAG.getConstant(4, DL, Ptr.getValueType()));
12158       Alignment = MinAlign(Alignment, 4U);
12159       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12160                                  ST->getPointerInfo().getWithOffset(4),
12161                                  Alignment, MMOFlags, AAInfo);
12162       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12163                          St0, St1);
12164     }
12165 
12166     return SDValue();
12167   }
12168 }
12169 
12170 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12171   StoreSDNode *ST  = cast<StoreSDNode>(N);
12172   SDValue Chain = ST->getChain();
12173   SDValue Value = ST->getValue();
12174   SDValue Ptr   = ST->getBasePtr();
12175 
12176   // If this is a store of a bit convert, store the input value if the
12177   // resultant store does not need a higher alignment than the original.
12178   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12179       ST->isUnindexed()) {
12180     EVT SVT = Value.getOperand(0).getValueType();
12181     if (((!LegalOperations && !ST->isVolatile()) ||
12182          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12183         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12184       unsigned OrigAlign = ST->getAlignment();
12185       bool Fast = false;
12186       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12187                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12188           Fast) {
12189         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12190                             ST->getPointerInfo(), OrigAlign,
12191                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
12192       }
12193     }
12194   }
12195 
12196   // Turn 'store undef, Ptr' -> nothing.
12197   if (Value.isUndef() && ST->isUnindexed())
12198     return Chain;
12199 
12200   // Try to infer better alignment information than the store already has.
12201   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12202     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12203       if (Align > ST->getAlignment()) {
12204         SDValue NewStore =
12205             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12206                               ST->getMemoryVT(), Align,
12207                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
12208         if (NewStore.getNode() != N)
12209           return CombineTo(ST, NewStore, true);
12210       }
12211     }
12212   }
12213 
12214   // Try transforming a pair floating point load / store ops to integer
12215   // load / store ops.
12216   if (SDValue NewST = TransformFPLoadStorePair(N))
12217     return NewST;
12218 
12219   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12220                                                   : DAG.getSubtarget().useAA();
12221 #ifndef NDEBUG
12222   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12223       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12224     UseAA = false;
12225 #endif
12226   if (UseAA && ST->isUnindexed()) {
12227     // FIXME: We should do this even without AA enabled. AA will just allow
12228     // FindBetterChain to work in more situations. The problem with this is that
12229     // any combine that expects memory operations to be on consecutive chains
12230     // first needs to be updated to look for users of the same chain.
12231 
12232     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12233     // adjacent stores.
12234     if (findBetterNeighborChains(ST)) {
12235       // replaceStoreChain uses CombineTo, which handled all of the worklist
12236       // manipulation. Return the original node to not do anything else.
12237       return SDValue(ST, 0);
12238     }
12239     Chain = ST->getChain();
12240   }
12241 
12242   // Try transforming N to an indexed store.
12243   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12244     return SDValue(N, 0);
12245 
12246   // FIXME: is there such a thing as a truncating indexed store?
12247   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12248       Value.getValueType().isInteger()) {
12249     // See if we can simplify the input to this truncstore with knowledge that
12250     // only the low bits are being used.  For example:
12251     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12252     SDValue Shorter = GetDemandedBits(
12253         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12254                                     ST->getMemoryVT().getScalarSizeInBits()));
12255     AddToWorklist(Value.getNode());
12256     if (Shorter.getNode())
12257       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12258                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12259 
12260     // Otherwise, see if we can simplify the operation with
12261     // SimplifyDemandedBits, which only works if the value has a single use.
12262     if (SimplifyDemandedBits(
12263             Value,
12264             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12265                                  ST->getMemoryVT().getScalarSizeInBits())))
12266       return SDValue(N, 0);
12267   }
12268 
12269   // If this is a load followed by a store to the same location, then the store
12270   // is dead/noop.
12271   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12272     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12273         ST->isUnindexed() && !ST->isVolatile() &&
12274         // There can't be any side effects between the load and store, such as
12275         // a call or store.
12276         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12277       // The store is dead, remove it.
12278       return Chain;
12279     }
12280   }
12281 
12282   // If this is a store followed by a store with the same value to the same
12283   // location, then the store is dead/noop.
12284   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12285     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12286         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12287         ST1->isUnindexed() && !ST1->isVolatile()) {
12288       // The store is dead, remove it.
12289       return Chain;
12290     }
12291   }
12292 
12293   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12294   // truncating store.  We can do this even if this is already a truncstore.
12295   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12296       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12297       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12298                             ST->getMemoryVT())) {
12299     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12300                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12301   }
12302 
12303   // Only perform this optimization before the types are legal, because we
12304   // don't want to perform this optimization on every DAGCombine invocation.
12305   if (!LegalTypes) {
12306     bool EverChanged = false;
12307 
12308     do {
12309       // There can be multiple store sequences on the same chain.
12310       // Keep trying to merge store sequences until we are unable to do so
12311       // or until we merge the last store on the chain.
12312       bool Changed = MergeConsecutiveStores(ST);
12313       EverChanged |= Changed;
12314       if (!Changed) break;
12315     } while (ST->getOpcode() != ISD::DELETED_NODE);
12316 
12317     if (EverChanged)
12318       return SDValue(N, 0);
12319   }
12320 
12321   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12322   //
12323   // Make sure to do this only after attempting to merge stores in order to
12324   //  avoid changing the types of some subset of stores due to visit order,
12325   //  preventing their merging.
12326   if (isa<ConstantFPSDNode>(Value)) {
12327     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12328       return NewSt;
12329   }
12330 
12331   if (SDValue NewSt = splitMergedValStore(ST))
12332     return NewSt;
12333 
12334   return ReduceLoadOpStoreWidth(N);
12335 }
12336 
12337 /// For the instruction sequence of store below, F and I values
12338 /// are bundled together as an i64 value before being stored into memory.
12339 /// Sometimes it is more efficent to generate separate stores for F and I,
12340 /// which can remove the bitwise instructions or sink them to colder places.
12341 ///
12342 ///   (store (or (zext (bitcast F to i32) to i64),
12343 ///              (shl (zext I to i64), 32)), addr)  -->
12344 ///   (store F, addr) and (store I, addr+4)
12345 ///
12346 /// Similarly, splitting for other merged store can also be beneficial, like:
12347 /// For pair of {i32, i32}, i64 store --> two i32 stores.
12348 /// For pair of {i32, i16}, i64 store --> two i32 stores.
12349 /// For pair of {i16, i16}, i32 store --> two i16 stores.
12350 /// For pair of {i16, i8},  i32 store --> two i16 stores.
12351 /// For pair of {i8, i8},   i16 store --> two i8 stores.
12352 ///
12353 /// We allow each target to determine specifically which kind of splitting is
12354 /// supported.
12355 ///
12356 /// The store patterns are commonly seen from the simple code snippet below
12357 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
12358 ///   void goo(const std::pair<int, float> &);
12359 ///   hoo() {
12360 ///     ...
12361 ///     goo(std::make_pair(tmp, ftmp));
12362 ///     ...
12363 ///   }
12364 ///
12365 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
12366   if (OptLevel == CodeGenOpt::None)
12367     return SDValue();
12368 
12369   SDValue Val = ST->getValue();
12370   SDLoc DL(ST);
12371 
12372   // Match OR operand.
12373   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
12374     return SDValue();
12375 
12376   // Match SHL operand and get Lower and Higher parts of Val.
12377   SDValue Op1 = Val.getOperand(0);
12378   SDValue Op2 = Val.getOperand(1);
12379   SDValue Lo, Hi;
12380   if (Op1.getOpcode() != ISD::SHL) {
12381     std::swap(Op1, Op2);
12382     if (Op1.getOpcode() != ISD::SHL)
12383       return SDValue();
12384   }
12385   Lo = Op2;
12386   Hi = Op1.getOperand(0);
12387   if (!Op1.hasOneUse())
12388     return SDValue();
12389 
12390   // Match shift amount to HalfValBitSize.
12391   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
12392   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
12393   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
12394     return SDValue();
12395 
12396   // Lo and Hi are zero-extended from int with size less equal than 32
12397   // to i64.
12398   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
12399       !Lo.getOperand(0).getValueType().isScalarInteger() ||
12400       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
12401       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
12402       !Hi.getOperand(0).getValueType().isScalarInteger() ||
12403       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
12404     return SDValue();
12405 
12406   if (!TLI.isMultiStoresCheaperThanBitsMerge(Lo.getOperand(0),
12407                                              Hi.getOperand(0)))
12408     return SDValue();
12409 
12410   // Start to split store.
12411   unsigned Alignment = ST->getAlignment();
12412   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12413   AAMDNodes AAInfo = ST->getAAInfo();
12414 
12415   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
12416   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
12417   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
12418   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
12419 
12420   SDValue Chain = ST->getChain();
12421   SDValue Ptr = ST->getBasePtr();
12422   // Lower value store.
12423   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12424                              ST->getAlignment(), MMOFlags, AAInfo);
12425   Ptr =
12426       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12427                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
12428   // Higher value store.
12429   SDValue St1 =
12430       DAG.getStore(St0, DL, Hi, Ptr,
12431                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
12432                    Alignment / 2, MMOFlags, AAInfo);
12433   return St1;
12434 }
12435 
12436 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12437   SDValue InVec = N->getOperand(0);
12438   SDValue InVal = N->getOperand(1);
12439   SDValue EltNo = N->getOperand(2);
12440   SDLoc DL(N);
12441 
12442   // If the inserted element is an UNDEF, just use the input vector.
12443   if (InVal.isUndef())
12444     return InVec;
12445 
12446   EVT VT = InVec.getValueType();
12447 
12448   // If we can't generate a legal BUILD_VECTOR, exit
12449   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12450     return SDValue();
12451 
12452   // Check that we know which element is being inserted
12453   if (!isa<ConstantSDNode>(EltNo))
12454     return SDValue();
12455   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12456 
12457   // Canonicalize insert_vector_elt dag nodes.
12458   // Example:
12459   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12460   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12461   //
12462   // Do this only if the child insert_vector node has one use; also
12463   // do this only if indices are both constants and Idx1 < Idx0.
12464   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12465       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12466     unsigned OtherElt =
12467       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12468     if (Elt < OtherElt) {
12469       // Swap nodes.
12470       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
12471                                   InVec.getOperand(0), InVal, EltNo);
12472       AddToWorklist(NewOp.getNode());
12473       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12474                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12475     }
12476   }
12477 
12478   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12479   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12480   // vector elements.
12481   SmallVector<SDValue, 8> Ops;
12482   // Do not combine these two vectors if the output vector will not replace
12483   // the input vector.
12484   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12485     Ops.append(InVec.getNode()->op_begin(),
12486                InVec.getNode()->op_end());
12487   } else if (InVec.isUndef()) {
12488     unsigned NElts = VT.getVectorNumElements();
12489     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12490   } else {
12491     return SDValue();
12492   }
12493 
12494   // Insert the element
12495   if (Elt < Ops.size()) {
12496     // All the operands of BUILD_VECTOR must have the same type;
12497     // we enforce that here.
12498     EVT OpVT = Ops[0].getValueType();
12499     if (InVal.getValueType() != OpVT)
12500       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12501                 DAG.getNode(ISD::ANY_EXTEND, DL, OpVT, InVal) :
12502                 DAG.getNode(ISD::TRUNCATE, DL, OpVT, InVal);
12503     Ops[Elt] = InVal;
12504   }
12505 
12506   // Return the new vector
12507   return DAG.getBuildVector(VT, DL, Ops);
12508 }
12509 
12510 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12511     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12512   assert(!OriginalLoad->isVolatile());
12513 
12514   EVT ResultVT = EVE->getValueType(0);
12515   EVT VecEltVT = InVecVT.getVectorElementType();
12516   unsigned Align = OriginalLoad->getAlignment();
12517   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12518       VecEltVT.getTypeForEVT(*DAG.getContext()));
12519 
12520   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12521     return SDValue();
12522 
12523   Align = NewAlign;
12524 
12525   SDValue NewPtr = OriginalLoad->getBasePtr();
12526   SDValue Offset;
12527   EVT PtrType = NewPtr.getValueType();
12528   MachinePointerInfo MPI;
12529   SDLoc DL(EVE);
12530   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12531     int Elt = ConstEltNo->getZExtValue();
12532     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12533     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12534     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12535   } else {
12536     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12537     Offset = DAG.getNode(
12538         ISD::MUL, DL, PtrType, Offset,
12539         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12540     MPI = OriginalLoad->getPointerInfo();
12541   }
12542   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12543 
12544   // The replacement we need to do here is a little tricky: we need to
12545   // replace an extractelement of a load with a load.
12546   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12547   // Note that this replacement assumes that the extractvalue is the only
12548   // use of the load; that's okay because we don't want to perform this
12549   // transformation in other cases anyway.
12550   SDValue Load;
12551   SDValue Chain;
12552   if (ResultVT.bitsGT(VecEltVT)) {
12553     // If the result type of vextract is wider than the load, then issue an
12554     // extending load instead.
12555     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12556                                                   VecEltVT)
12557                                    ? ISD::ZEXTLOAD
12558                                    : ISD::EXTLOAD;
12559     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
12560                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
12561                           Align, OriginalLoad->getMemOperand()->getFlags(),
12562                           OriginalLoad->getAAInfo());
12563     Chain = Load.getValue(1);
12564   } else {
12565     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
12566                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
12567                        OriginalLoad->getAAInfo());
12568     Chain = Load.getValue(1);
12569     if (ResultVT.bitsLT(VecEltVT))
12570       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12571     else
12572       Load = DAG.getBitcast(ResultVT, Load);
12573   }
12574   WorklistRemover DeadNodes(*this);
12575   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12576   SDValue To[] = { Load, Chain };
12577   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12578   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12579   // worklist explicitly as well.
12580   AddToWorklist(Load.getNode());
12581   AddUsersToWorklist(Load.getNode()); // Add users too
12582   // Make sure to revisit this node to clean it up; it will usually be dead.
12583   AddToWorklist(EVE);
12584   ++OpsNarrowed;
12585   return SDValue(EVE, 0);
12586 }
12587 
12588 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12589   // (vextract (scalar_to_vector val, 0) -> val
12590   SDValue InVec = N->getOperand(0);
12591   EVT VT = InVec.getValueType();
12592   EVT NVT = N->getValueType(0);
12593 
12594   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12595     // Check if the result type doesn't match the inserted element type. A
12596     // SCALAR_TO_VECTOR may truncate the inserted element and the
12597     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12598     SDValue InOp = InVec.getOperand(0);
12599     if (InOp.getValueType() != NVT) {
12600       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12601       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12602     }
12603     return InOp;
12604   }
12605 
12606   SDValue EltNo = N->getOperand(1);
12607   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12608 
12609   // extract_vector_elt (build_vector x, y), 1 -> y
12610   if (ConstEltNo &&
12611       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12612       TLI.isTypeLegal(VT) &&
12613       (InVec.hasOneUse() ||
12614        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12615     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12616     EVT InEltVT = Elt.getValueType();
12617 
12618     // Sometimes build_vector's scalar input types do not match result type.
12619     if (NVT == InEltVT)
12620       return Elt;
12621 
12622     // TODO: It may be useful to truncate if free if the build_vector implicitly
12623     // converts.
12624   }
12625 
12626   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12627   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12628       ConstEltNo->isNullValue() && VT.isInteger()) {
12629     SDValue BCSrc = InVec.getOperand(0);
12630     if (BCSrc.getValueType().isScalarInteger())
12631       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12632   }
12633 
12634   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
12635   //
12636   // This only really matters if the index is non-constant since other combines
12637   // on the constant elements already work.
12638   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12639       EltNo == InVec.getOperand(2)) {
12640     SDValue Elt = InVec.getOperand(1);
12641     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
12642   }
12643 
12644   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12645   // We only perform this optimization before the op legalization phase because
12646   // we may introduce new vector instructions which are not backed by TD
12647   // patterns. For example on AVX, extracting elements from a wide vector
12648   // without using extract_subvector. However, if we can find an underlying
12649   // scalar value, then we can always use that.
12650   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12651     int NumElem = VT.getVectorNumElements();
12652     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12653     // Find the new index to extract from.
12654     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12655 
12656     // Extracting an undef index is undef.
12657     if (OrigElt == -1)
12658       return DAG.getUNDEF(NVT);
12659 
12660     // Select the right vector half to extract from.
12661     SDValue SVInVec;
12662     if (OrigElt < NumElem) {
12663       SVInVec = InVec->getOperand(0);
12664     } else {
12665       SVInVec = InVec->getOperand(1);
12666       OrigElt -= NumElem;
12667     }
12668 
12669     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12670       SDValue InOp = SVInVec.getOperand(OrigElt);
12671       if (InOp.getValueType() != NVT) {
12672         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12673         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12674       }
12675 
12676       return InOp;
12677     }
12678 
12679     // FIXME: We should handle recursing on other vector shuffles and
12680     // scalar_to_vector here as well.
12681 
12682     if (!LegalOperations) {
12683       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12684       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12685                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12686     }
12687   }
12688 
12689   bool BCNumEltsChanged = false;
12690   EVT ExtVT = VT.getVectorElementType();
12691   EVT LVT = ExtVT;
12692 
12693   // If the result of load has to be truncated, then it's not necessarily
12694   // profitable.
12695   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12696     return SDValue();
12697 
12698   if (InVec.getOpcode() == ISD::BITCAST) {
12699     // Don't duplicate a load with other uses.
12700     if (!InVec.hasOneUse())
12701       return SDValue();
12702 
12703     EVT BCVT = InVec.getOperand(0).getValueType();
12704     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12705       return SDValue();
12706     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12707       BCNumEltsChanged = true;
12708     InVec = InVec.getOperand(0);
12709     ExtVT = BCVT.getVectorElementType();
12710   }
12711 
12712   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12713   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12714       ISD::isNormalLoad(InVec.getNode()) &&
12715       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12716     SDValue Index = N->getOperand(1);
12717     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
12718       if (!OrigLoad->isVolatile()) {
12719         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12720                                                              OrigLoad);
12721       }
12722     }
12723   }
12724 
12725   // Perform only after legalization to ensure build_vector / vector_shuffle
12726   // optimizations have already been done.
12727   if (!LegalOperations) return SDValue();
12728 
12729   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12730   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12731   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12732 
12733   if (ConstEltNo) {
12734     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12735 
12736     LoadSDNode *LN0 = nullptr;
12737     const ShuffleVectorSDNode *SVN = nullptr;
12738     if (ISD::isNormalLoad(InVec.getNode())) {
12739       LN0 = cast<LoadSDNode>(InVec);
12740     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12741                InVec.getOperand(0).getValueType() == ExtVT &&
12742                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12743       // Don't duplicate a load with other uses.
12744       if (!InVec.hasOneUse())
12745         return SDValue();
12746 
12747       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12748     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12749       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12750       // =>
12751       // (load $addr+1*size)
12752 
12753       // Don't duplicate a load with other uses.
12754       if (!InVec.hasOneUse())
12755         return SDValue();
12756 
12757       // If the bit convert changed the number of elements, it is unsafe
12758       // to examine the mask.
12759       if (BCNumEltsChanged)
12760         return SDValue();
12761 
12762       // Select the input vector, guarding against out of range extract vector.
12763       unsigned NumElems = VT.getVectorNumElements();
12764       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12765       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12766 
12767       if (InVec.getOpcode() == ISD::BITCAST) {
12768         // Don't duplicate a load with other uses.
12769         if (!InVec.hasOneUse())
12770           return SDValue();
12771 
12772         InVec = InVec.getOperand(0);
12773       }
12774       if (ISD::isNormalLoad(InVec.getNode())) {
12775         LN0 = cast<LoadSDNode>(InVec);
12776         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12777         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12778       }
12779     }
12780 
12781     // Make sure we found a non-volatile load and the extractelement is
12782     // the only use.
12783     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12784       return SDValue();
12785 
12786     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12787     if (Elt == -1)
12788       return DAG.getUNDEF(LVT);
12789 
12790     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12791   }
12792 
12793   return SDValue();
12794 }
12795 
12796 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12797 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12798   // We perform this optimization post type-legalization because
12799   // the type-legalizer often scalarizes integer-promoted vectors.
12800   // Performing this optimization before may create bit-casts which
12801   // will be type-legalized to complex code sequences.
12802   // We perform this optimization only before the operation legalizer because we
12803   // may introduce illegal operations.
12804   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12805     return SDValue();
12806 
12807   unsigned NumInScalars = N->getNumOperands();
12808   SDLoc DL(N);
12809   EVT VT = N->getValueType(0);
12810 
12811   // Check to see if this is a BUILD_VECTOR of a bunch of values
12812   // which come from any_extend or zero_extend nodes. If so, we can create
12813   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12814   // optimizations. We do not handle sign-extend because we can't fill the sign
12815   // using shuffles.
12816   EVT SourceType = MVT::Other;
12817   bool AllAnyExt = true;
12818 
12819   for (unsigned i = 0; i != NumInScalars; ++i) {
12820     SDValue In = N->getOperand(i);
12821     // Ignore undef inputs.
12822     if (In.isUndef()) continue;
12823 
12824     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12825     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12826 
12827     // Abort if the element is not an extension.
12828     if (!ZeroExt && !AnyExt) {
12829       SourceType = MVT::Other;
12830       break;
12831     }
12832 
12833     // The input is a ZeroExt or AnyExt. Check the original type.
12834     EVT InTy = In.getOperand(0).getValueType();
12835 
12836     // Check that all of the widened source types are the same.
12837     if (SourceType == MVT::Other)
12838       // First time.
12839       SourceType = InTy;
12840     else if (InTy != SourceType) {
12841       // Multiple income types. Abort.
12842       SourceType = MVT::Other;
12843       break;
12844     }
12845 
12846     // Check if all of the extends are ANY_EXTENDs.
12847     AllAnyExt &= AnyExt;
12848   }
12849 
12850   // In order to have valid types, all of the inputs must be extended from the
12851   // same source type and all of the inputs must be any or zero extend.
12852   // Scalar sizes must be a power of two.
12853   EVT OutScalarTy = VT.getScalarType();
12854   bool ValidTypes = SourceType != MVT::Other &&
12855                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12856                  isPowerOf2_32(SourceType.getSizeInBits());
12857 
12858   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12859   // turn into a single shuffle instruction.
12860   if (!ValidTypes)
12861     return SDValue();
12862 
12863   bool isLE = DAG.getDataLayout().isLittleEndian();
12864   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12865   assert(ElemRatio > 1 && "Invalid element size ratio");
12866   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12867                                DAG.getConstant(0, DL, SourceType);
12868 
12869   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12870   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12871 
12872   // Populate the new build_vector
12873   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12874     SDValue Cast = N->getOperand(i);
12875     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12876             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12877             Cast.isUndef()) && "Invalid cast opcode");
12878     SDValue In;
12879     if (Cast.isUndef())
12880       In = DAG.getUNDEF(SourceType);
12881     else
12882       In = Cast->getOperand(0);
12883     unsigned Index = isLE ? (i * ElemRatio) :
12884                             (i * ElemRatio + (ElemRatio - 1));
12885 
12886     assert(Index < Ops.size() && "Invalid index");
12887     Ops[Index] = In;
12888   }
12889 
12890   // The type of the new BUILD_VECTOR node.
12891   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12892   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12893          "Invalid vector size");
12894   // Check if the new vector type is legal.
12895   if (!isTypeLegal(VecVT)) return SDValue();
12896 
12897   // Make the new BUILD_VECTOR.
12898   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
12899 
12900   // The new BUILD_VECTOR node has the potential to be further optimized.
12901   AddToWorklist(BV.getNode());
12902   // Bitcast to the desired type.
12903   return DAG.getBitcast(VT, BV);
12904 }
12905 
12906 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12907   EVT VT = N->getValueType(0);
12908 
12909   unsigned NumInScalars = N->getNumOperands();
12910   SDLoc DL(N);
12911 
12912   EVT SrcVT = MVT::Other;
12913   unsigned Opcode = ISD::DELETED_NODE;
12914   unsigned NumDefs = 0;
12915 
12916   for (unsigned i = 0; i != NumInScalars; ++i) {
12917     SDValue In = N->getOperand(i);
12918     unsigned Opc = In.getOpcode();
12919 
12920     if (Opc == ISD::UNDEF)
12921       continue;
12922 
12923     // If all scalar values are floats and converted from integers.
12924     if (Opcode == ISD::DELETED_NODE &&
12925         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12926       Opcode = Opc;
12927     }
12928 
12929     if (Opc != Opcode)
12930       return SDValue();
12931 
12932     EVT InVT = In.getOperand(0).getValueType();
12933 
12934     // If all scalar values are typed differently, bail out. It's chosen to
12935     // simplify BUILD_VECTOR of integer types.
12936     if (SrcVT == MVT::Other)
12937       SrcVT = InVT;
12938     if (SrcVT != InVT)
12939       return SDValue();
12940     NumDefs++;
12941   }
12942 
12943   // If the vector has just one element defined, it's not worth to fold it into
12944   // a vectorized one.
12945   if (NumDefs < 2)
12946     return SDValue();
12947 
12948   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12949          && "Should only handle conversion from integer to float.");
12950   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12951 
12952   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12953 
12954   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12955     return SDValue();
12956 
12957   // Just because the floating-point vector type is legal does not necessarily
12958   // mean that the corresponding integer vector type is.
12959   if (!isTypeLegal(NVT))
12960     return SDValue();
12961 
12962   SmallVector<SDValue, 8> Opnds;
12963   for (unsigned i = 0; i != NumInScalars; ++i) {
12964     SDValue In = N->getOperand(i);
12965 
12966     if (In.isUndef())
12967       Opnds.push_back(DAG.getUNDEF(SrcVT));
12968     else
12969       Opnds.push_back(In.getOperand(0));
12970   }
12971   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
12972   AddToWorklist(BV.getNode());
12973 
12974   return DAG.getNode(Opcode, DL, VT, BV);
12975 }
12976 
12977 SDValue DAGCombiner::createBuildVecShuffle(SDLoc DL, SDNode *N,
12978                                            ArrayRef<int> VectorMask,
12979                                            SDValue VecIn1, SDValue VecIn2,
12980                                            unsigned LeftIdx) {
12981   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12982   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
12983 
12984   EVT VT = N->getValueType(0);
12985   EVT InVT1 = VecIn1.getValueType();
12986   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
12987 
12988   unsigned Vec2Offset = InVT1.getVectorNumElements();
12989   unsigned NumElems = VT.getVectorNumElements();
12990   unsigned ShuffleNumElems = NumElems;
12991 
12992   // We can't generate a shuffle node with mismatched input and output types.
12993   // Try to make the types match the type of the output.
12994   if (InVT1 != VT || InVT2 != VT) {
12995     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
12996       // If the output vector length is a multiple of both input lengths,
12997       // we can concatenate them and pad the rest with undefs.
12998       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
12999       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13000       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13001       ConcatOps[0] = VecIn1;
13002       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13003       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13004       VecIn2 = SDValue();
13005     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13006       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13007         return SDValue();
13008 
13009       if (!VecIn2.getNode()) {
13010         // If we only have one input vector, and it's twice the size of the
13011         // output, split it in two.
13012         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13013                              DAG.getConstant(NumElems, DL, IdxTy));
13014         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13015         // Since we now have shorter input vectors, adjust the offset of the
13016         // second vector's start.
13017         Vec2Offset = NumElems;
13018       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13019         // VecIn1 is wider than the output, and we have another, possibly
13020         // smaller input. Pad the smaller input with undefs, shuffle at the
13021         // input vector width, and extract the output.
13022         // The shuffle type is different than VT, so check legality again.
13023         if (LegalOperations &&
13024             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13025           return SDValue();
13026 
13027         if (InVT1 != InVT2)
13028           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13029                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13030         ShuffleNumElems = NumElems * 2;
13031       } else {
13032         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13033         // than VecIn1. We can't handle this for now - this case will disappear
13034         // when we start sorting the vectors by type.
13035         return SDValue();
13036       }
13037     } else {
13038       // TODO: Support cases where the length mismatch isn't exactly by a
13039       // factor of 2.
13040       // TODO: Move this check upwards, so that if we have bad type
13041       // mismatches, we don't create any DAG nodes.
13042       return SDValue();
13043     }
13044   }
13045 
13046   // Initialize mask to undef.
13047   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13048 
13049   // Only need to run up to the number of elements actually used, not the
13050   // total number of elements in the shuffle - if we are shuffling a wider
13051   // vector, the high lanes should be set to undef.
13052   for (unsigned i = 0; i != NumElems; ++i) {
13053     if (VectorMask[i] <= 0)
13054       continue;
13055 
13056     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13057     if (VectorMask[i] == (int)LeftIdx) {
13058       Mask[i] = ExtIndex;
13059     } else if (VectorMask[i] == (int)LeftIdx + 1) {
13060       Mask[i] = Vec2Offset + ExtIndex;
13061     }
13062   }
13063 
13064   // The type the input vectors may have changed above.
13065   InVT1 = VecIn1.getValueType();
13066 
13067   // If we already have a VecIn2, it should have the same type as VecIn1.
13068   // If we don't, get an undef/zero vector of the appropriate type.
13069   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13070   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13071 
13072   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13073   if (ShuffleNumElems > NumElems)
13074     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13075 
13076   return Shuffle;
13077 }
13078 
13079 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13080 // operations. If the types of the vectors we're extracting from allow it,
13081 // turn this into a vector_shuffle node.
13082 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13083   SDLoc DL(N);
13084   EVT VT = N->getValueType(0);
13085 
13086   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13087   if (!isTypeLegal(VT))
13088     return SDValue();
13089 
13090   // May only combine to shuffle after legalize if shuffle is legal.
13091   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13092     return SDValue();
13093 
13094   bool UsesZeroVector = false;
13095   unsigned NumElems = N->getNumOperands();
13096 
13097   // Record, for each element of the newly built vector, which input vector
13098   // that element comes from. -1 stands for undef, 0 for the zero vector,
13099   // and positive values for the input vectors.
13100   // VectorMask maps each element to its vector number, and VecIn maps vector
13101   // numbers to their initial SDValues.
13102 
13103   SmallVector<int, 8> VectorMask(NumElems, -1);
13104   SmallVector<SDValue, 8> VecIn;
13105   VecIn.push_back(SDValue());
13106 
13107   for (unsigned i = 0; i != NumElems; ++i) {
13108     SDValue Op = N->getOperand(i);
13109 
13110     if (Op.isUndef())
13111       continue;
13112 
13113     // See if we can use a blend with a zero vector.
13114     // TODO: Should we generalize this to a blend with an arbitrary constant
13115     // vector?
13116     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13117       UsesZeroVector = true;
13118       VectorMask[i] = 0;
13119       continue;
13120     }
13121 
13122     // Not an undef or zero. If the input is something other than an
13123     // EXTRACT_VECTOR_ELT with a constant index, bail out.
13124     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13125         !isa<ConstantSDNode>(Op.getOperand(1)))
13126       return SDValue();
13127 
13128     SDValue ExtractedFromVec = Op.getOperand(0);
13129 
13130     // All inputs must have the same element type as the output.
13131     if (VT.getVectorElementType() !=
13132         ExtractedFromVec.getValueType().getVectorElementType())
13133       return SDValue();
13134 
13135     // Have we seen this input vector before?
13136     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13137     // a map back from SDValues to numbers isn't worth it.
13138     unsigned Idx = std::distance(
13139         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13140     if (Idx == VecIn.size())
13141       VecIn.push_back(ExtractedFromVec);
13142 
13143     VectorMask[i] = Idx;
13144   }
13145 
13146   // If we didn't find at least one input vector, bail out.
13147   if (VecIn.size() < 2)
13148     return SDValue();
13149 
13150   // TODO: We want to sort the vectors by descending length, so that adjacent
13151   // pairs have similar length, and the longer vector is always first in the
13152   // pair.
13153 
13154   // TODO: Should this fire if some of the input vectors has illegal type (like
13155   // it does now), or should we let legalization run its course first?
13156 
13157   // Shuffle phase:
13158   // Take pairs of vectors, and shuffle them so that the result has elements
13159   // from these vectors in the correct places.
13160   // For example, given:
13161   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13162   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13163   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13164   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13165   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13166   // We will generate:
13167   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13168   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13169   SmallVector<SDValue, 4> Shuffles;
13170   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13171     unsigned LeftIdx = 2 * In + 1;
13172     SDValue VecLeft = VecIn[LeftIdx];
13173     SDValue VecRight =
13174         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13175 
13176     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13177                                                 VecRight, LeftIdx))
13178       Shuffles.push_back(Shuffle);
13179     else
13180       return SDValue();
13181   }
13182 
13183   // If we need the zero vector as an "ingredient" in the blend tree, add it
13184   // to the list of shuffles.
13185   if (UsesZeroVector)
13186     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13187                                       : DAG.getConstantFP(0.0, DL, VT));
13188 
13189   // If we only have one shuffle, we're done.
13190   if (Shuffles.size() == 1)
13191     return Shuffles[0];
13192 
13193   // Update the vector mask to point to the post-shuffle vectors.
13194   for (int &Vec : VectorMask)
13195     if (Vec == 0)
13196       Vec = Shuffles.size() - 1;
13197     else
13198       Vec = (Vec - 1) / 2;
13199 
13200   // More than one shuffle. Generate a binary tree of blends, e.g. if from
13201   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13202   // generate:
13203   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13204   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13205   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13206   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13207   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13208   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13209   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13210 
13211   // Make sure the initial size of the shuffle list is even.
13212   if (Shuffles.size() % 2)
13213     Shuffles.push_back(DAG.getUNDEF(VT));
13214 
13215   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13216     if (CurSize % 2) {
13217       Shuffles[CurSize] = DAG.getUNDEF(VT);
13218       CurSize++;
13219     }
13220     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13221       int Left = 2 * In;
13222       int Right = 2 * In + 1;
13223       SmallVector<int, 8> Mask(NumElems, -1);
13224       for (unsigned i = 0; i != NumElems; ++i) {
13225         if (VectorMask[i] == Left) {
13226           Mask[i] = i;
13227           VectorMask[i] = In;
13228         } else if (VectorMask[i] == Right) {
13229           Mask[i] = i + NumElems;
13230           VectorMask[i] = In;
13231         }
13232       }
13233 
13234       Shuffles[In] =
13235           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13236     }
13237   }
13238 
13239   return Shuffles[0];
13240 }
13241 
13242 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13243   EVT VT = N->getValueType(0);
13244 
13245   // A vector built entirely of undefs is undef.
13246   if (ISD::allOperandsUndef(N))
13247     return DAG.getUNDEF(VT);
13248 
13249   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13250     return V;
13251 
13252   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13253     return V;
13254 
13255   if (SDValue V = reduceBuildVecToShuffle(N))
13256     return V;
13257 
13258   return SDValue();
13259 }
13260 
13261 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13262   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13263   EVT OpVT = N->getOperand(0).getValueType();
13264 
13265   // If the operands are legal vectors, leave them alone.
13266   if (TLI.isTypeLegal(OpVT))
13267     return SDValue();
13268 
13269   SDLoc DL(N);
13270   EVT VT = N->getValueType(0);
13271   SmallVector<SDValue, 8> Ops;
13272 
13273   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13274   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13275 
13276   // Keep track of what we encounter.
13277   bool AnyInteger = false;
13278   bool AnyFP = false;
13279   for (const SDValue &Op : N->ops()) {
13280     if (ISD::BITCAST == Op.getOpcode() &&
13281         !Op.getOperand(0).getValueType().isVector())
13282       Ops.push_back(Op.getOperand(0));
13283     else if (ISD::UNDEF == Op.getOpcode())
13284       Ops.push_back(ScalarUndef);
13285     else
13286       return SDValue();
13287 
13288     // Note whether we encounter an integer or floating point scalar.
13289     // If it's neither, bail out, it could be something weird like x86mmx.
13290     EVT LastOpVT = Ops.back().getValueType();
13291     if (LastOpVT.isFloatingPoint())
13292       AnyFP = true;
13293     else if (LastOpVT.isInteger())
13294       AnyInteger = true;
13295     else
13296       return SDValue();
13297   }
13298 
13299   // If any of the operands is a floating point scalar bitcast to a vector,
13300   // use floating point types throughout, and bitcast everything.
13301   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
13302   if (AnyFP) {
13303     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
13304     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13305     if (AnyInteger) {
13306       for (SDValue &Op : Ops) {
13307         if (Op.getValueType() == SVT)
13308           continue;
13309         if (Op.isUndef())
13310           Op = ScalarUndef;
13311         else
13312           Op = DAG.getBitcast(SVT, Op);
13313       }
13314     }
13315   }
13316 
13317   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
13318                                VT.getSizeInBits() / SVT.getSizeInBits());
13319   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
13320 }
13321 
13322 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
13323 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
13324 // most two distinct vectors the same size as the result, attempt to turn this
13325 // into a legal shuffle.
13326 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
13327   EVT VT = N->getValueType(0);
13328   EVT OpVT = N->getOperand(0).getValueType();
13329   int NumElts = VT.getVectorNumElements();
13330   int NumOpElts = OpVT.getVectorNumElements();
13331 
13332   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
13333   SmallVector<int, 8> Mask;
13334 
13335   for (SDValue Op : N->ops()) {
13336     // Peek through any bitcast.
13337     while (Op.getOpcode() == ISD::BITCAST)
13338       Op = Op.getOperand(0);
13339 
13340     // UNDEF nodes convert to UNDEF shuffle mask values.
13341     if (Op.isUndef()) {
13342       Mask.append((unsigned)NumOpElts, -1);
13343       continue;
13344     }
13345 
13346     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13347       return SDValue();
13348 
13349     // What vector are we extracting the subvector from and at what index?
13350     SDValue ExtVec = Op.getOperand(0);
13351 
13352     // We want the EVT of the original extraction to correctly scale the
13353     // extraction index.
13354     EVT ExtVT = ExtVec.getValueType();
13355 
13356     // Peek through any bitcast.
13357     while (ExtVec.getOpcode() == ISD::BITCAST)
13358       ExtVec = ExtVec.getOperand(0);
13359 
13360     // UNDEF nodes convert to UNDEF shuffle mask values.
13361     if (ExtVec.isUndef()) {
13362       Mask.append((unsigned)NumOpElts, -1);
13363       continue;
13364     }
13365 
13366     if (!isa<ConstantSDNode>(Op.getOperand(1)))
13367       return SDValue();
13368     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13369 
13370     // Ensure that we are extracting a subvector from a vector the same
13371     // size as the result.
13372     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13373       return SDValue();
13374 
13375     // Scale the subvector index to account for any bitcast.
13376     int NumExtElts = ExtVT.getVectorNumElements();
13377     if (0 == (NumExtElts % NumElts))
13378       ExtIdx /= (NumExtElts / NumElts);
13379     else if (0 == (NumElts % NumExtElts))
13380       ExtIdx *= (NumElts / NumExtElts);
13381     else
13382       return SDValue();
13383 
13384     // At most we can reference 2 inputs in the final shuffle.
13385     if (SV0.isUndef() || SV0 == ExtVec) {
13386       SV0 = ExtVec;
13387       for (int i = 0; i != NumOpElts; ++i)
13388         Mask.push_back(i + ExtIdx);
13389     } else if (SV1.isUndef() || SV1 == ExtVec) {
13390       SV1 = ExtVec;
13391       for (int i = 0; i != NumOpElts; ++i)
13392         Mask.push_back(i + ExtIdx + NumElts);
13393     } else {
13394       return SDValue();
13395     }
13396   }
13397 
13398   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13399     return SDValue();
13400 
13401   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13402                               DAG.getBitcast(VT, SV1), Mask);
13403 }
13404 
13405 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13406   // If we only have one input vector, we don't need to do any concatenation.
13407   if (N->getNumOperands() == 1)
13408     return N->getOperand(0);
13409 
13410   // Check if all of the operands are undefs.
13411   EVT VT = N->getValueType(0);
13412   if (ISD::allOperandsUndef(N))
13413     return DAG.getUNDEF(VT);
13414 
13415   // Optimize concat_vectors where all but the first of the vectors are undef.
13416   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13417         return Op.isUndef();
13418       })) {
13419     SDValue In = N->getOperand(0);
13420     assert(In.getValueType().isVector() && "Must concat vectors");
13421 
13422     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13423     if (In->getOpcode() == ISD::BITCAST &&
13424         !In->getOperand(0)->getValueType(0).isVector()) {
13425       SDValue Scalar = In->getOperand(0);
13426 
13427       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13428       // look through the trunc so we can still do the transform:
13429       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13430       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13431           !TLI.isTypeLegal(Scalar.getValueType()) &&
13432           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13433         Scalar = Scalar->getOperand(0);
13434 
13435       EVT SclTy = Scalar->getValueType(0);
13436 
13437       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13438         return SDValue();
13439 
13440       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13441                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13442       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13443         return SDValue();
13444 
13445       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
13446       return DAG.getBitcast(VT, Res);
13447     }
13448   }
13449 
13450   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13451   // We have already tested above for an UNDEF only concatenation.
13452   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13453   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13454   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13455     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13456   };
13457   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13458     SmallVector<SDValue, 8> Opnds;
13459     EVT SVT = VT.getScalarType();
13460 
13461     EVT MinVT = SVT;
13462     if (!SVT.isFloatingPoint()) {
13463       // If BUILD_VECTOR are from built from integer, they may have different
13464       // operand types. Get the smallest type and truncate all operands to it.
13465       bool FoundMinVT = false;
13466       for (const SDValue &Op : N->ops())
13467         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13468           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13469           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13470           FoundMinVT = true;
13471         }
13472       assert(FoundMinVT && "Concat vector type mismatch");
13473     }
13474 
13475     for (const SDValue &Op : N->ops()) {
13476       EVT OpVT = Op.getValueType();
13477       unsigned NumElts = OpVT.getVectorNumElements();
13478 
13479       if (ISD::UNDEF == Op.getOpcode())
13480         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13481 
13482       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13483         if (SVT.isFloatingPoint()) {
13484           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13485           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13486         } else {
13487           for (unsigned i = 0; i != NumElts; ++i)
13488             Opnds.push_back(
13489                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13490         }
13491       }
13492     }
13493 
13494     assert(VT.getVectorNumElements() == Opnds.size() &&
13495            "Concat vector type mismatch");
13496     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13497   }
13498 
13499   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13500   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13501     return V;
13502 
13503   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13504   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13505     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13506       return V;
13507 
13508   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13509   // nodes often generate nop CONCAT_VECTOR nodes.
13510   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13511   // place the incoming vectors at the exact same location.
13512   SDValue SingleSource = SDValue();
13513   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13514 
13515   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13516     SDValue Op = N->getOperand(i);
13517 
13518     if (Op.isUndef())
13519       continue;
13520 
13521     // Check if this is the identity extract:
13522     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13523       return SDValue();
13524 
13525     // Find the single incoming vector for the extract_subvector.
13526     if (SingleSource.getNode()) {
13527       if (Op.getOperand(0) != SingleSource)
13528         return SDValue();
13529     } else {
13530       SingleSource = Op.getOperand(0);
13531 
13532       // Check the source type is the same as the type of the result.
13533       // If not, this concat may extend the vector, so we can not
13534       // optimize it away.
13535       if (SingleSource.getValueType() != N->getValueType(0))
13536         return SDValue();
13537     }
13538 
13539     unsigned IdentityIndex = i * PartNumElem;
13540     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13541     // The extract index must be constant.
13542     if (!CS)
13543       return SDValue();
13544 
13545     // Check that we are reading from the identity index.
13546     if (CS->getZExtValue() != IdentityIndex)
13547       return SDValue();
13548   }
13549 
13550   if (SingleSource.getNode())
13551     return SingleSource;
13552 
13553   return SDValue();
13554 }
13555 
13556 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13557   EVT NVT = N->getValueType(0);
13558   SDValue V = N->getOperand(0);
13559 
13560   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13561     // Combine:
13562     //    (extract_subvec (concat V1, V2, ...), i)
13563     // Into:
13564     //    Vi if possible
13565     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13566     // type.
13567     if (V->getOperand(0).getValueType() != NVT)
13568       return SDValue();
13569     unsigned Idx = N->getConstantOperandVal(1);
13570     unsigned NumElems = NVT.getVectorNumElements();
13571     assert((Idx % NumElems) == 0 &&
13572            "IDX in concat is not a multiple of the result vector length.");
13573     return V->getOperand(Idx / NumElems);
13574   }
13575 
13576   // Skip bitcasting
13577   if (V->getOpcode() == ISD::BITCAST)
13578     V = V.getOperand(0);
13579 
13580   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13581     // Handle only simple case where vector being inserted and vector
13582     // being extracted are of same type, and are half size of larger vectors.
13583     EVT BigVT = V->getOperand(0).getValueType();
13584     EVT SmallVT = V->getOperand(1).getValueType();
13585     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13586       return SDValue();
13587 
13588     // Only handle cases where both indexes are constants with the same type.
13589     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13590     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13591 
13592     if (InsIdx && ExtIdx &&
13593         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13594         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13595       // Combine:
13596       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13597       // Into:
13598       //    indices are equal or bit offsets are equal => V1
13599       //    otherwise => (extract_subvec V1, ExtIdx)
13600       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
13601           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
13602         return DAG.getBitcast(NVT, V->getOperand(1));
13603       return DAG.getNode(
13604           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
13605           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13606           N->getOperand(1));
13607     }
13608   }
13609 
13610   return SDValue();
13611 }
13612 
13613 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13614                                                  SDValue V, SelectionDAG &DAG) {
13615   SDLoc DL(V);
13616   EVT VT = V.getValueType();
13617 
13618   switch (V.getOpcode()) {
13619   default:
13620     return V;
13621 
13622   case ISD::CONCAT_VECTORS: {
13623     EVT OpVT = V->getOperand(0).getValueType();
13624     int OpSize = OpVT.getVectorNumElements();
13625     SmallBitVector OpUsedElements(OpSize, false);
13626     bool FoundSimplification = false;
13627     SmallVector<SDValue, 4> NewOps;
13628     NewOps.reserve(V->getNumOperands());
13629     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13630       SDValue Op = V->getOperand(i);
13631       bool OpUsed = false;
13632       for (int j = 0; j < OpSize; ++j)
13633         if (UsedElements[i * OpSize + j]) {
13634           OpUsedElements[j] = true;
13635           OpUsed = true;
13636         }
13637       NewOps.push_back(
13638           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13639                  : DAG.getUNDEF(OpVT));
13640       FoundSimplification |= Op == NewOps.back();
13641       OpUsedElements.reset();
13642     }
13643     if (FoundSimplification)
13644       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13645     return V;
13646   }
13647 
13648   case ISD::INSERT_SUBVECTOR: {
13649     SDValue BaseV = V->getOperand(0);
13650     SDValue SubV = V->getOperand(1);
13651     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13652     if (!IdxN)
13653       return V;
13654 
13655     int SubSize = SubV.getValueType().getVectorNumElements();
13656     int Idx = IdxN->getZExtValue();
13657     bool SubVectorUsed = false;
13658     SmallBitVector SubUsedElements(SubSize, false);
13659     for (int i = 0; i < SubSize; ++i)
13660       if (UsedElements[i + Idx]) {
13661         SubVectorUsed = true;
13662         SubUsedElements[i] = true;
13663         UsedElements[i + Idx] = false;
13664       }
13665 
13666     // Now recurse on both the base and sub vectors.
13667     SDValue SimplifiedSubV =
13668         SubVectorUsed
13669             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13670             : DAG.getUNDEF(SubV.getValueType());
13671     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13672     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13673       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13674                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13675     return V;
13676   }
13677   }
13678 }
13679 
13680 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13681                                        SDValue N1, SelectionDAG &DAG) {
13682   EVT VT = SVN->getValueType(0);
13683   int NumElts = VT.getVectorNumElements();
13684   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13685   for (int M : SVN->getMask())
13686     if (M >= 0 && M < NumElts)
13687       N0UsedElements[M] = true;
13688     else if (M >= NumElts)
13689       N1UsedElements[M - NumElts] = true;
13690 
13691   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13692   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13693   if (S0 == N0 && S1 == N1)
13694     return SDValue();
13695 
13696   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13697 }
13698 
13699 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13700 // or turn a shuffle of a single concat into simpler shuffle then concat.
13701 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13702   EVT VT = N->getValueType(0);
13703   unsigned NumElts = VT.getVectorNumElements();
13704 
13705   SDValue N0 = N->getOperand(0);
13706   SDValue N1 = N->getOperand(1);
13707   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13708 
13709   SmallVector<SDValue, 4> Ops;
13710   EVT ConcatVT = N0.getOperand(0).getValueType();
13711   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13712   unsigned NumConcats = NumElts / NumElemsPerConcat;
13713 
13714   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13715   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13716   // half vector elements.
13717   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13718       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13719                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13720     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13721                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13722     N1 = DAG.getUNDEF(ConcatVT);
13723     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13724   }
13725 
13726   // Look at every vector that's inserted. We're looking for exact
13727   // subvector-sized copies from a concatenated vector
13728   for (unsigned I = 0; I != NumConcats; ++I) {
13729     // Make sure we're dealing with a copy.
13730     unsigned Begin = I * NumElemsPerConcat;
13731     bool AllUndef = true, NoUndef = true;
13732     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13733       if (SVN->getMaskElt(J) >= 0)
13734         AllUndef = false;
13735       else
13736         NoUndef = false;
13737     }
13738 
13739     if (NoUndef) {
13740       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13741         return SDValue();
13742 
13743       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13744         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13745           return SDValue();
13746 
13747       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13748       if (FirstElt < N0.getNumOperands())
13749         Ops.push_back(N0.getOperand(FirstElt));
13750       else
13751         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13752 
13753     } else if (AllUndef) {
13754       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13755     } else { // Mixed with general masks and undefs, can't do optimization.
13756       return SDValue();
13757     }
13758   }
13759 
13760   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13761 }
13762 
13763 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13764 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13765 // This combine is done in the following cases:
13766 // 1. Both N0,N1 are BUILD_VECTOR's composed of constants or undefs.
13767 // 2. Only one of N0,N1 is a BUILD_VECTOR composed of constants or undefs -
13768 //    Combine iff that node is ALL_ZEROS. We prefer not to combine a
13769 //    BUILD_VECTOR of all constants to allow efficient materialization of
13770 //    constant vectors, but the ALL_ZEROS is an exception because
13771 //    zero-extension matching seems to rely on having BUILD_VECTOR nodes with
13772 //    zero padding between elements. FIXME: Eliminate this exception for
13773 //    ALL_ZEROS constant vectors.
13774 // 3. Neither N0,N1 are composed of only constants.
13775 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
13776                                        SelectionDAG &DAG,
13777                                        const TargetLowering &TLI) {
13778   EVT VT = SVN->getValueType(0);
13779   unsigned NumElts = VT.getVectorNumElements();
13780   SDValue N0 = SVN->getOperand(0);
13781   SDValue N1 = SVN->getOperand(1);
13782 
13783   if (!N0->hasOneUse() || !N1->hasOneUse())
13784     return SDValue();
13785   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
13786   // discussed above.
13787   if (!N1.isUndef()) {
13788     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
13789     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
13790     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
13791       return SDValue();
13792     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
13793       return SDValue();
13794   }
13795 
13796   SmallVector<SDValue, 8> Ops;
13797   for (int M : SVN->getMask()) {
13798     SDValue Op = DAG.getUNDEF(VT.getScalarType());
13799     if (M >= 0) {
13800       int Idx = M < (int)NumElts ? M : M - NumElts;
13801       SDValue &S = (M < (int)NumElts ? N0 : N1);
13802       if (S.getOpcode() == ISD::BUILD_VECTOR) {
13803         Op = S.getOperand(Idx);
13804       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13805         if (Idx == 0)
13806           Op = S.getOperand(0);
13807       } else {
13808         // Operand can't be combined - bail out.
13809         return SDValue();
13810       }
13811     }
13812     Ops.push_back(Op);
13813   }
13814   // BUILD_VECTOR requires all inputs to be of the same type, find the
13815   // maximum type and extend them all.
13816   EVT SVT = VT.getScalarType();
13817   if (SVT.isInteger())
13818     for (SDValue &Op : Ops)
13819       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13820   if (SVT != VT.getScalarType())
13821     for (SDValue &Op : Ops)
13822       Op = TLI.isZExtFree(Op.getValueType(), SVT)
13823                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
13824                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
13825   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
13826 }
13827 
13828 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13829   EVT VT = N->getValueType(0);
13830   unsigned NumElts = VT.getVectorNumElements();
13831 
13832   SDValue N0 = N->getOperand(0);
13833   SDValue N1 = N->getOperand(1);
13834 
13835   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13836 
13837   // Canonicalize shuffle undef, undef -> undef
13838   if (N0.isUndef() && N1.isUndef())
13839     return DAG.getUNDEF(VT);
13840 
13841   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13842 
13843   // Canonicalize shuffle v, v -> v, undef
13844   if (N0 == N1) {
13845     SmallVector<int, 8> NewMask;
13846     for (unsigned i = 0; i != NumElts; ++i) {
13847       int Idx = SVN->getMaskElt(i);
13848       if (Idx >= (int)NumElts) Idx -= NumElts;
13849       NewMask.push_back(Idx);
13850     }
13851     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
13852   }
13853 
13854   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13855   if (N0.isUndef())
13856     return DAG.getCommutedVectorShuffle(*SVN);
13857 
13858   // Remove references to rhs if it is undef
13859   if (N1.isUndef()) {
13860     bool Changed = false;
13861     SmallVector<int, 8> NewMask;
13862     for (unsigned i = 0; i != NumElts; ++i) {
13863       int Idx = SVN->getMaskElt(i);
13864       if (Idx >= (int)NumElts) {
13865         Idx = -1;
13866         Changed = true;
13867       }
13868       NewMask.push_back(Idx);
13869     }
13870     if (Changed)
13871       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
13872   }
13873 
13874   // If it is a splat, check if the argument vector is another splat or a
13875   // build_vector.
13876   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13877     SDNode *V = N0.getNode();
13878 
13879     // If this is a bit convert that changes the element type of the vector but
13880     // not the number of vector elements, look through it.  Be careful not to
13881     // look though conversions that change things like v4f32 to v2f64.
13882     if (V->getOpcode() == ISD::BITCAST) {
13883       SDValue ConvInput = V->getOperand(0);
13884       if (ConvInput.getValueType().isVector() &&
13885           ConvInput.getValueType().getVectorNumElements() == NumElts)
13886         V = ConvInput.getNode();
13887     }
13888 
13889     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13890       assert(V->getNumOperands() == NumElts &&
13891              "BUILD_VECTOR has wrong number of operands");
13892       SDValue Base;
13893       bool AllSame = true;
13894       for (unsigned i = 0; i != NumElts; ++i) {
13895         if (!V->getOperand(i).isUndef()) {
13896           Base = V->getOperand(i);
13897           break;
13898         }
13899       }
13900       // Splat of <u, u, u, u>, return <u, u, u, u>
13901       if (!Base.getNode())
13902         return N0;
13903       for (unsigned i = 0; i != NumElts; ++i) {
13904         if (V->getOperand(i) != Base) {
13905           AllSame = false;
13906           break;
13907         }
13908       }
13909       // Splat of <x, x, x, x>, return <x, x, x, x>
13910       if (AllSame)
13911         return N0;
13912 
13913       // Canonicalize any other splat as a build_vector.
13914       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13915       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13916       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13917 
13918       // We may have jumped through bitcasts, so the type of the
13919       // BUILD_VECTOR may not match the type of the shuffle.
13920       if (V->getValueType(0) != VT)
13921         NewBV = DAG.getBitcast(VT, NewBV);
13922       return NewBV;
13923     }
13924   }
13925 
13926   // There are various patterns used to build up a vector from smaller vectors,
13927   // subvectors, or elements. Scan chains of these and replace unused insertions
13928   // or components with undef.
13929   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13930     return S;
13931 
13932   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13933       Level < AfterLegalizeVectorOps &&
13934       (N1.isUndef() ||
13935       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13936        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13937     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13938       return V;
13939   }
13940 
13941   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13942   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13943   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13944     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
13945       return Res;
13946 
13947   // If this shuffle only has a single input that is a bitcasted shuffle,
13948   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13949   // back to their original types.
13950   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13951       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13952       TLI.isTypeLegal(VT)) {
13953 
13954     // Peek through the bitcast only if there is one user.
13955     SDValue BC0 = N0;
13956     while (BC0.getOpcode() == ISD::BITCAST) {
13957       if (!BC0.hasOneUse())
13958         break;
13959       BC0 = BC0.getOperand(0);
13960     }
13961 
13962     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13963       if (Scale == 1)
13964         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13965 
13966       SmallVector<int, 8> NewMask;
13967       for (int M : Mask)
13968         for (int s = 0; s != Scale; ++s)
13969           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13970       return NewMask;
13971     };
13972 
13973     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13974       EVT SVT = VT.getScalarType();
13975       EVT InnerVT = BC0->getValueType(0);
13976       EVT InnerSVT = InnerVT.getScalarType();
13977 
13978       // Determine which shuffle works with the smaller scalar type.
13979       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13980       EVT ScaleSVT = ScaleVT.getScalarType();
13981 
13982       if (TLI.isTypeLegal(ScaleVT) &&
13983           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13984           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13985 
13986         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13987         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13988 
13989         // Scale the shuffle masks to the smaller scalar type.
13990         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13991         SmallVector<int, 8> InnerMask =
13992             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13993         SmallVector<int, 8> OuterMask =
13994             ScaleShuffleMask(SVN->getMask(), OuterScale);
13995 
13996         // Merge the shuffle masks.
13997         SmallVector<int, 8> NewMask;
13998         for (int M : OuterMask)
13999           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
14000 
14001         // Test for shuffle mask legality over both commutations.
14002         SDValue SV0 = BC0->getOperand(0);
14003         SDValue SV1 = BC0->getOperand(1);
14004         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14005         if (!LegalMask) {
14006           std::swap(SV0, SV1);
14007           ShuffleVectorSDNode::commuteMask(NewMask);
14008           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14009         }
14010 
14011         if (LegalMask) {
14012           SV0 = DAG.getBitcast(ScaleVT, SV0);
14013           SV1 = DAG.getBitcast(ScaleVT, SV1);
14014           return DAG.getBitcast(
14015               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
14016         }
14017       }
14018     }
14019   }
14020 
14021   // Canonicalize shuffles according to rules:
14022   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
14023   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
14024   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
14025   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
14026       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
14027       TLI.isTypeLegal(VT)) {
14028     // The incoming shuffle must be of the same type as the result of the
14029     // current shuffle.
14030     assert(N1->getOperand(0).getValueType() == VT &&
14031            "Shuffle types don't match");
14032 
14033     SDValue SV0 = N1->getOperand(0);
14034     SDValue SV1 = N1->getOperand(1);
14035     bool HasSameOp0 = N0 == SV0;
14036     bool IsSV1Undef = SV1.isUndef();
14037     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
14038       // Commute the operands of this shuffle so that next rule
14039       // will trigger.
14040       return DAG.getCommutedVectorShuffle(*SVN);
14041   }
14042 
14043   // Try to fold according to rules:
14044   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14045   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14046   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14047   // Don't try to fold shuffles with illegal type.
14048   // Only fold if this shuffle is the only user of the other shuffle.
14049   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
14050       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
14051     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
14052 
14053     // The incoming shuffle must be of the same type as the result of the
14054     // current shuffle.
14055     assert(OtherSV->getOperand(0).getValueType() == VT &&
14056            "Shuffle types don't match");
14057 
14058     SDValue SV0, SV1;
14059     SmallVector<int, 4> Mask;
14060     // Compute the combined shuffle mask for a shuffle with SV0 as the first
14061     // operand, and SV1 as the second operand.
14062     for (unsigned i = 0; i != NumElts; ++i) {
14063       int Idx = SVN->getMaskElt(i);
14064       if (Idx < 0) {
14065         // Propagate Undef.
14066         Mask.push_back(Idx);
14067         continue;
14068       }
14069 
14070       SDValue CurrentVec;
14071       if (Idx < (int)NumElts) {
14072         // This shuffle index refers to the inner shuffle N0. Lookup the inner
14073         // shuffle mask to identify which vector is actually referenced.
14074         Idx = OtherSV->getMaskElt(Idx);
14075         if (Idx < 0) {
14076           // Propagate Undef.
14077           Mask.push_back(Idx);
14078           continue;
14079         }
14080 
14081         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
14082                                            : OtherSV->getOperand(1);
14083       } else {
14084         // This shuffle index references an element within N1.
14085         CurrentVec = N1;
14086       }
14087 
14088       // Simple case where 'CurrentVec' is UNDEF.
14089       if (CurrentVec.isUndef()) {
14090         Mask.push_back(-1);
14091         continue;
14092       }
14093 
14094       // Canonicalize the shuffle index. We don't know yet if CurrentVec
14095       // will be the first or second operand of the combined shuffle.
14096       Idx = Idx % NumElts;
14097       if (!SV0.getNode() || SV0 == CurrentVec) {
14098         // Ok. CurrentVec is the left hand side.
14099         // Update the mask accordingly.
14100         SV0 = CurrentVec;
14101         Mask.push_back(Idx);
14102         continue;
14103       }
14104 
14105       // Bail out if we cannot convert the shuffle pair into a single shuffle.
14106       if (SV1.getNode() && SV1 != CurrentVec)
14107         return SDValue();
14108 
14109       // Ok. CurrentVec is the right hand side.
14110       // Update the mask accordingly.
14111       SV1 = CurrentVec;
14112       Mask.push_back(Idx + NumElts);
14113     }
14114 
14115     // Check if all indices in Mask are Undef. In case, propagate Undef.
14116     bool isUndefMask = true;
14117     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
14118       isUndefMask &= Mask[i] < 0;
14119 
14120     if (isUndefMask)
14121       return DAG.getUNDEF(VT);
14122 
14123     if (!SV0.getNode())
14124       SV0 = DAG.getUNDEF(VT);
14125     if (!SV1.getNode())
14126       SV1 = DAG.getUNDEF(VT);
14127 
14128     // Avoid introducing shuffles with illegal mask.
14129     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14130       ShuffleVectorSDNode::commuteMask(Mask);
14131 
14132       if (!TLI.isShuffleMaskLegal(Mask, VT))
14133         return SDValue();
14134 
14135       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14136       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14137       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14138       std::swap(SV0, SV1);
14139     }
14140 
14141     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14142     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14143     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14144     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14145   }
14146 
14147   return SDValue();
14148 }
14149 
14150 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14151   SDValue InVal = N->getOperand(0);
14152   EVT VT = N->getValueType(0);
14153 
14154   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14155   // with a VECTOR_SHUFFLE.
14156   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14157     SDValue InVec = InVal->getOperand(0);
14158     SDValue EltNo = InVal->getOperand(1);
14159 
14160     // FIXME: We could support implicit truncation if the shuffle can be
14161     // scaled to a smaller vector scalar type.
14162     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
14163     if (C0 && VT == InVec.getValueType() &&
14164         VT.getScalarType() == InVal.getValueType()) {
14165       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
14166       int Elt = C0->getZExtValue();
14167       NewMask[0] = Elt;
14168 
14169       if (TLI.isShuffleMaskLegal(NewMask, VT))
14170         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
14171                                     NewMask);
14172     }
14173   }
14174 
14175   return SDValue();
14176 }
14177 
14178 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
14179   EVT VT = N->getValueType(0);
14180   SDValue N0 = N->getOperand(0);
14181   SDValue N1 = N->getOperand(1);
14182   SDValue N2 = N->getOperand(2);
14183 
14184   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
14185   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
14186   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
14187   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
14188       N0.getOperand(1).getValueType() == N1.getValueType() &&
14189       N0.getOperand(2) == N2)
14190     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
14191                        N1, N2);
14192 
14193   if (N0.getValueType() != N1.getValueType())
14194     return SDValue();
14195 
14196   // If the input vector is a concatenation, and the insert replaces
14197   // one of the halves, we can optimize into a single concat_vectors.
14198   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
14199       N2.getOpcode() == ISD::Constant) {
14200     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
14201 
14202     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14203     // (concat_vectors Z, Y)
14204     if (InsIdx == 0)
14205       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
14206                          N0.getOperand(1));
14207 
14208     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14209     // (concat_vectors X, Z)
14210     if (InsIdx == VT.getVectorNumElements() / 2)
14211       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
14212                          N1);
14213   }
14214 
14215   return SDValue();
14216 }
14217 
14218 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
14219   SDValue N0 = N->getOperand(0);
14220 
14221   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
14222   if (N0->getOpcode() == ISD::FP16_TO_FP)
14223     return N0->getOperand(0);
14224 
14225   return SDValue();
14226 }
14227 
14228 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
14229   SDValue N0 = N->getOperand(0);
14230 
14231   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
14232   if (N0->getOpcode() == ISD::AND) {
14233     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
14234     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
14235       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
14236                          N0.getOperand(0));
14237     }
14238   }
14239 
14240   return SDValue();
14241 }
14242 
14243 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
14244 /// with the destination vector and a zero vector.
14245 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
14246 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
14247 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
14248   EVT VT = N->getValueType(0);
14249   SDValue LHS = N->getOperand(0);
14250   SDValue RHS = N->getOperand(1);
14251   SDLoc DL(N);
14252 
14253   // Make sure we're not running after operation legalization where it
14254   // may have custom lowered the vector shuffles.
14255   if (LegalOperations)
14256     return SDValue();
14257 
14258   if (N->getOpcode() != ISD::AND)
14259     return SDValue();
14260 
14261   if (RHS.getOpcode() == ISD::BITCAST)
14262     RHS = RHS.getOperand(0);
14263 
14264   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
14265     return SDValue();
14266 
14267   EVT RVT = RHS.getValueType();
14268   unsigned NumElts = RHS.getNumOperands();
14269 
14270   // Attempt to create a valid clear mask, splitting the mask into
14271   // sub elements and checking to see if each is
14272   // all zeros or all ones - suitable for shuffle masking.
14273   auto BuildClearMask = [&](int Split) {
14274     int NumSubElts = NumElts * Split;
14275     int NumSubBits = RVT.getScalarSizeInBits() / Split;
14276 
14277     SmallVector<int, 8> Indices;
14278     for (int i = 0; i != NumSubElts; ++i) {
14279       int EltIdx = i / Split;
14280       int SubIdx = i % Split;
14281       SDValue Elt = RHS.getOperand(EltIdx);
14282       if (Elt.isUndef()) {
14283         Indices.push_back(-1);
14284         continue;
14285       }
14286 
14287       APInt Bits;
14288       if (isa<ConstantSDNode>(Elt))
14289         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
14290       else if (isa<ConstantFPSDNode>(Elt))
14291         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
14292       else
14293         return SDValue();
14294 
14295       // Extract the sub element from the constant bit mask.
14296       if (DAG.getDataLayout().isBigEndian()) {
14297         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
14298       } else {
14299         Bits = Bits.lshr(SubIdx * NumSubBits);
14300       }
14301 
14302       if (Split > 1)
14303         Bits = Bits.trunc(NumSubBits);
14304 
14305       if (Bits.isAllOnesValue())
14306         Indices.push_back(i);
14307       else if (Bits == 0)
14308         Indices.push_back(i + NumSubElts);
14309       else
14310         return SDValue();
14311     }
14312 
14313     // Let's see if the target supports this vector_shuffle.
14314     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
14315     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
14316     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
14317       return SDValue();
14318 
14319     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
14320     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
14321                                                    DAG.getBitcast(ClearVT, LHS),
14322                                                    Zero, Indices));
14323   };
14324 
14325   // Determine maximum split level (byte level masking).
14326   int MaxSplit = 1;
14327   if (RVT.getScalarSizeInBits() % 8 == 0)
14328     MaxSplit = RVT.getScalarSizeInBits() / 8;
14329 
14330   for (int Split = 1; Split <= MaxSplit; ++Split)
14331     if (RVT.getScalarSizeInBits() % Split == 0)
14332       if (SDValue S = BuildClearMask(Split))
14333         return S;
14334 
14335   return SDValue();
14336 }
14337 
14338 /// Visit a binary vector operation, like ADD.
14339 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
14340   assert(N->getValueType(0).isVector() &&
14341          "SimplifyVBinOp only works on vectors!");
14342 
14343   SDValue LHS = N->getOperand(0);
14344   SDValue RHS = N->getOperand(1);
14345   SDValue Ops[] = {LHS, RHS};
14346 
14347   // See if we can constant fold the vector operation.
14348   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
14349           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
14350     return Fold;
14351 
14352   // Try to convert a constant mask AND into a shuffle clear mask.
14353   if (SDValue Shuffle = XformToShuffleWithZero(N))
14354     return Shuffle;
14355 
14356   // Type legalization might introduce new shuffles in the DAG.
14357   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
14358   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
14359   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
14360       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
14361       LHS.getOperand(1).isUndef() &&
14362       RHS.getOperand(1).isUndef()) {
14363     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
14364     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
14365 
14366     if (SVN0->getMask().equals(SVN1->getMask())) {
14367       EVT VT = N->getValueType(0);
14368       SDValue UndefVector = LHS.getOperand(1);
14369       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
14370                                      LHS.getOperand(0), RHS.getOperand(0),
14371                                      N->getFlags());
14372       AddUsersToWorklist(N);
14373       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
14374                                   SVN0->getMask());
14375     }
14376   }
14377 
14378   return SDValue();
14379 }
14380 
14381 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
14382                                     SDValue N2) {
14383   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
14384 
14385   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
14386                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
14387 
14388   // If we got a simplified select_cc node back from SimplifySelectCC, then
14389   // break it down into a new SETCC node, and a new SELECT node, and then return
14390   // the SELECT node, since we were called with a SELECT node.
14391   if (SCC.getNode()) {
14392     // Check to see if we got a select_cc back (to turn into setcc/select).
14393     // Otherwise, just return whatever node we got back, like fabs.
14394     if (SCC.getOpcode() == ISD::SELECT_CC) {
14395       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
14396                                   N0.getValueType(),
14397                                   SCC.getOperand(0), SCC.getOperand(1),
14398                                   SCC.getOperand(4));
14399       AddToWorklist(SETCC.getNode());
14400       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14401                            SCC.getOperand(2), SCC.getOperand(3));
14402     }
14403 
14404     return SCC;
14405   }
14406   return SDValue();
14407 }
14408 
14409 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14410 /// being selected between, see if we can simplify the select.  Callers of this
14411 /// should assume that TheSelect is deleted if this returns true.  As such, they
14412 /// should return the appropriate thing (e.g. the node) back to the top-level of
14413 /// the DAG combiner loop to avoid it being looked at.
14414 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14415                                     SDValue RHS) {
14416 
14417   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14418   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14419   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14420     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14421       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14422       SDValue Sqrt = RHS;
14423       ISD::CondCode CC;
14424       SDValue CmpLHS;
14425       const ConstantFPSDNode *Zero = nullptr;
14426 
14427       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14428         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14429         CmpLHS = TheSelect->getOperand(0);
14430         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14431       } else {
14432         // SELECT or VSELECT
14433         SDValue Cmp = TheSelect->getOperand(0);
14434         if (Cmp.getOpcode() == ISD::SETCC) {
14435           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14436           CmpLHS = Cmp.getOperand(0);
14437           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14438         }
14439       }
14440       if (Zero && Zero->isZero() &&
14441           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14442           CC == ISD::SETULT || CC == ISD::SETLT)) {
14443         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14444         CombineTo(TheSelect, Sqrt);
14445         return true;
14446       }
14447     }
14448   }
14449   // Cannot simplify select with vector condition
14450   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14451 
14452   // If this is a select from two identical things, try to pull the operation
14453   // through the select.
14454   if (LHS.getOpcode() != RHS.getOpcode() ||
14455       !LHS.hasOneUse() || !RHS.hasOneUse())
14456     return false;
14457 
14458   // If this is a load and the token chain is identical, replace the select
14459   // of two loads with a load through a select of the address to load from.
14460   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14461   // constants have been dropped into the constant pool.
14462   if (LHS.getOpcode() == ISD::LOAD) {
14463     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14464     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14465 
14466     // Token chains must be identical.
14467     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14468         // Do not let this transformation reduce the number of volatile loads.
14469         LLD->isVolatile() || RLD->isVolatile() ||
14470         // FIXME: If either is a pre/post inc/dec load,
14471         // we'd need to split out the address adjustment.
14472         LLD->isIndexed() || RLD->isIndexed() ||
14473         // If this is an EXTLOAD, the VT's must match.
14474         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14475         // If this is an EXTLOAD, the kind of extension must match.
14476         (LLD->getExtensionType() != RLD->getExtensionType() &&
14477          // The only exception is if one of the extensions is anyext.
14478          LLD->getExtensionType() != ISD::EXTLOAD &&
14479          RLD->getExtensionType() != ISD::EXTLOAD) ||
14480         // FIXME: this discards src value information.  This is
14481         // over-conservative. It would be beneficial to be able to remember
14482         // both potential memory locations.  Since we are discarding
14483         // src value info, don't do the transformation if the memory
14484         // locations are not in the default address space.
14485         LLD->getPointerInfo().getAddrSpace() != 0 ||
14486         RLD->getPointerInfo().getAddrSpace() != 0 ||
14487         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14488                                       LLD->getBasePtr().getValueType()))
14489       return false;
14490 
14491     // Check that the select condition doesn't reach either load.  If so,
14492     // folding this will induce a cycle into the DAG.  If not, this is safe to
14493     // xform, so create a select of the addresses.
14494     SDValue Addr;
14495     if (TheSelect->getOpcode() == ISD::SELECT) {
14496       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14497       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14498           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14499         return false;
14500       // The loads must not depend on one another.
14501       if (LLD->isPredecessorOf(RLD) ||
14502           RLD->isPredecessorOf(LLD))
14503         return false;
14504       Addr = DAG.getSelect(SDLoc(TheSelect),
14505                            LLD->getBasePtr().getValueType(),
14506                            TheSelect->getOperand(0), LLD->getBasePtr(),
14507                            RLD->getBasePtr());
14508     } else {  // Otherwise SELECT_CC
14509       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14510       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14511 
14512       if ((LLD->hasAnyUseOfValue(1) &&
14513            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14514           (RLD->hasAnyUseOfValue(1) &&
14515            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14516         return false;
14517 
14518       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14519                          LLD->getBasePtr().getValueType(),
14520                          TheSelect->getOperand(0),
14521                          TheSelect->getOperand(1),
14522                          LLD->getBasePtr(), RLD->getBasePtr(),
14523                          TheSelect->getOperand(4));
14524     }
14525 
14526     SDValue Load;
14527     // It is safe to replace the two loads if they have different alignments,
14528     // but the new load must be the minimum (most restrictive) alignment of the
14529     // inputs.
14530     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14531     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
14532     if (!RLD->isInvariant())
14533       MMOFlags &= ~MachineMemOperand::MOInvariant;
14534     if (!RLD->isDereferenceable())
14535       MMOFlags &= ~MachineMemOperand::MODereferenceable;
14536     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14537       // FIXME: Discards pointer and AA info.
14538       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
14539                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
14540                          MMOFlags);
14541     } else {
14542       // FIXME: Discards pointer and AA info.
14543       Load = DAG.getExtLoad(
14544           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
14545                                                   : LLD->getExtensionType(),
14546           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
14547           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
14548     }
14549 
14550     // Users of the select now use the result of the load.
14551     CombineTo(TheSelect, Load);
14552 
14553     // Users of the old loads now use the new load's chain.  We know the
14554     // old-load value is dead now.
14555     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14556     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14557     return true;
14558   }
14559 
14560   return false;
14561 }
14562 
14563 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14564 /// where 'cond' is the comparison specified by CC.
14565 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
14566                                       SDValue N2, SDValue N3, ISD::CondCode CC,
14567                                       bool NotExtCompare) {
14568   // (x ? y : y) -> y.
14569   if (N2 == N3) return N2;
14570 
14571   EVT VT = N2.getValueType();
14572   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14573   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14574 
14575   // Determine if the condition we're dealing with is constant
14576   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14577                               N0, N1, CC, DL, false);
14578   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14579 
14580   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14581     // fold select_cc true, x, y -> x
14582     // fold select_cc false, x, y -> y
14583     return !SCCC->isNullValue() ? N2 : N3;
14584   }
14585 
14586   // Check to see if we can simplify the select into an fabs node
14587   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14588     // Allow either -0.0 or 0.0
14589     if (CFP->isZero()) {
14590       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14591       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14592           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14593           N2 == N3.getOperand(0))
14594         return DAG.getNode(ISD::FABS, DL, VT, N0);
14595 
14596       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14597       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14598           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14599           N2.getOperand(0) == N3)
14600         return DAG.getNode(ISD::FABS, DL, VT, N3);
14601     }
14602   }
14603 
14604   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14605   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14606   // in it.  This is a win when the constant is not otherwise available because
14607   // it replaces two constant pool loads with one.  We only do this if the FP
14608   // type is known to be legal, because if it isn't, then we are before legalize
14609   // types an we want the other legalization to happen first (e.g. to avoid
14610   // messing with soft float) and if the ConstantFP is not legal, because if
14611   // it is legal, we may not need to store the FP constant in a constant pool.
14612   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14613     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14614       if (TLI.isTypeLegal(N2.getValueType()) &&
14615           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14616                TargetLowering::Legal &&
14617            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14618            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14619           // If both constants have multiple uses, then we won't need to do an
14620           // extra load, they are likely around in registers for other users.
14621           (TV->hasOneUse() || FV->hasOneUse())) {
14622         Constant *Elts[] = {
14623           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14624           const_cast<ConstantFP*>(TV->getConstantFPValue())
14625         };
14626         Type *FPTy = Elts[0]->getType();
14627         const DataLayout &TD = DAG.getDataLayout();
14628 
14629         // Create a ConstantArray of the two constants.
14630         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14631         SDValue CPIdx =
14632             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14633                                 TD.getPrefTypeAlignment(FPTy));
14634         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14635 
14636         // Get the offsets to the 0 and 1 element of the array so that we can
14637         // select between them.
14638         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14639         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14640         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14641 
14642         SDValue Cond = DAG.getSetCC(DL,
14643                                     getSetCCResultType(N0.getValueType()),
14644                                     N0, N1, CC);
14645         AddToWorklist(Cond.getNode());
14646         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14647                                           Cond, One, Zero);
14648         AddToWorklist(CstOffset.getNode());
14649         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14650                             CstOffset);
14651         AddToWorklist(CPIdx.getNode());
14652         return DAG.getLoad(
14653             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14654             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14655             Alignment);
14656       }
14657     }
14658 
14659   // Check to see if we can perform the "gzip trick", transforming
14660   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14661   if (isNullConstant(N3) && CC == ISD::SETLT &&
14662       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14663        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14664     EVT XType = N0.getValueType();
14665     EVT AType = N2.getValueType();
14666     if (XType.bitsGE(AType)) {
14667       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14668       // single-bit constant.
14669       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14670         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14671         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14672         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14673                                        getShiftAmountTy(N0.getValueType()));
14674         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14675                                     XType, N0, ShCt);
14676         AddToWorklist(Shift.getNode());
14677 
14678         if (XType.bitsGT(AType)) {
14679           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14680           AddToWorklist(Shift.getNode());
14681         }
14682 
14683         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14684       }
14685 
14686       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14687                                   XType, N0,
14688                                   DAG.getConstant(XType.getSizeInBits() - 1,
14689                                                   SDLoc(N0),
14690                                          getShiftAmountTy(N0.getValueType())));
14691       AddToWorklist(Shift.getNode());
14692 
14693       if (XType.bitsGT(AType)) {
14694         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14695         AddToWorklist(Shift.getNode());
14696       }
14697 
14698       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14699     }
14700   }
14701 
14702   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14703   // where y is has a single bit set.
14704   // A plaintext description would be, we can turn the SELECT_CC into an AND
14705   // when the condition can be materialized as an all-ones register.  Any
14706   // single bit-test can be materialized as an all-ones register with
14707   // shift-left and shift-right-arith.
14708   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14709       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14710     SDValue AndLHS = N0->getOperand(0);
14711     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14712     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14713       // Shift the tested bit over the sign bit.
14714       const APInt &AndMask = ConstAndRHS->getAPIntValue();
14715       SDValue ShlAmt =
14716         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14717                         getShiftAmountTy(AndLHS.getValueType()));
14718       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14719 
14720       // Now arithmetic right shift it all the way over, so the result is either
14721       // all-ones, or zero.
14722       SDValue ShrAmt =
14723         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14724                         getShiftAmountTy(Shl.getValueType()));
14725       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14726 
14727       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14728     }
14729   }
14730 
14731   // fold select C, 16, 0 -> shl C, 4
14732   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14733       TLI.getBooleanContents(N0.getValueType()) ==
14734           TargetLowering::ZeroOrOneBooleanContent) {
14735 
14736     // If the caller doesn't want us to simplify this into a zext of a compare,
14737     // don't do it.
14738     if (NotExtCompare && N2C->isOne())
14739       return SDValue();
14740 
14741     // Get a SetCC of the condition
14742     // NOTE: Don't create a SETCC if it's not legal on this target.
14743     if (!LegalOperations ||
14744         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14745       SDValue Temp, SCC;
14746       // cast from setcc result type to select result type
14747       if (LegalTypes) {
14748         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14749                             N0, N1, CC);
14750         if (N2.getValueType().bitsLT(SCC.getValueType()))
14751           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14752                                         N2.getValueType());
14753         else
14754           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14755                              N2.getValueType(), SCC);
14756       } else {
14757         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14758         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14759                            N2.getValueType(), SCC);
14760       }
14761 
14762       AddToWorklist(SCC.getNode());
14763       AddToWorklist(Temp.getNode());
14764 
14765       if (N2C->isOne())
14766         return Temp;
14767 
14768       // shl setcc result by log2 n2c
14769       return DAG.getNode(
14770           ISD::SHL, DL, N2.getValueType(), Temp,
14771           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14772                           getShiftAmountTy(Temp.getValueType())));
14773     }
14774   }
14775 
14776   // Check to see if this is an integer abs.
14777   // select_cc setg[te] X,  0,  X, -X ->
14778   // select_cc setgt    X, -1,  X, -X ->
14779   // select_cc setl[te] X,  0, -X,  X ->
14780   // select_cc setlt    X,  1, -X,  X ->
14781   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14782   if (N1C) {
14783     ConstantSDNode *SubC = nullptr;
14784     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14785          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14786         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14787       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14788     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14789               (N1C->isOne() && CC == ISD::SETLT)) &&
14790              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14791       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14792 
14793     EVT XType = N0.getValueType();
14794     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14795       SDLoc DL(N0);
14796       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14797                                   N0,
14798                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14799                                          getShiftAmountTy(N0.getValueType())));
14800       SDValue Add = DAG.getNode(ISD::ADD, DL,
14801                                 XType, N0, Shift);
14802       AddToWorklist(Shift.getNode());
14803       AddToWorklist(Add.getNode());
14804       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14805     }
14806   }
14807 
14808   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14809   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14810   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14811   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14812   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14813   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14814   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14815   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14816   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14817     SDValue ValueOnZero = N2;
14818     SDValue Count = N3;
14819     // If the condition is NE instead of E, swap the operands.
14820     if (CC == ISD::SETNE)
14821       std::swap(ValueOnZero, Count);
14822     // Check if the value on zero is a constant equal to the bits in the type.
14823     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14824       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14825         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14826         // legal, combine to just cttz.
14827         if ((Count.getOpcode() == ISD::CTTZ ||
14828              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14829             N0 == Count.getOperand(0) &&
14830             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14831           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14832         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14833         // legal, combine to just ctlz.
14834         if ((Count.getOpcode() == ISD::CTLZ ||
14835              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14836             N0 == Count.getOperand(0) &&
14837             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14838           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14839       }
14840     }
14841   }
14842 
14843   return SDValue();
14844 }
14845 
14846 /// This is a stub for TargetLowering::SimplifySetCC.
14847 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
14848                                    ISD::CondCode Cond, const SDLoc &DL,
14849                                    bool foldBooleans) {
14850   TargetLowering::DAGCombinerInfo
14851     DagCombineInfo(DAG, Level, false, this);
14852   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14853 }
14854 
14855 /// Given an ISD::SDIV node expressing a divide by constant, return
14856 /// a DAG expression to select that will generate the same value by multiplying
14857 /// by a magic number.
14858 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14859 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14860   // when optimising for minimum size, we don't want to expand a div to a mul
14861   // and a shift.
14862   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14863     return SDValue();
14864 
14865   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14866   if (!C)
14867     return SDValue();
14868 
14869   // Avoid division by zero.
14870   if (C->isNullValue())
14871     return SDValue();
14872 
14873   std::vector<SDNode*> Built;
14874   SDValue S =
14875       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14876 
14877   for (SDNode *N : Built)
14878     AddToWorklist(N);
14879   return S;
14880 }
14881 
14882 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14883 /// DAG expression that will generate the same value by right shifting.
14884 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14885   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14886   if (!C)
14887     return SDValue();
14888 
14889   // Avoid division by zero.
14890   if (C->isNullValue())
14891     return SDValue();
14892 
14893   std::vector<SDNode *> Built;
14894   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14895 
14896   for (SDNode *N : Built)
14897     AddToWorklist(N);
14898   return S;
14899 }
14900 
14901 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14902 /// expression that will generate the same value by multiplying by a magic
14903 /// number.
14904 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14905 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14906   // when optimising for minimum size, we don't want to expand a div to a mul
14907   // and a shift.
14908   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14909     return SDValue();
14910 
14911   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14912   if (!C)
14913     return SDValue();
14914 
14915   // Avoid division by zero.
14916   if (C->isNullValue())
14917     return SDValue();
14918 
14919   std::vector<SDNode*> Built;
14920   SDValue S =
14921       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14922 
14923   for (SDNode *N : Built)
14924     AddToWorklist(N);
14925   return S;
14926 }
14927 
14928 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14929   if (Level >= AfterLegalizeDAG)
14930     return SDValue();
14931 
14932   // TODO: Handle half and/or extended types?
14933   EVT VT = Op.getValueType();
14934   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
14935     return SDValue();
14936 
14937   // If estimates are explicitly disabled for this function, we're done.
14938   MachineFunction &MF = DAG.getMachineFunction();
14939   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
14940   if (Enabled == TLI.ReciprocalEstimate::Disabled)
14941     return SDValue();
14942 
14943   // Estimates may be explicitly enabled for this type with a custom number of
14944   // refinement steps.
14945   int Iterations = TLI.getDivRefinementSteps(VT, MF);
14946   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
14947     if (Iterations) {
14948       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14949       // For the reciprocal, we need to find the zero of the function:
14950       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14951       //     =>
14952       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14953       //     does not require additional intermediate precision]
14954       EVT VT = Op.getValueType();
14955       SDLoc DL(Op);
14956       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14957 
14958       AddToWorklist(Est.getNode());
14959 
14960       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14961       for (int i = 0; i < Iterations; ++i) {
14962         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14963         AddToWorklist(NewEst.getNode());
14964 
14965         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14966         AddToWorklist(NewEst.getNode());
14967 
14968         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14969         AddToWorklist(NewEst.getNode());
14970 
14971         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14972         AddToWorklist(Est.getNode());
14973       }
14974     }
14975     return Est;
14976   }
14977 
14978   return SDValue();
14979 }
14980 
14981 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14982 /// For the reciprocal sqrt, we need to find the zero of the function:
14983 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14984 ///     =>
14985 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14986 /// As a result, we precompute A/2 prior to the iteration loop.
14987 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
14988                                          unsigned Iterations,
14989                                          SDNodeFlags *Flags, bool Reciprocal) {
14990   EVT VT = Arg.getValueType();
14991   SDLoc DL(Arg);
14992   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14993 
14994   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14995   // this entire sequence requires only one FP constant.
14996   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14997   AddToWorklist(HalfArg.getNode());
14998 
14999   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
15000   AddToWorklist(HalfArg.getNode());
15001 
15002   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
15003   for (unsigned i = 0; i < Iterations; ++i) {
15004     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
15005     AddToWorklist(NewEst.getNode());
15006 
15007     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
15008     AddToWorklist(NewEst.getNode());
15009 
15010     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
15011     AddToWorklist(NewEst.getNode());
15012 
15013     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15014     AddToWorklist(Est.getNode());
15015   }
15016 
15017   // If non-reciprocal square root is requested, multiply the result by Arg.
15018   if (!Reciprocal) {
15019     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
15020     AddToWorklist(Est.getNode());
15021   }
15022 
15023   return Est;
15024 }
15025 
15026 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15027 /// For the reciprocal sqrt, we need to find the zero of the function:
15028 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15029 ///     =>
15030 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
15031 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
15032                                          unsigned Iterations,
15033                                          SDNodeFlags *Flags, bool Reciprocal) {
15034   EVT VT = Arg.getValueType();
15035   SDLoc DL(Arg);
15036   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
15037   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
15038 
15039   // This routine must enter the loop below to work correctly
15040   // when (Reciprocal == false).
15041   assert(Iterations > 0);
15042 
15043   // Newton iterations for reciprocal square root:
15044   // E = (E * -0.5) * ((A * E) * E + -3.0)
15045   for (unsigned i = 0; i < Iterations; ++i) {
15046     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
15047     AddToWorklist(AE.getNode());
15048 
15049     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
15050     AddToWorklist(AEE.getNode());
15051 
15052     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
15053     AddToWorklist(RHS.getNode());
15054 
15055     // When calculating a square root at the last iteration build:
15056     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
15057     // (notice a common subexpression)
15058     SDValue LHS;
15059     if (Reciprocal || (i + 1) < Iterations) {
15060       // RSQRT: LHS = (E * -0.5)
15061       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
15062     } else {
15063       // SQRT: LHS = (A * E) * -0.5
15064       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
15065     }
15066     AddToWorklist(LHS.getNode());
15067 
15068     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
15069     AddToWorklist(Est.getNode());
15070   }
15071 
15072   return Est;
15073 }
15074 
15075 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
15076 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
15077 /// Op can be zero.
15078 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
15079                                            bool Reciprocal) {
15080   if (Level >= AfterLegalizeDAG)
15081     return SDValue();
15082 
15083   // TODO: Handle half and/or extended types?
15084   EVT VT = Op.getValueType();
15085   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15086     return SDValue();
15087 
15088   // If estimates are explicitly disabled for this function, we're done.
15089   MachineFunction &MF = DAG.getMachineFunction();
15090   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
15091   if (Enabled == TLI.ReciprocalEstimate::Disabled)
15092     return SDValue();
15093 
15094   // Estimates may be explicitly enabled for this type with a custom number of
15095   // refinement steps.
15096   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
15097 
15098   bool UseOneConstNR = false;
15099   if (SDValue Est =
15100       TLI.getRsqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR)) {
15101     AddToWorklist(Est.getNode());
15102     if (Iterations) {
15103       Est = UseOneConstNR
15104       ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
15105       : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
15106     }
15107     return Est;
15108   }
15109 
15110   return SDValue();
15111 }
15112 
15113 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15114   return buildSqrtEstimateImpl(Op, Flags, true);
15115 }
15116 
15117 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15118   SDValue Est = buildSqrtEstimateImpl(Op, Flags, false);
15119   if (!Est)
15120     return SDValue();
15121 
15122   // Unfortunately, Est is now NaN if the input was exactly 0.
15123   // Select out this case and force the answer to 0.
15124   EVT VT = Est.getValueType();
15125   SDLoc DL(Op);
15126   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
15127   EVT CCVT = getSetCCResultType(VT);
15128   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, Zero, ISD::SETEQ);
15129   AddToWorklist(ZeroCmp.getNode());
15130 
15131   Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, ZeroCmp,
15132                     Zero, Est);
15133   AddToWorklist(Est.getNode());
15134   return Est;
15135 }
15136 
15137 /// Return true if base is a frame index, which is known not to alias with
15138 /// anything but itself.  Provides base object and offset as results.
15139 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
15140                            const GlobalValue *&GV, const void *&CV) {
15141   // Assume it is a primitive operation.
15142   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
15143 
15144   // If it's an adding a simple constant then integrate the offset.
15145   if (Base.getOpcode() == ISD::ADD) {
15146     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
15147       Base = Base.getOperand(0);
15148       Offset += C->getZExtValue();
15149     }
15150   }
15151 
15152   // Return the underlying GlobalValue, and update the Offset.  Return false
15153   // for GlobalAddressSDNode since the same GlobalAddress may be represented
15154   // by multiple nodes with different offsets.
15155   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
15156     GV = G->getGlobal();
15157     Offset += G->getOffset();
15158     return false;
15159   }
15160 
15161   // Return the underlying Constant value, and update the Offset.  Return false
15162   // for ConstantSDNodes since the same constant pool entry may be represented
15163   // by multiple nodes with different offsets.
15164   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
15165     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
15166                                          : (const void *)C->getConstVal();
15167     Offset += C->getOffset();
15168     return false;
15169   }
15170   // If it's any of the following then it can't alias with anything but itself.
15171   return isa<FrameIndexSDNode>(Base);
15172 }
15173 
15174 /// Return true if there is any possibility that the two addresses overlap.
15175 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
15176   // If they are the same then they must be aliases.
15177   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
15178 
15179   // If they are both volatile then they cannot be reordered.
15180   if (Op0->isVolatile() && Op1->isVolatile()) return true;
15181 
15182   // If one operation reads from invariant memory, and the other may store, they
15183   // cannot alias. These should really be checking the equivalent of mayWrite,
15184   // but it only matters for memory nodes other than load /store.
15185   if (Op0->isInvariant() && Op1->writeMem())
15186     return false;
15187 
15188   if (Op1->isInvariant() && Op0->writeMem())
15189     return false;
15190 
15191   // Gather base node and offset information.
15192   SDValue Base1, Base2;
15193   int64_t Offset1, Offset2;
15194   const GlobalValue *GV1, *GV2;
15195   const void *CV1, *CV2;
15196   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
15197                                       Base1, Offset1, GV1, CV1);
15198   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
15199                                       Base2, Offset2, GV2, CV2);
15200 
15201   // If they have a same base address then check to see if they overlap.
15202   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
15203     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15204              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15205 
15206   // It is possible for different frame indices to alias each other, mostly
15207   // when tail call optimization reuses return address slots for arguments.
15208   // To catch this case, look up the actual index of frame indices to compute
15209   // the real alias relationship.
15210   if (isFrameIndex1 && isFrameIndex2) {
15211     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
15212     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
15213     Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
15214     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15215              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15216   }
15217 
15218   // Otherwise, if we know what the bases are, and they aren't identical, then
15219   // we know they cannot alias.
15220   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
15221     return false;
15222 
15223   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
15224   // compared to the size and offset of the access, we may be able to prove they
15225   // do not alias.  This check is conservative for now to catch cases created by
15226   // splitting vector types.
15227   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
15228       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
15229       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
15230        Op1->getMemoryVT().getSizeInBits() >> 3) &&
15231       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
15232     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
15233     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
15234 
15235     // There is no overlap between these relatively aligned accesses of similar
15236     // size, return no alias.
15237     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
15238         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
15239       return false;
15240   }
15241 
15242   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
15243                    ? CombinerGlobalAA
15244                    : DAG.getSubtarget().useAA();
15245 #ifndef NDEBUG
15246   if (CombinerAAOnlyFunc.getNumOccurrences() &&
15247       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
15248     UseAA = false;
15249 #endif
15250   if (UseAA &&
15251       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
15252     // Use alias analysis information.
15253     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
15254                                  Op1->getSrcValueOffset());
15255     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
15256         Op0->getSrcValueOffset() - MinOffset;
15257     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
15258         Op1->getSrcValueOffset() - MinOffset;
15259     AliasResult AAResult =
15260         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
15261                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
15262                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
15263                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
15264     if (AAResult == NoAlias)
15265       return false;
15266   }
15267 
15268   // Otherwise we have to assume they alias.
15269   return true;
15270 }
15271 
15272 /// Walk up chain skipping non-aliasing memory nodes,
15273 /// looking for aliasing nodes and adding them to the Aliases vector.
15274 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
15275                                    SmallVectorImpl<SDValue> &Aliases) {
15276   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
15277   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
15278 
15279   // Get alias information for node.
15280   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
15281 
15282   // Starting off.
15283   Chains.push_back(OriginalChain);
15284   unsigned Depth = 0;
15285 
15286   // Look at each chain and determine if it is an alias.  If so, add it to the
15287   // aliases list.  If not, then continue up the chain looking for the next
15288   // candidate.
15289   while (!Chains.empty()) {
15290     SDValue Chain = Chains.pop_back_val();
15291 
15292     // For TokenFactor nodes, look at each operand and only continue up the
15293     // chain until we reach the depth limit.
15294     //
15295     // FIXME: The depth check could be made to return the last non-aliasing
15296     // chain we found before we hit a tokenfactor rather than the original
15297     // chain.
15298     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
15299       Aliases.clear();
15300       Aliases.push_back(OriginalChain);
15301       return;
15302     }
15303 
15304     // Don't bother if we've been before.
15305     if (!Visited.insert(Chain.getNode()).second)
15306       continue;
15307 
15308     switch (Chain.getOpcode()) {
15309     case ISD::EntryToken:
15310       // Entry token is ideal chain operand, but handled in FindBetterChain.
15311       break;
15312 
15313     case ISD::LOAD:
15314     case ISD::STORE: {
15315       // Get alias information for Chain.
15316       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
15317           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
15318 
15319       // If chain is alias then stop here.
15320       if (!(IsLoad && IsOpLoad) &&
15321           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
15322         Aliases.push_back(Chain);
15323       } else {
15324         // Look further up the chain.
15325         Chains.push_back(Chain.getOperand(0));
15326         ++Depth;
15327       }
15328       break;
15329     }
15330 
15331     case ISD::TokenFactor:
15332       // We have to check each of the operands of the token factor for "small"
15333       // token factors, so we queue them up.  Adding the operands to the queue
15334       // (stack) in reverse order maintains the original order and increases the
15335       // likelihood that getNode will find a matching token factor (CSE.)
15336       if (Chain.getNumOperands() > 16) {
15337         Aliases.push_back(Chain);
15338         break;
15339       }
15340       for (unsigned n = Chain.getNumOperands(); n;)
15341         Chains.push_back(Chain.getOperand(--n));
15342       ++Depth;
15343       break;
15344 
15345     default:
15346       // For all other instructions we will just have to take what we can get.
15347       Aliases.push_back(Chain);
15348       break;
15349     }
15350   }
15351 }
15352 
15353 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
15354 /// (aliasing node.)
15355 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
15356   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
15357 
15358   // Accumulate all the aliases to this node.
15359   GatherAllAliases(N, OldChain, Aliases);
15360 
15361   // If no operands then chain to entry token.
15362   if (Aliases.size() == 0)
15363     return DAG.getEntryNode();
15364 
15365   // If a single operand then chain to it.  We don't need to revisit it.
15366   if (Aliases.size() == 1)
15367     return Aliases[0];
15368 
15369   // Construct a custom tailored token factor.
15370   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
15371 }
15372 
15373 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
15374   // This holds the base pointer, index, and the offset in bytes from the base
15375   // pointer.
15376   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
15377 
15378   // We must have a base and an offset.
15379   if (!BasePtr.Base.getNode())
15380     return false;
15381 
15382   // Do not handle stores to undef base pointers.
15383   if (BasePtr.Base.isUndef())
15384     return false;
15385 
15386   SmallVector<StoreSDNode *, 8> ChainedStores;
15387   ChainedStores.push_back(St);
15388 
15389   // Walk up the chain and look for nodes with offsets from the same
15390   // base pointer. Stop when reaching an instruction with a different kind
15391   // or instruction which has a different base pointer.
15392   StoreSDNode *Index = St;
15393   while (Index) {
15394     // If the chain has more than one use, then we can't reorder the mem ops.
15395     if (Index != St && !SDValue(Index, 0)->hasOneUse())
15396       break;
15397 
15398     if (Index->isVolatile() || Index->isIndexed())
15399       break;
15400 
15401     // Find the base pointer and offset for this memory node.
15402     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
15403 
15404     // Check that the base pointer is the same as the original one.
15405     if (!Ptr.equalBaseIndex(BasePtr))
15406       break;
15407 
15408     // Find the next memory operand in the chain. If the next operand in the
15409     // chain is a store then move up and continue the scan with the next
15410     // memory operand. If the next operand is a load save it and use alias
15411     // information to check if it interferes with anything.
15412     SDNode *NextInChain = Index->getChain().getNode();
15413     while (true) {
15414       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
15415         // We found a store node. Use it for the next iteration.
15416         if (STn->isVolatile() || STn->isIndexed()) {
15417           Index = nullptr;
15418           break;
15419         }
15420         ChainedStores.push_back(STn);
15421         Index = STn;
15422         break;
15423       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
15424         NextInChain = Ldn->getChain().getNode();
15425         continue;
15426       } else {
15427         Index = nullptr;
15428         break;
15429       }
15430     }
15431   }
15432 
15433   bool MadeChangeToSt = false;
15434   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
15435 
15436   for (StoreSDNode *ChainedStore : ChainedStores) {
15437     SDValue Chain = ChainedStore->getChain();
15438     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15439 
15440     if (Chain != BetterChain) {
15441       if (ChainedStore == St)
15442         MadeChangeToSt = true;
15443       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15444     }
15445   }
15446 
15447   // Do all replacements after finding the replacements to make to avoid making
15448   // the chains more complicated by introducing new TokenFactors.
15449   for (auto Replacement : BetterChains)
15450     replaceStoreChain(Replacement.first, Replacement.second);
15451 
15452   return MadeChangeToSt;
15453 }
15454 
15455 /// This is the entry point for the file.
15456 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15457                            CodeGenOpt::Level OptLevel) {
15458   /// This is the main entry point to this class.
15459   DAGCombiner(*this, AA, OptLevel).Run(Level);
15460 }
15461