1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 #include <algorithm>
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "dagcombine"
45 
46 STATISTIC(NodesCombined   , "Number of dag nodes combined");
47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
49 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
50 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
51 STATISTIC(SlicedLoads, "Number of load sliced");
52 
53 namespace {
54   static cl::opt<bool>
55     CombinerAA("combiner-alias-analysis", cl::Hidden,
56                cl::desc("Enable DAG combiner alias-analysis heuristics"));
57 
58   static cl::opt<bool>
59     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60                cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 
62   static cl::opt<bool>
63     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
64                cl::desc("Enable DAG combiner's use of TBAA"));
65 
66 #ifndef NDEBUG
67   static cl::opt<std::string>
68     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
69                cl::desc("Only use DAG-combiner alias analysis in this"
70                         " function"));
71 #endif
72 
73   /// Hidden option to stress test load slicing, i.e., when this option
74   /// is enabled, load slicing bypasses most of its profitability guards.
75   static cl::opt<bool>
76   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
77                     cl::desc("Bypass the profitability model of load "
78                              "slicing"),
79                     cl::init(false));
80 
81   static cl::opt<bool>
82     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
83                       cl::desc("DAG combiner may split indexing from loads"));
84 
85 //------------------------------ DAGCombiner ---------------------------------//
86 
87   class DAGCombiner {
88     SelectionDAG &DAG;
89     const TargetLowering &TLI;
90     CombineLevel Level;
91     CodeGenOpt::Level OptLevel;
92     bool LegalOperations;
93     bool LegalTypes;
94     bool ForCodeSize;
95 
96     /// \brief Worklist of all of the nodes that need to be simplified.
97     ///
98     /// This must behave as a stack -- new nodes to process are pushed onto the
99     /// back and when processing we pop off of the back.
100     ///
101     /// The worklist will not contain duplicates but may contain null entries
102     /// due to nodes being deleted from the underlying DAG.
103     SmallVector<SDNode *, 64> Worklist;
104 
105     /// \brief Mapping from an SDNode to its position on the worklist.
106     ///
107     /// This is used to find and remove nodes from the worklist (by nulling
108     /// them) when they are deleted from the underlying DAG. It relies on
109     /// stable indices of nodes within the worklist.
110     DenseMap<SDNode *, unsigned> WorklistMap;
111 
112     /// \brief Set of nodes which have been combined (at least once).
113     ///
114     /// This is used to allow us to reliably add any operands of a DAG node
115     /// which have not yet been combined to the worklist.
116     SmallPtrSet<SDNode *, 32> CombinedNodes;
117 
118     // AA - Used for DAG load/store alias analysis.
119     AliasAnalysis &AA;
120 
121     /// When an instruction is simplified, add all users of the instruction to
122     /// the work lists because they might get more simplified now.
123     void AddUsersToWorklist(SDNode *N) {
124       for (SDNode *Node : N->uses())
125         AddToWorklist(Node);
126     }
127 
128     /// Call the node-specific routine that folds each particular type of node.
129     SDValue visit(SDNode *N);
130 
131   public:
132     /// Add to the worklist making sure its instance is at the back (next to be
133     /// processed.)
134     void AddToWorklist(SDNode *N) {
135       // Skip handle nodes as they can't usefully be combined and confuse the
136       // zero-use deletion strategy.
137       if (N->getOpcode() == ISD::HANDLENODE)
138         return;
139 
140       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
141         Worklist.push_back(N);
142     }
143 
144     /// Remove all instances of N from the worklist.
145     void removeFromWorklist(SDNode *N) {
146       CombinedNodes.erase(N);
147 
148       auto It = WorklistMap.find(N);
149       if (It == WorklistMap.end())
150         return; // Not in the worklist.
151 
152       // Null out the entry rather than erasing it to avoid a linear operation.
153       Worklist[It->second] = nullptr;
154       WorklistMap.erase(It);
155     }
156 
157     void deleteAndRecombine(SDNode *N);
158     bool recursivelyDeleteUnusedNodes(SDNode *N);
159 
160     /// Replaces all uses of the results of one DAG node with new values.
161     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162                       bool AddTo = true);
163 
164     /// Replaces all uses of the results of one DAG node with new values.
165     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
166       return CombineTo(N, &Res, 1, AddTo);
167     }
168 
169     /// Replaces all uses of the results of one DAG node with new values.
170     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
171                       bool AddTo = true) {
172       SDValue To[] = { Res0, Res1 };
173       return CombineTo(N, To, 2, AddTo);
174     }
175 
176     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
177 
178   private:
179 
180     /// Check the specified integer node value to see if it can be simplified or
181     /// if things it uses can be simplified by bit propagation.
182     /// If so, return true.
183     bool SimplifyDemandedBits(SDValue Op) {
184       unsigned BitWidth = Op.getScalarValueSizeInBits();
185       APInt Demanded = APInt::getAllOnesValue(BitWidth);
186       return SimplifyDemandedBits(Op, Demanded);
187     }
188 
189     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
190 
191     bool CombineToPreIndexedLoadStore(SDNode *N);
192     bool CombineToPostIndexedLoadStore(SDNode *N);
193     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
194     bool SliceUpLoad(SDNode *N);
195 
196     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
197     ///   load.
198     ///
199     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
200     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
201     /// \param EltNo index of the vector element to load.
202     /// \param OriginalLoad load that EVE came from to be replaced.
203     /// \returns EVE on success SDValue() on failure.
204     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
205         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
206     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
207     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
208     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
210     SDValue PromoteIntBinOp(SDValue Op);
211     SDValue PromoteIntShiftOp(SDValue Op);
212     SDValue PromoteExtend(SDValue Op);
213     bool PromoteLoad(SDValue Op);
214 
215     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
216                          SDValue ExtLoad, const SDLoc &DL,
217                          ISD::NodeType ExtType);
218 
219     /// Call the node-specific routine that knows how to fold each
220     /// particular type of node. If that doesn't do anything, try the
221     /// target-specific DAG combines.
222     SDValue combine(SDNode *N);
223 
224     // Visitation implementation - Implement dag node combining for different
225     // node types.  The semantics are as follows:
226     // Return Value:
227     //   SDValue.getNode() == 0 - No change was made
228     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
229     //   otherwise              - N should be replaced by the returned Operand.
230     //
231     SDValue visitTokenFactor(SDNode *N);
232     SDValue visitMERGE_VALUES(SDNode *N);
233     SDValue visitADD(SDNode *N);
234     SDValue visitSUB(SDNode *N);
235     SDValue visitADDC(SDNode *N);
236     SDValue visitSUBC(SDNode *N);
237     SDValue visitADDE(SDNode *N);
238     SDValue visitSUBE(SDNode *N);
239     SDValue visitMUL(SDNode *N);
240     SDValue useDivRem(SDNode *N);
241     SDValue visitSDIV(SDNode *N);
242     SDValue visitUDIV(SDNode *N);
243     SDValue visitREM(SDNode *N);
244     SDValue visitMULHU(SDNode *N);
245     SDValue visitMULHS(SDNode *N);
246     SDValue visitSMUL_LOHI(SDNode *N);
247     SDValue visitUMUL_LOHI(SDNode *N);
248     SDValue visitSMULO(SDNode *N);
249     SDValue visitUMULO(SDNode *N);
250     SDValue visitIMINMAX(SDNode *N);
251     SDValue visitAND(SDNode *N);
252     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
253     SDValue visitOR(SDNode *N);
254     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
255     SDValue visitXOR(SDNode *N);
256     SDValue SimplifyVBinOp(SDNode *N);
257     SDValue visitSHL(SDNode *N);
258     SDValue visitSRA(SDNode *N);
259     SDValue visitSRL(SDNode *N);
260     SDValue visitRotate(SDNode *N);
261     SDValue visitBSWAP(SDNode *N);
262     SDValue visitBITREVERSE(SDNode *N);
263     SDValue visitCTLZ(SDNode *N);
264     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
265     SDValue visitCTTZ(SDNode *N);
266     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
267     SDValue visitCTPOP(SDNode *N);
268     SDValue visitSELECT(SDNode *N);
269     SDValue visitVSELECT(SDNode *N);
270     SDValue visitSELECT_CC(SDNode *N);
271     SDValue visitSETCC(SDNode *N);
272     SDValue visitSETCCE(SDNode *N);
273     SDValue visitSIGN_EXTEND(SDNode *N);
274     SDValue visitZERO_EXTEND(SDNode *N);
275     SDValue visitANY_EXTEND(SDNode *N);
276     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
277     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
278     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
279     SDValue visitTRUNCATE(SDNode *N);
280     SDValue visitBITCAST(SDNode *N);
281     SDValue visitBUILD_PAIR(SDNode *N);
282     SDValue visitFADD(SDNode *N);
283     SDValue visitFSUB(SDNode *N);
284     SDValue visitFMUL(SDNode *N);
285     SDValue visitFMA(SDNode *N);
286     SDValue visitFDIV(SDNode *N);
287     SDValue visitFREM(SDNode *N);
288     SDValue visitFSQRT(SDNode *N);
289     SDValue visitFCOPYSIGN(SDNode *N);
290     SDValue visitSINT_TO_FP(SDNode *N);
291     SDValue visitUINT_TO_FP(SDNode *N);
292     SDValue visitFP_TO_SINT(SDNode *N);
293     SDValue visitFP_TO_UINT(SDNode *N);
294     SDValue visitFP_ROUND(SDNode *N);
295     SDValue visitFP_ROUND_INREG(SDNode *N);
296     SDValue visitFP_EXTEND(SDNode *N);
297     SDValue visitFNEG(SDNode *N);
298     SDValue visitFABS(SDNode *N);
299     SDValue visitFCEIL(SDNode *N);
300     SDValue visitFTRUNC(SDNode *N);
301     SDValue visitFFLOOR(SDNode *N);
302     SDValue visitFMINNUM(SDNode *N);
303     SDValue visitFMAXNUM(SDNode *N);
304     SDValue visitBRCOND(SDNode *N);
305     SDValue visitBR_CC(SDNode *N);
306     SDValue visitLOAD(SDNode *N);
307 
308     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
309     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
310 
311     SDValue visitSTORE(SDNode *N);
312     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
313     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
314     SDValue visitBUILD_VECTOR(SDNode *N);
315     SDValue visitCONCAT_VECTORS(SDNode *N);
316     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
317     SDValue visitVECTOR_SHUFFLE(SDNode *N);
318     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
319     SDValue visitINSERT_SUBVECTOR(SDNode *N);
320     SDValue visitMLOAD(SDNode *N);
321     SDValue visitMSTORE(SDNode *N);
322     SDValue visitMGATHER(SDNode *N);
323     SDValue visitMSCATTER(SDNode *N);
324     SDValue visitFP_TO_FP16(SDNode *N);
325     SDValue visitFP16_TO_FP(SDNode *N);
326 
327     SDValue visitFADDForFMACombine(SDNode *N);
328     SDValue visitFSUBForFMACombine(SDNode *N);
329     SDValue visitFMULForFMACombine(SDNode *N);
330 
331     SDValue XformToShuffleWithZero(SDNode *N);
332     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
333                            SDValue RHS);
334 
335     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
336 
337     SDValue foldSelectOfConstants(SDNode *N);
338     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
339     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
340     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
341     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
342                              SDValue N2, SDValue N3, ISD::CondCode CC,
343                              bool NotExtCompare = false);
344     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
345                           const SDLoc &DL, bool foldBooleans = true);
346 
347     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
348                            SDValue &CC) const;
349     bool isOneUseSetCC(SDValue N) const;
350 
351     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
352                                          unsigned HiOp);
353     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
354     SDValue CombineExtLoad(SDNode *N);
355     SDValue combineRepeatedFPDivisors(SDNode *N);
356     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
357     SDValue BuildSDIV(SDNode *N);
358     SDValue BuildSDIVPow2(SDNode *N);
359     SDValue BuildUDIV(SDNode *N);
360     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
361     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
362     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
363     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
364     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
365                                 SDNodeFlags *Flags, bool Reciprocal);
366     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
367                                 SDNodeFlags *Flags, bool Reciprocal);
368     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
369                                bool DemandHighBits = true);
370     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
371     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
372                               SDValue InnerPos, SDValue InnerNeg,
373                               unsigned PosOpcode, unsigned NegOpcode,
374                               const SDLoc &DL);
375     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
376     SDValue ReduceLoadWidth(SDNode *N);
377     SDValue ReduceLoadOpStoreWidth(SDNode *N);
378     SDValue splitMergedValStore(StoreSDNode *ST);
379     SDValue TransformFPLoadStorePair(SDNode *N);
380     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
381     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
382     SDValue reduceBuildVecToShuffle(SDNode *N);
383     SDValue createBuildVecShuffle(SDLoc DL, SDNode *N, ArrayRef<int> VectorMask,
384                                   SDValue VecIn1, SDValue VecIn2,
385                                   unsigned LeftIdx);
386 
387     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
388 
389     /// Walk up chain skipping non-aliasing memory nodes,
390     /// looking for aliasing nodes and adding them to the Aliases vector.
391     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
392                           SmallVectorImpl<SDValue> &Aliases);
393 
394     /// Return true if there is any possibility that the two addresses overlap.
395     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
396 
397     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
398     /// chain (aliasing node.)
399     SDValue FindBetterChain(SDNode *N, SDValue Chain);
400 
401     /// Try to replace a store and any possibly adjacent stores on
402     /// consecutive chains with better chains. Return true only if St is
403     /// replaced.
404     ///
405     /// Notice that other chains may still be replaced even if the function
406     /// returns false.
407     bool findBetterNeighborChains(StoreSDNode *St);
408 
409     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
410     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
411 
412     /// Holds a pointer to an LSBaseSDNode as well as information on where it
413     /// is located in a sequence of memory operations connected by a chain.
414     struct MemOpLink {
415       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
416       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
417       // Ptr to the mem node.
418       LSBaseSDNode *MemNode;
419       // Offset from the base ptr.
420       int64_t OffsetFromBase;
421       // What is the sequence number of this mem node.
422       // Lowest mem operand in the DAG starts at zero.
423       unsigned SequenceNum;
424     };
425 
426     /// This is a helper function for visitMUL to check the profitability
427     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
428     /// MulNode is the original multiply, AddNode is (add x, c1),
429     /// and ConstNode is c2.
430     bool isMulAddWithConstProfitable(SDNode *MulNode,
431                                      SDValue &AddNode,
432                                      SDValue &ConstNode);
433 
434     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
435     /// constant build_vector of the stored constant values in Stores.
436     SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL,
437                                          ArrayRef<MemOpLink> Stores,
438                                          SmallVectorImpl<SDValue> &Chains,
439                                          EVT Ty) const;
440 
441     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
442     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
443     /// the type of the loaded value to be extended.  LoadedVT returns the type
444     /// of the original loaded value.  NarrowLoad returns whether the load would
445     /// need to be narrowed in order to match.
446     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
447                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
448                           bool &NarrowLoad);
449 
450     /// This is a helper function for MergeConsecutiveStores. When the source
451     /// elements of the consecutive stores are all constants or all extracted
452     /// vector elements, try to merge them into one larger store.
453     /// \return True if a merged store was created.
454     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
455                                          EVT MemVT, unsigned NumStores,
456                                          bool IsConstantSrc, bool UseVector);
457 
458     /// This is a helper function for MergeConsecutiveStores.
459     /// Stores that may be merged are placed in StoreNodes.
460     /// Loads that may alias with those stores are placed in AliasLoadNodes.
461     void getStoreMergeAndAliasCandidates(
462         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
463         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
464 
465     /// Helper function for MergeConsecutiveStores. Checks if
466     /// Candidate stores have indirect dependency through their
467     /// operands. \return True if safe to merge
468     bool checkMergeStoreCandidatesForDependencies(
469         SmallVectorImpl<MemOpLink> &StoreNodes);
470 
471     /// Merge consecutive store operations into a wide store.
472     /// This optimization uses wide integers or vectors when possible.
473     /// \return True if some memory operations were changed.
474     bool MergeConsecutiveStores(StoreSDNode *N);
475 
476     /// \brief Try to transform a truncation where C is a constant:
477     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
478     ///
479     /// \p N needs to be a truncation and its first operand an AND. Other
480     /// requirements are checked by the function (e.g. that trunc is
481     /// single-use) and if missed an empty SDValue is returned.
482     SDValue distributeTruncateThroughAnd(SDNode *N);
483 
484   public:
485     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
486         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
487           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
488       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
489     }
490 
491     /// Runs the dag combiner on all nodes in the work list
492     void Run(CombineLevel AtLevel);
493 
494     SelectionDAG &getDAG() const { return DAG; }
495 
496     /// Returns a type large enough to hold any valid shift amount - before type
497     /// legalization these can be huge.
498     EVT getShiftAmountTy(EVT LHSTy) {
499       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
500       if (LHSTy.isVector())
501         return LHSTy;
502       auto &DL = DAG.getDataLayout();
503       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
504                         : TLI.getPointerTy(DL);
505     }
506 
507     /// This method returns true if we are running before type legalization or
508     /// if the specified VT is legal.
509     bool isTypeLegal(const EVT &VT) {
510       if (!LegalTypes) return true;
511       return TLI.isTypeLegal(VT);
512     }
513 
514     /// Convenience wrapper around TargetLowering::getSetCCResultType
515     EVT getSetCCResultType(EVT VT) const {
516       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
517     }
518   };
519 }
520 
521 
522 namespace {
523 /// This class is a DAGUpdateListener that removes any deleted
524 /// nodes from the worklist.
525 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
526   DAGCombiner &DC;
527 public:
528   explicit WorklistRemover(DAGCombiner &dc)
529     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
530 
531   void NodeDeleted(SDNode *N, SDNode *E) override {
532     DC.removeFromWorklist(N);
533   }
534 };
535 }
536 
537 //===----------------------------------------------------------------------===//
538 //  TargetLowering::DAGCombinerInfo implementation
539 //===----------------------------------------------------------------------===//
540 
541 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
542   ((DAGCombiner*)DC)->AddToWorklist(N);
543 }
544 
545 SDValue TargetLowering::DAGCombinerInfo::
546 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
547   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
548 }
549 
550 SDValue TargetLowering::DAGCombinerInfo::
551 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
552   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
553 }
554 
555 
556 SDValue TargetLowering::DAGCombinerInfo::
557 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
558   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
559 }
560 
561 void TargetLowering::DAGCombinerInfo::
562 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
563   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
564 }
565 
566 //===----------------------------------------------------------------------===//
567 // Helper Functions
568 //===----------------------------------------------------------------------===//
569 
570 void DAGCombiner::deleteAndRecombine(SDNode *N) {
571   removeFromWorklist(N);
572 
573   // If the operands of this node are only used by the node, they will now be
574   // dead. Make sure to re-visit them and recursively delete dead nodes.
575   for (const SDValue &Op : N->ops())
576     // For an operand generating multiple values, one of the values may
577     // become dead allowing further simplification (e.g. split index
578     // arithmetic from an indexed load).
579     if (Op->hasOneUse() || Op->getNumValues() > 1)
580       AddToWorklist(Op.getNode());
581 
582   DAG.DeleteNode(N);
583 }
584 
585 /// Return 1 if we can compute the negated form of the specified expression for
586 /// the same cost as the expression itself, or 2 if we can compute the negated
587 /// form more cheaply than the expression itself.
588 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
589                                const TargetLowering &TLI,
590                                const TargetOptions *Options,
591                                unsigned Depth = 0) {
592   // fneg is removable even if it has multiple uses.
593   if (Op.getOpcode() == ISD::FNEG) return 2;
594 
595   // Don't allow anything with multiple uses.
596   if (!Op.hasOneUse()) return 0;
597 
598   // Don't recurse exponentially.
599   if (Depth > 6) return 0;
600 
601   switch (Op.getOpcode()) {
602   default: return false;
603   case ISD::ConstantFP:
604     // Don't invert constant FP values after legalize.  The negated constant
605     // isn't necessarily legal.
606     return LegalOperations ? 0 : 1;
607   case ISD::FADD:
608     // FIXME: determine better conditions for this xform.
609     if (!Options->UnsafeFPMath) return 0;
610 
611     // After operation legalization, it might not be legal to create new FSUBs.
612     if (LegalOperations &&
613         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
614       return 0;
615 
616     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
617     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
618                                     Options, Depth + 1))
619       return V;
620     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
621     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
622                               Depth + 1);
623   case ISD::FSUB:
624     // We can't turn -(A-B) into B-A when we honor signed zeros.
625     if (!Options->UnsafeFPMath) return 0;
626 
627     // fold (fneg (fsub A, B)) -> (fsub B, A)
628     return 1;
629 
630   case ISD::FMUL:
631   case ISD::FDIV:
632     if (Options->HonorSignDependentRoundingFPMath()) return 0;
633 
634     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
635     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
636                                     Options, Depth + 1))
637       return V;
638 
639     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
640                               Depth + 1);
641 
642   case ISD::FP_EXTEND:
643   case ISD::FP_ROUND:
644   case ISD::FSIN:
645     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
646                               Depth + 1);
647   }
648 }
649 
650 /// If isNegatibleForFree returns true, return the newly negated expression.
651 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
652                                     bool LegalOperations, unsigned Depth = 0) {
653   const TargetOptions &Options = DAG.getTarget().Options;
654   // fneg is removable even if it has multiple uses.
655   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
656 
657   // Don't allow anything with multiple uses.
658   assert(Op.hasOneUse() && "Unknown reuse!");
659 
660   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
661 
662   const SDNodeFlags *Flags = Op.getNode()->getFlags();
663 
664   switch (Op.getOpcode()) {
665   default: llvm_unreachable("Unknown code");
666   case ISD::ConstantFP: {
667     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
668     V.changeSign();
669     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
670   }
671   case ISD::FADD:
672     // FIXME: determine better conditions for this xform.
673     assert(Options.UnsafeFPMath);
674 
675     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
676     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
677                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
678       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
679                          GetNegatedExpression(Op.getOperand(0), DAG,
680                                               LegalOperations, Depth+1),
681                          Op.getOperand(1), Flags);
682     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
683     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
684                        GetNegatedExpression(Op.getOperand(1), DAG,
685                                             LegalOperations, Depth+1),
686                        Op.getOperand(0), Flags);
687   case ISD::FSUB:
688     // We can't turn -(A-B) into B-A when we honor signed zeros.
689     assert(Options.UnsafeFPMath);
690 
691     // fold (fneg (fsub 0, B)) -> B
692     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
693       if (N0CFP->isZero())
694         return Op.getOperand(1);
695 
696     // fold (fneg (fsub A, B)) -> (fsub B, A)
697     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
698                        Op.getOperand(1), Op.getOperand(0), Flags);
699 
700   case ISD::FMUL:
701   case ISD::FDIV:
702     assert(!Options.HonorSignDependentRoundingFPMath());
703 
704     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
705     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
706                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
707       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
708                          GetNegatedExpression(Op.getOperand(0), DAG,
709                                               LegalOperations, Depth+1),
710                          Op.getOperand(1), Flags);
711 
712     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
713     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
714                        Op.getOperand(0),
715                        GetNegatedExpression(Op.getOperand(1), DAG,
716                                             LegalOperations, Depth+1), Flags);
717 
718   case ISD::FP_EXTEND:
719   case ISD::FSIN:
720     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
721                        GetNegatedExpression(Op.getOperand(0), DAG,
722                                             LegalOperations, Depth+1));
723   case ISD::FP_ROUND:
724       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
725                          GetNegatedExpression(Op.getOperand(0), DAG,
726                                               LegalOperations, Depth+1),
727                          Op.getOperand(1));
728   }
729 }
730 
731 // APInts must be the same size for most operations, this helper
732 // function zero extends the shorter of the pair so that they match.
733 // We provide an Offset so that we can create bitwidths that won't overflow.
734 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
735   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
736   LHS = LHS.zextOrSelf(Bits);
737   RHS = RHS.zextOrSelf(Bits);
738 }
739 
740 // Return true if this node is a setcc, or is a select_cc
741 // that selects between the target values used for true and false, making it
742 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
743 // the appropriate nodes based on the type of node we are checking. This
744 // simplifies life a bit for the callers.
745 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
746                                     SDValue &CC) const {
747   if (N.getOpcode() == ISD::SETCC) {
748     LHS = N.getOperand(0);
749     RHS = N.getOperand(1);
750     CC  = N.getOperand(2);
751     return true;
752   }
753 
754   if (N.getOpcode() != ISD::SELECT_CC ||
755       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
756       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
757     return false;
758 
759   if (TLI.getBooleanContents(N.getValueType()) ==
760       TargetLowering::UndefinedBooleanContent)
761     return false;
762 
763   LHS = N.getOperand(0);
764   RHS = N.getOperand(1);
765   CC  = N.getOperand(4);
766   return true;
767 }
768 
769 /// Return true if this is a SetCC-equivalent operation with only one use.
770 /// If this is true, it allows the users to invert the operation for free when
771 /// it is profitable to do so.
772 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
773   SDValue N0, N1, N2;
774   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
775     return true;
776   return false;
777 }
778 
779 // \brief Returns the SDNode if it is a constant float BuildVector
780 // or constant float.
781 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
782   if (isa<ConstantFPSDNode>(N))
783     return N.getNode();
784   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
785     return N.getNode();
786   return nullptr;
787 }
788 
789 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
790 // int.
791 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
792   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
793     return CN;
794 
795   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
796     BitVector UndefElements;
797     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
798 
799     // BuildVectors can truncate their operands. Ignore that case here.
800     // FIXME: We blindly ignore splats which include undef which is overly
801     // pessimistic.
802     if (CN && UndefElements.none() &&
803         CN->getValueType(0) == N.getValueType().getScalarType())
804       return CN;
805   }
806 
807   return nullptr;
808 }
809 
810 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
811 // float.
812 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
813   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
814     return CN;
815 
816   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
817     BitVector UndefElements;
818     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
819 
820     if (CN && UndefElements.none())
821       return CN;
822   }
823 
824   return nullptr;
825 }
826 
827 // Determines if it is a constant integer or a build vector of constant
828 // integers (and undefs).
829 // Do not permit build vector implicit truncation.
830 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
831   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
832     return !(Const->isOpaque() && NoOpaques);
833   if (N.getOpcode() != ISD::BUILD_VECTOR)
834     return false;
835   unsigned BitWidth = N.getScalarValueSizeInBits();
836   for (const SDValue &Op : N->op_values()) {
837     if (Op.isUndef())
838       continue;
839     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
840     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
841         (Const->isOpaque() && NoOpaques))
842       return false;
843   }
844   return true;
845 }
846 
847 // Determines if it is a constant null integer or a splatted vector of a
848 // constant null integer (with no undefs).
849 // Build vector implicit truncation is not an issue for null values.
850 static bool isNullConstantOrNullSplatConstant(SDValue N) {
851   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
852     return Splat->isNullValue();
853   return false;
854 }
855 
856 // Determines if it is a constant integer of one or a splatted vector of a
857 // constant integer of one (with no undefs).
858 // Do not permit build vector implicit truncation.
859 static bool isOneConstantOrOneSplatConstant(SDValue N) {
860   unsigned BitWidth = N.getScalarValueSizeInBits();
861   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
862     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
863   return false;
864 }
865 
866 // Determines if it is a constant integer of all ones or a splatted vector of a
867 // constant integer of all ones (with no undefs).
868 // Do not permit build vector implicit truncation.
869 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
870   unsigned BitWidth = N.getScalarValueSizeInBits();
871   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
872     return Splat->isAllOnesValue() &&
873            Splat->getAPIntValue().getBitWidth() == BitWidth;
874   return false;
875 }
876 
877 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
878                                     SDValue N1) {
879   EVT VT = N0.getValueType();
880   if (N0.getOpcode() == Opc) {
881     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
882       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
883         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
884         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
885           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
886         return SDValue();
887       }
888       if (N0.hasOneUse()) {
889         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
890         // use
891         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
892         if (!OpNode.getNode())
893           return SDValue();
894         AddToWorklist(OpNode.getNode());
895         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
896       }
897     }
898   }
899 
900   if (N1.getOpcode() == Opc) {
901     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
902       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
903         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
904         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
905           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
906         return SDValue();
907       }
908       if (N1.hasOneUse()) {
909         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
910         // use
911         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
912         if (!OpNode.getNode())
913           return SDValue();
914         AddToWorklist(OpNode.getNode());
915         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
916       }
917     }
918   }
919 
920   return SDValue();
921 }
922 
923 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
924                                bool AddTo) {
925   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
926   ++NodesCombined;
927   DEBUG(dbgs() << "\nReplacing.1 ";
928         N->dump(&DAG);
929         dbgs() << "\nWith: ";
930         To[0].getNode()->dump(&DAG);
931         dbgs() << " and " << NumTo-1 << " other values\n");
932   for (unsigned i = 0, e = NumTo; i != e; ++i)
933     assert((!To[i].getNode() ||
934             N->getValueType(i) == To[i].getValueType()) &&
935            "Cannot combine value to value of different type!");
936 
937   WorklistRemover DeadNodes(*this);
938   DAG.ReplaceAllUsesWith(N, To);
939   if (AddTo) {
940     // Push the new nodes and any users onto the worklist
941     for (unsigned i = 0, e = NumTo; i != e; ++i) {
942       if (To[i].getNode()) {
943         AddToWorklist(To[i].getNode());
944         AddUsersToWorklist(To[i].getNode());
945       }
946     }
947   }
948 
949   // Finally, if the node is now dead, remove it from the graph.  The node
950   // may not be dead if the replacement process recursively simplified to
951   // something else needing this node.
952   if (N->use_empty())
953     deleteAndRecombine(N);
954   return SDValue(N, 0);
955 }
956 
957 void DAGCombiner::
958 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
959   // Replace all uses.  If any nodes become isomorphic to other nodes and
960   // are deleted, make sure to remove them from our worklist.
961   WorklistRemover DeadNodes(*this);
962   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
963 
964   // Push the new node and any (possibly new) users onto the worklist.
965   AddToWorklist(TLO.New.getNode());
966   AddUsersToWorklist(TLO.New.getNode());
967 
968   // Finally, if the node is now dead, remove it from the graph.  The node
969   // may not be dead if the replacement process recursively simplified to
970   // something else needing this node.
971   if (TLO.Old.getNode()->use_empty())
972     deleteAndRecombine(TLO.Old.getNode());
973 }
974 
975 /// Check the specified integer node value to see if it can be simplified or if
976 /// things it uses can be simplified by bit propagation. If so, return true.
977 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
978   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
979   APInt KnownZero, KnownOne;
980   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
981     return false;
982 
983   // Revisit the node.
984   AddToWorklist(Op.getNode());
985 
986   // Replace the old value with the new one.
987   ++NodesCombined;
988   DEBUG(dbgs() << "\nReplacing.2 ";
989         TLO.Old.getNode()->dump(&DAG);
990         dbgs() << "\nWith: ";
991         TLO.New.getNode()->dump(&DAG);
992         dbgs() << '\n');
993 
994   CommitTargetLoweringOpt(TLO);
995   return true;
996 }
997 
998 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
999   SDLoc DL(Load);
1000   EVT VT = Load->getValueType(0);
1001   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1002 
1003   DEBUG(dbgs() << "\nReplacing.9 ";
1004         Load->dump(&DAG);
1005         dbgs() << "\nWith: ";
1006         Trunc.getNode()->dump(&DAG);
1007         dbgs() << '\n');
1008   WorklistRemover DeadNodes(*this);
1009   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1010   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1011   deleteAndRecombine(Load);
1012   AddToWorklist(Trunc.getNode());
1013 }
1014 
1015 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1016   Replace = false;
1017   SDLoc DL(Op);
1018   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1019     LoadSDNode *LD = cast<LoadSDNode>(Op);
1020     EVT MemVT = LD->getMemoryVT();
1021     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1022       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1023                                                        : ISD::EXTLOAD)
1024       : LD->getExtensionType();
1025     Replace = true;
1026     return DAG.getExtLoad(ExtType, DL, PVT,
1027                           LD->getChain(), LD->getBasePtr(),
1028                           MemVT, LD->getMemOperand());
1029   }
1030 
1031   unsigned Opc = Op.getOpcode();
1032   switch (Opc) {
1033   default: break;
1034   case ISD::AssertSext:
1035     return DAG.getNode(ISD::AssertSext, DL, PVT,
1036                        SExtPromoteOperand(Op.getOperand(0), PVT),
1037                        Op.getOperand(1));
1038   case ISD::AssertZext:
1039     return DAG.getNode(ISD::AssertZext, DL, PVT,
1040                        ZExtPromoteOperand(Op.getOperand(0), PVT),
1041                        Op.getOperand(1));
1042   case ISD::Constant: {
1043     unsigned ExtOpc =
1044       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1045     return DAG.getNode(ExtOpc, DL, PVT, Op);
1046   }
1047   }
1048 
1049   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1050     return SDValue();
1051   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1052 }
1053 
1054 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1055   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1056     return SDValue();
1057   EVT OldVT = Op.getValueType();
1058   SDLoc DL(Op);
1059   bool Replace = false;
1060   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1061   if (!NewOp.getNode())
1062     return SDValue();
1063   AddToWorklist(NewOp.getNode());
1064 
1065   if (Replace)
1066     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1067   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1068                      DAG.getValueType(OldVT));
1069 }
1070 
1071 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1072   EVT OldVT = Op.getValueType();
1073   SDLoc DL(Op);
1074   bool Replace = false;
1075   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1076   if (!NewOp.getNode())
1077     return SDValue();
1078   AddToWorklist(NewOp.getNode());
1079 
1080   if (Replace)
1081     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1082   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1083 }
1084 
1085 /// Promote the specified integer binary operation if the target indicates it is
1086 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1087 /// i32 since i16 instructions are longer.
1088 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1089   if (!LegalOperations)
1090     return SDValue();
1091 
1092   EVT VT = Op.getValueType();
1093   if (VT.isVector() || !VT.isInteger())
1094     return SDValue();
1095 
1096   // If operation type is 'undesirable', e.g. i16 on x86, consider
1097   // promoting it.
1098   unsigned Opc = Op.getOpcode();
1099   if (TLI.isTypeDesirableForOp(Opc, VT))
1100     return SDValue();
1101 
1102   EVT PVT = VT;
1103   // Consult target whether it is a good idea to promote this operation and
1104   // what's the right type to promote it to.
1105   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1106     assert(PVT != VT && "Don't know what type to promote to!");
1107 
1108     bool Replace0 = false;
1109     SDValue N0 = Op.getOperand(0);
1110     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1111     if (!NN0.getNode())
1112       return SDValue();
1113 
1114     bool Replace1 = false;
1115     SDValue N1 = Op.getOperand(1);
1116     SDValue NN1;
1117     if (N0 == N1)
1118       NN1 = NN0;
1119     else {
1120       NN1 = PromoteOperand(N1, PVT, Replace1);
1121       if (!NN1.getNode())
1122         return SDValue();
1123     }
1124 
1125     AddToWorklist(NN0.getNode());
1126     if (NN1.getNode())
1127       AddToWorklist(NN1.getNode());
1128 
1129     if (Replace0)
1130       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1131     if (Replace1)
1132       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1133 
1134     DEBUG(dbgs() << "\nPromoting ";
1135           Op.getNode()->dump(&DAG));
1136     SDLoc DL(Op);
1137     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1138                        DAG.getNode(Opc, DL, PVT, NN0, NN1));
1139   }
1140   return SDValue();
1141 }
1142 
1143 /// Promote the specified integer shift operation if the target indicates it is
1144 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1145 /// i32 since i16 instructions are longer.
1146 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1147   if (!LegalOperations)
1148     return SDValue();
1149 
1150   EVT VT = Op.getValueType();
1151   if (VT.isVector() || !VT.isInteger())
1152     return SDValue();
1153 
1154   // If operation type is 'undesirable', e.g. i16 on x86, consider
1155   // promoting it.
1156   unsigned Opc = Op.getOpcode();
1157   if (TLI.isTypeDesirableForOp(Opc, VT))
1158     return SDValue();
1159 
1160   EVT PVT = VT;
1161   // Consult target whether it is a good idea to promote this operation and
1162   // what's the right type to promote it to.
1163   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1164     assert(PVT != VT && "Don't know what type to promote to!");
1165 
1166     bool Replace = false;
1167     SDValue N0 = Op.getOperand(0);
1168     if (Opc == ISD::SRA)
1169       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1170     else if (Opc == ISD::SRL)
1171       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1172     else
1173       N0 = PromoteOperand(N0, PVT, Replace);
1174     if (!N0.getNode())
1175       return SDValue();
1176 
1177     AddToWorklist(N0.getNode());
1178     if (Replace)
1179       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1180 
1181     DEBUG(dbgs() << "\nPromoting ";
1182           Op.getNode()->dump(&DAG));
1183     SDLoc DL(Op);
1184     return DAG.getNode(ISD::TRUNCATE, DL, VT,
1185                        DAG.getNode(Opc, DL, PVT, N0, Op.getOperand(1)));
1186   }
1187   return SDValue();
1188 }
1189 
1190 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1191   if (!LegalOperations)
1192     return SDValue();
1193 
1194   EVT VT = Op.getValueType();
1195   if (VT.isVector() || !VT.isInteger())
1196     return SDValue();
1197 
1198   // If operation type is 'undesirable', e.g. i16 on x86, consider
1199   // promoting it.
1200   unsigned Opc = Op.getOpcode();
1201   if (TLI.isTypeDesirableForOp(Opc, VT))
1202     return SDValue();
1203 
1204   EVT PVT = VT;
1205   // Consult target whether it is a good idea to promote this operation and
1206   // what's the right type to promote it to.
1207   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1208     assert(PVT != VT && "Don't know what type to promote to!");
1209     // fold (aext (aext x)) -> (aext x)
1210     // fold (aext (zext x)) -> (zext x)
1211     // fold (aext (sext x)) -> (sext x)
1212     DEBUG(dbgs() << "\nPromoting ";
1213           Op.getNode()->dump(&DAG));
1214     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1215   }
1216   return SDValue();
1217 }
1218 
1219 bool DAGCombiner::PromoteLoad(SDValue Op) {
1220   if (!LegalOperations)
1221     return false;
1222 
1223   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1224     return false;
1225 
1226   EVT VT = Op.getValueType();
1227   if (VT.isVector() || !VT.isInteger())
1228     return false;
1229 
1230   // If operation type is 'undesirable', e.g. i16 on x86, consider
1231   // promoting it.
1232   unsigned Opc = Op.getOpcode();
1233   if (TLI.isTypeDesirableForOp(Opc, VT))
1234     return false;
1235 
1236   EVT PVT = VT;
1237   // Consult target whether it is a good idea to promote this operation and
1238   // what's the right type to promote it to.
1239   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1240     assert(PVT != VT && "Don't know what type to promote to!");
1241 
1242     SDLoc DL(Op);
1243     SDNode *N = Op.getNode();
1244     LoadSDNode *LD = cast<LoadSDNode>(N);
1245     EVT MemVT = LD->getMemoryVT();
1246     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1247       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1248                                                        : ISD::EXTLOAD)
1249       : LD->getExtensionType();
1250     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1251                                    LD->getChain(), LD->getBasePtr(),
1252                                    MemVT, LD->getMemOperand());
1253     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1254 
1255     DEBUG(dbgs() << "\nPromoting ";
1256           N->dump(&DAG);
1257           dbgs() << "\nTo: ";
1258           Result.getNode()->dump(&DAG);
1259           dbgs() << '\n');
1260     WorklistRemover DeadNodes(*this);
1261     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1262     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1263     deleteAndRecombine(N);
1264     AddToWorklist(Result.getNode());
1265     return true;
1266   }
1267   return false;
1268 }
1269 
1270 /// \brief Recursively delete a node which has no uses and any operands for
1271 /// which it is the only use.
1272 ///
1273 /// Note that this both deletes the nodes and removes them from the worklist.
1274 /// It also adds any nodes who have had a user deleted to the worklist as they
1275 /// may now have only one use and subject to other combines.
1276 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1277   if (!N->use_empty())
1278     return false;
1279 
1280   SmallSetVector<SDNode *, 16> Nodes;
1281   Nodes.insert(N);
1282   do {
1283     N = Nodes.pop_back_val();
1284     if (!N)
1285       continue;
1286 
1287     if (N->use_empty()) {
1288       for (const SDValue &ChildN : N->op_values())
1289         Nodes.insert(ChildN.getNode());
1290 
1291       removeFromWorklist(N);
1292       DAG.DeleteNode(N);
1293     } else {
1294       AddToWorklist(N);
1295     }
1296   } while (!Nodes.empty());
1297   return true;
1298 }
1299 
1300 //===----------------------------------------------------------------------===//
1301 //  Main DAG Combiner implementation
1302 //===----------------------------------------------------------------------===//
1303 
1304 void DAGCombiner::Run(CombineLevel AtLevel) {
1305   // set the instance variables, so that the various visit routines may use it.
1306   Level = AtLevel;
1307   LegalOperations = Level >= AfterLegalizeVectorOps;
1308   LegalTypes = Level >= AfterLegalizeTypes;
1309 
1310   // Add all the dag nodes to the worklist.
1311   for (SDNode &Node : DAG.allnodes())
1312     AddToWorklist(&Node);
1313 
1314   // Create a dummy node (which is not added to allnodes), that adds a reference
1315   // to the root node, preventing it from being deleted, and tracking any
1316   // changes of the root.
1317   HandleSDNode Dummy(DAG.getRoot());
1318 
1319   // While the worklist isn't empty, find a node and try to combine it.
1320   while (!WorklistMap.empty()) {
1321     SDNode *N;
1322     // The Worklist holds the SDNodes in order, but it may contain null entries.
1323     do {
1324       N = Worklist.pop_back_val();
1325     } while (!N);
1326 
1327     bool GoodWorklistEntry = WorklistMap.erase(N);
1328     (void)GoodWorklistEntry;
1329     assert(GoodWorklistEntry &&
1330            "Found a worklist entry without a corresponding map entry!");
1331 
1332     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1333     // N is deleted from the DAG, since they too may now be dead or may have a
1334     // reduced number of uses, allowing other xforms.
1335     if (recursivelyDeleteUnusedNodes(N))
1336       continue;
1337 
1338     WorklistRemover DeadNodes(*this);
1339 
1340     // If this combine is running after legalizing the DAG, re-legalize any
1341     // nodes pulled off the worklist.
1342     if (Level == AfterLegalizeDAG) {
1343       SmallSetVector<SDNode *, 16> UpdatedNodes;
1344       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1345 
1346       for (SDNode *LN : UpdatedNodes) {
1347         AddToWorklist(LN);
1348         AddUsersToWorklist(LN);
1349       }
1350       if (!NIsValid)
1351         continue;
1352     }
1353 
1354     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1355 
1356     // Add any operands of the new node which have not yet been combined to the
1357     // worklist as well. Because the worklist uniques things already, this
1358     // won't repeatedly process the same operand.
1359     CombinedNodes.insert(N);
1360     for (const SDValue &ChildN : N->op_values())
1361       if (!CombinedNodes.count(ChildN.getNode()))
1362         AddToWorklist(ChildN.getNode());
1363 
1364     SDValue RV = combine(N);
1365 
1366     if (!RV.getNode())
1367       continue;
1368 
1369     ++NodesCombined;
1370 
1371     // If we get back the same node we passed in, rather than a new node or
1372     // zero, we know that the node must have defined multiple values and
1373     // CombineTo was used.  Since CombineTo takes care of the worklist
1374     // mechanics for us, we have no work to do in this case.
1375     if (RV.getNode() == N)
1376       continue;
1377 
1378     assert(N->getOpcode() != ISD::DELETED_NODE &&
1379            RV.getOpcode() != ISD::DELETED_NODE &&
1380            "Node was deleted but visit returned new node!");
1381 
1382     DEBUG(dbgs() << " ... into: ";
1383           RV.getNode()->dump(&DAG));
1384 
1385     if (N->getNumValues() == RV.getNode()->getNumValues())
1386       DAG.ReplaceAllUsesWith(N, RV.getNode());
1387     else {
1388       assert(N->getValueType(0) == RV.getValueType() &&
1389              N->getNumValues() == 1 && "Type mismatch");
1390       SDValue OpV = RV;
1391       DAG.ReplaceAllUsesWith(N, &OpV);
1392     }
1393 
1394     // Push the new node and any users onto the worklist
1395     AddToWorklist(RV.getNode());
1396     AddUsersToWorklist(RV.getNode());
1397 
1398     // Finally, if the node is now dead, remove it from the graph.  The node
1399     // may not be dead if the replacement process recursively simplified to
1400     // something else needing this node. This will also take care of adding any
1401     // operands which have lost a user to the worklist.
1402     recursivelyDeleteUnusedNodes(N);
1403   }
1404 
1405   // If the root changed (e.g. it was a dead load, update the root).
1406   DAG.setRoot(Dummy.getValue());
1407   DAG.RemoveDeadNodes();
1408 }
1409 
1410 SDValue DAGCombiner::visit(SDNode *N) {
1411   switch (N->getOpcode()) {
1412   default: break;
1413   case ISD::TokenFactor:        return visitTokenFactor(N);
1414   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1415   case ISD::ADD:                return visitADD(N);
1416   case ISD::SUB:                return visitSUB(N);
1417   case ISD::ADDC:               return visitADDC(N);
1418   case ISD::SUBC:               return visitSUBC(N);
1419   case ISD::ADDE:               return visitADDE(N);
1420   case ISD::SUBE:               return visitSUBE(N);
1421   case ISD::MUL:                return visitMUL(N);
1422   case ISD::SDIV:               return visitSDIV(N);
1423   case ISD::UDIV:               return visitUDIV(N);
1424   case ISD::SREM:
1425   case ISD::UREM:               return visitREM(N);
1426   case ISD::MULHU:              return visitMULHU(N);
1427   case ISD::MULHS:              return visitMULHS(N);
1428   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1429   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1430   case ISD::SMULO:              return visitSMULO(N);
1431   case ISD::UMULO:              return visitUMULO(N);
1432   case ISD::SMIN:
1433   case ISD::SMAX:
1434   case ISD::UMIN:
1435   case ISD::UMAX:               return visitIMINMAX(N);
1436   case ISD::AND:                return visitAND(N);
1437   case ISD::OR:                 return visitOR(N);
1438   case ISD::XOR:                return visitXOR(N);
1439   case ISD::SHL:                return visitSHL(N);
1440   case ISD::SRA:                return visitSRA(N);
1441   case ISD::SRL:                return visitSRL(N);
1442   case ISD::ROTR:
1443   case ISD::ROTL:               return visitRotate(N);
1444   case ISD::BSWAP:              return visitBSWAP(N);
1445   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1446   case ISD::CTLZ:               return visitCTLZ(N);
1447   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1448   case ISD::CTTZ:               return visitCTTZ(N);
1449   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1450   case ISD::CTPOP:              return visitCTPOP(N);
1451   case ISD::SELECT:             return visitSELECT(N);
1452   case ISD::VSELECT:            return visitVSELECT(N);
1453   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1454   case ISD::SETCC:              return visitSETCC(N);
1455   case ISD::SETCCE:             return visitSETCCE(N);
1456   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1457   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1458   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1459   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1460   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1461   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1462   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1463   case ISD::BITCAST:            return visitBITCAST(N);
1464   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1465   case ISD::FADD:               return visitFADD(N);
1466   case ISD::FSUB:               return visitFSUB(N);
1467   case ISD::FMUL:               return visitFMUL(N);
1468   case ISD::FMA:                return visitFMA(N);
1469   case ISD::FDIV:               return visitFDIV(N);
1470   case ISD::FREM:               return visitFREM(N);
1471   case ISD::FSQRT:              return visitFSQRT(N);
1472   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1473   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1474   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1475   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1476   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1477   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1478   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1479   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1480   case ISD::FNEG:               return visitFNEG(N);
1481   case ISD::FABS:               return visitFABS(N);
1482   case ISD::FFLOOR:             return visitFFLOOR(N);
1483   case ISD::FMINNUM:            return visitFMINNUM(N);
1484   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1485   case ISD::FCEIL:              return visitFCEIL(N);
1486   case ISD::FTRUNC:             return visitFTRUNC(N);
1487   case ISD::BRCOND:             return visitBRCOND(N);
1488   case ISD::BR_CC:              return visitBR_CC(N);
1489   case ISD::LOAD:               return visitLOAD(N);
1490   case ISD::STORE:              return visitSTORE(N);
1491   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1492   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1493   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1494   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1495   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1496   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1497   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1498   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1499   case ISD::MGATHER:            return visitMGATHER(N);
1500   case ISD::MLOAD:              return visitMLOAD(N);
1501   case ISD::MSCATTER:           return visitMSCATTER(N);
1502   case ISD::MSTORE:             return visitMSTORE(N);
1503   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1504   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1505   }
1506   return SDValue();
1507 }
1508 
1509 SDValue DAGCombiner::combine(SDNode *N) {
1510   SDValue RV = visit(N);
1511 
1512   // If nothing happened, try a target-specific DAG combine.
1513   if (!RV.getNode()) {
1514     assert(N->getOpcode() != ISD::DELETED_NODE &&
1515            "Node was deleted but visit returned NULL!");
1516 
1517     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1518         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1519 
1520       // Expose the DAG combiner to the target combiner impls.
1521       TargetLowering::DAGCombinerInfo
1522         DagCombineInfo(DAG, Level, false, this);
1523 
1524       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1525     }
1526   }
1527 
1528   // If nothing happened still, try promoting the operation.
1529   if (!RV.getNode()) {
1530     switch (N->getOpcode()) {
1531     default: break;
1532     case ISD::ADD:
1533     case ISD::SUB:
1534     case ISD::MUL:
1535     case ISD::AND:
1536     case ISD::OR:
1537     case ISD::XOR:
1538       RV = PromoteIntBinOp(SDValue(N, 0));
1539       break;
1540     case ISD::SHL:
1541     case ISD::SRA:
1542     case ISD::SRL:
1543       RV = PromoteIntShiftOp(SDValue(N, 0));
1544       break;
1545     case ISD::SIGN_EXTEND:
1546     case ISD::ZERO_EXTEND:
1547     case ISD::ANY_EXTEND:
1548       RV = PromoteExtend(SDValue(N, 0));
1549       break;
1550     case ISD::LOAD:
1551       if (PromoteLoad(SDValue(N, 0)))
1552         RV = SDValue(N, 0);
1553       break;
1554     }
1555   }
1556 
1557   // If N is a commutative binary node, try commuting it to enable more
1558   // sdisel CSE.
1559   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1560       N->getNumValues() == 1) {
1561     SDValue N0 = N->getOperand(0);
1562     SDValue N1 = N->getOperand(1);
1563 
1564     // Constant operands are canonicalized to RHS.
1565     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1566       SDValue Ops[] = {N1, N0};
1567       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1568                                             N->getFlags());
1569       if (CSENode)
1570         return SDValue(CSENode, 0);
1571     }
1572   }
1573 
1574   return RV;
1575 }
1576 
1577 /// Given a node, return its input chain if it has one, otherwise return a null
1578 /// sd operand.
1579 static SDValue getInputChainForNode(SDNode *N) {
1580   if (unsigned NumOps = N->getNumOperands()) {
1581     if (N->getOperand(0).getValueType() == MVT::Other)
1582       return N->getOperand(0);
1583     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1584       return N->getOperand(NumOps-1);
1585     for (unsigned i = 1; i < NumOps-1; ++i)
1586       if (N->getOperand(i).getValueType() == MVT::Other)
1587         return N->getOperand(i);
1588   }
1589   return SDValue();
1590 }
1591 
1592 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1593   // If N has two operands, where one has an input chain equal to the other,
1594   // the 'other' chain is redundant.
1595   if (N->getNumOperands() == 2) {
1596     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1597       return N->getOperand(0);
1598     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1599       return N->getOperand(1);
1600   }
1601 
1602   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1603   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1604   SmallPtrSet<SDNode*, 16> SeenOps;
1605   bool Changed = false;             // If we should replace this token factor.
1606 
1607   // Start out with this token factor.
1608   TFs.push_back(N);
1609 
1610   // Iterate through token factors.  The TFs grows when new token factors are
1611   // encountered.
1612   for (unsigned i = 0; i < TFs.size(); ++i) {
1613     SDNode *TF = TFs[i];
1614 
1615     // Check each of the operands.
1616     for (const SDValue &Op : TF->op_values()) {
1617 
1618       switch (Op.getOpcode()) {
1619       case ISD::EntryToken:
1620         // Entry tokens don't need to be added to the list. They are
1621         // redundant.
1622         Changed = true;
1623         break;
1624 
1625       case ISD::TokenFactor:
1626         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1627           // Queue up for processing.
1628           TFs.push_back(Op.getNode());
1629           // Clean up in case the token factor is removed.
1630           AddToWorklist(Op.getNode());
1631           Changed = true;
1632           break;
1633         }
1634         LLVM_FALLTHROUGH;
1635 
1636       default:
1637         // Only add if it isn't already in the list.
1638         if (SeenOps.insert(Op.getNode()).second)
1639           Ops.push_back(Op);
1640         else
1641           Changed = true;
1642         break;
1643       }
1644     }
1645   }
1646 
1647   SDValue Result;
1648 
1649   // If we've changed things around then replace token factor.
1650   if (Changed) {
1651     if (Ops.empty()) {
1652       // The entry token is the only possible outcome.
1653       Result = DAG.getEntryNode();
1654     } else {
1655       // New and improved token factor.
1656       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1657     }
1658 
1659     // Add users to worklist if AA is enabled, since it may introduce
1660     // a lot of new chained token factors while removing memory deps.
1661     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1662       : DAG.getSubtarget().useAA();
1663     return CombineTo(N, Result, UseAA /*add to worklist*/);
1664   }
1665 
1666   return Result;
1667 }
1668 
1669 /// MERGE_VALUES can always be eliminated.
1670 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1671   WorklistRemover DeadNodes(*this);
1672   // Replacing results may cause a different MERGE_VALUES to suddenly
1673   // be CSE'd with N, and carry its uses with it. Iterate until no
1674   // uses remain, to ensure that the node can be safely deleted.
1675   // First add the users of this node to the work list so that they
1676   // can be tried again once they have new operands.
1677   AddUsersToWorklist(N);
1678   do {
1679     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1680       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1681   } while (!N->use_empty());
1682   deleteAndRecombine(N);
1683   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1684 }
1685 
1686 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1687 /// ConstantSDNode pointer else nullptr.
1688 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1689   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1690   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1691 }
1692 
1693 SDValue DAGCombiner::visitADD(SDNode *N) {
1694   SDValue N0 = N->getOperand(0);
1695   SDValue N1 = N->getOperand(1);
1696   EVT VT = N0.getValueType();
1697   SDLoc DL(N);
1698 
1699   // fold vector ops
1700   if (VT.isVector()) {
1701     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1702       return FoldedVOp;
1703 
1704     // fold (add x, 0) -> x, vector edition
1705     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1706       return N0;
1707     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1708       return N1;
1709   }
1710 
1711   // fold (add x, undef) -> undef
1712   if (N0.isUndef())
1713     return N0;
1714 
1715   if (N1.isUndef())
1716     return N1;
1717 
1718   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1719     // canonicalize constant to RHS
1720     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1721       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1722     // fold (add c1, c2) -> c1+c2
1723     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1724                                       N1.getNode());
1725   }
1726 
1727   // fold (add x, 0) -> x
1728   if (isNullConstant(N1))
1729     return N0;
1730 
1731   // fold ((c1-A)+c2) -> (c1+c2)-A
1732   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1733     if (N0.getOpcode() == ISD::SUB)
1734       if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1735         return DAG.getNode(ISD::SUB, DL, VT,
1736                            DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1737                            N0.getOperand(1));
1738       }
1739   }
1740 
1741   // reassociate add
1742   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1743     return RADD;
1744 
1745   // fold ((0-A) + B) -> B-A
1746   if (N0.getOpcode() == ISD::SUB &&
1747       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1748     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1749 
1750   // fold (A + (0-B)) -> A-B
1751   if (N1.getOpcode() == ISD::SUB &&
1752       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1753     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1754 
1755   // fold (A+(B-A)) -> B
1756   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1757     return N1.getOperand(0);
1758 
1759   // fold ((B-A)+A) -> B
1760   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1761     return N0.getOperand(0);
1762 
1763   // fold (A+(B-(A+C))) to (B-C)
1764   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1765       N0 == N1.getOperand(1).getOperand(0))
1766     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1767                        N1.getOperand(1).getOperand(1));
1768 
1769   // fold (A+(B-(C+A))) to (B-C)
1770   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1771       N0 == N1.getOperand(1).getOperand(1))
1772     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1773                        N1.getOperand(1).getOperand(0));
1774 
1775   // fold (A+((B-A)+or-C)) to (B+or-C)
1776   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1777       N1.getOperand(0).getOpcode() == ISD::SUB &&
1778       N0 == N1.getOperand(0).getOperand(1))
1779     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1780                        N1.getOperand(1));
1781 
1782   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1783   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1784     SDValue N00 = N0.getOperand(0);
1785     SDValue N01 = N0.getOperand(1);
1786     SDValue N10 = N1.getOperand(0);
1787     SDValue N11 = N1.getOperand(1);
1788 
1789     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1790       return DAG.getNode(ISD::SUB, DL, VT,
1791                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1792                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1793   }
1794 
1795   if (SimplifyDemandedBits(SDValue(N, 0)))
1796     return SDValue(N, 0);
1797 
1798   // fold (a+b) -> (a|b) iff a and b share no bits.
1799   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1800       VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1801     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1802 
1803   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1804   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1805       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1806     return DAG.getNode(ISD::SUB, DL, VT, N0,
1807                        DAG.getNode(ISD::SHL, DL, VT,
1808                                    N1.getOperand(0).getOperand(1),
1809                                    N1.getOperand(1)));
1810   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1811       isNullConstantOrNullSplatConstant(N0.getOperand(0).getOperand(0)))
1812     return DAG.getNode(ISD::SUB, DL, VT, N1,
1813                        DAG.getNode(ISD::SHL, DL, VT,
1814                                    N0.getOperand(0).getOperand(1),
1815                                    N0.getOperand(1)));
1816 
1817   if (N1.getOpcode() == ISD::AND) {
1818     SDValue AndOp0 = N1.getOperand(0);
1819     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1820     unsigned DestBits = VT.getScalarSizeInBits();
1821 
1822     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1823     // and similar xforms where the inner op is either ~0 or 0.
1824     if (NumSignBits == DestBits &&
1825         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1826       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1827   }
1828 
1829   // add (sext i1), X -> sub X, (zext i1)
1830   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1831       N0.getOperand(0).getValueType() == MVT::i1 &&
1832       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1833     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1834     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1835   }
1836 
1837   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1838   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1839     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1840     if (TN->getVT() == MVT::i1) {
1841       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1842                                  DAG.getConstant(1, DL, VT));
1843       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1844     }
1845   }
1846 
1847   return SDValue();
1848 }
1849 
1850 SDValue DAGCombiner::visitADDC(SDNode *N) {
1851   SDValue N0 = N->getOperand(0);
1852   SDValue N1 = N->getOperand(1);
1853   EVT VT = N0.getValueType();
1854 
1855   // If the flag result is dead, turn this into an ADD.
1856   if (!N->hasAnyUseOfValue(1))
1857     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1858                      DAG.getNode(ISD::CARRY_FALSE,
1859                                  SDLoc(N), MVT::Glue));
1860 
1861   // canonicalize constant to RHS.
1862   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1863   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1864   if (N0C && !N1C)
1865     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1866 
1867   // fold (addc x, 0) -> x + no carry out
1868   if (isNullConstant(N1))
1869     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1870                                         SDLoc(N), MVT::Glue));
1871 
1872   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1873   APInt LHSZero, LHSOne;
1874   APInt RHSZero, RHSOne;
1875   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1876 
1877   if (LHSZero.getBoolValue()) {
1878     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1879 
1880     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1881     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1882     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1883       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1884                        DAG.getNode(ISD::CARRY_FALSE,
1885                                    SDLoc(N), MVT::Glue));
1886   }
1887 
1888   return SDValue();
1889 }
1890 
1891 SDValue DAGCombiner::visitADDE(SDNode *N) {
1892   SDValue N0 = N->getOperand(0);
1893   SDValue N1 = N->getOperand(1);
1894   SDValue CarryIn = N->getOperand(2);
1895 
1896   // canonicalize constant to RHS
1897   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1898   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1899   if (N0C && !N1C)
1900     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1901                        N1, N0, CarryIn);
1902 
1903   // fold (adde x, y, false) -> (addc x, y)
1904   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1905     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1906 
1907   return SDValue();
1908 }
1909 
1910 // Since it may not be valid to emit a fold to zero for vector initializers
1911 // check if we can before folding.
1912 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
1913                              SelectionDAG &DAG, bool LegalOperations,
1914                              bool LegalTypes) {
1915   if (!VT.isVector())
1916     return DAG.getConstant(0, DL, VT);
1917   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1918     return DAG.getConstant(0, DL, VT);
1919   return SDValue();
1920 }
1921 
1922 SDValue DAGCombiner::visitSUB(SDNode *N) {
1923   SDValue N0 = N->getOperand(0);
1924   SDValue N1 = N->getOperand(1);
1925   EVT VT = N0.getValueType();
1926   SDLoc DL(N);
1927 
1928   // fold vector ops
1929   if (VT.isVector()) {
1930     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1931       return FoldedVOp;
1932 
1933     // fold (sub x, 0) -> x, vector edition
1934     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1935       return N0;
1936   }
1937 
1938   // fold (sub x, x) -> 0
1939   // FIXME: Refactor this and xor and other similar operations together.
1940   if (N0 == N1)
1941     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
1942   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1943       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1944     // fold (sub c1, c2) -> c1-c2
1945     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
1946                                       N1.getNode());
1947   }
1948 
1949   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1950 
1951   // fold (sub x, c) -> (add x, -c)
1952   if (N1C) {
1953     return DAG.getNode(ISD::ADD, DL, VT, N0,
1954                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1955   }
1956 
1957   // Right-shifting everything out but the sign bit followed by negation is the
1958   // same as flipping arithmetic/logical shift type without the negation:
1959   // -(X >>u 31) -> (X >>s 31)
1960   // -(X >>s 31) -> (X >>u 31)
1961   if (isNullConstantOrNullSplatConstant(N0) &&
1962       (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL)) {
1963     ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
1964     if (ShiftAmt && ShiftAmt->getZExtValue() == VT.getScalarSizeInBits() - 1) {
1965       auto NewOpc = N1->getOpcode() == ISD::SRA ? ISD::SRL :ISD::SRA;
1966       if (!LegalOperations || TLI.isOperationLegal(NewOpc, VT))
1967         return DAG.getNode(NewOpc, DL, VT, N1.getOperand(0), N1.getOperand(1));
1968     }
1969   }
1970 
1971   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1972   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
1973     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
1974 
1975   // fold A-(A-B) -> B
1976   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1977     return N1.getOperand(1);
1978 
1979   // fold (A+B)-A -> B
1980   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1981     return N0.getOperand(1);
1982 
1983   // fold (A+B)-B -> A
1984   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1985     return N0.getOperand(0);
1986 
1987   // fold C2-(A+C1) -> (C2-C1)-A
1988   if (N1.getOpcode() == ISD::ADD) {
1989     SDValue N11 = N1.getOperand(1);
1990     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
1991         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
1992       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
1993       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
1994     }
1995   }
1996 
1997   // fold ((A+(B+or-C))-B) -> A+or-C
1998   if (N0.getOpcode() == ISD::ADD &&
1999       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2000        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2001       N0.getOperand(1).getOperand(0) == N1)
2002     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2003                        N0.getOperand(1).getOperand(1));
2004 
2005   // fold ((A+(C+B))-B) -> A+C
2006   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2007       N0.getOperand(1).getOperand(1) == N1)
2008     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2009                        N0.getOperand(1).getOperand(0));
2010 
2011   // fold ((A-(B-C))-C) -> A-B
2012   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2013       N0.getOperand(1).getOperand(1) == N1)
2014     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2015                        N0.getOperand(1).getOperand(0));
2016 
2017   // If either operand of a sub is undef, the result is undef
2018   if (N0.isUndef())
2019     return N0;
2020   if (N1.isUndef())
2021     return N1;
2022 
2023   // If the relocation model supports it, consider symbol offsets.
2024   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2025     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2026       // fold (sub Sym, c) -> Sym-c
2027       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2028         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2029                                     GA->getOffset() -
2030                                         (uint64_t)N1C->getSExtValue());
2031       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2032       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2033         if (GA->getGlobal() == GB->getGlobal())
2034           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2035                                  DL, VT);
2036     }
2037 
2038   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2039   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2040     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2041     if (TN->getVT() == MVT::i1) {
2042       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2043                                  DAG.getConstant(1, DL, VT));
2044       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2045     }
2046   }
2047 
2048   return SDValue();
2049 }
2050 
2051 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2052   SDValue N0 = N->getOperand(0);
2053   SDValue N1 = N->getOperand(1);
2054   EVT VT = N0.getValueType();
2055   SDLoc DL(N);
2056 
2057   // If the flag result is dead, turn this into an SUB.
2058   if (!N->hasAnyUseOfValue(1))
2059     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2060                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2061 
2062   // fold (subc x, x) -> 0 + no borrow
2063   if (N0 == N1)
2064     return CombineTo(N, DAG.getConstant(0, DL, VT),
2065                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2066 
2067   // fold (subc x, 0) -> x + no borrow
2068   if (isNullConstant(N1))
2069     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2070 
2071   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2072   if (isAllOnesConstant(N0))
2073     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2074                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2075 
2076   return SDValue();
2077 }
2078 
2079 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2080   SDValue N0 = N->getOperand(0);
2081   SDValue N1 = N->getOperand(1);
2082   SDValue CarryIn = N->getOperand(2);
2083 
2084   // fold (sube x, y, false) -> (subc x, y)
2085   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2086     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2087 
2088   return SDValue();
2089 }
2090 
2091 SDValue DAGCombiner::visitMUL(SDNode *N) {
2092   SDValue N0 = N->getOperand(0);
2093   SDValue N1 = N->getOperand(1);
2094   EVT VT = N0.getValueType();
2095 
2096   // fold (mul x, undef) -> 0
2097   if (N0.isUndef() || N1.isUndef())
2098     return DAG.getConstant(0, SDLoc(N), VT);
2099 
2100   bool N0IsConst = false;
2101   bool N1IsConst = false;
2102   bool N1IsOpaqueConst = false;
2103   bool N0IsOpaqueConst = false;
2104   APInt ConstValue0, ConstValue1;
2105   // fold vector ops
2106   if (VT.isVector()) {
2107     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2108       return FoldedVOp;
2109 
2110     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2111     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2112   } else {
2113     N0IsConst = isa<ConstantSDNode>(N0);
2114     if (N0IsConst) {
2115       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2116       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2117     }
2118     N1IsConst = isa<ConstantSDNode>(N1);
2119     if (N1IsConst) {
2120       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2121       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2122     }
2123   }
2124 
2125   // fold (mul c1, c2) -> c1*c2
2126   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2127     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2128                                       N0.getNode(), N1.getNode());
2129 
2130   // canonicalize constant to RHS (vector doesn't have to splat)
2131   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2132      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2133     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2134   // fold (mul x, 0) -> 0
2135   if (N1IsConst && ConstValue1 == 0)
2136     return N1;
2137   // We require a splat of the entire scalar bit width for non-contiguous
2138   // bit patterns.
2139   bool IsFullSplat =
2140     ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2141   // fold (mul x, 1) -> x
2142   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2143     return N0;
2144   // fold (mul x, -1) -> 0-x
2145   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2146     SDLoc DL(N);
2147     return DAG.getNode(ISD::SUB, DL, VT,
2148                        DAG.getConstant(0, DL, VT), N0);
2149   }
2150   // fold (mul x, (1 << c)) -> x << c
2151   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2152       IsFullSplat) {
2153     SDLoc DL(N);
2154     return DAG.getNode(ISD::SHL, DL, VT, N0,
2155                        DAG.getConstant(ConstValue1.logBase2(), DL,
2156                                        getShiftAmountTy(N0.getValueType())));
2157   }
2158   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2159   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2160       IsFullSplat) {
2161     unsigned Log2Val = (-ConstValue1).logBase2();
2162     SDLoc DL(N);
2163     // FIXME: If the input is something that is easily negated (e.g. a
2164     // single-use add), we should put the negate there.
2165     return DAG.getNode(ISD::SUB, DL, VT,
2166                        DAG.getConstant(0, DL, VT),
2167                        DAG.getNode(ISD::SHL, DL, VT, N0,
2168                             DAG.getConstant(Log2Val, DL,
2169                                       getShiftAmountTy(N0.getValueType()))));
2170   }
2171 
2172   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2173   if (N0.getOpcode() == ISD::SHL &&
2174       isConstantOrConstantVector(N1) &&
2175       isConstantOrConstantVector(N0.getOperand(1))) {
2176     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2177     AddToWorklist(C3.getNode());
2178     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2179   }
2180 
2181   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2182   // use.
2183   {
2184     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2185 
2186     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2187     if (N0.getOpcode() == ISD::SHL &&
2188         isConstantOrConstantVector(N0.getOperand(1)) &&
2189         N0.getNode()->hasOneUse()) {
2190       Sh = N0; Y = N1;
2191     } else if (N1.getOpcode() == ISD::SHL &&
2192                isConstantOrConstantVector(N1.getOperand(1)) &&
2193                N1.getNode()->hasOneUse()) {
2194       Sh = N1; Y = N0;
2195     }
2196 
2197     if (Sh.getNode()) {
2198       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2199       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2200     }
2201   }
2202 
2203   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2204   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2205       N0.getOpcode() == ISD::ADD &&
2206       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2207       isMulAddWithConstProfitable(N, N0, N1))
2208       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2209                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2210                                      N0.getOperand(0), N1),
2211                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2212                                      N0.getOperand(1), N1));
2213 
2214   // reassociate mul
2215   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2216     return RMUL;
2217 
2218   return SDValue();
2219 }
2220 
2221 /// Return true if divmod libcall is available.
2222 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2223                                      const TargetLowering &TLI) {
2224   RTLIB::Libcall LC;
2225   EVT NodeType = Node->getValueType(0);
2226   if (!NodeType.isSimple())
2227     return false;
2228   switch (NodeType.getSimpleVT().SimpleTy) {
2229   default: return false; // No libcall for vector types.
2230   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2231   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2232   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2233   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2234   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2235   }
2236 
2237   return TLI.getLibcallName(LC) != nullptr;
2238 }
2239 
2240 /// Issue divrem if both quotient and remainder are needed.
2241 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2242   if (Node->use_empty())
2243     return SDValue(); // This is a dead node, leave it alone.
2244 
2245   unsigned Opcode = Node->getOpcode();
2246   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2247   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2248 
2249   // DivMod lib calls can still work on non-legal types if using lib-calls.
2250   EVT VT = Node->getValueType(0);
2251   if (VT.isVector() || !VT.isInteger())
2252     return SDValue();
2253 
2254   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2255     return SDValue();
2256 
2257   // If DIVREM is going to get expanded into a libcall,
2258   // but there is no libcall available, then don't combine.
2259   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2260       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2261     return SDValue();
2262 
2263   // If div is legal, it's better to do the normal expansion
2264   unsigned OtherOpcode = 0;
2265   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2266     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2267     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2268       return SDValue();
2269   } else {
2270     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2271     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2272       return SDValue();
2273   }
2274 
2275   SDValue Op0 = Node->getOperand(0);
2276   SDValue Op1 = Node->getOperand(1);
2277   SDValue combined;
2278   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2279          UE = Op0.getNode()->use_end(); UI != UE;) {
2280     SDNode *User = *UI++;
2281     if (User == Node || User->use_empty())
2282       continue;
2283     // Convert the other matching node(s), too;
2284     // otherwise, the DIVREM may get target-legalized into something
2285     // target-specific that we won't be able to recognize.
2286     unsigned UserOpc = User->getOpcode();
2287     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2288         User->getOperand(0) == Op0 &&
2289         User->getOperand(1) == Op1) {
2290       if (!combined) {
2291         if (UserOpc == OtherOpcode) {
2292           SDVTList VTs = DAG.getVTList(VT, VT);
2293           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2294         } else if (UserOpc == DivRemOpc) {
2295           combined = SDValue(User, 0);
2296         } else {
2297           assert(UserOpc == Opcode);
2298           continue;
2299         }
2300       }
2301       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2302         CombineTo(User, combined);
2303       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2304         CombineTo(User, combined.getValue(1));
2305     }
2306   }
2307   return combined;
2308 }
2309 
2310 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2311   SDValue N0 = N->getOperand(0);
2312   SDValue N1 = N->getOperand(1);
2313   EVT VT = N->getValueType(0);
2314 
2315   // fold vector ops
2316   if (VT.isVector())
2317     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2318       return FoldedVOp;
2319 
2320   SDLoc DL(N);
2321 
2322   // fold (sdiv c1, c2) -> c1/c2
2323   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2324   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2325   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2326     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2327   // fold (sdiv X, 1) -> X
2328   if (N1C && N1C->isOne())
2329     return N0;
2330   // fold (sdiv X, -1) -> 0-X
2331   if (N1C && N1C->isAllOnesValue())
2332     return DAG.getNode(ISD::SUB, DL, VT,
2333                        DAG.getConstant(0, DL, VT), N0);
2334 
2335   // If we know the sign bits of both operands are zero, strength reduce to a
2336   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2337   if (!VT.isVector()) {
2338     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2339       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2340   }
2341 
2342   // fold (sdiv X, pow2) -> simple ops after legalize
2343   // FIXME: We check for the exact bit here because the generic lowering gives
2344   // better results in that case. The target-specific lowering should learn how
2345   // to handle exact sdivs efficiently.
2346   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2347       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2348       (N1C->getAPIntValue().isPowerOf2() ||
2349        (-N1C->getAPIntValue()).isPowerOf2())) {
2350     // Target-specific implementation of sdiv x, pow2.
2351     if (SDValue Res = BuildSDIVPow2(N))
2352       return Res;
2353 
2354     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2355 
2356     // Splat the sign bit into the register
2357     SDValue SGN =
2358         DAG.getNode(ISD::SRA, DL, VT, N0,
2359                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2360                                     getShiftAmountTy(N0.getValueType())));
2361     AddToWorklist(SGN.getNode());
2362 
2363     // Add (N0 < 0) ? abs2 - 1 : 0;
2364     SDValue SRL =
2365         DAG.getNode(ISD::SRL, DL, VT, SGN,
2366                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2367                                     getShiftAmountTy(SGN.getValueType())));
2368     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2369     AddToWorklist(SRL.getNode());
2370     AddToWorklist(ADD.getNode());    // Divide by pow2
2371     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2372                   DAG.getConstant(lg2, DL,
2373                                   getShiftAmountTy(ADD.getValueType())));
2374 
2375     // If we're dividing by a positive value, we're done.  Otherwise, we must
2376     // negate the result.
2377     if (N1C->getAPIntValue().isNonNegative())
2378       return SRA;
2379 
2380     AddToWorklist(SRA.getNode());
2381     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2382   }
2383 
2384   // If integer divide is expensive and we satisfy the requirements, emit an
2385   // alternate sequence.  Targets may check function attributes for size/speed
2386   // trade-offs.
2387   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2388   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2389     if (SDValue Op = BuildSDIV(N))
2390       return Op;
2391 
2392   // sdiv, srem -> sdivrem
2393   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2394   // Otherwise, we break the simplification logic in visitREM().
2395   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2396     if (SDValue DivRem = useDivRem(N))
2397         return DivRem;
2398 
2399   // undef / X -> 0
2400   if (N0.isUndef())
2401     return DAG.getConstant(0, DL, VT);
2402   // X / undef -> undef
2403   if (N1.isUndef())
2404     return N1;
2405 
2406   return SDValue();
2407 }
2408 
2409 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2410   SDValue N0 = N->getOperand(0);
2411   SDValue N1 = N->getOperand(1);
2412   EVT VT = N->getValueType(0);
2413 
2414   // fold vector ops
2415   if (VT.isVector())
2416     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2417       return FoldedVOp;
2418 
2419   SDLoc DL(N);
2420 
2421   // fold (udiv c1, c2) -> c1/c2
2422   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2423   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2424   if (N0C && N1C)
2425     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2426                                                     N0C, N1C))
2427       return Folded;
2428   // fold (udiv x, (1 << c)) -> x >>u c
2429   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2430     return DAG.getNode(ISD::SRL, DL, VT, N0,
2431                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2432                                        getShiftAmountTy(N0.getValueType())));
2433 
2434   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2435   if (N1.getOpcode() == ISD::SHL) {
2436     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2437       if (SHC->getAPIntValue().isPowerOf2()) {
2438         EVT ADDVT = N1.getOperand(1).getValueType();
2439         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2440                                   N1.getOperand(1),
2441                                   DAG.getConstant(SHC->getAPIntValue()
2442                                                                   .logBase2(),
2443                                                   DL, ADDVT));
2444         AddToWorklist(Add.getNode());
2445         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2446       }
2447     }
2448   }
2449 
2450   // fold (udiv x, c) -> alternate
2451   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2452   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2453     if (SDValue Op = BuildUDIV(N))
2454       return Op;
2455 
2456   // sdiv, srem -> sdivrem
2457   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2458   // Otherwise, we break the simplification logic in visitREM().
2459   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2460     if (SDValue DivRem = useDivRem(N))
2461         return DivRem;
2462 
2463   // undef / X -> 0
2464   if (N0.isUndef())
2465     return DAG.getConstant(0, DL, VT);
2466   // X / undef -> undef
2467   if (N1.isUndef())
2468     return N1;
2469 
2470   return SDValue();
2471 }
2472 
2473 // handles ISD::SREM and ISD::UREM
2474 SDValue DAGCombiner::visitREM(SDNode *N) {
2475   unsigned Opcode = N->getOpcode();
2476   SDValue N0 = N->getOperand(0);
2477   SDValue N1 = N->getOperand(1);
2478   EVT VT = N->getValueType(0);
2479   bool isSigned = (Opcode == ISD::SREM);
2480   SDLoc DL(N);
2481 
2482   // fold (rem c1, c2) -> c1%c2
2483   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2484   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2485   if (N0C && N1C)
2486     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2487       return Folded;
2488 
2489   if (isSigned) {
2490     // If we know the sign bits of both operands are zero, strength reduce to a
2491     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2492     if (!VT.isVector()) {
2493       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2494         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2495     }
2496   } else {
2497     // fold (urem x, pow2) -> (and x, pow2-1)
2498     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2499         N1C->getAPIntValue().isPowerOf2()) {
2500       return DAG.getNode(ISD::AND, DL, VT, N0,
2501                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2502     }
2503     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2504     if (N1.getOpcode() == ISD::SHL) {
2505       ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0));
2506       if (SHC && SHC->getAPIntValue().isPowerOf2()) {
2507         APInt NegOne = APInt::getAllOnesValue(VT.getSizeInBits());
2508         SDValue Add =
2509             DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2510         AddToWorklist(Add.getNode());
2511         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2512       }
2513     }
2514   }
2515 
2516   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2517 
2518   // If X/C can be simplified by the division-by-constant logic, lower
2519   // X%C to the equivalent of X-X/C*C.
2520   // To avoid mangling nodes, this simplification requires that the combine()
2521   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2522   // against this by skipping the simplification if isIntDivCheap().  When
2523   // div is not cheap, combine will not return a DIVREM.  Regardless,
2524   // checking cheapness here makes sense since the simplification results in
2525   // fatter code.
2526   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2527     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2528     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2529     AddToWorklist(Div.getNode());
2530     SDValue OptimizedDiv = combine(Div.getNode());
2531     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2532       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2533              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2534       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2535       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2536       AddToWorklist(Mul.getNode());
2537       return Sub;
2538     }
2539   }
2540 
2541   // sdiv, srem -> sdivrem
2542   if (SDValue DivRem = useDivRem(N))
2543     return DivRem.getValue(1);
2544 
2545   // undef % X -> 0
2546   if (N0.isUndef())
2547     return DAG.getConstant(0, DL, VT);
2548   // X % undef -> undef
2549   if (N1.isUndef())
2550     return N1;
2551 
2552   return SDValue();
2553 }
2554 
2555 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2556   SDValue N0 = N->getOperand(0);
2557   SDValue N1 = N->getOperand(1);
2558   EVT VT = N->getValueType(0);
2559   SDLoc DL(N);
2560 
2561   // fold (mulhs x, 0) -> 0
2562   if (isNullConstant(N1))
2563     return N1;
2564   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2565   if (isOneConstant(N1)) {
2566     SDLoc DL(N);
2567     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2568                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2569                                        getShiftAmountTy(N0.getValueType())));
2570   }
2571   // fold (mulhs x, undef) -> 0
2572   if (N0.isUndef() || N1.isUndef())
2573     return DAG.getConstant(0, SDLoc(N), VT);
2574 
2575   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2576   // plus a shift.
2577   if (VT.isSimple() && !VT.isVector()) {
2578     MVT Simple = VT.getSimpleVT();
2579     unsigned SimpleSize = Simple.getSizeInBits();
2580     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2581     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2582       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2583       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2584       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2585       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2586             DAG.getConstant(SimpleSize, DL,
2587                             getShiftAmountTy(N1.getValueType())));
2588       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2589     }
2590   }
2591 
2592   return SDValue();
2593 }
2594 
2595 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2596   SDValue N0 = N->getOperand(0);
2597   SDValue N1 = N->getOperand(1);
2598   EVT VT = N->getValueType(0);
2599   SDLoc DL(N);
2600 
2601   // fold (mulhu x, 0) -> 0
2602   if (isNullConstant(N1))
2603     return N1;
2604   // fold (mulhu x, 1) -> 0
2605   if (isOneConstant(N1))
2606     return DAG.getConstant(0, DL, N0.getValueType());
2607   // fold (mulhu x, undef) -> 0
2608   if (N0.isUndef() || N1.isUndef())
2609     return DAG.getConstant(0, DL, VT);
2610 
2611   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2612   // plus a shift.
2613   if (VT.isSimple() && !VT.isVector()) {
2614     MVT Simple = VT.getSimpleVT();
2615     unsigned SimpleSize = Simple.getSizeInBits();
2616     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2617     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2618       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2619       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2620       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2621       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2622             DAG.getConstant(SimpleSize, DL,
2623                             getShiftAmountTy(N1.getValueType())));
2624       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2625     }
2626   }
2627 
2628   return SDValue();
2629 }
2630 
2631 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2632 /// give the opcodes for the two computations that are being performed. Return
2633 /// true if a simplification was made.
2634 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2635                                                 unsigned HiOp) {
2636   // If the high half is not needed, just compute the low half.
2637   bool HiExists = N->hasAnyUseOfValue(1);
2638   if (!HiExists &&
2639       (!LegalOperations ||
2640        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2641     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2642     return CombineTo(N, Res, Res);
2643   }
2644 
2645   // If the low half is not needed, just compute the high half.
2646   bool LoExists = N->hasAnyUseOfValue(0);
2647   if (!LoExists &&
2648       (!LegalOperations ||
2649        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2650     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2651     return CombineTo(N, Res, Res);
2652   }
2653 
2654   // If both halves are used, return as it is.
2655   if (LoExists && HiExists)
2656     return SDValue();
2657 
2658   // If the two computed results can be simplified separately, separate them.
2659   if (LoExists) {
2660     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2661     AddToWorklist(Lo.getNode());
2662     SDValue LoOpt = combine(Lo.getNode());
2663     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2664         (!LegalOperations ||
2665          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2666       return CombineTo(N, LoOpt, LoOpt);
2667   }
2668 
2669   if (HiExists) {
2670     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2671     AddToWorklist(Hi.getNode());
2672     SDValue HiOpt = combine(Hi.getNode());
2673     if (HiOpt.getNode() && HiOpt != Hi &&
2674         (!LegalOperations ||
2675          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2676       return CombineTo(N, HiOpt, HiOpt);
2677   }
2678 
2679   return SDValue();
2680 }
2681 
2682 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2683   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2684     return Res;
2685 
2686   EVT VT = N->getValueType(0);
2687   SDLoc DL(N);
2688 
2689   // If the type is twice as wide is legal, transform the mulhu to a wider
2690   // multiply plus a shift.
2691   if (VT.isSimple() && !VT.isVector()) {
2692     MVT Simple = VT.getSimpleVT();
2693     unsigned SimpleSize = Simple.getSizeInBits();
2694     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2695     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2696       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2697       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2698       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2699       // Compute the high part as N1.
2700       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2701             DAG.getConstant(SimpleSize, DL,
2702                             getShiftAmountTy(Lo.getValueType())));
2703       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2704       // Compute the low part as N0.
2705       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2706       return CombineTo(N, Lo, Hi);
2707     }
2708   }
2709 
2710   return SDValue();
2711 }
2712 
2713 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2714   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2715     return Res;
2716 
2717   EVT VT = N->getValueType(0);
2718   SDLoc DL(N);
2719 
2720   // If the type is twice as wide is legal, transform the mulhu to a wider
2721   // multiply plus a shift.
2722   if (VT.isSimple() && !VT.isVector()) {
2723     MVT Simple = VT.getSimpleVT();
2724     unsigned SimpleSize = Simple.getSizeInBits();
2725     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2726     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2727       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2728       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2729       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2730       // Compute the high part as N1.
2731       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2732             DAG.getConstant(SimpleSize, DL,
2733                             getShiftAmountTy(Lo.getValueType())));
2734       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2735       // Compute the low part as N0.
2736       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2737       return CombineTo(N, Lo, Hi);
2738     }
2739   }
2740 
2741   return SDValue();
2742 }
2743 
2744 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2745   // (smulo x, 2) -> (saddo x, x)
2746   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2747     if (C2->getAPIntValue() == 2)
2748       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2749                          N->getOperand(0), N->getOperand(0));
2750 
2751   return SDValue();
2752 }
2753 
2754 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2755   // (umulo x, 2) -> (uaddo x, x)
2756   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2757     if (C2->getAPIntValue() == 2)
2758       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2759                          N->getOperand(0), N->getOperand(0));
2760 
2761   return SDValue();
2762 }
2763 
2764 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2765   SDValue N0 = N->getOperand(0);
2766   SDValue N1 = N->getOperand(1);
2767   EVT VT = N0.getValueType();
2768 
2769   // fold vector ops
2770   if (VT.isVector())
2771     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2772       return FoldedVOp;
2773 
2774   // fold (add c1, c2) -> c1+c2
2775   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2776   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2777   if (N0C && N1C)
2778     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2779 
2780   // canonicalize constant to RHS
2781   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2782      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2783     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2784 
2785   return SDValue();
2786 }
2787 
2788 /// If this is a binary operator with two operands of the same opcode, try to
2789 /// simplify it.
2790 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2791   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2792   EVT VT = N0.getValueType();
2793   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2794 
2795   // Bail early if none of these transforms apply.
2796   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2797 
2798   // For each of OP in AND/OR/XOR:
2799   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2800   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2801   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2802   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2803   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2804   //
2805   // do not sink logical op inside of a vector extend, since it may combine
2806   // into a vsetcc.
2807   EVT Op0VT = N0.getOperand(0).getValueType();
2808   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2809        N0.getOpcode() == ISD::SIGN_EXTEND ||
2810        N0.getOpcode() == ISD::BSWAP ||
2811        // Avoid infinite looping with PromoteIntBinOp.
2812        (N0.getOpcode() == ISD::ANY_EXTEND &&
2813         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2814        (N0.getOpcode() == ISD::TRUNCATE &&
2815         (!TLI.isZExtFree(VT, Op0VT) ||
2816          !TLI.isTruncateFree(Op0VT, VT)) &&
2817         TLI.isTypeLegal(Op0VT))) &&
2818       !VT.isVector() &&
2819       Op0VT == N1.getOperand(0).getValueType() &&
2820       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2821     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2822                                  N0.getOperand(0).getValueType(),
2823                                  N0.getOperand(0), N1.getOperand(0));
2824     AddToWorklist(ORNode.getNode());
2825     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2826   }
2827 
2828   // For each of OP in SHL/SRL/SRA/AND...
2829   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2830   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2831   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2832   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2833        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2834       N0.getOperand(1) == N1.getOperand(1)) {
2835     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2836                                  N0.getOperand(0).getValueType(),
2837                                  N0.getOperand(0), N1.getOperand(0));
2838     AddToWorklist(ORNode.getNode());
2839     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2840                        ORNode, N0.getOperand(1));
2841   }
2842 
2843   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2844   // Only perform this optimization up until type legalization, before
2845   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2846   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2847   // we don't want to undo this promotion.
2848   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2849   // on scalars.
2850   if ((N0.getOpcode() == ISD::BITCAST ||
2851        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2852        Level <= AfterLegalizeTypes) {
2853     SDValue In0 = N0.getOperand(0);
2854     SDValue In1 = N1.getOperand(0);
2855     EVT In0Ty = In0.getValueType();
2856     EVT In1Ty = In1.getValueType();
2857     SDLoc DL(N);
2858     // If both incoming values are integers, and the original types are the
2859     // same.
2860     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2861       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2862       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2863       AddToWorklist(Op.getNode());
2864       return BC;
2865     }
2866   }
2867 
2868   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2869   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2870   // If both shuffles use the same mask, and both shuffle within a single
2871   // vector, then it is worthwhile to move the swizzle after the operation.
2872   // The type-legalizer generates this pattern when loading illegal
2873   // vector types from memory. In many cases this allows additional shuffle
2874   // optimizations.
2875   // There are other cases where moving the shuffle after the xor/and/or
2876   // is profitable even if shuffles don't perform a swizzle.
2877   // If both shuffles use the same mask, and both shuffles have the same first
2878   // or second operand, then it might still be profitable to move the shuffle
2879   // after the xor/and/or operation.
2880   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2881     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2882     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2883 
2884     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2885            "Inputs to shuffles are not the same type");
2886 
2887     // Check that both shuffles use the same mask. The masks are known to be of
2888     // the same length because the result vector type is the same.
2889     // Check also that shuffles have only one use to avoid introducing extra
2890     // instructions.
2891     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2892         SVN0->getMask().equals(SVN1->getMask())) {
2893       SDValue ShOp = N0->getOperand(1);
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       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2898         if (!LegalTypes)
2899           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2900         else
2901           ShOp = SDValue();
2902       }
2903 
2904       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2905       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2906       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2907       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2908         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2909                                       N0->getOperand(0), N1->getOperand(0));
2910         AddToWorklist(NewNode.getNode());
2911         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2912                                     SVN0->getMask());
2913       }
2914 
2915       // Don't try to fold this node if it requires introducing a
2916       // build vector of all zeros that might be illegal at this stage.
2917       ShOp = N0->getOperand(0);
2918       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2919         if (!LegalTypes)
2920           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2921         else
2922           ShOp = SDValue();
2923       }
2924 
2925       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2926       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2927       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2928       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2929         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2930                                       N0->getOperand(1), N1->getOperand(1));
2931         AddToWorklist(NewNode.getNode());
2932         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2933                                     SVN0->getMask());
2934       }
2935     }
2936   }
2937 
2938   return SDValue();
2939 }
2940 
2941 /// This contains all DAGCombine rules which reduce two values combined by
2942 /// an And operation to a single value. This makes them reusable in the context
2943 /// of visitSELECT(). Rules involving constants are not included as
2944 /// visitSELECT() already handles those cases.
2945 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2946                                   SDNode *LocReference) {
2947   EVT VT = N1.getValueType();
2948 
2949   // fold (and x, undef) -> 0
2950   if (N0.isUndef() || N1.isUndef())
2951     return DAG.getConstant(0, SDLoc(LocReference), VT);
2952   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2953   SDValue LL, LR, RL, RR, CC0, CC1;
2954   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2955     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2956     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2957 
2958     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2959         LL.getValueType().isInteger()) {
2960       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2961       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2962         EVT CCVT = getSetCCResultType(LR.getValueType());
2963         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2964           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2965                                        LR.getValueType(), LL, RL);
2966           AddToWorklist(ORNode.getNode());
2967           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2968         }
2969       }
2970       if (isAllOnesConstant(LR)) {
2971         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2972         if (Op1 == ISD::SETEQ) {
2973           EVT CCVT = getSetCCResultType(LR.getValueType());
2974           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2975             SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2976                                           LR.getValueType(), LL, RL);
2977             AddToWorklist(ANDNode.getNode());
2978             return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2979           }
2980         }
2981         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2982         if (Op1 == ISD::SETGT) {
2983           EVT CCVT = getSetCCResultType(LR.getValueType());
2984           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2985             SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2986                                          LR.getValueType(), LL, RL);
2987             AddToWorklist(ORNode.getNode());
2988             return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2989           }
2990         }
2991       }
2992     }
2993     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2994     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2995         Op0 == Op1 && LL.getValueType().isInteger() &&
2996       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2997                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2998       EVT CCVT = getSetCCResultType(LL.getValueType());
2999       if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3000         SDLoc DL(N0);
3001         SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
3002                                       LL, DAG.getConstant(1, DL,
3003                                                           LL.getValueType()));
3004         AddToWorklist(ADDNode.getNode());
3005         return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
3006                             DAG.getConstant(2, DL, LL.getValueType()),
3007                             ISD::SETUGE);
3008       }
3009     }
3010     // canonicalize equivalent to ll == rl
3011     if (LL == RR && LR == RL) {
3012       Op1 = ISD::getSetCCSwappedOperands(Op1);
3013       std::swap(RL, RR);
3014     }
3015     if (LL == RL && LR == RR) {
3016       bool isInteger = LL.getValueType().isInteger();
3017       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
3018       if (Result != ISD::SETCC_INVALID &&
3019           (!LegalOperations ||
3020            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3021             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3022         EVT CCVT = getSetCCResultType(LL.getValueType());
3023         if (N0.getValueType() == CCVT ||
3024             (!LegalOperations && N0.getValueType() == MVT::i1))
3025           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3026                               LL, LR, Result);
3027       }
3028     }
3029   }
3030 
3031   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3032       VT.getSizeInBits() <= 64) {
3033     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3034       APInt ADDC = ADDI->getAPIntValue();
3035       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3036         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3037         // immediate for an add, but it is legal if its top c2 bits are set,
3038         // transform the ADD so the immediate doesn't need to be materialized
3039         // in a register.
3040         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3041           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3042                                              SRLI->getZExtValue());
3043           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3044             ADDC |= Mask;
3045             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3046               SDLoc DL(N0);
3047               SDValue NewAdd =
3048                 DAG.getNode(ISD::ADD, DL, VT,
3049                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3050               CombineTo(N0.getNode(), NewAdd);
3051               // Return N so it doesn't get rechecked!
3052               return SDValue(LocReference, 0);
3053             }
3054           }
3055         }
3056       }
3057     }
3058   }
3059 
3060   // Reduce bit extract of low half of an integer to the narrower type.
3061   // (and (srl i64:x, K), KMask) ->
3062   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3063   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3064     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3065       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3066         unsigned Size = VT.getSizeInBits();
3067         const APInt &AndMask = CAnd->getAPIntValue();
3068         unsigned ShiftBits = CShift->getZExtValue();
3069         unsigned MaskBits = AndMask.countTrailingOnes();
3070         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3071 
3072         if (APIntOps::isMask(AndMask) &&
3073             // Required bits must not span the two halves of the integer and
3074             // must fit in the half size type.
3075             (ShiftBits + MaskBits <= Size / 2) &&
3076             TLI.isNarrowingProfitable(VT, HalfVT) &&
3077             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3078             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3079             TLI.isTruncateFree(VT, HalfVT) &&
3080             TLI.isZExtFree(HalfVT, VT)) {
3081           // The isNarrowingProfitable is to avoid regressions on PPC and
3082           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3083           // on downstream users of this. Those patterns could probably be
3084           // extended to handle extensions mixed in.
3085 
3086           SDValue SL(N0);
3087           assert(ShiftBits != 0 && MaskBits <= Size);
3088 
3089           // Extracting the highest bit of the low half.
3090           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3091           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3092                                       N0.getOperand(0));
3093 
3094           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3095           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3096           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3097           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3098           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3099         }
3100       }
3101     }
3102   }
3103 
3104   return SDValue();
3105 }
3106 
3107 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3108                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3109                                    bool &NarrowLoad) {
3110   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3111 
3112   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3113     return false;
3114 
3115   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3116   LoadedVT = LoadN->getMemoryVT();
3117 
3118   if (ExtVT == LoadedVT &&
3119       (!LegalOperations ||
3120        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3121     // ZEXTLOAD will match without needing to change the size of the value being
3122     // loaded.
3123     NarrowLoad = false;
3124     return true;
3125   }
3126 
3127   // Do not change the width of a volatile load.
3128   if (LoadN->isVolatile())
3129     return false;
3130 
3131   // Do not generate loads of non-round integer types since these can
3132   // be expensive (and would be wrong if the type is not byte sized).
3133   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3134     return false;
3135 
3136   if (LegalOperations &&
3137       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3138     return false;
3139 
3140   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3141     return false;
3142 
3143   NarrowLoad = true;
3144   return true;
3145 }
3146 
3147 SDValue DAGCombiner::visitAND(SDNode *N) {
3148   SDValue N0 = N->getOperand(0);
3149   SDValue N1 = N->getOperand(1);
3150   EVT VT = N1.getValueType();
3151 
3152   // fold vector ops
3153   if (VT.isVector()) {
3154     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3155       return FoldedVOp;
3156 
3157     // fold (and x, 0) -> 0, vector edition
3158     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3159       // do not return N0, because undef node may exist in N0
3160       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3161                              SDLoc(N), N0.getValueType());
3162     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3163       // do not return N1, because undef node may exist in N1
3164       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3165                              SDLoc(N), N1.getValueType());
3166 
3167     // fold (and x, -1) -> x, vector edition
3168     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3169       return N1;
3170     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3171       return N0;
3172   }
3173 
3174   // fold (and c1, c2) -> c1&c2
3175   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3176   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3177   if (N0C && N1C && !N1C->isOpaque())
3178     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3179   // canonicalize constant to RHS
3180   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3181      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3182     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3183   // fold (and x, -1) -> x
3184   if (isAllOnesConstant(N1))
3185     return N0;
3186   // if (and x, c) is known to be zero, return 0
3187   unsigned BitWidth = VT.getScalarSizeInBits();
3188   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3189                                    APInt::getAllOnesValue(BitWidth)))
3190     return DAG.getConstant(0, SDLoc(N), VT);
3191   // reassociate and
3192   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3193     return RAND;
3194   // fold (and (or x, C), D) -> D if (C & D) == D
3195   if (N1C && N0.getOpcode() == ISD::OR)
3196     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3197       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3198         return N1;
3199   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3200   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3201     SDValue N0Op0 = N0.getOperand(0);
3202     APInt Mask = ~N1C->getAPIntValue();
3203     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3204     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3205       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3206                                  N0.getValueType(), N0Op0);
3207 
3208       // Replace uses of the AND with uses of the Zero extend node.
3209       CombineTo(N, Zext);
3210 
3211       // We actually want to replace all uses of the any_extend with the
3212       // zero_extend, to avoid duplicating things.  This will later cause this
3213       // AND to be folded.
3214       CombineTo(N0.getNode(), Zext);
3215       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3216     }
3217   }
3218   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3219   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3220   // already be zero by virtue of the width of the base type of the load.
3221   //
3222   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3223   // more cases.
3224   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3225        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3226        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3227        N0.getOperand(0).getResNo() == 0) ||
3228       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3229     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3230                                          N0 : N0.getOperand(0) );
3231 
3232     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3233     // This can be a pure constant or a vector splat, in which case we treat the
3234     // vector as a scalar and use the splat value.
3235     APInt Constant = APInt::getNullValue(1);
3236     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3237       Constant = C->getAPIntValue();
3238     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3239       APInt SplatValue, SplatUndef;
3240       unsigned SplatBitSize;
3241       bool HasAnyUndefs;
3242       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3243                                              SplatBitSize, HasAnyUndefs);
3244       if (IsSplat) {
3245         // Undef bits can contribute to a possible optimisation if set, so
3246         // set them.
3247         SplatValue |= SplatUndef;
3248 
3249         // The splat value may be something like "0x00FFFFFF", which means 0 for
3250         // the first vector value and FF for the rest, repeating. We need a mask
3251         // that will apply equally to all members of the vector, so AND all the
3252         // lanes of the constant together.
3253         EVT VT = Vector->getValueType(0);
3254         unsigned BitWidth = VT.getScalarSizeInBits();
3255 
3256         // If the splat value has been compressed to a bitlength lower
3257         // than the size of the vector lane, we need to re-expand it to
3258         // the lane size.
3259         if (BitWidth > SplatBitSize)
3260           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3261                SplatBitSize < BitWidth;
3262                SplatBitSize = SplatBitSize * 2)
3263             SplatValue |= SplatValue.shl(SplatBitSize);
3264 
3265         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3266         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3267         if (SplatBitSize % BitWidth == 0) {
3268           Constant = APInt::getAllOnesValue(BitWidth);
3269           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3270             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3271         }
3272       }
3273     }
3274 
3275     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3276     // actually legal and isn't going to get expanded, else this is a false
3277     // optimisation.
3278     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3279                                                     Load->getValueType(0),
3280                                                     Load->getMemoryVT());
3281 
3282     // Resize the constant to the same size as the original memory access before
3283     // extension. If it is still the AllOnesValue then this AND is completely
3284     // unneeded.
3285     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3286 
3287     bool B;
3288     switch (Load->getExtensionType()) {
3289     default: B = false; break;
3290     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3291     case ISD::ZEXTLOAD:
3292     case ISD::NON_EXTLOAD: B = true; break;
3293     }
3294 
3295     if (B && Constant.isAllOnesValue()) {
3296       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3297       // preserve semantics once we get rid of the AND.
3298       SDValue NewLoad(Load, 0);
3299       if (Load->getExtensionType() == ISD::EXTLOAD) {
3300         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3301                               Load->getValueType(0), SDLoc(Load),
3302                               Load->getChain(), Load->getBasePtr(),
3303                               Load->getOffset(), Load->getMemoryVT(),
3304                               Load->getMemOperand());
3305         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3306         if (Load->getNumValues() == 3) {
3307           // PRE/POST_INC loads have 3 values.
3308           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3309                            NewLoad.getValue(2) };
3310           CombineTo(Load, To, 3, true);
3311         } else {
3312           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3313         }
3314       }
3315 
3316       // Fold the AND away, taking care not to fold to the old load node if we
3317       // replaced it.
3318       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3319 
3320       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3321     }
3322   }
3323 
3324   // fold (and (load x), 255) -> (zextload x, i8)
3325   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3326   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3327   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3328                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3329                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3330     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3331     LoadSDNode *LN0 = HasAnyExt
3332       ? cast<LoadSDNode>(N0.getOperand(0))
3333       : cast<LoadSDNode>(N0);
3334     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3335         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3336       auto NarrowLoad = false;
3337       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3338       EVT ExtVT, LoadedVT;
3339       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3340                            NarrowLoad)) {
3341         if (!NarrowLoad) {
3342           SDValue NewLoad =
3343             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3344                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3345                            LN0->getMemOperand());
3346           AddToWorklist(N);
3347           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3348           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3349         } else {
3350           EVT PtrType = LN0->getOperand(1).getValueType();
3351 
3352           unsigned Alignment = LN0->getAlignment();
3353           SDValue NewPtr = LN0->getBasePtr();
3354 
3355           // For big endian targets, we need to add an offset to the pointer
3356           // to load the correct bytes.  For little endian systems, we merely
3357           // need to read fewer bytes from the same pointer.
3358           if (DAG.getDataLayout().isBigEndian()) {
3359             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3360             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3361             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3362             SDLoc DL(LN0);
3363             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3364                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3365             Alignment = MinAlign(Alignment, PtrOff);
3366           }
3367 
3368           AddToWorklist(NewPtr.getNode());
3369 
3370           SDValue Load = DAG.getExtLoad(
3371               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3372               LN0->getPointerInfo(), ExtVT, Alignment,
3373               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3374           AddToWorklist(N);
3375           CombineTo(LN0, Load, Load.getValue(1));
3376           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3377         }
3378       }
3379     }
3380   }
3381 
3382   if (SDValue Combined = visitANDLike(N0, N1, N))
3383     return Combined;
3384 
3385   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3386   if (N0.getOpcode() == N1.getOpcode())
3387     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3388       return Tmp;
3389 
3390   // Masking the negated extension of a boolean is just the zero-extended
3391   // boolean:
3392   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3393   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3394   //
3395   // Note: the SimplifyDemandedBits fold below can make an information-losing
3396   // transform, and then we have no way to find this better fold.
3397   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3398     ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3399     SDValue SubRHS = N0.getOperand(1);
3400     if (SubLHS && SubLHS->isNullValue()) {
3401       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3402           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3403         return SubRHS;
3404       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3405           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3406         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3407     }
3408   }
3409 
3410   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3411   // fold (and (sra)) -> (and (srl)) when possible.
3412   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
3413     return SDValue(N, 0);
3414 
3415   // fold (zext_inreg (extload x)) -> (zextload x)
3416   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3417     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3418     EVT MemVT = LN0->getMemoryVT();
3419     // If we zero all the possible extended bits, then we can turn this into
3420     // a zextload if we are running before legalize or the operation is legal.
3421     unsigned BitWidth = N1.getScalarValueSizeInBits();
3422     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3423                            BitWidth - MemVT.getScalarSizeInBits())) &&
3424         ((!LegalOperations && !LN0->isVolatile()) ||
3425          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3426       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3427                                        LN0->getChain(), LN0->getBasePtr(),
3428                                        MemVT, LN0->getMemOperand());
3429       AddToWorklist(N);
3430       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3431       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3432     }
3433   }
3434   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3435   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3436       N0.hasOneUse()) {
3437     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3438     EVT MemVT = LN0->getMemoryVT();
3439     // If we zero all the possible extended bits, then we can turn this into
3440     // a zextload if we are running before legalize or the operation is legal.
3441     unsigned BitWidth = N1.getScalarValueSizeInBits();
3442     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3443                            BitWidth - MemVT.getScalarSizeInBits())) &&
3444         ((!LegalOperations && !LN0->isVolatile()) ||
3445          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3446       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3447                                        LN0->getChain(), LN0->getBasePtr(),
3448                                        MemVT, LN0->getMemOperand());
3449       AddToWorklist(N);
3450       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3451       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3452     }
3453   }
3454   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3455   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3456     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3457                                            N0.getOperand(1), false))
3458       return BSwap;
3459   }
3460 
3461   return SDValue();
3462 }
3463 
3464 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3465 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3466                                         bool DemandHighBits) {
3467   if (!LegalOperations)
3468     return SDValue();
3469 
3470   EVT VT = N->getValueType(0);
3471   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3472     return SDValue();
3473   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3474     return SDValue();
3475 
3476   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3477   bool LookPassAnd0 = false;
3478   bool LookPassAnd1 = false;
3479   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3480       std::swap(N0, N1);
3481   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3482       std::swap(N0, N1);
3483   if (N0.getOpcode() == ISD::AND) {
3484     if (!N0.getNode()->hasOneUse())
3485       return SDValue();
3486     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3487     if (!N01C || N01C->getZExtValue() != 0xFF00)
3488       return SDValue();
3489     N0 = N0.getOperand(0);
3490     LookPassAnd0 = true;
3491   }
3492 
3493   if (N1.getOpcode() == ISD::AND) {
3494     if (!N1.getNode()->hasOneUse())
3495       return SDValue();
3496     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3497     if (!N11C || N11C->getZExtValue() != 0xFF)
3498       return SDValue();
3499     N1 = N1.getOperand(0);
3500     LookPassAnd1 = true;
3501   }
3502 
3503   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3504     std::swap(N0, N1);
3505   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3506     return SDValue();
3507   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3508     return SDValue();
3509 
3510   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3511   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3512   if (!N01C || !N11C)
3513     return SDValue();
3514   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3515     return SDValue();
3516 
3517   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3518   SDValue N00 = N0->getOperand(0);
3519   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3520     if (!N00.getNode()->hasOneUse())
3521       return SDValue();
3522     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3523     if (!N001C || N001C->getZExtValue() != 0xFF)
3524       return SDValue();
3525     N00 = N00.getOperand(0);
3526     LookPassAnd0 = true;
3527   }
3528 
3529   SDValue N10 = N1->getOperand(0);
3530   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3531     if (!N10.getNode()->hasOneUse())
3532       return SDValue();
3533     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3534     if (!N101C || N101C->getZExtValue() != 0xFF00)
3535       return SDValue();
3536     N10 = N10.getOperand(0);
3537     LookPassAnd1 = true;
3538   }
3539 
3540   if (N00 != N10)
3541     return SDValue();
3542 
3543   // Make sure everything beyond the low halfword gets set to zero since the SRL
3544   // 16 will clear the top bits.
3545   unsigned OpSizeInBits = VT.getSizeInBits();
3546   if (DemandHighBits && OpSizeInBits > 16) {
3547     // If the left-shift isn't masked out then the only way this is a bswap is
3548     // if all bits beyond the low 8 are 0. In that case the entire pattern
3549     // reduces to a left shift anyway: leave it for other parts of the combiner.
3550     if (!LookPassAnd0)
3551       return SDValue();
3552 
3553     // However, if the right shift isn't masked out then it might be because
3554     // it's not needed. See if we can spot that too.
3555     if (!LookPassAnd1 &&
3556         !DAG.MaskedValueIsZero(
3557             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3558       return SDValue();
3559   }
3560 
3561   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3562   if (OpSizeInBits > 16) {
3563     SDLoc DL(N);
3564     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3565                       DAG.getConstant(OpSizeInBits - 16, DL,
3566                                       getShiftAmountTy(VT)));
3567   }
3568   return Res;
3569 }
3570 
3571 /// Return true if the specified node is an element that makes up a 32-bit
3572 /// packed halfword byteswap.
3573 /// ((x & 0x000000ff) << 8) |
3574 /// ((x & 0x0000ff00) >> 8) |
3575 /// ((x & 0x00ff0000) << 8) |
3576 /// ((x & 0xff000000) >> 8)
3577 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3578   if (!N.getNode()->hasOneUse())
3579     return false;
3580 
3581   unsigned Opc = N.getOpcode();
3582   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3583     return false;
3584 
3585   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3586   if (!N1C)
3587     return false;
3588 
3589   unsigned Num;
3590   switch (N1C->getZExtValue()) {
3591   default:
3592     return false;
3593   case 0xFF:       Num = 0; break;
3594   case 0xFF00:     Num = 1; break;
3595   case 0xFF0000:   Num = 2; break;
3596   case 0xFF000000: Num = 3; break;
3597   }
3598 
3599   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3600   SDValue N0 = N.getOperand(0);
3601   if (Opc == ISD::AND) {
3602     if (Num == 0 || Num == 2) {
3603       // (x >> 8) & 0xff
3604       // (x >> 8) & 0xff0000
3605       if (N0.getOpcode() != ISD::SRL)
3606         return false;
3607       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3608       if (!C || C->getZExtValue() != 8)
3609         return false;
3610     } else {
3611       // (x << 8) & 0xff00
3612       // (x << 8) & 0xff000000
3613       if (N0.getOpcode() != ISD::SHL)
3614         return false;
3615       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3616       if (!C || C->getZExtValue() != 8)
3617         return false;
3618     }
3619   } else if (Opc == ISD::SHL) {
3620     // (x & 0xff) << 8
3621     // (x & 0xff0000) << 8
3622     if (Num != 0 && Num != 2)
3623       return false;
3624     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3625     if (!C || C->getZExtValue() != 8)
3626       return false;
3627   } else { // Opc == ISD::SRL
3628     // (x & 0xff00) >> 8
3629     // (x & 0xff000000) >> 8
3630     if (Num != 1 && Num != 3)
3631       return false;
3632     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3633     if (!C || C->getZExtValue() != 8)
3634       return false;
3635   }
3636 
3637   if (Parts[Num])
3638     return false;
3639 
3640   Parts[Num] = N0.getOperand(0).getNode();
3641   return true;
3642 }
3643 
3644 /// Match a 32-bit packed halfword bswap. That is
3645 /// ((x & 0x000000ff) << 8) |
3646 /// ((x & 0x0000ff00) >> 8) |
3647 /// ((x & 0x00ff0000) << 8) |
3648 /// ((x & 0xff000000) >> 8)
3649 /// => (rotl (bswap x), 16)
3650 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3651   if (!LegalOperations)
3652     return SDValue();
3653 
3654   EVT VT = N->getValueType(0);
3655   if (VT != MVT::i32)
3656     return SDValue();
3657   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3658     return SDValue();
3659 
3660   // Look for either
3661   // (or (or (and), (and)), (or (and), (and)))
3662   // (or (or (or (and), (and)), (and)), (and))
3663   if (N0.getOpcode() != ISD::OR)
3664     return SDValue();
3665   SDValue N00 = N0.getOperand(0);
3666   SDValue N01 = N0.getOperand(1);
3667   SDNode *Parts[4] = {};
3668 
3669   if (N1.getOpcode() == ISD::OR &&
3670       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3671     // (or (or (and), (and)), (or (and), (and)))
3672     SDValue N000 = N00.getOperand(0);
3673     if (!isBSwapHWordElement(N000, Parts))
3674       return SDValue();
3675 
3676     SDValue N001 = N00.getOperand(1);
3677     if (!isBSwapHWordElement(N001, Parts))
3678       return SDValue();
3679     SDValue N010 = N01.getOperand(0);
3680     if (!isBSwapHWordElement(N010, Parts))
3681       return SDValue();
3682     SDValue N011 = N01.getOperand(1);
3683     if (!isBSwapHWordElement(N011, Parts))
3684       return SDValue();
3685   } else {
3686     // (or (or (or (and), (and)), (and)), (and))
3687     if (!isBSwapHWordElement(N1, Parts))
3688       return SDValue();
3689     if (!isBSwapHWordElement(N01, Parts))
3690       return SDValue();
3691     if (N00.getOpcode() != ISD::OR)
3692       return SDValue();
3693     SDValue N000 = N00.getOperand(0);
3694     if (!isBSwapHWordElement(N000, Parts))
3695       return SDValue();
3696     SDValue N001 = N00.getOperand(1);
3697     if (!isBSwapHWordElement(N001, Parts))
3698       return SDValue();
3699   }
3700 
3701   // Make sure the parts are all coming from the same node.
3702   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3703     return SDValue();
3704 
3705   SDLoc DL(N);
3706   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3707                               SDValue(Parts[0], 0));
3708 
3709   // Result of the bswap should be rotated by 16. If it's not legal, then
3710   // do  (x << 16) | (x >> 16).
3711   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3712   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3713     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3714   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3715     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3716   return DAG.getNode(ISD::OR, DL, VT,
3717                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3718                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3719 }
3720 
3721 /// This contains all DAGCombine rules which reduce two values combined by
3722 /// an Or operation to a single value \see visitANDLike().
3723 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3724   EVT VT = N1.getValueType();
3725   // fold (or x, undef) -> -1
3726   if (!LegalOperations &&
3727       (N0.isUndef() || N1.isUndef())) {
3728     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3729     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3730                            SDLoc(LocReference), VT);
3731   }
3732   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3733   SDValue LL, LR, RL, RR, CC0, CC1;
3734   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3735     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3736     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3737 
3738     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3739       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3740       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3741       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3742         EVT CCVT = getSetCCResultType(LR.getValueType());
3743         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3744           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3745                                        LR.getValueType(), LL, RL);
3746           AddToWorklist(ORNode.getNode());
3747           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3748         }
3749       }
3750       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3751       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3752       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3753         EVT CCVT = getSetCCResultType(LR.getValueType());
3754         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3755           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3756                                         LR.getValueType(), LL, RL);
3757           AddToWorklist(ANDNode.getNode());
3758           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3759         }
3760       }
3761     }
3762     // canonicalize equivalent to ll == rl
3763     if (LL == RR && LR == RL) {
3764       Op1 = ISD::getSetCCSwappedOperands(Op1);
3765       std::swap(RL, RR);
3766     }
3767     if (LL == RL && LR == RR) {
3768       bool isInteger = LL.getValueType().isInteger();
3769       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3770       if (Result != ISD::SETCC_INVALID &&
3771           (!LegalOperations ||
3772            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3773             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3774         EVT CCVT = getSetCCResultType(LL.getValueType());
3775         if (N0.getValueType() == CCVT ||
3776             (!LegalOperations && N0.getValueType() == MVT::i1))
3777           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3778                               LL, LR, Result);
3779       }
3780     }
3781   }
3782 
3783   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3784   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3785       // Don't increase # computations.
3786       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3787     // We can only do this xform if we know that bits from X that are set in C2
3788     // but not in C1 are already zero.  Likewise for Y.
3789     if (const ConstantSDNode *N0O1C =
3790         getAsNonOpaqueConstant(N0.getOperand(1))) {
3791       if (const ConstantSDNode *N1O1C =
3792           getAsNonOpaqueConstant(N1.getOperand(1))) {
3793         // We can only do this xform if we know that bits from X that are set in
3794         // C2 but not in C1 are already zero.  Likewise for Y.
3795         const APInt &LHSMask = N0O1C->getAPIntValue();
3796         const APInt &RHSMask = N1O1C->getAPIntValue();
3797 
3798         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3799             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3800           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3801                                   N0.getOperand(0), N1.getOperand(0));
3802           SDLoc DL(LocReference);
3803           return DAG.getNode(ISD::AND, DL, VT, X,
3804                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3805         }
3806       }
3807     }
3808   }
3809 
3810   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3811   if (N0.getOpcode() == ISD::AND &&
3812       N1.getOpcode() == ISD::AND &&
3813       N0.getOperand(0) == N1.getOperand(0) &&
3814       // Don't increase # computations.
3815       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3816     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3817                             N0.getOperand(1), N1.getOperand(1));
3818     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3819   }
3820 
3821   return SDValue();
3822 }
3823 
3824 SDValue DAGCombiner::visitOR(SDNode *N) {
3825   SDValue N0 = N->getOperand(0);
3826   SDValue N1 = N->getOperand(1);
3827   EVT VT = N1.getValueType();
3828 
3829   // fold vector ops
3830   if (VT.isVector()) {
3831     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3832       return FoldedVOp;
3833 
3834     // fold (or x, 0) -> x, vector edition
3835     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3836       return N1;
3837     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3838       return N0;
3839 
3840     // fold (or x, -1) -> -1, vector edition
3841     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3842       // do not return N0, because undef node may exist in N0
3843       return DAG.getConstant(
3844           APInt::getAllOnesValue(N0.getScalarValueSizeInBits()), SDLoc(N),
3845           N0.getValueType());
3846     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3847       // do not return N1, because undef node may exist in N1
3848       return DAG.getConstant(
3849           APInt::getAllOnesValue(N1.getScalarValueSizeInBits()), SDLoc(N),
3850           N1.getValueType());
3851 
3852     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
3853     // Do this only if the resulting shuffle is legal.
3854     if (isa<ShuffleVectorSDNode>(N0) &&
3855         isa<ShuffleVectorSDNode>(N1) &&
3856         // Avoid folding a node with illegal type.
3857         TLI.isTypeLegal(VT)) {
3858       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
3859       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
3860       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
3861       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
3862       // Ensure both shuffles have a zero input.
3863       if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) {
3864         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
3865         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
3866         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3867         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3868         bool CanFold = true;
3869         int NumElts = VT.getVectorNumElements();
3870         SmallVector<int, 4> Mask(NumElts);
3871 
3872         for (int i = 0; i != NumElts; ++i) {
3873           int M0 = SV0->getMaskElt(i);
3874           int M1 = SV1->getMaskElt(i);
3875 
3876           // Determine if either index is pointing to a zero vector.
3877           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
3878           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
3879 
3880           // If one element is zero and the otherside is undef, keep undef.
3881           // This also handles the case that both are undef.
3882           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
3883             Mask[i] = -1;
3884             continue;
3885           }
3886 
3887           // Make sure only one of the elements is zero.
3888           if (M0Zero == M1Zero) {
3889             CanFold = false;
3890             break;
3891           }
3892 
3893           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
3894 
3895           // We have a zero and non-zero element. If the non-zero came from
3896           // SV0 make the index a LHS index. If it came from SV1, make it
3897           // a RHS index. We need to mod by NumElts because we don't care
3898           // which operand it came from in the original shuffles.
3899           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
3900         }
3901 
3902         if (CanFold) {
3903           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
3904           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
3905 
3906           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3907           if (!LegalMask) {
3908             std::swap(NewLHS, NewRHS);
3909             ShuffleVectorSDNode::commuteMask(Mask);
3910             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3911           }
3912 
3913           if (LegalMask)
3914             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
3915         }
3916       }
3917     }
3918   }
3919 
3920   // fold (or c1, c2) -> c1|c2
3921   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3922   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3923   if (N0C && N1C && !N1C->isOpaque())
3924     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3925   // canonicalize constant to RHS
3926   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3927      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3928     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3929   // fold (or x, 0) -> x
3930   if (isNullConstant(N1))
3931     return N0;
3932   // fold (or x, -1) -> -1
3933   if (isAllOnesConstant(N1))
3934     return N1;
3935   // fold (or x, c) -> c iff (x & ~c) == 0
3936   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3937     return N1;
3938 
3939   if (SDValue Combined = visitORLike(N0, N1, N))
3940     return Combined;
3941 
3942   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3943   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3944     return BSwap;
3945   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3946     return BSwap;
3947 
3948   // reassociate or
3949   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3950     return ROR;
3951   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3952   // iff (c1 & c2) == 0.
3953   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3954              isa<ConstantSDNode>(N0.getOperand(1))) {
3955     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3956     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3957       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3958                                                    N1C, C1))
3959         return DAG.getNode(
3960             ISD::AND, SDLoc(N), VT,
3961             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3962       return SDValue();
3963     }
3964   }
3965   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3966   if (N0.getOpcode() == N1.getOpcode())
3967     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3968       return Tmp;
3969 
3970   // See if this is some rotate idiom.
3971   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3972     return SDValue(Rot, 0);
3973 
3974   // Simplify the operands using demanded-bits information.
3975   if (!VT.isVector() &&
3976       SimplifyDemandedBits(SDValue(N, 0)))
3977     return SDValue(N, 0);
3978 
3979   return SDValue();
3980 }
3981 
3982 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3983 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3984   if (Op.getOpcode() == ISD::AND) {
3985     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3986       Mask = Op.getOperand(1);
3987       Op = Op.getOperand(0);
3988     } else {
3989       return false;
3990     }
3991   }
3992 
3993   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3994     Shift = Op;
3995     return true;
3996   }
3997 
3998   return false;
3999 }
4000 
4001 // Return true if we can prove that, whenever Neg and Pos are both in the
4002 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4003 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4004 //
4005 //     (or (shift1 X, Neg), (shift2 X, Pos))
4006 //
4007 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4008 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4009 // to consider shift amounts with defined behavior.
4010 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4011   // If EltSize is a power of 2 then:
4012   //
4013   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4014   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4015   //
4016   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4017   // for the stronger condition:
4018   //
4019   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4020   //
4021   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4022   // we can just replace Neg with Neg' for the rest of the function.
4023   //
4024   // In other cases we check for the even stronger condition:
4025   //
4026   //     Neg == EltSize - Pos                                    [B]
4027   //
4028   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4029   // behavior if Pos == 0 (and consequently Neg == EltSize).
4030   //
4031   // We could actually use [A] whenever EltSize is a power of 2, but the
4032   // only extra cases that it would match are those uninteresting ones
4033   // where Neg and Pos are never in range at the same time.  E.g. for
4034   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4035   // as well as (sub 32, Pos), but:
4036   //
4037   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4038   //
4039   // always invokes undefined behavior for 32-bit X.
4040   //
4041   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4042   unsigned MaskLoBits = 0;
4043   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4044     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4045       if (NegC->getAPIntValue() == EltSize - 1) {
4046         Neg = Neg.getOperand(0);
4047         MaskLoBits = Log2_64(EltSize);
4048       }
4049     }
4050   }
4051 
4052   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4053   if (Neg.getOpcode() != ISD::SUB)
4054     return false;
4055   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4056   if (!NegC)
4057     return false;
4058   SDValue NegOp1 = Neg.getOperand(1);
4059 
4060   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4061   // Pos'.  The truncation is redundant for the purpose of the equality.
4062   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4063     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4064       if (PosC->getAPIntValue() == EltSize - 1)
4065         Pos = Pos.getOperand(0);
4066 
4067   // The condition we need is now:
4068   //
4069   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4070   //
4071   // If NegOp1 == Pos then we need:
4072   //
4073   //              EltSize & Mask == NegC & Mask
4074   //
4075   // (because "x & Mask" is a truncation and distributes through subtraction).
4076   APInt Width;
4077   if (Pos == NegOp1)
4078     Width = NegC->getAPIntValue();
4079 
4080   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4081   // Then the condition we want to prove becomes:
4082   //
4083   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4084   //
4085   // which, again because "x & Mask" is a truncation, becomes:
4086   //
4087   //                NegC & Mask == (EltSize - PosC) & Mask
4088   //             EltSize & Mask == (NegC + PosC) & Mask
4089   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4090     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4091       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4092     else
4093       return false;
4094   } else
4095     return false;
4096 
4097   // Now we just need to check that EltSize & Mask == Width & Mask.
4098   if (MaskLoBits)
4099     // EltSize & Mask is 0 since Mask is EltSize - 1.
4100     return Width.getLoBits(MaskLoBits) == 0;
4101   return Width == EltSize;
4102 }
4103 
4104 // A subroutine of MatchRotate used once we have found an OR of two opposite
4105 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4106 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4107 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4108 // Neg with outer conversions stripped away.
4109 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4110                                        SDValue Neg, SDValue InnerPos,
4111                                        SDValue InnerNeg, unsigned PosOpcode,
4112                                        unsigned NegOpcode, const SDLoc &DL) {
4113   // fold (or (shl x, (*ext y)),
4114   //          (srl x, (*ext (sub 32, y)))) ->
4115   //   (rotl x, y) or (rotr x, (sub 32, y))
4116   //
4117   // fold (or (shl x, (*ext (sub 32, y))),
4118   //          (srl x, (*ext y))) ->
4119   //   (rotr x, y) or (rotl x, (sub 32, y))
4120   EVT VT = Shifted.getValueType();
4121   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4122     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4123     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4124                        HasPos ? Pos : Neg).getNode();
4125   }
4126 
4127   return nullptr;
4128 }
4129 
4130 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4131 // idioms for rotate, and if the target supports rotation instructions, generate
4132 // a rot[lr].
4133 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4134   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4135   EVT VT = LHS.getValueType();
4136   if (!TLI.isTypeLegal(VT)) return nullptr;
4137 
4138   // The target must have at least one rotate flavor.
4139   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4140   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4141   if (!HasROTL && !HasROTR) return nullptr;
4142 
4143   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4144   SDValue LHSShift;   // The shift.
4145   SDValue LHSMask;    // AND value if any.
4146   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4147     return nullptr; // Not part of a rotate.
4148 
4149   SDValue RHSShift;   // The shift.
4150   SDValue RHSMask;    // AND value if any.
4151   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4152     return nullptr; // Not part of a rotate.
4153 
4154   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4155     return nullptr;   // Not shifting the same value.
4156 
4157   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4158     return nullptr;   // Shifts must disagree.
4159 
4160   // Canonicalize shl to left side in a shl/srl pair.
4161   if (RHSShift.getOpcode() == ISD::SHL) {
4162     std::swap(LHS, RHS);
4163     std::swap(LHSShift, RHSShift);
4164     std::swap(LHSMask, RHSMask);
4165   }
4166 
4167   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4168   SDValue LHSShiftArg = LHSShift.getOperand(0);
4169   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4170   SDValue RHSShiftArg = RHSShift.getOperand(0);
4171   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4172 
4173   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4174   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4175   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4176     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4177     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4178     if ((LShVal + RShVal) != EltSizeInBits)
4179       return nullptr;
4180 
4181     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4182                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4183 
4184     // If there is an AND of either shifted operand, apply it to the result.
4185     if (LHSMask.getNode() || RHSMask.getNode()) {
4186       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4187       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4188 
4189       if (LHSMask.getNode()) {
4190         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4191         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4192                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4193                                        DAG.getConstant(RHSBits, DL, VT)));
4194       }
4195       if (RHSMask.getNode()) {
4196         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4197         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4198                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4199                                        DAG.getConstant(LHSBits, DL, VT)));
4200       }
4201 
4202       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4203     }
4204 
4205     return Rot.getNode();
4206   }
4207 
4208   // If there is a mask here, and we have a variable shift, we can't be sure
4209   // that we're masking out the right stuff.
4210   if (LHSMask.getNode() || RHSMask.getNode())
4211     return nullptr;
4212 
4213   // If the shift amount is sign/zext/any-extended just peel it off.
4214   SDValue LExtOp0 = LHSShiftAmt;
4215   SDValue RExtOp0 = RHSShiftAmt;
4216   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4217        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4218        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4219        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4220       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4221        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4222        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4223        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4224     LExtOp0 = LHSShiftAmt.getOperand(0);
4225     RExtOp0 = RHSShiftAmt.getOperand(0);
4226   }
4227 
4228   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4229                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4230   if (TryL)
4231     return TryL;
4232 
4233   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4234                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4235   if (TryR)
4236     return TryR;
4237 
4238   return nullptr;
4239 }
4240 
4241 SDValue DAGCombiner::visitXOR(SDNode *N) {
4242   SDValue N0 = N->getOperand(0);
4243   SDValue N1 = N->getOperand(1);
4244   EVT VT = N0.getValueType();
4245 
4246   // fold vector ops
4247   if (VT.isVector()) {
4248     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4249       return FoldedVOp;
4250 
4251     // fold (xor x, 0) -> x, vector edition
4252     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4253       return N1;
4254     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4255       return N0;
4256   }
4257 
4258   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4259   if (N0.isUndef() && N1.isUndef())
4260     return DAG.getConstant(0, SDLoc(N), VT);
4261   // fold (xor x, undef) -> undef
4262   if (N0.isUndef())
4263     return N0;
4264   if (N1.isUndef())
4265     return N1;
4266   // fold (xor c1, c2) -> c1^c2
4267   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4268   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4269   if (N0C && N1C)
4270     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4271   // canonicalize constant to RHS
4272   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4273      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4274     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4275   // fold (xor x, 0) -> x
4276   if (isNullConstant(N1))
4277     return N0;
4278   // reassociate xor
4279   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4280     return RXOR;
4281 
4282   // fold !(x cc y) -> (x !cc y)
4283   SDValue LHS, RHS, CC;
4284   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4285     bool isInt = LHS.getValueType().isInteger();
4286     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4287                                                isInt);
4288 
4289     if (!LegalOperations ||
4290         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4291       switch (N0.getOpcode()) {
4292       default:
4293         llvm_unreachable("Unhandled SetCC Equivalent!");
4294       case ISD::SETCC:
4295         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4296       case ISD::SELECT_CC:
4297         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4298                                N0.getOperand(3), NotCC);
4299       }
4300     }
4301   }
4302 
4303   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4304   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4305       N0.getNode()->hasOneUse() &&
4306       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4307     SDValue V = N0.getOperand(0);
4308     SDLoc DL(N0);
4309     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4310                     DAG.getConstant(1, DL, V.getValueType()));
4311     AddToWorklist(V.getNode());
4312     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4313   }
4314 
4315   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4316   if (isOneConstant(N1) && VT == MVT::i1 &&
4317       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4318     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4319     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4320       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4321       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4322       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4323       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4324       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4325     }
4326   }
4327   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4328   if (isAllOnesConstant(N1) &&
4329       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4330     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4331     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4332       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4333       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4334       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4335       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4336       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4337     }
4338   }
4339   // fold (xor (and x, y), y) -> (and (not x), y)
4340   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4341       N0->getOperand(1) == N1) {
4342     SDValue X = N0->getOperand(0);
4343     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4344     AddToWorklist(NotX.getNode());
4345     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4346   }
4347   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4348   if (N1C && N0.getOpcode() == ISD::XOR) {
4349     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4350       SDLoc DL(N);
4351       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4352                          DAG.getConstant(N1C->getAPIntValue() ^
4353                                          N00C->getAPIntValue(), DL, VT));
4354     }
4355     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4356       SDLoc DL(N);
4357       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4358                          DAG.getConstant(N1C->getAPIntValue() ^
4359                                          N01C->getAPIntValue(), DL, VT));
4360     }
4361   }
4362   // fold (xor x, x) -> 0
4363   if (N0 == N1)
4364     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4365 
4366   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4367   // Here is a concrete example of this equivalence:
4368   // i16   x ==  14
4369   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4370   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4371   //
4372   // =>
4373   //
4374   // i16     ~1      == 0b1111111111111110
4375   // i16 rol(~1, 14) == 0b1011111111111111
4376   //
4377   // Some additional tips to help conceptualize this transform:
4378   // - Try to see the operation as placing a single zero in a value of all ones.
4379   // - There exists no value for x which would allow the result to contain zero.
4380   // - Values of x larger than the bitwidth are undefined and do not require a
4381   //   consistent result.
4382   // - Pushing the zero left requires shifting one bits in from the right.
4383   // A rotate left of ~1 is a nice way of achieving the desired result.
4384   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4385       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4386     SDLoc DL(N);
4387     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4388                        N0.getOperand(1));
4389   }
4390 
4391   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4392   if (N0.getOpcode() == N1.getOpcode())
4393     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4394       return Tmp;
4395 
4396   // Simplify the expression using non-local knowledge.
4397   if (!VT.isVector() &&
4398       SimplifyDemandedBits(SDValue(N, 0)))
4399     return SDValue(N, 0);
4400 
4401   return SDValue();
4402 }
4403 
4404 /// Handle transforms common to the three shifts, when the shift amount is a
4405 /// constant.
4406 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4407   SDNode *LHS = N->getOperand(0).getNode();
4408   if (!LHS->hasOneUse()) return SDValue();
4409 
4410   // We want to pull some binops through shifts, so that we have (and (shift))
4411   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4412   // thing happens with address calculations, so it's important to canonicalize
4413   // it.
4414   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4415 
4416   switch (LHS->getOpcode()) {
4417   default: return SDValue();
4418   case ISD::OR:
4419   case ISD::XOR:
4420     HighBitSet = false; // We can only transform sra if the high bit is clear.
4421     break;
4422   case ISD::AND:
4423     HighBitSet = true;  // We can only transform sra if the high bit is set.
4424     break;
4425   case ISD::ADD:
4426     if (N->getOpcode() != ISD::SHL)
4427       return SDValue(); // only shl(add) not sr[al](add).
4428     HighBitSet = false; // We can only transform sra if the high bit is clear.
4429     break;
4430   }
4431 
4432   // We require the RHS of the binop to be a constant and not opaque as well.
4433   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4434   if (!BinOpCst) return SDValue();
4435 
4436   // FIXME: disable this unless the input to the binop is a shift by a constant.
4437   // If it is not a shift, it pessimizes some common cases like:
4438   //
4439   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4440   //    int bar(int *X, int i) { return X[i & 255]; }
4441   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4442   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4443        BinOpLHSVal->getOpcode() != ISD::SRA &&
4444        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4445       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4446     return SDValue();
4447 
4448   EVT VT = N->getValueType(0);
4449 
4450   // If this is a signed shift right, and the high bit is modified by the
4451   // logical operation, do not perform the transformation. The highBitSet
4452   // boolean indicates the value of the high bit of the constant which would
4453   // cause it to be modified for this operation.
4454   if (N->getOpcode() == ISD::SRA) {
4455     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4456     if (BinOpRHSSignSet != HighBitSet)
4457       return SDValue();
4458   }
4459 
4460   if (!TLI.isDesirableToCommuteWithShift(LHS))
4461     return SDValue();
4462 
4463   // Fold the constants, shifting the binop RHS by the shift amount.
4464   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4465                                N->getValueType(0),
4466                                LHS->getOperand(1), N->getOperand(1));
4467   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4468 
4469   // Create the new shift.
4470   SDValue NewShift = DAG.getNode(N->getOpcode(),
4471                                  SDLoc(LHS->getOperand(0)),
4472                                  VT, LHS->getOperand(0), N->getOperand(1));
4473 
4474   // Create the new binop.
4475   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4476 }
4477 
4478 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4479   assert(N->getOpcode() == ISD::TRUNCATE);
4480   assert(N->getOperand(0).getOpcode() == ISD::AND);
4481 
4482   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4483   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4484     SDValue N01 = N->getOperand(0).getOperand(1);
4485 
4486     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4487       if (!N01C->isOpaque()) {
4488         EVT TruncVT = N->getValueType(0);
4489         SDValue N00 = N->getOperand(0).getOperand(0);
4490         APInt TruncC = N01C->getAPIntValue();
4491         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4492         SDLoc DL(N);
4493 
4494         return DAG.getNode(ISD::AND, DL, TruncVT,
4495                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4496                            DAG.getConstant(TruncC, DL, TruncVT));
4497       }
4498     }
4499   }
4500 
4501   return SDValue();
4502 }
4503 
4504 SDValue DAGCombiner::visitRotate(SDNode *N) {
4505   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4506   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4507       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4508     if (SDValue NewOp1 =
4509             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4510       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4511                          N->getOperand(0), NewOp1);
4512   }
4513   return SDValue();
4514 }
4515 
4516 SDValue DAGCombiner::visitSHL(SDNode *N) {
4517   SDValue N0 = N->getOperand(0);
4518   SDValue N1 = N->getOperand(1);
4519   EVT VT = N0.getValueType();
4520   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4521 
4522   // fold vector ops
4523   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4524   if (VT.isVector()) {
4525     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4526       return FoldedVOp;
4527 
4528     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4529     // If setcc produces all-one true value then:
4530     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4531     if (N1CV && N1CV->isConstant()) {
4532       if (N0.getOpcode() == ISD::AND) {
4533         SDValue N00 = N0->getOperand(0);
4534         SDValue N01 = N0->getOperand(1);
4535         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4536 
4537         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4538             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4539                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4540           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4541                                                      N01CV, N1CV))
4542             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4543         }
4544       } else {
4545         N1C = isConstOrConstSplat(N1);
4546       }
4547     }
4548   }
4549 
4550   // fold (shl c1, c2) -> c1<<c2
4551   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4552   if (N0C && N1C && !N1C->isOpaque())
4553     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4554   // fold (shl 0, x) -> 0
4555   if (isNullConstant(N0))
4556     return N0;
4557   // fold (shl x, c >= size(x)) -> undef
4558   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4559     return DAG.getUNDEF(VT);
4560   // fold (shl x, 0) -> x
4561   if (N1C && N1C->isNullValue())
4562     return N0;
4563   // fold (shl undef, x) -> 0
4564   if (N0.isUndef())
4565     return DAG.getConstant(0, SDLoc(N), VT);
4566   // if (shl x, c) is known to be zero, return 0
4567   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4568                             APInt::getAllOnesValue(OpSizeInBits)))
4569     return DAG.getConstant(0, SDLoc(N), VT);
4570   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4571   if (N1.getOpcode() == ISD::TRUNCATE &&
4572       N1.getOperand(0).getOpcode() == ISD::AND) {
4573     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4574       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4575   }
4576 
4577   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4578     return SDValue(N, 0);
4579 
4580   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4581   if (N1C && N0.getOpcode() == ISD::SHL) {
4582     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4583       SDLoc DL(N);
4584       APInt c1 = N0C1->getAPIntValue();
4585       APInt c2 = N1C->getAPIntValue();
4586       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4587 
4588       APInt Sum = c1 + c2;
4589       if (Sum.uge(OpSizeInBits))
4590         return DAG.getConstant(0, DL, VT);
4591 
4592       return DAG.getNode(
4593           ISD::SHL, DL, VT, N0.getOperand(0),
4594           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4595     }
4596   }
4597 
4598   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4599   // For this to be valid, the second form must not preserve any of the bits
4600   // that are shifted out by the inner shift in the first form.  This means
4601   // the outer shift size must be >= the number of bits added by the ext.
4602   // As a corollary, we don't care what kind of ext it is.
4603   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4604               N0.getOpcode() == ISD::ANY_EXTEND ||
4605               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4606       N0.getOperand(0).getOpcode() == ISD::SHL) {
4607     SDValue N0Op0 = N0.getOperand(0);
4608     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4609       APInt c1 = N0Op0C1->getAPIntValue();
4610       APInt c2 = N1C->getAPIntValue();
4611       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4612 
4613       EVT InnerShiftVT = N0Op0.getValueType();
4614       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4615       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
4616         SDLoc DL(N0);
4617         APInt Sum = c1 + c2;
4618         if (Sum.uge(OpSizeInBits))
4619           return DAG.getConstant(0, DL, VT);
4620 
4621         return DAG.getNode(
4622             ISD::SHL, DL, VT,
4623             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
4624             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4625       }
4626     }
4627   }
4628 
4629   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4630   // Only fold this if the inner zext has no other uses to avoid increasing
4631   // the total number of instructions.
4632   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4633       N0.getOperand(0).getOpcode() == ISD::SRL) {
4634     SDValue N0Op0 = N0.getOperand(0);
4635     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4636       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
4637         uint64_t c1 = N0Op0C1->getZExtValue();
4638         uint64_t c2 = N1C->getZExtValue();
4639         if (c1 == c2) {
4640           SDValue NewOp0 = N0.getOperand(0);
4641           EVT CountVT = NewOp0.getOperand(1).getValueType();
4642           SDLoc DL(N);
4643           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4644                                        NewOp0,
4645                                        DAG.getConstant(c2, DL, CountVT));
4646           AddToWorklist(NewSHL.getNode());
4647           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4648         }
4649       }
4650     }
4651   }
4652 
4653   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4654   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4655   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4656       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4657     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4658       uint64_t C1 = N0C1->getZExtValue();
4659       uint64_t C2 = N1C->getZExtValue();
4660       SDLoc DL(N);
4661       if (C1 <= C2)
4662         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4663                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4664       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4665                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4666     }
4667   }
4668 
4669   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4670   //                               (and (srl x, (sub c1, c2), MASK)
4671   // Only fold this if the inner shift has no other uses -- if it does, folding
4672   // this will increase the total number of instructions.
4673   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4674     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4675       uint64_t c1 = N0C1->getZExtValue();
4676       if (c1 < OpSizeInBits) {
4677         uint64_t c2 = N1C->getZExtValue();
4678         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4679         SDValue Shift;
4680         if (c2 > c1) {
4681           Mask = Mask.shl(c2 - c1);
4682           SDLoc DL(N);
4683           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4684                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4685         } else {
4686           Mask = Mask.lshr(c1 - c2);
4687           SDLoc DL(N);
4688           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4689                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4690         }
4691         SDLoc DL(N0);
4692         return DAG.getNode(ISD::AND, DL, VT, Shift,
4693                            DAG.getConstant(Mask, DL, VT));
4694       }
4695     }
4696   }
4697   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4698   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4699     unsigned BitSize = VT.getScalarSizeInBits();
4700     SDLoc DL(N);
4701     SDValue HiBitsMask =
4702       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4703                                             BitSize - N1C->getZExtValue()),
4704                       DL, VT);
4705     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4706                        HiBitsMask);
4707   }
4708 
4709   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4710   // Variant of version done on multiply, except mul by a power of 2 is turned
4711   // into a shift.
4712   APInt Val;
4713   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4714       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4715        ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4716     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4717     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4718     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4719   }
4720 
4721   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4722   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4723     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4724       if (SDValue Folded =
4725               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4726         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4727     }
4728   }
4729 
4730   if (N1C && !N1C->isOpaque())
4731     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4732       return NewSHL;
4733 
4734   return SDValue();
4735 }
4736 
4737 SDValue DAGCombiner::visitSRA(SDNode *N) {
4738   SDValue N0 = N->getOperand(0);
4739   SDValue N1 = N->getOperand(1);
4740   EVT VT = N0.getValueType();
4741   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4742 
4743   // fold vector ops
4744   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4745   if (VT.isVector()) {
4746     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4747       return FoldedVOp;
4748 
4749     N1C = isConstOrConstSplat(N1);
4750   }
4751 
4752   // fold (sra c1, c2) -> (sra c1, c2)
4753   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4754   if (N0C && N1C && !N1C->isOpaque())
4755     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4756   // fold (sra 0, x) -> 0
4757   if (isNullConstant(N0))
4758     return N0;
4759   // fold (sra -1, x) -> -1
4760   if (isAllOnesConstant(N0))
4761     return N0;
4762   // fold (sra x, c >= size(x)) -> undef
4763   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4764     return DAG.getUNDEF(VT);
4765   // fold (sra x, 0) -> x
4766   if (N1C && N1C->isNullValue())
4767     return N0;
4768   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4769   // sext_inreg.
4770   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4771     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4772     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4773     if (VT.isVector())
4774       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4775                                ExtVT, VT.getVectorNumElements());
4776     if ((!LegalOperations ||
4777          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4778       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4779                          N0.getOperand(0), DAG.getValueType(ExtVT));
4780   }
4781 
4782   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4783   if (N1C && N0.getOpcode() == ISD::SRA) {
4784     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4785       SDLoc DL(N);
4786       APInt c1 = N0C1->getAPIntValue();
4787       APInt c2 = N1C->getAPIntValue();
4788       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4789 
4790       APInt Sum = c1 + c2;
4791       if (Sum.uge(OpSizeInBits))
4792         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
4793 
4794       return DAG.getNode(
4795           ISD::SRA, DL, VT, N0.getOperand(0),
4796           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4797     }
4798   }
4799 
4800   // fold (sra (shl X, m), (sub result_size, n))
4801   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4802   // result_size - n != m.
4803   // If truncate is free for the target sext(shl) is likely to result in better
4804   // code.
4805   if (N0.getOpcode() == ISD::SHL && N1C) {
4806     // Get the two constanst of the shifts, CN0 = m, CN = n.
4807     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4808     if (N01C) {
4809       LLVMContext &Ctx = *DAG.getContext();
4810       // Determine what the truncate's result bitsize and type would be.
4811       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4812 
4813       if (VT.isVector())
4814         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4815 
4816       // Determine the residual right-shift amount.
4817       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4818 
4819       // If the shift is not a no-op (in which case this should be just a sign
4820       // extend already), the truncated to type is legal, sign_extend is legal
4821       // on that type, and the truncate to that type is both legal and free,
4822       // perform the transform.
4823       if ((ShiftAmt > 0) &&
4824           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4825           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4826           TLI.isTruncateFree(VT, TruncVT)) {
4827 
4828         SDLoc DL(N);
4829         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4830             getShiftAmountTy(N0.getOperand(0).getValueType()));
4831         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4832                                     N0.getOperand(0), Amt);
4833         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4834                                     Shift);
4835         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4836                            N->getValueType(0), Trunc);
4837       }
4838     }
4839   }
4840 
4841   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4842   if (N1.getOpcode() == ISD::TRUNCATE &&
4843       N1.getOperand(0).getOpcode() == ISD::AND) {
4844     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4845       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4846   }
4847 
4848   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4849   //      if c1 is equal to the number of bits the trunc removes
4850   if (N0.getOpcode() == ISD::TRUNCATE &&
4851       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4852        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4853       N0.getOperand(0).hasOneUse() &&
4854       N0.getOperand(0).getOperand(1).hasOneUse() &&
4855       N1C) {
4856     SDValue N0Op0 = N0.getOperand(0);
4857     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4858       unsigned LargeShiftVal = LargeShift->getZExtValue();
4859       EVT LargeVT = N0Op0.getValueType();
4860 
4861       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4862         SDLoc DL(N);
4863         SDValue Amt =
4864           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4865                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4866         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4867                                   N0Op0.getOperand(0), Amt);
4868         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4869       }
4870     }
4871   }
4872 
4873   // Simplify, based on bits shifted out of the LHS.
4874   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4875     return SDValue(N, 0);
4876 
4877 
4878   // If the sign bit is known to be zero, switch this to a SRL.
4879   if (DAG.SignBitIsZero(N0))
4880     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4881 
4882   if (N1C && !N1C->isOpaque())
4883     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4884       return NewSRA;
4885 
4886   return SDValue();
4887 }
4888 
4889 SDValue DAGCombiner::visitSRL(SDNode *N) {
4890   SDValue N0 = N->getOperand(0);
4891   SDValue N1 = N->getOperand(1);
4892   EVT VT = N0.getValueType();
4893   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4894 
4895   // fold vector ops
4896   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4897   if (VT.isVector()) {
4898     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4899       return FoldedVOp;
4900 
4901     N1C = isConstOrConstSplat(N1);
4902   }
4903 
4904   // fold (srl c1, c2) -> c1 >>u c2
4905   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4906   if (N0C && N1C && !N1C->isOpaque())
4907     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4908   // fold (srl 0, x) -> 0
4909   if (isNullConstant(N0))
4910     return N0;
4911   // fold (srl x, c >= size(x)) -> undef
4912   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4913     return DAG.getUNDEF(VT);
4914   // fold (srl x, 0) -> x
4915   if (N1C && N1C->isNullValue())
4916     return N0;
4917   // if (srl x, c) is known to be zero, return 0
4918   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4919                                    APInt::getAllOnesValue(OpSizeInBits)))
4920     return DAG.getConstant(0, SDLoc(N), VT);
4921 
4922   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4923   if (N1C && N0.getOpcode() == ISD::SRL) {
4924     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4925       SDLoc DL(N);
4926       APInt c1 = N0C1->getAPIntValue();
4927       APInt c2 = N1C->getAPIntValue();
4928       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4929 
4930       APInt Sum = c1 + c2;
4931       if (Sum.uge(OpSizeInBits))
4932         return DAG.getConstant(0, DL, VT);
4933 
4934       return DAG.getNode(
4935           ISD::SRL, DL, VT, N0.getOperand(0),
4936           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4937     }
4938   }
4939 
4940   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4941   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4942       N0.getOperand(0).getOpcode() == ISD::SRL &&
4943       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4944     uint64_t c1 =
4945       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4946     uint64_t c2 = N1C->getZExtValue();
4947     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4948     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4949     uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4950     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4951     if (c1 + OpSizeInBits == InnerShiftSize) {
4952       SDLoc DL(N0);
4953       if (c1 + c2 >= InnerShiftSize)
4954         return DAG.getConstant(0, DL, VT);
4955       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4956                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4957                                      N0.getOperand(0)->getOperand(0),
4958                                      DAG.getConstant(c1 + c2, DL,
4959                                                      ShiftCountVT)));
4960     }
4961   }
4962 
4963   // fold (srl (shl x, c), c) -> (and x, cst2)
4964   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4965     unsigned BitSize = N0.getScalarValueSizeInBits();
4966     if (BitSize <= 64) {
4967       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4968       SDLoc DL(N);
4969       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4970                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4971     }
4972   }
4973 
4974   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4975   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4976     // Shifting in all undef bits?
4977     EVT SmallVT = N0.getOperand(0).getValueType();
4978     unsigned BitSize = SmallVT.getScalarSizeInBits();
4979     if (N1C->getZExtValue() >= BitSize)
4980       return DAG.getUNDEF(VT);
4981 
4982     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4983       uint64_t ShiftAmt = N1C->getZExtValue();
4984       SDLoc DL0(N0);
4985       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4986                                        N0.getOperand(0),
4987                           DAG.getConstant(ShiftAmt, DL0,
4988                                           getShiftAmountTy(SmallVT)));
4989       AddToWorklist(SmallShift.getNode());
4990       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4991       SDLoc DL(N);
4992       return DAG.getNode(ISD::AND, DL, VT,
4993                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4994                          DAG.getConstant(Mask, DL, VT));
4995     }
4996   }
4997 
4998   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4999   // bit, which is unmodified by sra.
5000   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5001     if (N0.getOpcode() == ISD::SRA)
5002       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5003   }
5004 
5005   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
5006   if (N1C && N0.getOpcode() == ISD::CTLZ &&
5007       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5008     APInt KnownZero, KnownOne;
5009     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
5010 
5011     // If any of the input bits are KnownOne, then the input couldn't be all
5012     // zeros, thus the result of the srl will always be zero.
5013     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5014 
5015     // If all of the bits input the to ctlz node are known to be zero, then
5016     // the result of the ctlz is "32" and the result of the shift is one.
5017     APInt UnknownBits = ~KnownZero;
5018     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5019 
5020     // Otherwise, check to see if there is exactly one bit input to the ctlz.
5021     if ((UnknownBits & (UnknownBits - 1)) == 0) {
5022       // Okay, we know that only that the single bit specified by UnknownBits
5023       // could be set on input to the CTLZ node. If this bit is set, the SRL
5024       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5025       // to an SRL/XOR pair, which is likely to simplify more.
5026       unsigned ShAmt = UnknownBits.countTrailingZeros();
5027       SDValue Op = N0.getOperand(0);
5028 
5029       if (ShAmt) {
5030         SDLoc DL(N0);
5031         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5032                   DAG.getConstant(ShAmt, DL,
5033                                   getShiftAmountTy(Op.getValueType())));
5034         AddToWorklist(Op.getNode());
5035       }
5036 
5037       SDLoc DL(N);
5038       return DAG.getNode(ISD::XOR, DL, VT,
5039                          Op, DAG.getConstant(1, DL, VT));
5040     }
5041   }
5042 
5043   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5044   if (N1.getOpcode() == ISD::TRUNCATE &&
5045       N1.getOperand(0).getOpcode() == ISD::AND) {
5046     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5047       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5048   }
5049 
5050   // fold operands of srl based on knowledge that the low bits are not
5051   // demanded.
5052   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5053     return SDValue(N, 0);
5054 
5055   if (N1C && !N1C->isOpaque())
5056     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5057       return NewSRL;
5058 
5059   // Attempt to convert a srl of a load into a narrower zero-extending load.
5060   if (SDValue NarrowLoad = ReduceLoadWidth(N))
5061     return NarrowLoad;
5062 
5063   // Here is a common situation. We want to optimize:
5064   //
5065   //   %a = ...
5066   //   %b = and i32 %a, 2
5067   //   %c = srl i32 %b, 1
5068   //   brcond i32 %c ...
5069   //
5070   // into
5071   //
5072   //   %a = ...
5073   //   %b = and %a, 2
5074   //   %c = setcc eq %b, 0
5075   //   brcond %c ...
5076   //
5077   // However when after the source operand of SRL is optimized into AND, the SRL
5078   // itself may not be optimized further. Look for it and add the BRCOND into
5079   // the worklist.
5080   if (N->hasOneUse()) {
5081     SDNode *Use = *N->use_begin();
5082     if (Use->getOpcode() == ISD::BRCOND)
5083       AddToWorklist(Use);
5084     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5085       // Also look pass the truncate.
5086       Use = *Use->use_begin();
5087       if (Use->getOpcode() == ISD::BRCOND)
5088         AddToWorklist(Use);
5089     }
5090   }
5091 
5092   return SDValue();
5093 }
5094 
5095 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5096   SDValue N0 = N->getOperand(0);
5097   EVT VT = N->getValueType(0);
5098 
5099   // fold (bswap c1) -> c2
5100   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5101     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5102   // fold (bswap (bswap x)) -> x
5103   if (N0.getOpcode() == ISD::BSWAP)
5104     return N0->getOperand(0);
5105   return SDValue();
5106 }
5107 
5108 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5109   SDValue N0 = N->getOperand(0);
5110 
5111   // fold (bitreverse (bitreverse x)) -> x
5112   if (N0.getOpcode() == ISD::BITREVERSE)
5113     return N0.getOperand(0);
5114   return SDValue();
5115 }
5116 
5117 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5118   SDValue N0 = N->getOperand(0);
5119   EVT VT = N->getValueType(0);
5120 
5121   // fold (ctlz c1) -> c2
5122   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5123     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5124   return SDValue();
5125 }
5126 
5127 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5128   SDValue N0 = N->getOperand(0);
5129   EVT VT = N->getValueType(0);
5130 
5131   // fold (ctlz_zero_undef c1) -> c2
5132   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5133     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5134   return SDValue();
5135 }
5136 
5137 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5138   SDValue N0 = N->getOperand(0);
5139   EVT VT = N->getValueType(0);
5140 
5141   // fold (cttz c1) -> c2
5142   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5143     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5144   return SDValue();
5145 }
5146 
5147 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5148   SDValue N0 = N->getOperand(0);
5149   EVT VT = N->getValueType(0);
5150 
5151   // fold (cttz_zero_undef c1) -> c2
5152   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5153     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5154   return SDValue();
5155 }
5156 
5157 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5158   SDValue N0 = N->getOperand(0);
5159   EVT VT = N->getValueType(0);
5160 
5161   // fold (ctpop c1) -> c2
5162   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5163     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5164   return SDValue();
5165 }
5166 
5167 
5168 /// \brief Generate Min/Max node
5169 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5170                                    SDValue RHS, SDValue True, SDValue False,
5171                                    ISD::CondCode CC, const TargetLowering &TLI,
5172                                    SelectionDAG &DAG) {
5173   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5174     return SDValue();
5175 
5176   switch (CC) {
5177   case ISD::SETOLT:
5178   case ISD::SETOLE:
5179   case ISD::SETLT:
5180   case ISD::SETLE:
5181   case ISD::SETULT:
5182   case ISD::SETULE: {
5183     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5184     if (TLI.isOperationLegal(Opcode, VT))
5185       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5186     return SDValue();
5187   }
5188   case ISD::SETOGT:
5189   case ISD::SETOGE:
5190   case ISD::SETGT:
5191   case ISD::SETGE:
5192   case ISD::SETUGT:
5193   case ISD::SETUGE: {
5194     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5195     if (TLI.isOperationLegal(Opcode, VT))
5196       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5197     return SDValue();
5198   }
5199   default:
5200     return SDValue();
5201   }
5202 }
5203 
5204 // TODO: We should handle other cases of selecting between {-1,0,1} here.
5205 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5206   SDValue Cond = N->getOperand(0);
5207   SDValue N1 = N->getOperand(1);
5208   SDValue N2 = N->getOperand(2);
5209   EVT VT = N->getValueType(0);
5210   EVT CondVT = Cond.getValueType();
5211   SDLoc DL(N);
5212 
5213   // fold (select Cond, 0, 1) -> (xor Cond, 1)
5214   // We can't do this reliably if integer based booleans have different contents
5215   // to floating point based booleans. This is because we can't tell whether we
5216   // have an integer-based boolean or a floating-point-based boolean unless we
5217   // can find the SETCC that produced it and inspect its operands. This is
5218   // fairly easy if C is the SETCC node, but it can potentially be
5219   // undiscoverable (or not reasonably discoverable). For example, it could be
5220   // in another basic block or it could require searching a complicated
5221   // expression.
5222   if (VT.isInteger() &&
5223       (CondVT == MVT::i1 || (CondVT.isInteger() &&
5224                              TLI.getBooleanContents(false, true) ==
5225                                  TargetLowering::ZeroOrOneBooleanContent &&
5226                              TLI.getBooleanContents(false, false) ==
5227                                  TargetLowering::ZeroOrOneBooleanContent)) &&
5228       isNullConstant(N1) && isOneConstant(N2)) {
5229     SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond,
5230                                   DAG.getConstant(1, DL, CondVT));
5231     if (VT.bitsEq(CondVT))
5232       return NotCond;
5233     return DAG.getZExtOrTrunc(NotCond, DL, VT);
5234   }
5235 
5236   return SDValue();
5237 }
5238 
5239 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5240   SDValue N0 = N->getOperand(0);
5241   SDValue N1 = N->getOperand(1);
5242   SDValue N2 = N->getOperand(2);
5243   EVT VT = N->getValueType(0);
5244   EVT VT0 = N0.getValueType();
5245 
5246   // fold (select C, X, X) -> X
5247   if (N1 == N2)
5248     return N1;
5249   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5250     // fold (select true, X, Y) -> X
5251     // fold (select false, X, Y) -> Y
5252     return !N0C->isNullValue() ? N1 : N2;
5253   }
5254   // fold (select C, 1, X) -> (or C, X)
5255   if (VT == MVT::i1 && isOneConstant(N1))
5256     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5257 
5258   if (SDValue V = foldSelectOfConstants(N))
5259     return V;
5260 
5261   // fold (select C, 0, X) -> (and (not C), X)
5262   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5263     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5264     AddToWorklist(NOTNode.getNode());
5265     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5266   }
5267   // fold (select C, X, 1) -> (or (not C), X)
5268   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5269     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5270     AddToWorklist(NOTNode.getNode());
5271     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5272   }
5273   // fold (select C, X, 0) -> (and C, X)
5274   if (VT == MVT::i1 && isNullConstant(N2))
5275     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5276   // fold (select X, X, Y) -> (or X, Y)
5277   // fold (select X, 1, Y) -> (or X, Y)
5278   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5279     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5280   // fold (select X, Y, X) -> (and X, Y)
5281   // fold (select X, Y, 0) -> (and X, Y)
5282   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5283     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5284 
5285   // If we can fold this based on the true/false value, do so.
5286   if (SimplifySelectOps(N, N1, N2))
5287     return SDValue(N, 0);  // Don't revisit N.
5288 
5289   if (VT0 == MVT::i1) {
5290     // The code in this block deals with the following 2 equivalences:
5291     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5292     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5293     // The target can specify its prefered form with the
5294     // shouldNormalizeToSelectSequence() callback. However we always transform
5295     // to the right anyway if we find the inner select exists in the DAG anyway
5296     // and we always transform to the left side if we know that we can further
5297     // optimize the combination of the conditions.
5298     bool normalizeToSequence
5299       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5300     // select (and Cond0, Cond1), X, Y
5301     //   -> select Cond0, (select Cond1, X, Y), Y
5302     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5303       SDValue Cond0 = N0->getOperand(0);
5304       SDValue Cond1 = N0->getOperand(1);
5305       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5306                                         N1.getValueType(), Cond1, N1, N2);
5307       if (normalizeToSequence || !InnerSelect.use_empty())
5308         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5309                            InnerSelect, N2);
5310     }
5311     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5312     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5313       SDValue Cond0 = N0->getOperand(0);
5314       SDValue Cond1 = N0->getOperand(1);
5315       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5316                                         N1.getValueType(), Cond1, N1, N2);
5317       if (normalizeToSequence || !InnerSelect.use_empty())
5318         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5319                            InnerSelect);
5320     }
5321 
5322     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5323     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5324       SDValue N1_0 = N1->getOperand(0);
5325       SDValue N1_1 = N1->getOperand(1);
5326       SDValue N1_2 = N1->getOperand(2);
5327       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5328         // Create the actual and node if we can generate good code for it.
5329         if (!normalizeToSequence) {
5330           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5331                                     N0, N1_0);
5332           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5333                              N1_1, N2);
5334         }
5335         // Otherwise see if we can optimize the "and" to a better pattern.
5336         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5337           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5338                              N1_1, N2);
5339       }
5340     }
5341     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5342     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5343       SDValue N2_0 = N2->getOperand(0);
5344       SDValue N2_1 = N2->getOperand(1);
5345       SDValue N2_2 = N2->getOperand(2);
5346       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5347         // Create the actual or node if we can generate good code for it.
5348         if (!normalizeToSequence) {
5349           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5350                                    N0, N2_0);
5351           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5352                              N1, N2_2);
5353         }
5354         // Otherwise see if we can optimize to a better pattern.
5355         if (SDValue Combined = visitORLike(N0, N2_0, N))
5356           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5357                              N1, N2_2);
5358       }
5359     }
5360   }
5361 
5362   // select (xor Cond, 1), X, Y -> select Cond, Y, X
5363   // select (xor Cond, 0), X, Y -> selext Cond, X, Y
5364   if (VT0 == MVT::i1) {
5365     if (N0->getOpcode() == ISD::XOR) {
5366       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
5367         SDValue Cond0 = N0->getOperand(0);
5368         if (C->isOne())
5369           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5370                              Cond0, N2, N1);
5371         else
5372           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5373                              Cond0, N1, N2);
5374       }
5375     }
5376   }
5377 
5378   // fold selects based on a setcc into other things, such as min/max/abs
5379   if (N0.getOpcode() == ISD::SETCC) {
5380     // select x, y (fcmp lt x, y) -> fminnum x, y
5381     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5382     //
5383     // This is OK if we don't care about what happens if either operand is a
5384     // NaN.
5385     //
5386 
5387     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5388     // no signed zeros as well as no nans.
5389     const TargetOptions &Options = DAG.getTarget().Options;
5390     if (Options.UnsafeFPMath &&
5391         VT.isFloatingPoint() && N0.hasOneUse() &&
5392         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5393       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5394 
5395       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5396                                                 N0.getOperand(1), N1, N2, CC,
5397                                                 TLI, DAG))
5398         return FMinMax;
5399     }
5400 
5401     if ((!LegalOperations &&
5402          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5403         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5404       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5405                          N0.getOperand(0), N0.getOperand(1),
5406                          N1, N2, N0.getOperand(2));
5407     return SimplifySelect(SDLoc(N), N0, N1, N2);
5408   }
5409 
5410   return SDValue();
5411 }
5412 
5413 static
5414 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5415   SDLoc DL(N);
5416   EVT LoVT, HiVT;
5417   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5418 
5419   // Split the inputs.
5420   SDValue Lo, Hi, LL, LH, RL, RH;
5421   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5422   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5423 
5424   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5425   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5426 
5427   return std::make_pair(Lo, Hi);
5428 }
5429 
5430 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5431 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5432 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5433   SDLoc DL(N);
5434   SDValue Cond = N->getOperand(0);
5435   SDValue LHS = N->getOperand(1);
5436   SDValue RHS = N->getOperand(2);
5437   EVT VT = N->getValueType(0);
5438   int NumElems = VT.getVectorNumElements();
5439   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5440          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5441          Cond.getOpcode() == ISD::BUILD_VECTOR);
5442 
5443   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5444   // binary ones here.
5445   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5446     return SDValue();
5447 
5448   // We're sure we have an even number of elements due to the
5449   // concat_vectors we have as arguments to vselect.
5450   // Skip BV elements until we find one that's not an UNDEF
5451   // After we find an UNDEF element, keep looping until we get to half the
5452   // length of the BV and see if all the non-undef nodes are the same.
5453   ConstantSDNode *BottomHalf = nullptr;
5454   for (int i = 0; i < NumElems / 2; ++i) {
5455     if (Cond->getOperand(i)->isUndef())
5456       continue;
5457 
5458     if (BottomHalf == nullptr)
5459       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5460     else if (Cond->getOperand(i).getNode() != BottomHalf)
5461       return SDValue();
5462   }
5463 
5464   // Do the same for the second half of the BuildVector
5465   ConstantSDNode *TopHalf = nullptr;
5466   for (int i = NumElems / 2; i < NumElems; ++i) {
5467     if (Cond->getOperand(i)->isUndef())
5468       continue;
5469 
5470     if (TopHalf == nullptr)
5471       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5472     else if (Cond->getOperand(i).getNode() != TopHalf)
5473       return SDValue();
5474   }
5475 
5476   assert(TopHalf && BottomHalf &&
5477          "One half of the selector was all UNDEFs and the other was all the "
5478          "same value. This should have been addressed before this function.");
5479   return DAG.getNode(
5480       ISD::CONCAT_VECTORS, DL, VT,
5481       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5482       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5483 }
5484 
5485 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5486 
5487   if (Level >= AfterLegalizeTypes)
5488     return SDValue();
5489 
5490   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5491   SDValue Mask = MSC->getMask();
5492   SDValue Data  = MSC->getValue();
5493   SDLoc DL(N);
5494 
5495   // If the MSCATTER data type requires splitting and the mask is provided by a
5496   // SETCC, then split both nodes and its operands before legalization. This
5497   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5498   // and enables future optimizations (e.g. min/max pattern matching on X86).
5499   if (Mask.getOpcode() != ISD::SETCC)
5500     return SDValue();
5501 
5502   // Check if any splitting is required.
5503   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5504       TargetLowering::TypeSplitVector)
5505     return SDValue();
5506   SDValue MaskLo, MaskHi, Lo, Hi;
5507   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5508 
5509   EVT LoVT, HiVT;
5510   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5511 
5512   SDValue Chain = MSC->getChain();
5513 
5514   EVT MemoryVT = MSC->getMemoryVT();
5515   unsigned Alignment = MSC->getOriginalAlignment();
5516 
5517   EVT LoMemVT, HiMemVT;
5518   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5519 
5520   SDValue DataLo, DataHi;
5521   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5522 
5523   SDValue BasePtr = MSC->getBasePtr();
5524   SDValue IndexLo, IndexHi;
5525   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5526 
5527   MachineMemOperand *MMO = DAG.getMachineFunction().
5528     getMachineMemOperand(MSC->getPointerInfo(),
5529                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5530                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5531 
5532   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5533   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5534                             DL, OpsLo, MMO);
5535 
5536   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5537   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5538                             DL, OpsHi, MMO);
5539 
5540   AddToWorklist(Lo.getNode());
5541   AddToWorklist(Hi.getNode());
5542 
5543   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5544 }
5545 
5546 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5547 
5548   if (Level >= AfterLegalizeTypes)
5549     return SDValue();
5550 
5551   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5552   SDValue Mask = MST->getMask();
5553   SDValue Data  = MST->getValue();
5554   SDLoc DL(N);
5555 
5556   // If the MSTORE data type requires splitting and the mask is provided by a
5557   // SETCC, then split both nodes and its operands before legalization. This
5558   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5559   // and enables future optimizations (e.g. min/max pattern matching on X86).
5560   if (Mask.getOpcode() == ISD::SETCC) {
5561 
5562     // Check if any splitting is required.
5563     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5564         TargetLowering::TypeSplitVector)
5565       return SDValue();
5566 
5567     SDValue MaskLo, MaskHi, Lo, Hi;
5568     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5569 
5570     EVT LoVT, HiVT;
5571     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5572 
5573     SDValue Chain = MST->getChain();
5574     SDValue Ptr   = MST->getBasePtr();
5575 
5576     EVT MemoryVT = MST->getMemoryVT();
5577     unsigned Alignment = MST->getOriginalAlignment();
5578 
5579     // if Alignment is equal to the vector size,
5580     // take the half of it for the second part
5581     unsigned SecondHalfAlignment =
5582       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5583          Alignment/2 : Alignment;
5584 
5585     EVT LoMemVT, HiMemVT;
5586     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5587 
5588     SDValue DataLo, DataHi;
5589     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5590 
5591     MachineMemOperand *MMO = DAG.getMachineFunction().
5592       getMachineMemOperand(MST->getPointerInfo(),
5593                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5594                            Alignment, MST->getAAInfo(), MST->getRanges());
5595 
5596     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5597                             MST->isTruncatingStore());
5598 
5599     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5600     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5601                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5602 
5603     MMO = DAG.getMachineFunction().
5604       getMachineMemOperand(MST->getPointerInfo(),
5605                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5606                            SecondHalfAlignment, MST->getAAInfo(),
5607                            MST->getRanges());
5608 
5609     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5610                             MST->isTruncatingStore());
5611 
5612     AddToWorklist(Lo.getNode());
5613     AddToWorklist(Hi.getNode());
5614 
5615     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5616   }
5617   return SDValue();
5618 }
5619 
5620 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5621 
5622   if (Level >= AfterLegalizeTypes)
5623     return SDValue();
5624 
5625   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5626   SDValue Mask = MGT->getMask();
5627   SDLoc DL(N);
5628 
5629   // If the MGATHER result requires splitting and the mask is provided by a
5630   // SETCC, then split both nodes and its operands before legalization. This
5631   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5632   // and enables future optimizations (e.g. min/max pattern matching on X86).
5633 
5634   if (Mask.getOpcode() != ISD::SETCC)
5635     return SDValue();
5636 
5637   EVT VT = N->getValueType(0);
5638 
5639   // Check if any splitting is required.
5640   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5641       TargetLowering::TypeSplitVector)
5642     return SDValue();
5643 
5644   SDValue MaskLo, MaskHi, Lo, Hi;
5645   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5646 
5647   SDValue Src0 = MGT->getValue();
5648   SDValue Src0Lo, Src0Hi;
5649   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5650 
5651   EVT LoVT, HiVT;
5652   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5653 
5654   SDValue Chain = MGT->getChain();
5655   EVT MemoryVT = MGT->getMemoryVT();
5656   unsigned Alignment = MGT->getOriginalAlignment();
5657 
5658   EVT LoMemVT, HiMemVT;
5659   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5660 
5661   SDValue BasePtr = MGT->getBasePtr();
5662   SDValue Index = MGT->getIndex();
5663   SDValue IndexLo, IndexHi;
5664   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5665 
5666   MachineMemOperand *MMO = DAG.getMachineFunction().
5667     getMachineMemOperand(MGT->getPointerInfo(),
5668                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5669                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5670 
5671   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5672   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5673                             MMO);
5674 
5675   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5676   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5677                             MMO);
5678 
5679   AddToWorklist(Lo.getNode());
5680   AddToWorklist(Hi.getNode());
5681 
5682   // Build a factor node to remember that this load is independent of the
5683   // other one.
5684   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5685                       Hi.getValue(1));
5686 
5687   // Legalized the chain result - switch anything that used the old chain to
5688   // use the new one.
5689   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5690 
5691   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5692 
5693   SDValue RetOps[] = { GatherRes, Chain };
5694   return DAG.getMergeValues(RetOps, DL);
5695 }
5696 
5697 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5698 
5699   if (Level >= AfterLegalizeTypes)
5700     return SDValue();
5701 
5702   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5703   SDValue Mask = MLD->getMask();
5704   SDLoc DL(N);
5705 
5706   // If the MLOAD result requires splitting and the mask is provided by a
5707   // SETCC, then split both nodes and its operands before legalization. This
5708   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5709   // and enables future optimizations (e.g. min/max pattern matching on X86).
5710 
5711   if (Mask.getOpcode() == ISD::SETCC) {
5712     EVT VT = N->getValueType(0);
5713 
5714     // Check if any splitting is required.
5715     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5716         TargetLowering::TypeSplitVector)
5717       return SDValue();
5718 
5719     SDValue MaskLo, MaskHi, Lo, Hi;
5720     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5721 
5722     SDValue Src0 = MLD->getSrc0();
5723     SDValue Src0Lo, Src0Hi;
5724     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5725 
5726     EVT LoVT, HiVT;
5727     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5728 
5729     SDValue Chain = MLD->getChain();
5730     SDValue Ptr   = MLD->getBasePtr();
5731     EVT MemoryVT = MLD->getMemoryVT();
5732     unsigned Alignment = MLD->getOriginalAlignment();
5733 
5734     // if Alignment is equal to the vector size,
5735     // take the half of it for the second part
5736     unsigned SecondHalfAlignment =
5737       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5738          Alignment/2 : Alignment;
5739 
5740     EVT LoMemVT, HiMemVT;
5741     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5742 
5743     MachineMemOperand *MMO = DAG.getMachineFunction().
5744     getMachineMemOperand(MLD->getPointerInfo(),
5745                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5746                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5747 
5748     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5749                            ISD::NON_EXTLOAD);
5750 
5751     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5752     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5753                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5754 
5755     MMO = DAG.getMachineFunction().
5756     getMachineMemOperand(MLD->getPointerInfo(),
5757                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5758                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5759 
5760     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5761                            ISD::NON_EXTLOAD);
5762 
5763     AddToWorklist(Lo.getNode());
5764     AddToWorklist(Hi.getNode());
5765 
5766     // Build a factor node to remember that this load is independent of the
5767     // other one.
5768     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5769                         Hi.getValue(1));
5770 
5771     // Legalized the chain result - switch anything that used the old chain to
5772     // use the new one.
5773     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5774 
5775     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5776 
5777     SDValue RetOps[] = { LoadRes, Chain };
5778     return DAG.getMergeValues(RetOps, DL);
5779   }
5780   return SDValue();
5781 }
5782 
5783 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5784   SDValue N0 = N->getOperand(0);
5785   SDValue N1 = N->getOperand(1);
5786   SDValue N2 = N->getOperand(2);
5787   SDLoc DL(N);
5788 
5789   // Canonicalize integer abs.
5790   // vselect (setg[te] X,  0),  X, -X ->
5791   // vselect (setgt    X, -1),  X, -X ->
5792   // vselect (setl[te] X,  0), -X,  X ->
5793   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5794   if (N0.getOpcode() == ISD::SETCC) {
5795     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5796     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5797     bool isAbs = false;
5798     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5799 
5800     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5801          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5802         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5803       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5804     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5805              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5806       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5807 
5808     if (isAbs) {
5809       EVT VT = LHS.getValueType();
5810       SDValue Shift = DAG.getNode(
5811           ISD::SRA, DL, VT, LHS,
5812           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
5813       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5814       AddToWorklist(Shift.getNode());
5815       AddToWorklist(Add.getNode());
5816       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5817     }
5818   }
5819 
5820   if (SimplifySelectOps(N, N1, N2))
5821     return SDValue(N, 0);  // Don't revisit N.
5822 
5823   // If the VSELECT result requires splitting and the mask is provided by a
5824   // SETCC, then split both nodes and its operands before legalization. This
5825   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5826   // and enables future optimizations (e.g. min/max pattern matching on X86).
5827   if (N0.getOpcode() == ISD::SETCC) {
5828     EVT VT = N->getValueType(0);
5829 
5830     // Check if any splitting is required.
5831     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5832         TargetLowering::TypeSplitVector)
5833       return SDValue();
5834 
5835     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5836     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5837     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5838     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5839 
5840     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5841     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5842 
5843     // Add the new VSELECT nodes to the work list in case they need to be split
5844     // again.
5845     AddToWorklist(Lo.getNode());
5846     AddToWorklist(Hi.getNode());
5847 
5848     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5849   }
5850 
5851   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5852   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5853     return N1;
5854   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5855   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5856     return N2;
5857 
5858   // The ConvertSelectToConcatVector function is assuming both the above
5859   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5860   // and addressed.
5861   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5862       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5863       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5864     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5865       return CV;
5866   }
5867 
5868   return SDValue();
5869 }
5870 
5871 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5872   SDValue N0 = N->getOperand(0);
5873   SDValue N1 = N->getOperand(1);
5874   SDValue N2 = N->getOperand(2);
5875   SDValue N3 = N->getOperand(3);
5876   SDValue N4 = N->getOperand(4);
5877   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5878 
5879   // fold select_cc lhs, rhs, x, x, cc -> x
5880   if (N2 == N3)
5881     return N2;
5882 
5883   // Determine if the condition we're dealing with is constant
5884   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5885                                   CC, SDLoc(N), false)) {
5886     AddToWorklist(SCC.getNode());
5887 
5888     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5889       if (!SCCC->isNullValue())
5890         return N2;    // cond always true -> true val
5891       else
5892         return N3;    // cond always false -> false val
5893     } else if (SCC->isUndef()) {
5894       // When the condition is UNDEF, just return the first operand. This is
5895       // coherent the DAG creation, no setcc node is created in this case
5896       return N2;
5897     } else if (SCC.getOpcode() == ISD::SETCC) {
5898       // Fold to a simpler select_cc
5899       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5900                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5901                          SCC.getOperand(2));
5902     }
5903   }
5904 
5905   // If we can fold this based on the true/false value, do so.
5906   if (SimplifySelectOps(N, N2, N3))
5907     return SDValue(N, 0);  // Don't revisit N.
5908 
5909   // fold select_cc into other things, such as min/max/abs
5910   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5911 }
5912 
5913 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5914   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5915                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5916                        SDLoc(N));
5917 }
5918 
5919 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5920   SDValue LHS = N->getOperand(0);
5921   SDValue RHS = N->getOperand(1);
5922   SDValue Carry = N->getOperand(2);
5923   SDValue Cond = N->getOperand(3);
5924 
5925   // If Carry is false, fold to a regular SETCC.
5926   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5927     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5928 
5929   return SDValue();
5930 }
5931 
5932 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5933 /// a build_vector of constants.
5934 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5935 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5936 /// Vector extends are not folded if operations are legal; this is to
5937 /// avoid introducing illegal build_vector dag nodes.
5938 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5939                                          SelectionDAG &DAG, bool LegalTypes,
5940                                          bool LegalOperations) {
5941   unsigned Opcode = N->getOpcode();
5942   SDValue N0 = N->getOperand(0);
5943   EVT VT = N->getValueType(0);
5944 
5945   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5946          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5947          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5948          && "Expected EXTEND dag node in input!");
5949 
5950   // fold (sext c1) -> c1
5951   // fold (zext c1) -> c1
5952   // fold (aext c1) -> c1
5953   if (isa<ConstantSDNode>(N0))
5954     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5955 
5956   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5957   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5958   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5959   EVT SVT = VT.getScalarType();
5960   if (!(VT.isVector() &&
5961       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5962       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5963     return nullptr;
5964 
5965   // We can fold this node into a build_vector.
5966   unsigned VTBits = SVT.getSizeInBits();
5967   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
5968   SmallVector<SDValue, 8> Elts;
5969   unsigned NumElts = VT.getVectorNumElements();
5970   SDLoc DL(N);
5971 
5972   for (unsigned i=0; i != NumElts; ++i) {
5973     SDValue Op = N0->getOperand(i);
5974     if (Op->isUndef()) {
5975       Elts.push_back(DAG.getUNDEF(SVT));
5976       continue;
5977     }
5978 
5979     SDLoc DL(Op);
5980     // Get the constant value and if needed trunc it to the size of the type.
5981     // Nodes like build_vector might have constants wider than the scalar type.
5982     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5983     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5984       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5985     else
5986       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5987   }
5988 
5989   return DAG.getBuildVector(VT, DL, Elts).getNode();
5990 }
5991 
5992 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5993 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5994 // transformation. Returns true if extension are possible and the above
5995 // mentioned transformation is profitable.
5996 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5997                                     unsigned ExtOpc,
5998                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5999                                     const TargetLowering &TLI) {
6000   bool HasCopyToRegUses = false;
6001   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6002   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6003                             UE = N0.getNode()->use_end();
6004        UI != UE; ++UI) {
6005     SDNode *User = *UI;
6006     if (User == N)
6007       continue;
6008     if (UI.getUse().getResNo() != N0.getResNo())
6009       continue;
6010     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6011     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6012       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6013       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6014         // Sign bits will be lost after a zext.
6015         return false;
6016       bool Add = false;
6017       for (unsigned i = 0; i != 2; ++i) {
6018         SDValue UseOp = User->getOperand(i);
6019         if (UseOp == N0)
6020           continue;
6021         if (!isa<ConstantSDNode>(UseOp))
6022           return false;
6023         Add = true;
6024       }
6025       if (Add)
6026         ExtendNodes.push_back(User);
6027       continue;
6028     }
6029     // If truncates aren't free and there are users we can't
6030     // extend, it isn't worthwhile.
6031     if (!isTruncFree)
6032       return false;
6033     // Remember if this value is live-out.
6034     if (User->getOpcode() == ISD::CopyToReg)
6035       HasCopyToRegUses = true;
6036   }
6037 
6038   if (HasCopyToRegUses) {
6039     bool BothLiveOut = false;
6040     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6041          UI != UE; ++UI) {
6042       SDUse &Use = UI.getUse();
6043       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6044         BothLiveOut = true;
6045         break;
6046       }
6047     }
6048     if (BothLiveOut)
6049       // Both unextended and extended values are live out. There had better be
6050       // a good reason for the transformation.
6051       return ExtendNodes.size();
6052   }
6053   return true;
6054 }
6055 
6056 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6057                                   SDValue Trunc, SDValue ExtLoad,
6058                                   const SDLoc &DL, ISD::NodeType ExtType) {
6059   // Extend SetCC uses if necessary.
6060   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6061     SDNode *SetCC = SetCCs[i];
6062     SmallVector<SDValue, 4> Ops;
6063 
6064     for (unsigned j = 0; j != 2; ++j) {
6065       SDValue SOp = SetCC->getOperand(j);
6066       if (SOp == Trunc)
6067         Ops.push_back(ExtLoad);
6068       else
6069         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6070     }
6071 
6072     Ops.push_back(SetCC->getOperand(2));
6073     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6074   }
6075 }
6076 
6077 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6078 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6079   SDValue N0 = N->getOperand(0);
6080   EVT DstVT = N->getValueType(0);
6081   EVT SrcVT = N0.getValueType();
6082 
6083   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6084           N->getOpcode() == ISD::ZERO_EXTEND) &&
6085          "Unexpected node type (not an extend)!");
6086 
6087   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6088   // For example, on a target with legal v4i32, but illegal v8i32, turn:
6089   //   (v8i32 (sext (v8i16 (load x))))
6090   // into:
6091   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
6092   //                          (v4i32 (sextload (x + 16)))))
6093   // Where uses of the original load, i.e.:
6094   //   (v8i16 (load x))
6095   // are replaced with:
6096   //   (v8i16 (truncate
6097   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6098   //                            (v4i32 (sextload (x + 16)))))))
6099   //
6100   // This combine is only applicable to illegal, but splittable, vectors.
6101   // All legal types, and illegal non-vector types, are handled elsewhere.
6102   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6103   //
6104   if (N0->getOpcode() != ISD::LOAD)
6105     return SDValue();
6106 
6107   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6108 
6109   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6110       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6111       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6112     return SDValue();
6113 
6114   SmallVector<SDNode *, 4> SetCCs;
6115   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6116     return SDValue();
6117 
6118   ISD::LoadExtType ExtType =
6119       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6120 
6121   // Try to split the vector types to get down to legal types.
6122   EVT SplitSrcVT = SrcVT;
6123   EVT SplitDstVT = DstVT;
6124   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6125          SplitSrcVT.getVectorNumElements() > 1) {
6126     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6127     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6128   }
6129 
6130   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6131     return SDValue();
6132 
6133   SDLoc DL(N);
6134   const unsigned NumSplits =
6135       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6136   const unsigned Stride = SplitSrcVT.getStoreSize();
6137   SmallVector<SDValue, 4> Loads;
6138   SmallVector<SDValue, 4> Chains;
6139 
6140   SDValue BasePtr = LN0->getBasePtr();
6141   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6142     const unsigned Offset = Idx * Stride;
6143     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6144 
6145     SDValue SplitLoad = DAG.getExtLoad(
6146         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6147         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6148         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6149 
6150     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6151                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6152 
6153     Loads.push_back(SplitLoad.getValue(0));
6154     Chains.push_back(SplitLoad.getValue(1));
6155   }
6156 
6157   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6158   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6159 
6160   CombineTo(N, NewValue);
6161 
6162   // Replace uses of the original load (before extension)
6163   // with a truncate of the concatenated sextloaded vectors.
6164   SDValue Trunc =
6165       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6166   CombineTo(N0.getNode(), Trunc, NewChain);
6167   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6168                   (ISD::NodeType)N->getOpcode());
6169   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6170 }
6171 
6172 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6173   SDValue N0 = N->getOperand(0);
6174   EVT VT = N->getValueType(0);
6175 
6176   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6177                                               LegalOperations))
6178     return SDValue(Res, 0);
6179 
6180   // fold (sext (sext x)) -> (sext x)
6181   // fold (sext (aext x)) -> (sext x)
6182   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6183     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6184                        N0.getOperand(0));
6185 
6186   if (N0.getOpcode() == ISD::TRUNCATE) {
6187     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6188     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6189     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6190       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6191       if (NarrowLoad.getNode() != N0.getNode()) {
6192         CombineTo(N0.getNode(), NarrowLoad);
6193         // CombineTo deleted the truncate, if needed, but not what's under it.
6194         AddToWorklist(oye);
6195       }
6196       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6197     }
6198 
6199     // See if the value being truncated is already sign extended.  If so, just
6200     // eliminate the trunc/sext pair.
6201     SDValue Op = N0.getOperand(0);
6202     unsigned OpBits   = Op.getScalarValueSizeInBits();
6203     unsigned MidBits  = N0.getScalarValueSizeInBits();
6204     unsigned DestBits = VT.getScalarSizeInBits();
6205     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6206 
6207     if (OpBits == DestBits) {
6208       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6209       // bits, it is already ready.
6210       if (NumSignBits > DestBits-MidBits)
6211         return Op;
6212     } else if (OpBits < DestBits) {
6213       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6214       // bits, just sext from i32.
6215       if (NumSignBits > OpBits-MidBits)
6216         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6217     } else {
6218       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6219       // bits, just truncate to i32.
6220       if (NumSignBits > OpBits-MidBits)
6221         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6222     }
6223 
6224     // fold (sext (truncate x)) -> (sextinreg x).
6225     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6226                                                  N0.getValueType())) {
6227       if (OpBits < DestBits)
6228         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6229       else if (OpBits > DestBits)
6230         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6231       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6232                          DAG.getValueType(N0.getValueType()));
6233     }
6234   }
6235 
6236   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6237   // Only generate vector extloads when 1) they're legal, and 2) they are
6238   // deemed desirable by the target.
6239   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6240       ((!LegalOperations && !VT.isVector() &&
6241         !cast<LoadSDNode>(N0)->isVolatile()) ||
6242        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6243     bool DoXform = true;
6244     SmallVector<SDNode*, 4> SetCCs;
6245     if (!N0.hasOneUse())
6246       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6247     if (VT.isVector())
6248       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6249     if (DoXform) {
6250       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6251       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6252                                        LN0->getChain(),
6253                                        LN0->getBasePtr(), N0.getValueType(),
6254                                        LN0->getMemOperand());
6255       CombineTo(N, ExtLoad);
6256       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6257                                   N0.getValueType(), ExtLoad);
6258       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6259       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6260                       ISD::SIGN_EXTEND);
6261       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6262     }
6263   }
6264 
6265   // fold (sext (load x)) to multiple smaller sextloads.
6266   // Only on illegal but splittable vectors.
6267   if (SDValue ExtLoad = CombineExtLoad(N))
6268     return ExtLoad;
6269 
6270   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6271   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6272   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6273       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6274     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6275     EVT MemVT = LN0->getMemoryVT();
6276     if ((!LegalOperations && !LN0->isVolatile()) ||
6277         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6278       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6279                                        LN0->getChain(),
6280                                        LN0->getBasePtr(), MemVT,
6281                                        LN0->getMemOperand());
6282       CombineTo(N, ExtLoad);
6283       CombineTo(N0.getNode(),
6284                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6285                             N0.getValueType(), ExtLoad),
6286                 ExtLoad.getValue(1));
6287       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6288     }
6289   }
6290 
6291   // fold (sext (and/or/xor (load x), cst)) ->
6292   //      (and/or/xor (sextload x), (sext cst))
6293   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6294        N0.getOpcode() == ISD::XOR) &&
6295       isa<LoadSDNode>(N0.getOperand(0)) &&
6296       N0.getOperand(1).getOpcode() == ISD::Constant &&
6297       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6298       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6299     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6300     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6301       bool DoXform = true;
6302       SmallVector<SDNode*, 4> SetCCs;
6303       if (!N0.hasOneUse())
6304         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6305                                           SetCCs, TLI);
6306       if (DoXform) {
6307         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6308                                          LN0->getChain(), LN0->getBasePtr(),
6309                                          LN0->getMemoryVT(),
6310                                          LN0->getMemOperand());
6311         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6312         Mask = Mask.sext(VT.getSizeInBits());
6313         SDLoc DL(N);
6314         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6315                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6316         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6317                                     SDLoc(N0.getOperand(0)),
6318                                     N0.getOperand(0).getValueType(), ExtLoad);
6319         CombineTo(N, And);
6320         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6321         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6322                         ISD::SIGN_EXTEND);
6323         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6324       }
6325     }
6326   }
6327 
6328   if (N0.getOpcode() == ISD::SETCC) {
6329     EVT N0VT = N0.getOperand(0).getValueType();
6330     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6331     // Only do this before legalize for now.
6332     if (VT.isVector() && !LegalOperations &&
6333         TLI.getBooleanContents(N0VT) ==
6334             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6335       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6336       // of the same size as the compared operands. Only optimize sext(setcc())
6337       // if this is the case.
6338       EVT SVT = getSetCCResultType(N0VT);
6339 
6340       // We know that the # elements of the results is the same as the
6341       // # elements of the compare (and the # elements of the compare result
6342       // for that matter).  Check to see that they are the same size.  If so,
6343       // we know that the element size of the sext'd result matches the
6344       // element size of the compare operands.
6345       if (VT.getSizeInBits() == SVT.getSizeInBits())
6346         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6347                              N0.getOperand(1),
6348                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6349 
6350       // If the desired elements are smaller or larger than the source
6351       // elements we can use a matching integer vector type and then
6352       // truncate/sign extend
6353       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6354       if (SVT == MatchingVectorType) {
6355         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6356                                N0.getOperand(0), N0.getOperand(1),
6357                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6358         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6359       }
6360     }
6361 
6362     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
6363     // Here, T can be 1 or -1, depending on the type of the setcc and
6364     // getBooleanContents().
6365     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
6366 
6367     SDLoc DL(N);
6368     // To determine the "true" side of the select, we need to know the high bit
6369     // of the value returned by the setcc if it evaluates to true.
6370     // If the type of the setcc is i1, then the true case of the select is just
6371     // sext(i1 1), that is, -1.
6372     // If the type of the setcc is larger (say, i8) then the value of the high
6373     // bit depends on getBooleanContents(). So, ask TLI for a real "true" value
6374     // of the appropriate width.
6375     SDValue ExtTrueVal =
6376         (SetCCWidth == 1)
6377             ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()),
6378                               DL, VT)
6379             : TLI.getConstTrueVal(DAG, VT, DL);
6380 
6381     if (SDValue SCC = SimplifySelectCC(
6382             DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal,
6383             DAG.getConstant(0, DL, VT),
6384             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6385       return SCC;
6386 
6387     if (!VT.isVector()) {
6388       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6389       if (!LegalOperations ||
6390           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6391         SDLoc DL(N);
6392         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6393         SDValue SetCC =
6394             DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC);
6395         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal,
6396                              DAG.getConstant(0, DL, VT));
6397       }
6398     }
6399   }
6400 
6401   // fold (sext x) -> (zext x) if the sign bit is known zero.
6402   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6403       DAG.SignBitIsZero(N0))
6404     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6405 
6406   return SDValue();
6407 }
6408 
6409 // isTruncateOf - If N is a truncate of some other value, return true, record
6410 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6411 // This function computes KnownZero to avoid a duplicated call to
6412 // computeKnownBits in the caller.
6413 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6414                          APInt &KnownZero) {
6415   APInt KnownOne;
6416   if (N->getOpcode() == ISD::TRUNCATE) {
6417     Op = N->getOperand(0);
6418     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6419     return true;
6420   }
6421 
6422   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6423       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6424     return false;
6425 
6426   SDValue Op0 = N->getOperand(0);
6427   SDValue Op1 = N->getOperand(1);
6428   assert(Op0.getValueType() == Op1.getValueType());
6429 
6430   if (isNullConstant(Op0))
6431     Op = Op1;
6432   else if (isNullConstant(Op1))
6433     Op = Op0;
6434   else
6435     return false;
6436 
6437   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6438 
6439   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6440     return false;
6441 
6442   return true;
6443 }
6444 
6445 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6446   SDValue N0 = N->getOperand(0);
6447   EVT VT = N->getValueType(0);
6448 
6449   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6450                                               LegalOperations))
6451     return SDValue(Res, 0);
6452 
6453   // fold (zext (zext x)) -> (zext x)
6454   // fold (zext (aext x)) -> (zext x)
6455   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6456     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6457                        N0.getOperand(0));
6458 
6459   // fold (zext (truncate x)) -> (zext x) or
6460   //      (zext (truncate x)) -> (truncate x)
6461   // This is valid when the truncated bits of x are already zero.
6462   // FIXME: We should extend this to work for vectors too.
6463   SDValue Op;
6464   APInt KnownZero;
6465   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6466     APInt TruncatedBits =
6467       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6468       APInt(Op.getValueSizeInBits(), 0) :
6469       APInt::getBitsSet(Op.getValueSizeInBits(),
6470                         N0.getValueSizeInBits(),
6471                         std::min(Op.getValueSizeInBits(),
6472                                  VT.getSizeInBits()));
6473     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6474       if (VT.bitsGT(Op.getValueType()))
6475         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6476       if (VT.bitsLT(Op.getValueType()))
6477         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6478 
6479       return Op;
6480     }
6481   }
6482 
6483   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6484   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6485   if (N0.getOpcode() == ISD::TRUNCATE) {
6486     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6487       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6488       if (NarrowLoad.getNode() != N0.getNode()) {
6489         CombineTo(N0.getNode(), NarrowLoad);
6490         // CombineTo deleted the truncate, if needed, but not what's under it.
6491         AddToWorklist(oye);
6492       }
6493       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6494     }
6495   }
6496 
6497   // fold (zext (truncate x)) -> (and x, mask)
6498   if (N0.getOpcode() == ISD::TRUNCATE) {
6499     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6500     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6501     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6502       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6503       if (NarrowLoad.getNode() != N0.getNode()) {
6504         CombineTo(N0.getNode(), NarrowLoad);
6505         // CombineTo deleted the truncate, if needed, but not what's under it.
6506         AddToWorklist(oye);
6507       }
6508       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6509     }
6510 
6511     EVT SrcVT = N0.getOperand(0).getValueType();
6512     EVT MinVT = N0.getValueType();
6513 
6514     // Try to mask before the extension to avoid having to generate a larger mask,
6515     // possibly over several sub-vectors.
6516     if (SrcVT.bitsLT(VT)) {
6517       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6518                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6519         SDValue Op = N0.getOperand(0);
6520         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6521         AddToWorklist(Op.getNode());
6522         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6523       }
6524     }
6525 
6526     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6527       SDValue Op = N0.getOperand(0);
6528       if (SrcVT.bitsLT(VT)) {
6529         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6530         AddToWorklist(Op.getNode());
6531       } else if (SrcVT.bitsGT(VT)) {
6532         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6533         AddToWorklist(Op.getNode());
6534       }
6535       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6536     }
6537   }
6538 
6539   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6540   // if either of the casts is not free.
6541   if (N0.getOpcode() == ISD::AND &&
6542       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6543       N0.getOperand(1).getOpcode() == ISD::Constant &&
6544       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6545                            N0.getValueType()) ||
6546        !TLI.isZExtFree(N0.getValueType(), VT))) {
6547     SDValue X = N0.getOperand(0).getOperand(0);
6548     if (X.getValueType().bitsLT(VT)) {
6549       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6550     } else if (X.getValueType().bitsGT(VT)) {
6551       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6552     }
6553     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6554     Mask = Mask.zext(VT.getSizeInBits());
6555     SDLoc DL(N);
6556     return DAG.getNode(ISD::AND, DL, VT,
6557                        X, DAG.getConstant(Mask, DL, VT));
6558   }
6559 
6560   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6561   // Only generate vector extloads when 1) they're legal, and 2) they are
6562   // deemed desirable by the target.
6563   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6564       ((!LegalOperations && !VT.isVector() &&
6565         !cast<LoadSDNode>(N0)->isVolatile()) ||
6566        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6567     bool DoXform = true;
6568     SmallVector<SDNode*, 4> SetCCs;
6569     if (!N0.hasOneUse())
6570       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6571     if (VT.isVector())
6572       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6573     if (DoXform) {
6574       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6575       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6576                                        LN0->getChain(),
6577                                        LN0->getBasePtr(), N0.getValueType(),
6578                                        LN0->getMemOperand());
6579       CombineTo(N, ExtLoad);
6580       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6581                                   N0.getValueType(), ExtLoad);
6582       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6583 
6584       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6585                       ISD::ZERO_EXTEND);
6586       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6587     }
6588   }
6589 
6590   // fold (zext (load x)) to multiple smaller zextloads.
6591   // Only on illegal but splittable vectors.
6592   if (SDValue ExtLoad = CombineExtLoad(N))
6593     return ExtLoad;
6594 
6595   // fold (zext (and/or/xor (load x), cst)) ->
6596   //      (and/or/xor (zextload x), (zext cst))
6597   // Unless (and (load x) cst) will match as a zextload already and has
6598   // additional users.
6599   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6600        N0.getOpcode() == ISD::XOR) &&
6601       isa<LoadSDNode>(N0.getOperand(0)) &&
6602       N0.getOperand(1).getOpcode() == ISD::Constant &&
6603       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6604       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6605     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6606     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6607       bool DoXform = true;
6608       SmallVector<SDNode*, 4> SetCCs;
6609       if (!N0.hasOneUse()) {
6610         if (N0.getOpcode() == ISD::AND) {
6611           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6612           auto NarrowLoad = false;
6613           EVT LoadResultTy = AndC->getValueType(0);
6614           EVT ExtVT, LoadedVT;
6615           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6616                                NarrowLoad))
6617             DoXform = false;
6618         }
6619         if (DoXform)
6620           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6621                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6622       }
6623       if (DoXform) {
6624         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6625                                          LN0->getChain(), LN0->getBasePtr(),
6626                                          LN0->getMemoryVT(),
6627                                          LN0->getMemOperand());
6628         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6629         Mask = Mask.zext(VT.getSizeInBits());
6630         SDLoc DL(N);
6631         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6632                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6633         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6634                                     SDLoc(N0.getOperand(0)),
6635                                     N0.getOperand(0).getValueType(), ExtLoad);
6636         CombineTo(N, And);
6637         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6638         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6639                         ISD::ZERO_EXTEND);
6640         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6641       }
6642     }
6643   }
6644 
6645   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6646   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6647   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6648       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6649     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6650     EVT MemVT = LN0->getMemoryVT();
6651     if ((!LegalOperations && !LN0->isVolatile()) ||
6652         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6653       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6654                                        LN0->getChain(),
6655                                        LN0->getBasePtr(), MemVT,
6656                                        LN0->getMemOperand());
6657       CombineTo(N, ExtLoad);
6658       CombineTo(N0.getNode(),
6659                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6660                             ExtLoad),
6661                 ExtLoad.getValue(1));
6662       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6663     }
6664   }
6665 
6666   if (N0.getOpcode() == ISD::SETCC) {
6667     // Only do this before legalize for now.
6668     if (!LegalOperations && VT.isVector() &&
6669         N0.getValueType().getVectorElementType() == MVT::i1) {
6670       EVT N00VT = N0.getOperand(0).getValueType();
6671       if (getSetCCResultType(N00VT) == N0.getValueType())
6672         return SDValue();
6673 
6674       // We know that the # elements of the results is the same as the #
6675       // elements of the compare (and the # elements of the compare result for
6676       // that matter). Check to see that they are the same size. If so, we know
6677       // that the element size of the sext'd result matches the element size of
6678       // the compare operands.
6679       SDLoc DL(N);
6680       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6681       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
6682         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6683         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
6684                                      N0.getOperand(1), N0.getOperand(2));
6685         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
6686       }
6687 
6688       // If the desired elements are smaller or larger than the source
6689       // elements we can use a matching integer vector type and then
6690       // truncate/sign extend.
6691       EVT MatchingElementType = EVT::getIntegerVT(
6692           *DAG.getContext(), N00VT.getScalarSizeInBits());
6693       EVT MatchingVectorType = EVT::getVectorVT(
6694           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
6695       SDValue VsetCC =
6696           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
6697                       N0.getOperand(1), N0.getOperand(2));
6698       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
6699                          VecOnes);
6700     }
6701 
6702     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6703     SDLoc DL(N);
6704     if (SDValue SCC = SimplifySelectCC(
6705             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6706             DAG.getConstant(0, DL, VT),
6707             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6708       return SCC;
6709   }
6710 
6711   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6712   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6713       isa<ConstantSDNode>(N0.getOperand(1)) &&
6714       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6715       N0.hasOneUse()) {
6716     SDValue ShAmt = N0.getOperand(1);
6717     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6718     if (N0.getOpcode() == ISD::SHL) {
6719       SDValue InnerZExt = N0.getOperand(0);
6720       // If the original shl may be shifting out bits, do not perform this
6721       // transformation.
6722       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
6723         InnerZExt.getOperand(0).getValueSizeInBits();
6724       if (ShAmtVal > KnownZeroBits)
6725         return SDValue();
6726     }
6727 
6728     SDLoc DL(N);
6729 
6730     // Ensure that the shift amount is wide enough for the shifted value.
6731     if (VT.getSizeInBits() >= 256)
6732       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6733 
6734     return DAG.getNode(N0.getOpcode(), DL, VT,
6735                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6736                        ShAmt);
6737   }
6738 
6739   return SDValue();
6740 }
6741 
6742 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6743   SDValue N0 = N->getOperand(0);
6744   EVT VT = N->getValueType(0);
6745 
6746   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6747                                               LegalOperations))
6748     return SDValue(Res, 0);
6749 
6750   // fold (aext (aext x)) -> (aext x)
6751   // fold (aext (zext x)) -> (zext x)
6752   // fold (aext (sext x)) -> (sext x)
6753   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6754       N0.getOpcode() == ISD::ZERO_EXTEND ||
6755       N0.getOpcode() == ISD::SIGN_EXTEND)
6756     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6757 
6758   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6759   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6760   if (N0.getOpcode() == ISD::TRUNCATE) {
6761     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6762       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6763       if (NarrowLoad.getNode() != N0.getNode()) {
6764         CombineTo(N0.getNode(), NarrowLoad);
6765         // CombineTo deleted the truncate, if needed, but not what's under it.
6766         AddToWorklist(oye);
6767       }
6768       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6769     }
6770   }
6771 
6772   // fold (aext (truncate x))
6773   if (N0.getOpcode() == ISD::TRUNCATE) {
6774     SDValue TruncOp = N0.getOperand(0);
6775     if (TruncOp.getValueType() == VT)
6776       return TruncOp; // x iff x size == zext size.
6777     if (TruncOp.getValueType().bitsGT(VT))
6778       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6779     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6780   }
6781 
6782   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6783   // if the trunc is not free.
6784   if (N0.getOpcode() == ISD::AND &&
6785       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6786       N0.getOperand(1).getOpcode() == ISD::Constant &&
6787       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6788                           N0.getValueType())) {
6789     SDValue X = N0.getOperand(0).getOperand(0);
6790     if (X.getValueType().bitsLT(VT)) {
6791       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6792     } else if (X.getValueType().bitsGT(VT)) {
6793       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6794     }
6795     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6796     Mask = Mask.zext(VT.getSizeInBits());
6797     SDLoc DL(N);
6798     return DAG.getNode(ISD::AND, DL, VT,
6799                        X, DAG.getConstant(Mask, DL, VT));
6800   }
6801 
6802   // fold (aext (load x)) -> (aext (truncate (extload x)))
6803   // None of the supported targets knows how to perform load and any_ext
6804   // on vectors in one instruction.  We only perform this transformation on
6805   // scalars.
6806   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6807       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6808       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6809     bool DoXform = true;
6810     SmallVector<SDNode*, 4> SetCCs;
6811     if (!N0.hasOneUse())
6812       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6813     if (DoXform) {
6814       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6815       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6816                                        LN0->getChain(),
6817                                        LN0->getBasePtr(), N0.getValueType(),
6818                                        LN0->getMemOperand());
6819       CombineTo(N, ExtLoad);
6820       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6821                                   N0.getValueType(), ExtLoad);
6822       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6823       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6824                       ISD::ANY_EXTEND);
6825       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6826     }
6827   }
6828 
6829   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6830   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6831   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6832   if (N0.getOpcode() == ISD::LOAD &&
6833       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6834       N0.hasOneUse()) {
6835     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6836     ISD::LoadExtType ExtType = LN0->getExtensionType();
6837     EVT MemVT = LN0->getMemoryVT();
6838     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6839       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6840                                        VT, LN0->getChain(), LN0->getBasePtr(),
6841                                        MemVT, LN0->getMemOperand());
6842       CombineTo(N, ExtLoad);
6843       CombineTo(N0.getNode(),
6844                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6845                             N0.getValueType(), ExtLoad),
6846                 ExtLoad.getValue(1));
6847       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6848     }
6849   }
6850 
6851   if (N0.getOpcode() == ISD::SETCC) {
6852     // For vectors:
6853     // aext(setcc) -> vsetcc
6854     // aext(setcc) -> truncate(vsetcc)
6855     // aext(setcc) -> aext(vsetcc)
6856     // Only do this before legalize for now.
6857     if (VT.isVector() && !LegalOperations) {
6858       EVT N0VT = N0.getOperand(0).getValueType();
6859         // We know that the # elements of the results is the same as the
6860         // # elements of the compare (and the # elements of the compare result
6861         // for that matter).  Check to see that they are the same size.  If so,
6862         // we know that the element size of the sext'd result matches the
6863         // element size of the compare operands.
6864       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6865         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6866                              N0.getOperand(1),
6867                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6868       // If the desired elements are smaller or larger than the source
6869       // elements we can use a matching integer vector type and then
6870       // truncate/any extend
6871       else {
6872         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6873         SDValue VsetCC =
6874           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6875                         N0.getOperand(1),
6876                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6877         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6878       }
6879     }
6880 
6881     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6882     SDLoc DL(N);
6883     if (SDValue SCC = SimplifySelectCC(
6884             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6885             DAG.getConstant(0, DL, VT),
6886             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6887       return SCC;
6888   }
6889 
6890   return SDValue();
6891 }
6892 
6893 /// See if the specified operand can be simplified with the knowledge that only
6894 /// the bits specified by Mask are used.  If so, return the simpler operand,
6895 /// otherwise return a null SDValue.
6896 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6897   switch (V.getOpcode()) {
6898   default: break;
6899   case ISD::Constant: {
6900     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6901     assert(CV && "Const value should be ConstSDNode.");
6902     const APInt &CVal = CV->getAPIntValue();
6903     APInt NewVal = CVal & Mask;
6904     if (NewVal != CVal)
6905       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6906     break;
6907   }
6908   case ISD::OR:
6909   case ISD::XOR:
6910     // If the LHS or RHS don't contribute bits to the or, drop them.
6911     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6912       return V.getOperand(1);
6913     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6914       return V.getOperand(0);
6915     break;
6916   case ISD::SRL:
6917     // Only look at single-use SRLs.
6918     if (!V.getNode()->hasOneUse())
6919       break;
6920     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6921       // See if we can recursively simplify the LHS.
6922       unsigned Amt = RHSC->getZExtValue();
6923 
6924       // Watch out for shift count overflow though.
6925       if (Amt >= Mask.getBitWidth()) break;
6926       APInt NewMask = Mask << Amt;
6927       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6928         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6929                            SimplifyLHS, V.getOperand(1));
6930     }
6931   }
6932   return SDValue();
6933 }
6934 
6935 /// If the result of a wider load is shifted to right of N  bits and then
6936 /// truncated to a narrower type and where N is a multiple of number of bits of
6937 /// the narrower type, transform it to a narrower load from address + N / num of
6938 /// bits of new type. If the result is to be extended, also fold the extension
6939 /// to form a extending load.
6940 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6941   unsigned Opc = N->getOpcode();
6942 
6943   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6944   SDValue N0 = N->getOperand(0);
6945   EVT VT = N->getValueType(0);
6946   EVT ExtVT = VT;
6947 
6948   // This transformation isn't valid for vector loads.
6949   if (VT.isVector())
6950     return SDValue();
6951 
6952   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6953   // extended to VT.
6954   if (Opc == ISD::SIGN_EXTEND_INREG) {
6955     ExtType = ISD::SEXTLOAD;
6956     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6957   } else if (Opc == ISD::SRL) {
6958     // Another special-case: SRL is basically zero-extending a narrower value.
6959     ExtType = ISD::ZEXTLOAD;
6960     N0 = SDValue(N, 0);
6961     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6962     if (!N01) return SDValue();
6963     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6964                               VT.getSizeInBits() - N01->getZExtValue());
6965   }
6966   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6967     return SDValue();
6968 
6969   unsigned EVTBits = ExtVT.getSizeInBits();
6970 
6971   // Do not generate loads of non-round integer types since these can
6972   // be expensive (and would be wrong if the type is not byte sized).
6973   if (!ExtVT.isRound())
6974     return SDValue();
6975 
6976   unsigned ShAmt = 0;
6977   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6978     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6979       ShAmt = N01->getZExtValue();
6980       // Is the shift amount a multiple of size of VT?
6981       if ((ShAmt & (EVTBits-1)) == 0) {
6982         N0 = N0.getOperand(0);
6983         // Is the load width a multiple of size of VT?
6984         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
6985           return SDValue();
6986       }
6987 
6988       // At this point, we must have a load or else we can't do the transform.
6989       if (!isa<LoadSDNode>(N0)) return SDValue();
6990 
6991       // Because a SRL must be assumed to *need* to zero-extend the high bits
6992       // (as opposed to anyext the high bits), we can't combine the zextload
6993       // lowering of SRL and an sextload.
6994       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6995         return SDValue();
6996 
6997       // If the shift amount is larger than the input type then we're not
6998       // accessing any of the loaded bytes.  If the load was a zextload/extload
6999       // then the result of the shift+trunc is zero/undef (handled elsewhere).
7000       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7001         return SDValue();
7002     }
7003   }
7004 
7005   // If the load is shifted left (and the result isn't shifted back right),
7006   // we can fold the truncate through the shift.
7007   unsigned ShLeftAmt = 0;
7008   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7009       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7010     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7011       ShLeftAmt = N01->getZExtValue();
7012       N0 = N0.getOperand(0);
7013     }
7014   }
7015 
7016   // If we haven't found a load, we can't narrow it.  Don't transform one with
7017   // multiple uses, this would require adding a new load.
7018   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7019     return SDValue();
7020 
7021   // Don't change the width of a volatile load.
7022   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7023   if (LN0->isVolatile())
7024     return SDValue();
7025 
7026   // Verify that we are actually reducing a load width here.
7027   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7028     return SDValue();
7029 
7030   // For the transform to be legal, the load must produce only two values
7031   // (the value loaded and the chain).  Don't transform a pre-increment
7032   // load, for example, which produces an extra value.  Otherwise the
7033   // transformation is not equivalent, and the downstream logic to replace
7034   // uses gets things wrong.
7035   if (LN0->getNumValues() > 2)
7036     return SDValue();
7037 
7038   // If the load that we're shrinking is an extload and we're not just
7039   // discarding the extension we can't simply shrink the load. Bail.
7040   // TODO: It would be possible to merge the extensions in some cases.
7041   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7042       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7043     return SDValue();
7044 
7045   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7046     return SDValue();
7047 
7048   EVT PtrType = N0.getOperand(1).getValueType();
7049 
7050   if (PtrType == MVT::Untyped || PtrType.isExtended())
7051     // It's not possible to generate a constant of extended or untyped type.
7052     return SDValue();
7053 
7054   // For big endian targets, we need to adjust the offset to the pointer to
7055   // load the correct bytes.
7056   if (DAG.getDataLayout().isBigEndian()) {
7057     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7058     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7059     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7060   }
7061 
7062   uint64_t PtrOff = ShAmt / 8;
7063   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7064   SDLoc DL(LN0);
7065   // The original load itself didn't wrap, so an offset within it doesn't.
7066   SDNodeFlags Flags;
7067   Flags.setNoUnsignedWrap(true);
7068   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7069                                PtrType, LN0->getBasePtr(),
7070                                DAG.getConstant(PtrOff, DL, PtrType),
7071                                &Flags);
7072   AddToWorklist(NewPtr.getNode());
7073 
7074   SDValue Load;
7075   if (ExtType == ISD::NON_EXTLOAD)
7076     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7077                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7078                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7079   else
7080     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7081                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7082                           NewAlign, LN0->getMemOperand()->getFlags(),
7083                           LN0->getAAInfo());
7084 
7085   // Replace the old load's chain with the new load's chain.
7086   WorklistRemover DeadNodes(*this);
7087   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7088 
7089   // Shift the result left, if we've swallowed a left shift.
7090   SDValue Result = Load;
7091   if (ShLeftAmt != 0) {
7092     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7093     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7094       ShImmTy = VT;
7095     // If the shift amount is as large as the result size (but, presumably,
7096     // no larger than the source) then the useful bits of the result are
7097     // zero; we can't simply return the shortened shift, because the result
7098     // of that operation is undefined.
7099     SDLoc DL(N0);
7100     if (ShLeftAmt >= VT.getSizeInBits())
7101       Result = DAG.getConstant(0, DL, VT);
7102     else
7103       Result = DAG.getNode(ISD::SHL, DL, VT,
7104                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7105   }
7106 
7107   // Return the new loaded value.
7108   return Result;
7109 }
7110 
7111 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7112   SDValue N0 = N->getOperand(0);
7113   SDValue N1 = N->getOperand(1);
7114   EVT VT = N->getValueType(0);
7115   EVT EVT = cast<VTSDNode>(N1)->getVT();
7116   unsigned VTBits = VT.getScalarSizeInBits();
7117   unsigned EVTBits = EVT.getScalarSizeInBits();
7118 
7119   if (N0.isUndef())
7120     return DAG.getUNDEF(VT);
7121 
7122   // fold (sext_in_reg c1) -> c1
7123   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7124     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7125 
7126   // If the input is already sign extended, just drop the extension.
7127   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7128     return N0;
7129 
7130   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7131   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7132       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7133     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7134                        N0.getOperand(0), N1);
7135 
7136   // fold (sext_in_reg (sext x)) -> (sext x)
7137   // fold (sext_in_reg (aext x)) -> (sext x)
7138   // if x is small enough.
7139   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7140     SDValue N00 = N0.getOperand(0);
7141     if (N00.getScalarValueSizeInBits() <= EVTBits &&
7142         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7143       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7144   }
7145 
7146   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7147   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7148     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7149 
7150   // fold operands of sext_in_reg based on knowledge that the top bits are not
7151   // demanded.
7152   if (SimplifyDemandedBits(SDValue(N, 0)))
7153     return SDValue(N, 0);
7154 
7155   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7156   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7157   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7158     return NarrowLoad;
7159 
7160   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7161   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7162   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7163   if (N0.getOpcode() == ISD::SRL) {
7164     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7165       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7166         // We can turn this into an SRA iff the input to the SRL is already sign
7167         // extended enough.
7168         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7169         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7170           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7171                              N0.getOperand(0), N0.getOperand(1));
7172       }
7173   }
7174 
7175   // fold (sext_inreg (extload x)) -> (sextload x)
7176   if (ISD::isEXTLoad(N0.getNode()) &&
7177       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7178       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7179       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7180        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7181     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7182     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7183                                      LN0->getChain(),
7184                                      LN0->getBasePtr(), EVT,
7185                                      LN0->getMemOperand());
7186     CombineTo(N, ExtLoad);
7187     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7188     AddToWorklist(ExtLoad.getNode());
7189     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7190   }
7191   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7192   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7193       N0.hasOneUse() &&
7194       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7195       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7196        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7197     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7198     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7199                                      LN0->getChain(),
7200                                      LN0->getBasePtr(), EVT,
7201                                      LN0->getMemOperand());
7202     CombineTo(N, ExtLoad);
7203     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7204     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7205   }
7206 
7207   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7208   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7209     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7210                                            N0.getOperand(1), false))
7211       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7212                          BSwap, N1);
7213   }
7214 
7215   return SDValue();
7216 }
7217 
7218 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7219   SDValue N0 = N->getOperand(0);
7220   EVT VT = N->getValueType(0);
7221 
7222   if (N0.isUndef())
7223     return DAG.getUNDEF(VT);
7224 
7225   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7226                                               LegalOperations))
7227     return SDValue(Res, 0);
7228 
7229   return SDValue();
7230 }
7231 
7232 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7233   SDValue N0 = N->getOperand(0);
7234   EVT VT = N->getValueType(0);
7235 
7236   if (N0.isUndef())
7237     return DAG.getUNDEF(VT);
7238 
7239   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7240                                               LegalOperations))
7241     return SDValue(Res, 0);
7242 
7243   return SDValue();
7244 }
7245 
7246 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7247   SDValue N0 = N->getOperand(0);
7248   EVT VT = N->getValueType(0);
7249   bool isLE = DAG.getDataLayout().isLittleEndian();
7250 
7251   // noop truncate
7252   if (N0.getValueType() == N->getValueType(0))
7253     return N0;
7254   // fold (truncate c1) -> c1
7255   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7256     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7257   // fold (truncate (truncate x)) -> (truncate x)
7258   if (N0.getOpcode() == ISD::TRUNCATE)
7259     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7260   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7261   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7262       N0.getOpcode() == ISD::SIGN_EXTEND ||
7263       N0.getOpcode() == ISD::ANY_EXTEND) {
7264     // if the source is smaller than the dest, we still need an extend.
7265     if (N0.getOperand(0).getValueType().bitsLT(VT))
7266       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7267     // if the source is larger than the dest, than we just need the truncate.
7268     if (N0.getOperand(0).getValueType().bitsGT(VT))
7269       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7270     // if the source and dest are the same type, we can drop both the extend
7271     // and the truncate.
7272     return N0.getOperand(0);
7273   }
7274 
7275   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
7276   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
7277     return SDValue();
7278 
7279   // Fold extract-and-trunc into a narrow extract. For example:
7280   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7281   //   i32 y = TRUNCATE(i64 x)
7282   //        -- becomes --
7283   //   v16i8 b = BITCAST (v2i64 val)
7284   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7285   //
7286   // Note: We only run this optimization after type legalization (which often
7287   // creates this pattern) and before operation legalization after which
7288   // we need to be more careful about the vector instructions that we generate.
7289   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7290       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7291 
7292     EVT VecTy = N0.getOperand(0).getValueType();
7293     EVT ExTy = N0.getValueType();
7294     EVT TrTy = N->getValueType(0);
7295 
7296     unsigned NumElem = VecTy.getVectorNumElements();
7297     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7298 
7299     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7300     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7301 
7302     SDValue EltNo = N0->getOperand(1);
7303     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7304       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7305       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7306       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7307 
7308       SDLoc DL(N);
7309       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7310                          DAG.getBitcast(NVT, N0.getOperand(0)),
7311                          DAG.getConstant(Index, DL, IndexTy));
7312     }
7313   }
7314 
7315   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7316   if (N0.getOpcode() == ISD::SELECT) {
7317     EVT SrcVT = N0.getValueType();
7318     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7319         TLI.isTruncateFree(SrcVT, VT)) {
7320       SDLoc SL(N0);
7321       SDValue Cond = N0.getOperand(0);
7322       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7323       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7324       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7325     }
7326   }
7327 
7328   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
7329   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7330       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7331       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7332     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7333       uint64_t Amt = CAmt->getZExtValue();
7334       unsigned Size = VT.getScalarSizeInBits();
7335 
7336       if (Amt < Size) {
7337         SDLoc SL(N);
7338         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7339 
7340         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7341         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7342                            DAG.getConstant(Amt, SL, AmtVT));
7343       }
7344     }
7345   }
7346 
7347   // Fold a series of buildvector, bitcast, and truncate if possible.
7348   // For example fold
7349   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7350   //   (2xi32 (buildvector x, y)).
7351   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7352       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7353       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7354       N0.getOperand(0).hasOneUse()) {
7355 
7356     SDValue BuildVect = N0.getOperand(0);
7357     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7358     EVT TruncVecEltTy = VT.getVectorElementType();
7359 
7360     // Check that the element types match.
7361     if (BuildVectEltTy == TruncVecEltTy) {
7362       // Now we only need to compute the offset of the truncated elements.
7363       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7364       unsigned TruncVecNumElts = VT.getVectorNumElements();
7365       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7366 
7367       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7368              "Invalid number of elements");
7369 
7370       SmallVector<SDValue, 8> Opnds;
7371       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7372         Opnds.push_back(BuildVect.getOperand(i));
7373 
7374       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7375     }
7376   }
7377 
7378   // See if we can simplify the input to this truncate through knowledge that
7379   // only the low bits are being used.
7380   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7381   // Currently we only perform this optimization on scalars because vectors
7382   // may have different active low bits.
7383   if (!VT.isVector()) {
7384     if (SDValue Shorter =
7385             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7386                                                      VT.getSizeInBits())))
7387       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7388   }
7389   // fold (truncate (load x)) -> (smaller load x)
7390   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7391   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7392     if (SDValue Reduced = ReduceLoadWidth(N))
7393       return Reduced;
7394 
7395     // Handle the case where the load remains an extending load even
7396     // after truncation.
7397     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7398       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7399       if (!LN0->isVolatile() &&
7400           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7401         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7402                                          VT, LN0->getChain(), LN0->getBasePtr(),
7403                                          LN0->getMemoryVT(),
7404                                          LN0->getMemOperand());
7405         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7406         return NewLoad;
7407       }
7408     }
7409   }
7410   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7411   // where ... are all 'undef'.
7412   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7413     SmallVector<EVT, 8> VTs;
7414     SDValue V;
7415     unsigned Idx = 0;
7416     unsigned NumDefs = 0;
7417 
7418     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7419       SDValue X = N0.getOperand(i);
7420       if (!X.isUndef()) {
7421         V = X;
7422         Idx = i;
7423         NumDefs++;
7424       }
7425       // Stop if more than one members are non-undef.
7426       if (NumDefs > 1)
7427         break;
7428       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7429                                      VT.getVectorElementType(),
7430                                      X.getValueType().getVectorNumElements()));
7431     }
7432 
7433     if (NumDefs == 0)
7434       return DAG.getUNDEF(VT);
7435 
7436     if (NumDefs == 1) {
7437       assert(V.getNode() && "The single defined operand is empty!");
7438       SmallVector<SDValue, 8> Opnds;
7439       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7440         if (i != Idx) {
7441           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7442           continue;
7443         }
7444         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7445         AddToWorklist(NV.getNode());
7446         Opnds.push_back(NV);
7447       }
7448       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7449     }
7450   }
7451 
7452   // Fold truncate of a bitcast of a vector to an extract of the low vector
7453   // element.
7454   //
7455   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7456   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7457     SDValue VecSrc = N0.getOperand(0);
7458     EVT SrcVT = VecSrc.getValueType();
7459     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7460         (!LegalOperations ||
7461          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7462       SDLoc SL(N);
7463 
7464       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7465       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7466                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7467     }
7468   }
7469 
7470   // Simplify the operands using demanded-bits information.
7471   if (!VT.isVector() &&
7472       SimplifyDemandedBits(SDValue(N, 0)))
7473     return SDValue(N, 0);
7474 
7475   return SDValue();
7476 }
7477 
7478 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7479   SDValue Elt = N->getOperand(i);
7480   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7481     return Elt.getNode();
7482   return Elt.getOperand(Elt.getResNo()).getNode();
7483 }
7484 
7485 /// build_pair (load, load) -> load
7486 /// if load locations are consecutive.
7487 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7488   assert(N->getOpcode() == ISD::BUILD_PAIR);
7489 
7490   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7491   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7492   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7493       LD1->getAddressSpace() != LD2->getAddressSpace())
7494     return SDValue();
7495   EVT LD1VT = LD1->getValueType(0);
7496   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7497   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7498       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7499     unsigned Align = LD1->getAlignment();
7500     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7501         VT.getTypeForEVT(*DAG.getContext()));
7502 
7503     if (NewAlign <= Align &&
7504         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7505       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
7506                          LD1->getPointerInfo(), Align);
7507   }
7508 
7509   return SDValue();
7510 }
7511 
7512 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7513   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7514   // and Lo parts; on big-endian machines it doesn't.
7515   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7516 }
7517 
7518 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7519                                     const TargetLowering &TLI) {
7520   // If this is not a bitcast to an FP type or if the target doesn't have
7521   // IEEE754-compliant FP logic, we're done.
7522   EVT VT = N->getValueType(0);
7523   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7524     return SDValue();
7525 
7526   // TODO: Use splat values for the constant-checking below and remove this
7527   // restriction.
7528   SDValue N0 = N->getOperand(0);
7529   EVT SourceVT = N0.getValueType();
7530   if (SourceVT.isVector())
7531     return SDValue();
7532 
7533   unsigned FPOpcode;
7534   APInt SignMask;
7535   switch (N0.getOpcode()) {
7536   case ISD::AND:
7537     FPOpcode = ISD::FABS;
7538     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7539     break;
7540   case ISD::XOR:
7541     FPOpcode = ISD::FNEG;
7542     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7543     break;
7544   // TODO: ISD::OR --> ISD::FNABS?
7545   default:
7546     return SDValue();
7547   }
7548 
7549   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7550   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7551   SDValue LogicOp0 = N0.getOperand(0);
7552   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7553   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7554       LogicOp0.getOpcode() == ISD::BITCAST &&
7555       LogicOp0->getOperand(0).getValueType() == VT)
7556     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7557 
7558   return SDValue();
7559 }
7560 
7561 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7562   SDValue N0 = N->getOperand(0);
7563   EVT VT = N->getValueType(0);
7564 
7565   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7566   // Only do this before legalize, since afterward the target may be depending
7567   // on the bitconvert.
7568   // First check to see if this is all constant.
7569   if (!LegalTypes &&
7570       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7571       VT.isVector()) {
7572     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7573 
7574     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7575     assert(!DestEltVT.isVector() &&
7576            "Element type of vector ValueType must not be vector!");
7577     if (isSimple)
7578       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7579   }
7580 
7581   // If the input is a constant, let getNode fold it.
7582   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7583     // If we can't allow illegal operations, we need to check that this is just
7584     // a fp -> int or int -> conversion and that the resulting operation will
7585     // be legal.
7586     if (!LegalOperations ||
7587         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7588          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7589         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7590          TLI.isOperationLegal(ISD::Constant, VT)))
7591       return DAG.getBitcast(VT, N0);
7592   }
7593 
7594   // (conv (conv x, t1), t2) -> (conv x, t2)
7595   if (N0.getOpcode() == ISD::BITCAST)
7596     return DAG.getBitcast(VT, N0.getOperand(0));
7597 
7598   // fold (conv (load x)) -> (load (conv*)x)
7599   // If the resultant load doesn't need a higher alignment than the original!
7600   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7601       // Do not change the width of a volatile load.
7602       !cast<LoadSDNode>(N0)->isVolatile() &&
7603       // Do not remove the cast if the types differ in endian layout.
7604       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7605           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7606       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7607       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7608     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7609     unsigned OrigAlign = LN0->getAlignment();
7610 
7611     bool Fast = false;
7612     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7613                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7614         Fast) {
7615       SDValue Load =
7616           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7617                       LN0->getPointerInfo(), OrigAlign,
7618                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7619       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7620       return Load;
7621     }
7622   }
7623 
7624   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7625     return V;
7626 
7627   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7628   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7629   //
7630   // For ppc_fp128:
7631   // fold (bitcast (fneg x)) ->
7632   //     flipbit = signbit
7633   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7634   //
7635   // fold (bitcast (fabs x)) ->
7636   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7637   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7638   // This often reduces constant pool loads.
7639   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7640        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7641       N0.getNode()->hasOneUse() && VT.isInteger() &&
7642       !VT.isVector() && !N0.getValueType().isVector()) {
7643     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7644     AddToWorklist(NewConv.getNode());
7645 
7646     SDLoc DL(N);
7647     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7648       assert(VT.getSizeInBits() == 128);
7649       SDValue SignBit = DAG.getConstant(
7650           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7651       SDValue FlipBit;
7652       if (N0.getOpcode() == ISD::FNEG) {
7653         FlipBit = SignBit;
7654         AddToWorklist(FlipBit.getNode());
7655       } else {
7656         assert(N0.getOpcode() == ISD::FABS);
7657         SDValue Hi =
7658             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7659                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7660                                               SDLoc(NewConv)));
7661         AddToWorklist(Hi.getNode());
7662         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7663         AddToWorklist(FlipBit.getNode());
7664       }
7665       SDValue FlipBits =
7666           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7667       AddToWorklist(FlipBits.getNode());
7668       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7669     }
7670     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7671     if (N0.getOpcode() == ISD::FNEG)
7672       return DAG.getNode(ISD::XOR, DL, VT,
7673                          NewConv, DAG.getConstant(SignBit, DL, VT));
7674     assert(N0.getOpcode() == ISD::FABS);
7675     return DAG.getNode(ISD::AND, DL, VT,
7676                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7677   }
7678 
7679   // fold (bitconvert (fcopysign cst, x)) ->
7680   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7681   // Note that we don't handle (copysign x, cst) because this can always be
7682   // folded to an fneg or fabs.
7683   //
7684   // For ppc_fp128:
7685   // fold (bitcast (fcopysign cst, x)) ->
7686   //     flipbit = (and (extract_element
7687   //                     (xor (bitcast cst), (bitcast x)), 0),
7688   //                    signbit)
7689   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7690   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7691       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7692       VT.isInteger() && !VT.isVector()) {
7693     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
7694     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7695     if (isTypeLegal(IntXVT)) {
7696       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7697       AddToWorklist(X.getNode());
7698 
7699       // If X has a different width than the result/lhs, sext it or truncate it.
7700       unsigned VTWidth = VT.getSizeInBits();
7701       if (OrigXWidth < VTWidth) {
7702         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7703         AddToWorklist(X.getNode());
7704       } else if (OrigXWidth > VTWidth) {
7705         // To get the sign bit in the right place, we have to shift it right
7706         // before truncating.
7707         SDLoc DL(X);
7708         X = DAG.getNode(ISD::SRL, DL,
7709                         X.getValueType(), X,
7710                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7711                                         X.getValueType()));
7712         AddToWorklist(X.getNode());
7713         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7714         AddToWorklist(X.getNode());
7715       }
7716 
7717       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7718         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7719         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7720         AddToWorklist(Cst.getNode());
7721         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7722         AddToWorklist(X.getNode());
7723         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7724         AddToWorklist(XorResult.getNode());
7725         SDValue XorResult64 = DAG.getNode(
7726             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7727             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7728                                   SDLoc(XorResult)));
7729         AddToWorklist(XorResult64.getNode());
7730         SDValue FlipBit =
7731             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7732                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7733         AddToWorklist(FlipBit.getNode());
7734         SDValue FlipBits =
7735             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7736         AddToWorklist(FlipBits.getNode());
7737         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7738       }
7739       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7740       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7741                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7742       AddToWorklist(X.getNode());
7743 
7744       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7745       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7746                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7747       AddToWorklist(Cst.getNode());
7748 
7749       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7750     }
7751   }
7752 
7753   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7754   if (N0.getOpcode() == ISD::BUILD_PAIR)
7755     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7756       return CombineLD;
7757 
7758   // Remove double bitcasts from shuffles - this is often a legacy of
7759   // XformToShuffleWithZero being used to combine bitmaskings (of
7760   // float vectors bitcast to integer vectors) into shuffles.
7761   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7762   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7763       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7764       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7765       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7766     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7767 
7768     // If operands are a bitcast, peek through if it casts the original VT.
7769     // If operands are a constant, just bitcast back to original VT.
7770     auto PeekThroughBitcast = [&](SDValue Op) {
7771       if (Op.getOpcode() == ISD::BITCAST &&
7772           Op.getOperand(0).getValueType() == VT)
7773         return SDValue(Op.getOperand(0));
7774       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7775           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7776         return DAG.getBitcast(VT, Op);
7777       return SDValue();
7778     };
7779 
7780     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7781     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7782     if (!(SV0 && SV1))
7783       return SDValue();
7784 
7785     int MaskScale =
7786         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7787     SmallVector<int, 8> NewMask;
7788     for (int M : SVN->getMask())
7789       for (int i = 0; i != MaskScale; ++i)
7790         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7791 
7792     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7793     if (!LegalMask) {
7794       std::swap(SV0, SV1);
7795       ShuffleVectorSDNode::commuteMask(NewMask);
7796       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7797     }
7798 
7799     if (LegalMask)
7800       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7801   }
7802 
7803   return SDValue();
7804 }
7805 
7806 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7807   EVT VT = N->getValueType(0);
7808   return CombineConsecutiveLoads(N, VT);
7809 }
7810 
7811 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7812 /// operands. DstEltVT indicates the destination element value type.
7813 SDValue DAGCombiner::
7814 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7815   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7816 
7817   // If this is already the right type, we're done.
7818   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7819 
7820   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7821   unsigned DstBitSize = DstEltVT.getSizeInBits();
7822 
7823   // If this is a conversion of N elements of one type to N elements of another
7824   // type, convert each element.  This handles FP<->INT cases.
7825   if (SrcBitSize == DstBitSize) {
7826     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7827                               BV->getValueType(0).getVectorNumElements());
7828 
7829     // Due to the FP element handling below calling this routine recursively,
7830     // we can end up with a scalar-to-vector node here.
7831     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7832       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7833                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7834 
7835     SmallVector<SDValue, 8> Ops;
7836     for (SDValue Op : BV->op_values()) {
7837       // If the vector element type is not legal, the BUILD_VECTOR operands
7838       // are promoted and implicitly truncated.  Make that explicit here.
7839       if (Op.getValueType() != SrcEltVT)
7840         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7841       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7842       AddToWorklist(Ops.back().getNode());
7843     }
7844     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7845   }
7846 
7847   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7848   // handle annoying details of growing/shrinking FP values, we convert them to
7849   // int first.
7850   if (SrcEltVT.isFloatingPoint()) {
7851     // Convert the input float vector to a int vector where the elements are the
7852     // same sizes.
7853     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7854     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7855     SrcEltVT = IntVT;
7856   }
7857 
7858   // Now we know the input is an integer vector.  If the output is a FP type,
7859   // convert to integer first, then to FP of the right size.
7860   if (DstEltVT.isFloatingPoint()) {
7861     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7862     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7863 
7864     // Next, convert to FP elements of the same size.
7865     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7866   }
7867 
7868   SDLoc DL(BV);
7869 
7870   // Okay, we know the src/dst types are both integers of differing types.
7871   // Handling growing first.
7872   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7873   if (SrcBitSize < DstBitSize) {
7874     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7875 
7876     SmallVector<SDValue, 8> Ops;
7877     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7878          i += NumInputsPerOutput) {
7879       bool isLE = DAG.getDataLayout().isLittleEndian();
7880       APInt NewBits = APInt(DstBitSize, 0);
7881       bool EltIsUndef = true;
7882       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7883         // Shift the previously computed bits over.
7884         NewBits <<= SrcBitSize;
7885         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7886         if (Op.isUndef()) continue;
7887         EltIsUndef = false;
7888 
7889         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7890                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7891       }
7892 
7893       if (EltIsUndef)
7894         Ops.push_back(DAG.getUNDEF(DstEltVT));
7895       else
7896         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7897     }
7898 
7899     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7900     return DAG.getBuildVector(VT, DL, Ops);
7901   }
7902 
7903   // Finally, this must be the case where we are shrinking elements: each input
7904   // turns into multiple outputs.
7905   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7906   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7907                             NumOutputsPerInput*BV->getNumOperands());
7908   SmallVector<SDValue, 8> Ops;
7909 
7910   for (const SDValue &Op : BV->op_values()) {
7911     if (Op.isUndef()) {
7912       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7913       continue;
7914     }
7915 
7916     APInt OpVal = cast<ConstantSDNode>(Op)->
7917                   getAPIntValue().zextOrTrunc(SrcBitSize);
7918 
7919     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7920       APInt ThisVal = OpVal.trunc(DstBitSize);
7921       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7922       OpVal = OpVal.lshr(DstBitSize);
7923     }
7924 
7925     // For big endian targets, swap the order of the pieces of each element.
7926     if (DAG.getDataLayout().isBigEndian())
7927       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7928   }
7929 
7930   return DAG.getBuildVector(VT, DL, Ops);
7931 }
7932 
7933 /// Try to perform FMA combining on a given FADD node.
7934 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7935   SDValue N0 = N->getOperand(0);
7936   SDValue N1 = N->getOperand(1);
7937   EVT VT = N->getValueType(0);
7938   SDLoc SL(N);
7939 
7940   const TargetOptions &Options = DAG.getTarget().Options;
7941   bool AllowFusion =
7942       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7943 
7944   // Floating-point multiply-add with intermediate rounding.
7945   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7946 
7947   // Floating-point multiply-add without intermediate rounding.
7948   bool HasFMA =
7949       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7950       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7951 
7952   // No valid opcode, do not combine.
7953   if (!HasFMAD && !HasFMA)
7954     return SDValue();
7955 
7956   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7957   ;
7958   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7959     return SDValue();
7960 
7961   // Always prefer FMAD to FMA for precision.
7962   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7963   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7964   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7965 
7966   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7967   // prefer to fold the multiply with fewer uses.
7968   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7969       N1.getOpcode() == ISD::FMUL) {
7970     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7971       std::swap(N0, N1);
7972   }
7973 
7974   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7975   if (N0.getOpcode() == ISD::FMUL &&
7976       (Aggressive || N0->hasOneUse())) {
7977     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7978                        N0.getOperand(0), N0.getOperand(1), N1);
7979   }
7980 
7981   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7982   // Note: Commutes FADD operands.
7983   if (N1.getOpcode() == ISD::FMUL &&
7984       (Aggressive || N1->hasOneUse())) {
7985     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7986                        N1.getOperand(0), N1.getOperand(1), N0);
7987   }
7988 
7989   // Look through FP_EXTEND nodes to do more combining.
7990   if (AllowFusion && LookThroughFPExt) {
7991     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7992     if (N0.getOpcode() == ISD::FP_EXTEND) {
7993       SDValue N00 = N0.getOperand(0);
7994       if (N00.getOpcode() == ISD::FMUL)
7995         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7996                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7997                                        N00.getOperand(0)),
7998                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7999                                        N00.getOperand(1)), N1);
8000     }
8001 
8002     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8003     // Note: Commutes FADD operands.
8004     if (N1.getOpcode() == ISD::FP_EXTEND) {
8005       SDValue N10 = N1.getOperand(0);
8006       if (N10.getOpcode() == ISD::FMUL)
8007         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8008                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8009                                        N10.getOperand(0)),
8010                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8011                                        N10.getOperand(1)), N0);
8012     }
8013   }
8014 
8015   // More folding opportunities when target permits.
8016   if ((AllowFusion || HasFMAD)  && Aggressive) {
8017     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8018     if (N0.getOpcode() == PreferredFusedOpcode &&
8019         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8020       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8021                          N0.getOperand(0), N0.getOperand(1),
8022                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8023                                      N0.getOperand(2).getOperand(0),
8024                                      N0.getOperand(2).getOperand(1),
8025                                      N1));
8026     }
8027 
8028     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8029     if (N1->getOpcode() == PreferredFusedOpcode &&
8030         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8031       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8032                          N1.getOperand(0), N1.getOperand(1),
8033                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8034                                      N1.getOperand(2).getOperand(0),
8035                                      N1.getOperand(2).getOperand(1),
8036                                      N0));
8037     }
8038 
8039     if (AllowFusion && LookThroughFPExt) {
8040       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8041       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
8042       auto FoldFAddFMAFPExtFMul = [&] (
8043           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8044         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8045                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8046                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8047                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8048                                        Z));
8049       };
8050       if (N0.getOpcode() == PreferredFusedOpcode) {
8051         SDValue N02 = N0.getOperand(2);
8052         if (N02.getOpcode() == ISD::FP_EXTEND) {
8053           SDValue N020 = N02.getOperand(0);
8054           if (N020.getOpcode() == ISD::FMUL)
8055             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8056                                         N020.getOperand(0), N020.getOperand(1),
8057                                         N1);
8058         }
8059       }
8060 
8061       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8062       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8063       // FIXME: This turns two single-precision and one double-precision
8064       // operation into two double-precision operations, which might not be
8065       // interesting for all targets, especially GPUs.
8066       auto FoldFAddFPExtFMAFMul = [&] (
8067           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8068         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8069                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8070                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8071                            DAG.getNode(PreferredFusedOpcode, SL, VT,
8072                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8073                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8074                                        Z));
8075       };
8076       if (N0.getOpcode() == ISD::FP_EXTEND) {
8077         SDValue N00 = N0.getOperand(0);
8078         if (N00.getOpcode() == PreferredFusedOpcode) {
8079           SDValue N002 = N00.getOperand(2);
8080           if (N002.getOpcode() == ISD::FMUL)
8081             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8082                                         N002.getOperand(0), N002.getOperand(1),
8083                                         N1);
8084         }
8085       }
8086 
8087       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
8088       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
8089       if (N1.getOpcode() == PreferredFusedOpcode) {
8090         SDValue N12 = N1.getOperand(2);
8091         if (N12.getOpcode() == ISD::FP_EXTEND) {
8092           SDValue N120 = N12.getOperand(0);
8093           if (N120.getOpcode() == ISD::FMUL)
8094             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8095                                         N120.getOperand(0), N120.getOperand(1),
8096                                         N0);
8097         }
8098       }
8099 
8100       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8101       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8102       // FIXME: This turns two single-precision and one double-precision
8103       // operation into two double-precision operations, which might not be
8104       // interesting for all targets, especially GPUs.
8105       if (N1.getOpcode() == ISD::FP_EXTEND) {
8106         SDValue N10 = N1.getOperand(0);
8107         if (N10.getOpcode() == PreferredFusedOpcode) {
8108           SDValue N102 = N10.getOperand(2);
8109           if (N102.getOpcode() == ISD::FMUL)
8110             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8111                                         N102.getOperand(0), N102.getOperand(1),
8112                                         N0);
8113         }
8114       }
8115     }
8116   }
8117 
8118   return SDValue();
8119 }
8120 
8121 /// Try to perform FMA combining on a given FSUB node.
8122 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8123   SDValue N0 = N->getOperand(0);
8124   SDValue N1 = N->getOperand(1);
8125   EVT VT = N->getValueType(0);
8126   SDLoc SL(N);
8127 
8128   const TargetOptions &Options = DAG.getTarget().Options;
8129   bool AllowFusion =
8130       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8131 
8132   // Floating-point multiply-add with intermediate rounding.
8133   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8134 
8135   // Floating-point multiply-add without intermediate rounding.
8136   bool HasFMA =
8137       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8138       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8139 
8140   // No valid opcode, do not combine.
8141   if (!HasFMAD && !HasFMA)
8142     return SDValue();
8143 
8144   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8145   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8146     return SDValue();
8147 
8148   // Always prefer FMAD to FMA for precision.
8149   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8150   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8151   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8152 
8153   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8154   if (N0.getOpcode() == ISD::FMUL &&
8155       (Aggressive || N0->hasOneUse())) {
8156     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8157                        N0.getOperand(0), N0.getOperand(1),
8158                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8159   }
8160 
8161   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8162   // Note: Commutes FSUB operands.
8163   if (N1.getOpcode() == ISD::FMUL &&
8164       (Aggressive || N1->hasOneUse()))
8165     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8166                        DAG.getNode(ISD::FNEG, SL, VT,
8167                                    N1.getOperand(0)),
8168                        N1.getOperand(1), N0);
8169 
8170   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8171   if (N0.getOpcode() == ISD::FNEG &&
8172       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8173       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8174     SDValue N00 = N0.getOperand(0).getOperand(0);
8175     SDValue N01 = N0.getOperand(0).getOperand(1);
8176     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8177                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8178                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8179   }
8180 
8181   // Look through FP_EXTEND nodes to do more combining.
8182   if (AllowFusion && LookThroughFPExt) {
8183     // fold (fsub (fpext (fmul x, y)), z)
8184     //   -> (fma (fpext x), (fpext y), (fneg z))
8185     if (N0.getOpcode() == ISD::FP_EXTEND) {
8186       SDValue N00 = N0.getOperand(0);
8187       if (N00.getOpcode() == ISD::FMUL)
8188         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8189                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8190                                        N00.getOperand(0)),
8191                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8192                                        N00.getOperand(1)),
8193                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8194     }
8195 
8196     // fold (fsub x, (fpext (fmul y, z)))
8197     //   -> (fma (fneg (fpext y)), (fpext z), x)
8198     // Note: Commutes FSUB operands.
8199     if (N1.getOpcode() == ISD::FP_EXTEND) {
8200       SDValue N10 = N1.getOperand(0);
8201       if (N10.getOpcode() == ISD::FMUL)
8202         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8203                            DAG.getNode(ISD::FNEG, SL, VT,
8204                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8205                                                    N10.getOperand(0))),
8206                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8207                                        N10.getOperand(1)),
8208                            N0);
8209     }
8210 
8211     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8212     //   -> (fneg (fma (fpext x), (fpext y), z))
8213     // Note: This could be removed with appropriate canonicalization of the
8214     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8215     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8216     // from implementing the canonicalization in visitFSUB.
8217     if (N0.getOpcode() == ISD::FP_EXTEND) {
8218       SDValue N00 = N0.getOperand(0);
8219       if (N00.getOpcode() == ISD::FNEG) {
8220         SDValue N000 = N00.getOperand(0);
8221         if (N000.getOpcode() == ISD::FMUL) {
8222           return DAG.getNode(ISD::FNEG, SL, VT,
8223                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8224                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8225                                                      N000.getOperand(0)),
8226                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8227                                                      N000.getOperand(1)),
8228                                          N1));
8229         }
8230       }
8231     }
8232 
8233     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8234     //   -> (fneg (fma (fpext x)), (fpext y), z)
8235     // Note: This could be removed with appropriate canonicalization of the
8236     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8237     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8238     // from implementing the canonicalization in visitFSUB.
8239     if (N0.getOpcode() == ISD::FNEG) {
8240       SDValue N00 = N0.getOperand(0);
8241       if (N00.getOpcode() == ISD::FP_EXTEND) {
8242         SDValue N000 = N00.getOperand(0);
8243         if (N000.getOpcode() == ISD::FMUL) {
8244           return DAG.getNode(ISD::FNEG, SL, VT,
8245                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8246                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8247                                                      N000.getOperand(0)),
8248                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8249                                                      N000.getOperand(1)),
8250                                          N1));
8251         }
8252       }
8253     }
8254 
8255   }
8256 
8257   // More folding opportunities when target permits.
8258   if ((AllowFusion || HasFMAD) && Aggressive) {
8259     // fold (fsub (fma x, y, (fmul u, v)), z)
8260     //   -> (fma x, y (fma u, v, (fneg z)))
8261     if (N0.getOpcode() == PreferredFusedOpcode &&
8262         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8263       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8264                          N0.getOperand(0), N0.getOperand(1),
8265                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8266                                      N0.getOperand(2).getOperand(0),
8267                                      N0.getOperand(2).getOperand(1),
8268                                      DAG.getNode(ISD::FNEG, SL, VT,
8269                                                  N1)));
8270     }
8271 
8272     // fold (fsub x, (fma y, z, (fmul u, v)))
8273     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8274     if (N1.getOpcode() == PreferredFusedOpcode &&
8275         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8276       SDValue N20 = N1.getOperand(2).getOperand(0);
8277       SDValue N21 = N1.getOperand(2).getOperand(1);
8278       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8279                          DAG.getNode(ISD::FNEG, SL, VT,
8280                                      N1.getOperand(0)),
8281                          N1.getOperand(1),
8282                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8283                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8284 
8285                                      N21, N0));
8286     }
8287 
8288     if (AllowFusion && LookThroughFPExt) {
8289       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8290       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8291       if (N0.getOpcode() == PreferredFusedOpcode) {
8292         SDValue N02 = N0.getOperand(2);
8293         if (N02.getOpcode() == ISD::FP_EXTEND) {
8294           SDValue N020 = N02.getOperand(0);
8295           if (N020.getOpcode() == ISD::FMUL)
8296             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8297                                N0.getOperand(0), N0.getOperand(1),
8298                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8299                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8300                                                        N020.getOperand(0)),
8301                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8302                                                        N020.getOperand(1)),
8303                                            DAG.getNode(ISD::FNEG, SL, VT,
8304                                                        N1)));
8305         }
8306       }
8307 
8308       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8309       //   -> (fma (fpext x), (fpext y),
8310       //           (fma (fpext u), (fpext v), (fneg z)))
8311       // FIXME: This turns two single-precision and one double-precision
8312       // operation into two double-precision operations, which might not be
8313       // interesting for all targets, especially GPUs.
8314       if (N0.getOpcode() == ISD::FP_EXTEND) {
8315         SDValue N00 = N0.getOperand(0);
8316         if (N00.getOpcode() == PreferredFusedOpcode) {
8317           SDValue N002 = N00.getOperand(2);
8318           if (N002.getOpcode() == ISD::FMUL)
8319             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8320                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8321                                            N00.getOperand(0)),
8322                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8323                                            N00.getOperand(1)),
8324                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8325                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8326                                                        N002.getOperand(0)),
8327                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8328                                                        N002.getOperand(1)),
8329                                            DAG.getNode(ISD::FNEG, SL, VT,
8330                                                        N1)));
8331         }
8332       }
8333 
8334       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8335       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8336       if (N1.getOpcode() == PreferredFusedOpcode &&
8337         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8338         SDValue N120 = N1.getOperand(2).getOperand(0);
8339         if (N120.getOpcode() == ISD::FMUL) {
8340           SDValue N1200 = N120.getOperand(0);
8341           SDValue N1201 = N120.getOperand(1);
8342           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8343                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8344                              N1.getOperand(1),
8345                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8346                                          DAG.getNode(ISD::FNEG, SL, VT,
8347                                              DAG.getNode(ISD::FP_EXTEND, SL,
8348                                                          VT, N1200)),
8349                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8350                                                      N1201),
8351                                          N0));
8352         }
8353       }
8354 
8355       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8356       //   -> (fma (fneg (fpext y)), (fpext z),
8357       //           (fma (fneg (fpext u)), (fpext v), x))
8358       // FIXME: This turns two single-precision and one double-precision
8359       // operation into two double-precision operations, which might not be
8360       // interesting for all targets, especially GPUs.
8361       if (N1.getOpcode() == ISD::FP_EXTEND &&
8362         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8363         SDValue N100 = N1.getOperand(0).getOperand(0);
8364         SDValue N101 = N1.getOperand(0).getOperand(1);
8365         SDValue N102 = N1.getOperand(0).getOperand(2);
8366         if (N102.getOpcode() == ISD::FMUL) {
8367           SDValue N1020 = N102.getOperand(0);
8368           SDValue N1021 = N102.getOperand(1);
8369           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8370                              DAG.getNode(ISD::FNEG, SL, VT,
8371                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8372                                                      N100)),
8373                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8374                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8375                                          DAG.getNode(ISD::FNEG, SL, VT,
8376                                              DAG.getNode(ISD::FP_EXTEND, SL,
8377                                                          VT, N1020)),
8378                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8379                                                      N1021),
8380                                          N0));
8381         }
8382       }
8383     }
8384   }
8385 
8386   return SDValue();
8387 }
8388 
8389 /// Try to perform FMA combining on a given FMUL node.
8390 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8391   SDValue N0 = N->getOperand(0);
8392   SDValue N1 = N->getOperand(1);
8393   EVT VT = N->getValueType(0);
8394   SDLoc SL(N);
8395 
8396   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8397 
8398   const TargetOptions &Options = DAG.getTarget().Options;
8399   bool AllowFusion =
8400       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8401 
8402   // Floating-point multiply-add with intermediate rounding.
8403   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8404 
8405   // Floating-point multiply-add without intermediate rounding.
8406   bool HasFMA =
8407       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8408       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8409 
8410   // No valid opcode, do not combine.
8411   if (!HasFMAD && !HasFMA)
8412     return SDValue();
8413 
8414   // Always prefer FMAD to FMA for precision.
8415   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8416   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8417 
8418   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8419   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8420   auto FuseFADD = [&](SDValue X, SDValue Y) {
8421     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8422       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8423       if (XC1 && XC1->isExactlyValue(+1.0))
8424         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8425       if (XC1 && XC1->isExactlyValue(-1.0))
8426         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8427                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8428     }
8429     return SDValue();
8430   };
8431 
8432   if (SDValue FMA = FuseFADD(N0, N1))
8433     return FMA;
8434   if (SDValue FMA = FuseFADD(N1, N0))
8435     return FMA;
8436 
8437   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8438   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8439   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8440   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8441   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8442     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8443       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8444       if (XC0 && XC0->isExactlyValue(+1.0))
8445         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8446                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8447                            Y);
8448       if (XC0 && XC0->isExactlyValue(-1.0))
8449         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8450                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8451                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8452 
8453       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8454       if (XC1 && XC1->isExactlyValue(+1.0))
8455         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8456                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8457       if (XC1 && XC1->isExactlyValue(-1.0))
8458         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8459     }
8460     return SDValue();
8461   };
8462 
8463   if (SDValue FMA = FuseFSUB(N0, N1))
8464     return FMA;
8465   if (SDValue FMA = FuseFSUB(N1, N0))
8466     return FMA;
8467 
8468   return SDValue();
8469 }
8470 
8471 SDValue DAGCombiner::visitFADD(SDNode *N) {
8472   SDValue N0 = N->getOperand(0);
8473   SDValue N1 = N->getOperand(1);
8474   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8475   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8476   EVT VT = N->getValueType(0);
8477   SDLoc DL(N);
8478   const TargetOptions &Options = DAG.getTarget().Options;
8479   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8480 
8481   // fold vector ops
8482   if (VT.isVector())
8483     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8484       return FoldedVOp;
8485 
8486   // fold (fadd c1, c2) -> c1 + c2
8487   if (N0CFP && N1CFP)
8488     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8489 
8490   // canonicalize constant to RHS
8491   if (N0CFP && !N1CFP)
8492     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8493 
8494   // fold (fadd A, (fneg B)) -> (fsub A, B)
8495   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8496       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8497     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8498                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8499 
8500   // fold (fadd (fneg A), B) -> (fsub B, A)
8501   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8502       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8503     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8504                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8505 
8506   // If 'unsafe math' is enabled, fold lots of things.
8507   if (Options.UnsafeFPMath) {
8508     // No FP constant should be created after legalization as Instruction
8509     // Selection pass has a hard time dealing with FP constants.
8510     bool AllowNewConst = (Level < AfterLegalizeDAG);
8511 
8512     // fold (fadd A, 0) -> A
8513     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8514       if (N1C->isZero())
8515         return N0;
8516 
8517     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8518     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8519         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8520       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8521                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8522                                      Flags),
8523                          Flags);
8524 
8525     // If allowed, fold (fadd (fneg x), x) -> 0.0
8526     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8527       return DAG.getConstantFP(0.0, DL, VT);
8528 
8529     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8530     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8531       return DAG.getConstantFP(0.0, DL, VT);
8532 
8533     // We can fold chains of FADD's of the same value into multiplications.
8534     // This transform is not safe in general because we are reducing the number
8535     // of rounding steps.
8536     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8537       if (N0.getOpcode() == ISD::FMUL) {
8538         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8539         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8540 
8541         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8542         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8543           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8544                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8545           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8546         }
8547 
8548         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8549         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8550             N1.getOperand(0) == N1.getOperand(1) &&
8551             N0.getOperand(0) == N1.getOperand(0)) {
8552           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8553                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8554           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8555         }
8556       }
8557 
8558       if (N1.getOpcode() == ISD::FMUL) {
8559         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8560         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8561 
8562         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8563         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8564           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8565                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8566           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8567         }
8568 
8569         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8570         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8571             N0.getOperand(0) == N0.getOperand(1) &&
8572             N1.getOperand(0) == N0.getOperand(0)) {
8573           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8574                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8575           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8576         }
8577       }
8578 
8579       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8580         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8581         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8582         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8583             (N0.getOperand(0) == N1)) {
8584           return DAG.getNode(ISD::FMUL, DL, VT,
8585                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8586         }
8587       }
8588 
8589       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8590         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8591         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8592         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8593             N1.getOperand(0) == N0) {
8594           return DAG.getNode(ISD::FMUL, DL, VT,
8595                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8596         }
8597       }
8598 
8599       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8600       if (AllowNewConst &&
8601           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8602           N0.getOperand(0) == N0.getOperand(1) &&
8603           N1.getOperand(0) == N1.getOperand(1) &&
8604           N0.getOperand(0) == N1.getOperand(0)) {
8605         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8606                            DAG.getConstantFP(4.0, DL, VT), Flags);
8607       }
8608     }
8609   } // enable-unsafe-fp-math
8610 
8611   // FADD -> FMA combines:
8612   if (SDValue Fused = visitFADDForFMACombine(N)) {
8613     AddToWorklist(Fused.getNode());
8614     return Fused;
8615   }
8616   return SDValue();
8617 }
8618 
8619 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8620   SDValue N0 = N->getOperand(0);
8621   SDValue N1 = N->getOperand(1);
8622   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8623   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8624   EVT VT = N->getValueType(0);
8625   SDLoc DL(N);
8626   const TargetOptions &Options = DAG.getTarget().Options;
8627   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8628 
8629   // fold vector ops
8630   if (VT.isVector())
8631     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8632       return FoldedVOp;
8633 
8634   // fold (fsub c1, c2) -> c1-c2
8635   if (N0CFP && N1CFP)
8636     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
8637 
8638   // fold (fsub A, (fneg B)) -> (fadd A, B)
8639   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8640     return DAG.getNode(ISD::FADD, DL, VT, N0,
8641                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8642 
8643   // If 'unsafe math' is enabled, fold lots of things.
8644   if (Options.UnsafeFPMath) {
8645     // (fsub A, 0) -> A
8646     if (N1CFP && N1CFP->isZero())
8647       return N0;
8648 
8649     // (fsub 0, B) -> -B
8650     if (N0CFP && N0CFP->isZero()) {
8651       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8652         return GetNegatedExpression(N1, DAG, LegalOperations);
8653       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8654         return DAG.getNode(ISD::FNEG, DL, VT, N1);
8655     }
8656 
8657     // (fsub x, x) -> 0.0
8658     if (N0 == N1)
8659       return DAG.getConstantFP(0.0f, DL, VT);
8660 
8661     // (fsub x, (fadd x, y)) -> (fneg y)
8662     // (fsub x, (fadd y, x)) -> (fneg y)
8663     if (N1.getOpcode() == ISD::FADD) {
8664       SDValue N10 = N1->getOperand(0);
8665       SDValue N11 = N1->getOperand(1);
8666 
8667       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8668         return GetNegatedExpression(N11, DAG, LegalOperations);
8669 
8670       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8671         return GetNegatedExpression(N10, DAG, LegalOperations);
8672     }
8673   }
8674 
8675   // FSUB -> FMA combines:
8676   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8677     AddToWorklist(Fused.getNode());
8678     return Fused;
8679   }
8680 
8681   return SDValue();
8682 }
8683 
8684 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8685   SDValue N0 = N->getOperand(0);
8686   SDValue N1 = N->getOperand(1);
8687   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8688   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8689   EVT VT = N->getValueType(0);
8690   SDLoc DL(N);
8691   const TargetOptions &Options = DAG.getTarget().Options;
8692   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8693 
8694   // fold vector ops
8695   if (VT.isVector()) {
8696     // This just handles C1 * C2 for vectors. Other vector folds are below.
8697     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8698       return FoldedVOp;
8699   }
8700 
8701   // fold (fmul c1, c2) -> c1*c2
8702   if (N0CFP && N1CFP)
8703     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8704 
8705   // canonicalize constant to RHS
8706   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8707      !isConstantFPBuildVectorOrConstantFP(N1))
8708     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8709 
8710   // fold (fmul A, 1.0) -> A
8711   if (N1CFP && N1CFP->isExactlyValue(1.0))
8712     return N0;
8713 
8714   if (Options.UnsafeFPMath) {
8715     // fold (fmul A, 0) -> 0
8716     if (N1CFP && N1CFP->isZero())
8717       return N1;
8718 
8719     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8720     if (N0.getOpcode() == ISD::FMUL) {
8721       // Fold scalars or any vector constants (not just splats).
8722       // This fold is done in general by InstCombine, but extra fmul insts
8723       // may have been generated during lowering.
8724       SDValue N00 = N0.getOperand(0);
8725       SDValue N01 = N0.getOperand(1);
8726       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8727       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8728       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8729 
8730       // Check 1: Make sure that the first operand of the inner multiply is NOT
8731       // a constant. Otherwise, we may induce infinite looping.
8732       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8733         // Check 2: Make sure that the second operand of the inner multiply and
8734         // the second operand of the outer multiply are constants.
8735         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8736             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8737           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8738           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8739         }
8740       }
8741     }
8742 
8743     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8744     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8745     // during an early run of DAGCombiner can prevent folding with fmuls
8746     // inserted during lowering.
8747     if (N0.getOpcode() == ISD::FADD &&
8748         (N0.getOperand(0) == N0.getOperand(1)) &&
8749         N0.hasOneUse()) {
8750       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8751       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8752       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8753     }
8754   }
8755 
8756   // fold (fmul X, 2.0) -> (fadd X, X)
8757   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8758     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8759 
8760   // fold (fmul X, -1.0) -> (fneg X)
8761   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8762     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8763       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8764 
8765   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8766   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8767     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8768       // Both can be negated for free, check to see if at least one is cheaper
8769       // negated.
8770       if (LHSNeg == 2 || RHSNeg == 2)
8771         return DAG.getNode(ISD::FMUL, DL, VT,
8772                            GetNegatedExpression(N0, DAG, LegalOperations),
8773                            GetNegatedExpression(N1, DAG, LegalOperations),
8774                            Flags);
8775     }
8776   }
8777 
8778   // FMUL -> FMA combines:
8779   if (SDValue Fused = visitFMULForFMACombine(N)) {
8780     AddToWorklist(Fused.getNode());
8781     return Fused;
8782   }
8783 
8784   return SDValue();
8785 }
8786 
8787 SDValue DAGCombiner::visitFMA(SDNode *N) {
8788   SDValue N0 = N->getOperand(0);
8789   SDValue N1 = N->getOperand(1);
8790   SDValue N2 = N->getOperand(2);
8791   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8792   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8793   EVT VT = N->getValueType(0);
8794   SDLoc DL(N);
8795   const TargetOptions &Options = DAG.getTarget().Options;
8796 
8797   // Constant fold FMA.
8798   if (isa<ConstantFPSDNode>(N0) &&
8799       isa<ConstantFPSDNode>(N1) &&
8800       isa<ConstantFPSDNode>(N2)) {
8801     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
8802   }
8803 
8804   if (Options.UnsafeFPMath) {
8805     if (N0CFP && N0CFP->isZero())
8806       return N2;
8807     if (N1CFP && N1CFP->isZero())
8808       return N2;
8809   }
8810   // TODO: The FMA node should have flags that propagate to these nodes.
8811   if (N0CFP && N0CFP->isExactlyValue(1.0))
8812     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8813   if (N1CFP && N1CFP->isExactlyValue(1.0))
8814     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8815 
8816   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8817   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8818      !isConstantFPBuildVectorOrConstantFP(N1))
8819     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8820 
8821   // TODO: FMA nodes should have flags that propagate to the created nodes.
8822   // For now, create a Flags object for use with all unsafe math transforms.
8823   SDNodeFlags Flags;
8824   Flags.setUnsafeAlgebra(true);
8825 
8826   if (Options.UnsafeFPMath) {
8827     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8828     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8829         isConstantFPBuildVectorOrConstantFP(N1) &&
8830         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8831       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8832                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
8833                                      &Flags), &Flags);
8834     }
8835 
8836     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8837     if (N0.getOpcode() == ISD::FMUL &&
8838         isConstantFPBuildVectorOrConstantFP(N1) &&
8839         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8840       return DAG.getNode(ISD::FMA, DL, VT,
8841                          N0.getOperand(0),
8842                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
8843                                      &Flags),
8844                          N2);
8845     }
8846   }
8847 
8848   // (fma x, 1, y) -> (fadd x, y)
8849   // (fma x, -1, y) -> (fadd (fneg x), y)
8850   if (N1CFP) {
8851     if (N1CFP->isExactlyValue(1.0))
8852       // TODO: The FMA node should have flags that propagate to this node.
8853       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
8854 
8855     if (N1CFP->isExactlyValue(-1.0) &&
8856         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8857       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
8858       AddToWorklist(RHSNeg.getNode());
8859       // TODO: The FMA node should have flags that propagate to this node.
8860       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
8861     }
8862   }
8863 
8864   if (Options.UnsafeFPMath) {
8865     // (fma x, c, x) -> (fmul x, (c+1))
8866     if (N1CFP && N0 == N2) {
8867       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8868                          DAG.getNode(ISD::FADD, DL, VT, N1,
8869                                      DAG.getConstantFP(1.0, DL, VT), &Flags),
8870                          &Flags);
8871     }
8872 
8873     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8874     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8875       return DAG.getNode(ISD::FMUL, DL, VT, N0,
8876                          DAG.getNode(ISD::FADD, DL, VT, N1,
8877                                      DAG.getConstantFP(-1.0, DL, VT), &Flags),
8878                          &Flags);
8879     }
8880   }
8881 
8882   return SDValue();
8883 }
8884 
8885 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8886 // reciprocal.
8887 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8888 // Notice that this is not always beneficial. One reason is different target
8889 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8890 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8891 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8892 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8893   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8894   const SDNodeFlags *Flags = N->getFlags();
8895   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8896     return SDValue();
8897 
8898   // Skip if current node is a reciprocal.
8899   SDValue N0 = N->getOperand(0);
8900   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8901   if (N0CFP && N0CFP->isExactlyValue(1.0))
8902     return SDValue();
8903 
8904   // Exit early if the target does not want this transform or if there can't
8905   // possibly be enough uses of the divisor to make the transform worthwhile.
8906   SDValue N1 = N->getOperand(1);
8907   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8908   if (!MinUses || N1->use_size() < MinUses)
8909     return SDValue();
8910 
8911   // Find all FDIV users of the same divisor.
8912   // Use a set because duplicates may be present in the user list.
8913   SetVector<SDNode *> Users;
8914   for (auto *U : N1->uses()) {
8915     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8916       // This division is eligible for optimization only if global unsafe math
8917       // is enabled or if this division allows reciprocal formation.
8918       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8919         Users.insert(U);
8920     }
8921   }
8922 
8923   // Now that we have the actual number of divisor uses, make sure it meets
8924   // the minimum threshold specified by the target.
8925   if (Users.size() < MinUses)
8926     return SDValue();
8927 
8928   EVT VT = N->getValueType(0);
8929   SDLoc DL(N);
8930   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8931   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8932 
8933   // Dividend / Divisor -> Dividend * Reciprocal
8934   for (auto *U : Users) {
8935     SDValue Dividend = U->getOperand(0);
8936     if (Dividend != FPOne) {
8937       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8938                                     Reciprocal, Flags);
8939       CombineTo(U, NewNode);
8940     } else if (U != Reciprocal.getNode()) {
8941       // In the absence of fast-math-flags, this user node is always the
8942       // same node as Reciprocal, but with FMF they may be different nodes.
8943       CombineTo(U, Reciprocal);
8944     }
8945   }
8946   return SDValue(N, 0);  // N was replaced.
8947 }
8948 
8949 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8950   SDValue N0 = N->getOperand(0);
8951   SDValue N1 = N->getOperand(1);
8952   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8953   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8954   EVT VT = N->getValueType(0);
8955   SDLoc DL(N);
8956   const TargetOptions &Options = DAG.getTarget().Options;
8957   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8958 
8959   // fold vector ops
8960   if (VT.isVector())
8961     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8962       return FoldedVOp;
8963 
8964   // fold (fdiv c1, c2) -> c1/c2
8965   if (N0CFP && N1CFP)
8966     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8967 
8968   if (Options.UnsafeFPMath) {
8969     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8970     if (N1CFP) {
8971       // Compute the reciprocal 1.0 / c2.
8972       const APFloat &N1APF = N1CFP->getValueAPF();
8973       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8974       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8975       // Only do the transform if the reciprocal is a legal fp immediate that
8976       // isn't too nasty (eg NaN, denormal, ...).
8977       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8978           (!LegalOperations ||
8979            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8980            // backend)... we should handle this gracefully after Legalize.
8981            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8982            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8983            TLI.isFPImmLegal(Recip, VT)))
8984         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8985                            DAG.getConstantFP(Recip, DL, VT), Flags);
8986     }
8987 
8988     // If this FDIV is part of a reciprocal square root, it may be folded
8989     // into a target-specific square root estimate instruction.
8990     if (N1.getOpcode() == ISD::FSQRT) {
8991       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
8992         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8993       }
8994     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8995                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8996       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8997                                           Flags)) {
8998         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8999         AddToWorklist(RV.getNode());
9000         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9001       }
9002     } else if (N1.getOpcode() == ISD::FP_ROUND &&
9003                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9004       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9005                                           Flags)) {
9006         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9007         AddToWorklist(RV.getNode());
9008         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9009       }
9010     } else if (N1.getOpcode() == ISD::FMUL) {
9011       // Look through an FMUL. Even though this won't remove the FDIV directly,
9012       // it's still worthwhile to get rid of the FSQRT if possible.
9013       SDValue SqrtOp;
9014       SDValue OtherOp;
9015       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9016         SqrtOp = N1.getOperand(0);
9017         OtherOp = N1.getOperand(1);
9018       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
9019         SqrtOp = N1.getOperand(1);
9020         OtherOp = N1.getOperand(0);
9021       }
9022       if (SqrtOp.getNode()) {
9023         // We found a FSQRT, so try to make this fold:
9024         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9025         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9026           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9027           AddToWorklist(RV.getNode());
9028           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9029         }
9030       }
9031     }
9032 
9033     // Fold into a reciprocal estimate and multiply instead of a real divide.
9034     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
9035       AddToWorklist(RV.getNode());
9036       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9037     }
9038   }
9039 
9040   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
9041   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9042     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9043       // Both can be negated for free, check to see if at least one is cheaper
9044       // negated.
9045       if (LHSNeg == 2 || RHSNeg == 2)
9046         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
9047                            GetNegatedExpression(N0, DAG, LegalOperations),
9048                            GetNegatedExpression(N1, DAG, LegalOperations),
9049                            Flags);
9050     }
9051   }
9052 
9053   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
9054     return CombineRepeatedDivisors;
9055 
9056   return SDValue();
9057 }
9058 
9059 SDValue DAGCombiner::visitFREM(SDNode *N) {
9060   SDValue N0 = N->getOperand(0);
9061   SDValue N1 = N->getOperand(1);
9062   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9063   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9064   EVT VT = N->getValueType(0);
9065 
9066   // fold (frem c1, c2) -> fmod(c1,c2)
9067   if (N0CFP && N1CFP)
9068     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
9069                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
9070 
9071   return SDValue();
9072 }
9073 
9074 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
9075   if (!DAG.getTarget().Options.UnsafeFPMath)
9076     return SDValue();
9077 
9078   SDValue N0 = N->getOperand(0);
9079   if (TLI.isFsqrtCheap(N0, DAG))
9080     return SDValue();
9081 
9082   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
9083   // For now, create a Flags object for use with all unsafe math transforms.
9084   SDNodeFlags Flags;
9085   Flags.setUnsafeAlgebra(true);
9086   return buildSqrtEstimate(N0, &Flags);
9087 }
9088 
9089 /// copysign(x, fp_extend(y)) -> copysign(x, y)
9090 /// copysign(x, fp_round(y)) -> copysign(x, y)
9091 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9092   SDValue N1 = N->getOperand(1);
9093   if ((N1.getOpcode() == ISD::FP_EXTEND ||
9094        N1.getOpcode() == ISD::FP_ROUND)) {
9095     // Do not optimize out type conversion of f128 type yet.
9096     // For some targets like x86_64, configuration is changed to keep one f128
9097     // value in one SSE register, but instruction selection cannot handle
9098     // FCOPYSIGN on SSE registers yet.
9099     EVT N1VT = N1->getValueType(0);
9100     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9101     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9102   }
9103   return false;
9104 }
9105 
9106 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9107   SDValue N0 = N->getOperand(0);
9108   SDValue N1 = N->getOperand(1);
9109   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9110   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9111   EVT VT = N->getValueType(0);
9112 
9113   if (N0CFP && N1CFP) // Constant fold
9114     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9115 
9116   if (N1CFP) {
9117     const APFloat &V = N1CFP->getValueAPF();
9118     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
9119     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9120     if (!V.isNegative()) {
9121       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9122         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9123     } else {
9124       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9125         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9126                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9127     }
9128   }
9129 
9130   // copysign(fabs(x), y) -> copysign(x, y)
9131   // copysign(fneg(x), y) -> copysign(x, y)
9132   // copysign(copysign(x,z), y) -> copysign(x, y)
9133   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9134       N0.getOpcode() == ISD::FCOPYSIGN)
9135     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9136 
9137   // copysign(x, abs(y)) -> abs(x)
9138   if (N1.getOpcode() == ISD::FABS)
9139     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9140 
9141   // copysign(x, copysign(y,z)) -> copysign(x, z)
9142   if (N1.getOpcode() == ISD::FCOPYSIGN)
9143     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9144 
9145   // copysign(x, fp_extend(y)) -> copysign(x, y)
9146   // copysign(x, fp_round(y)) -> copysign(x, y)
9147   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9148     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9149 
9150   return SDValue();
9151 }
9152 
9153 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9154   SDValue N0 = N->getOperand(0);
9155   EVT VT = N->getValueType(0);
9156   EVT OpVT = N0.getValueType();
9157 
9158   // fold (sint_to_fp c1) -> c1fp
9159   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9160       // ...but only if the target supports immediate floating-point values
9161       (!LegalOperations ||
9162        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9163     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9164 
9165   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9166   // but UINT_TO_FP is legal on this target, try to convert.
9167   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9168       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9169     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9170     if (DAG.SignBitIsZero(N0))
9171       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9172   }
9173 
9174   // The next optimizations are desirable only if SELECT_CC can be lowered.
9175   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9176     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9177     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9178         !VT.isVector() &&
9179         (!LegalOperations ||
9180          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9181       SDLoc DL(N);
9182       SDValue Ops[] =
9183         { N0.getOperand(0), N0.getOperand(1),
9184           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9185           N0.getOperand(2) };
9186       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9187     }
9188 
9189     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9190     //      (select_cc x, y, 1.0, 0.0,, cc)
9191     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9192         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9193         (!LegalOperations ||
9194          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9195       SDLoc DL(N);
9196       SDValue Ops[] =
9197         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9198           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9199           N0.getOperand(0).getOperand(2) };
9200       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9201     }
9202   }
9203 
9204   return SDValue();
9205 }
9206 
9207 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9208   SDValue N0 = N->getOperand(0);
9209   EVT VT = N->getValueType(0);
9210   EVT OpVT = N0.getValueType();
9211 
9212   // fold (uint_to_fp c1) -> c1fp
9213   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9214       // ...but only if the target supports immediate floating-point values
9215       (!LegalOperations ||
9216        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9217     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9218 
9219   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9220   // but SINT_TO_FP is legal on this target, try to convert.
9221   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9222       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9223     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9224     if (DAG.SignBitIsZero(N0))
9225       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9226   }
9227 
9228   // The next optimizations are desirable only if SELECT_CC can be lowered.
9229   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9230     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9231 
9232     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9233         (!LegalOperations ||
9234          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9235       SDLoc DL(N);
9236       SDValue Ops[] =
9237         { N0.getOperand(0), N0.getOperand(1),
9238           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9239           N0.getOperand(2) };
9240       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9241     }
9242   }
9243 
9244   return SDValue();
9245 }
9246 
9247 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9248 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9249   SDValue N0 = N->getOperand(0);
9250   EVT VT = N->getValueType(0);
9251 
9252   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9253     return SDValue();
9254 
9255   SDValue Src = N0.getOperand(0);
9256   EVT SrcVT = Src.getValueType();
9257   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9258   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9259 
9260   // We can safely assume the conversion won't overflow the output range,
9261   // because (for example) (uint8_t)18293.f is undefined behavior.
9262 
9263   // Since we can assume the conversion won't overflow, our decision as to
9264   // whether the input will fit in the float should depend on the minimum
9265   // of the input range and output range.
9266 
9267   // This means this is also safe for a signed input and unsigned output, since
9268   // a negative input would lead to undefined behavior.
9269   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9270   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9271   unsigned ActualSize = std::min(InputSize, OutputSize);
9272   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9273 
9274   // We can only fold away the float conversion if the input range can be
9275   // represented exactly in the float range.
9276   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9277     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9278       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9279                                                        : ISD::ZERO_EXTEND;
9280       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9281     }
9282     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9283       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9284     return DAG.getBitcast(VT, Src);
9285   }
9286   return SDValue();
9287 }
9288 
9289 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9290   SDValue N0 = N->getOperand(0);
9291   EVT VT = N->getValueType(0);
9292 
9293   // fold (fp_to_sint c1fp) -> c1
9294   if (isConstantFPBuildVectorOrConstantFP(N0))
9295     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9296 
9297   return FoldIntToFPToInt(N, DAG);
9298 }
9299 
9300 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9301   SDValue N0 = N->getOperand(0);
9302   EVT VT = N->getValueType(0);
9303 
9304   // fold (fp_to_uint c1fp) -> c1
9305   if (isConstantFPBuildVectorOrConstantFP(N0))
9306     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9307 
9308   return FoldIntToFPToInt(N, DAG);
9309 }
9310 
9311 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9312   SDValue N0 = N->getOperand(0);
9313   SDValue N1 = N->getOperand(1);
9314   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9315   EVT VT = N->getValueType(0);
9316 
9317   // fold (fp_round c1fp) -> c1fp
9318   if (N0CFP)
9319     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9320 
9321   // fold (fp_round (fp_extend x)) -> x
9322   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9323     return N0.getOperand(0);
9324 
9325   // fold (fp_round (fp_round x)) -> (fp_round x)
9326   if (N0.getOpcode() == ISD::FP_ROUND) {
9327     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9328     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9329 
9330     // Skip this folding if it results in an fp_round from f80 to f16.
9331     //
9332     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9333     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9334     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9335     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9336     // x86.
9337     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9338       return SDValue();
9339 
9340     // If the first fp_round isn't a value preserving truncation, it might
9341     // introduce a tie in the second fp_round, that wouldn't occur in the
9342     // single-step fp_round we want to fold to.
9343     // In other words, double rounding isn't the same as rounding.
9344     // Also, this is a value preserving truncation iff both fp_round's are.
9345     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9346       SDLoc DL(N);
9347       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9348                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9349     }
9350   }
9351 
9352   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9353   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9354     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9355                               N0.getOperand(0), N1);
9356     AddToWorklist(Tmp.getNode());
9357     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9358                        Tmp, N0.getOperand(1));
9359   }
9360 
9361   return SDValue();
9362 }
9363 
9364 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9365   SDValue N0 = N->getOperand(0);
9366   EVT VT = N->getValueType(0);
9367   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9368   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9369 
9370   // fold (fp_round_inreg c1fp) -> c1fp
9371   if (N0CFP && isTypeLegal(EVT)) {
9372     SDLoc DL(N);
9373     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9374     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9375   }
9376 
9377   return SDValue();
9378 }
9379 
9380 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9381   SDValue N0 = N->getOperand(0);
9382   EVT VT = N->getValueType(0);
9383 
9384   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9385   if (N->hasOneUse() &&
9386       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9387     return SDValue();
9388 
9389   // fold (fp_extend c1fp) -> c1fp
9390   if (isConstantFPBuildVectorOrConstantFP(N0))
9391     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9392 
9393   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9394   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9395       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9396     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9397 
9398   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9399   // value of X.
9400   if (N0.getOpcode() == ISD::FP_ROUND
9401       && N0.getNode()->getConstantOperandVal(1) == 1) {
9402     SDValue In = N0.getOperand(0);
9403     if (In.getValueType() == VT) return In;
9404     if (VT.bitsLT(In.getValueType()))
9405       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9406                          In, N0.getOperand(1));
9407     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9408   }
9409 
9410   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9411   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9412        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9413     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9414     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9415                                      LN0->getChain(),
9416                                      LN0->getBasePtr(), N0.getValueType(),
9417                                      LN0->getMemOperand());
9418     CombineTo(N, ExtLoad);
9419     CombineTo(N0.getNode(),
9420               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9421                           N0.getValueType(), ExtLoad,
9422                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9423               ExtLoad.getValue(1));
9424     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9425   }
9426 
9427   return SDValue();
9428 }
9429 
9430 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9431   SDValue N0 = N->getOperand(0);
9432   EVT VT = N->getValueType(0);
9433 
9434   // fold (fceil c1) -> fceil(c1)
9435   if (isConstantFPBuildVectorOrConstantFP(N0))
9436     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9437 
9438   return SDValue();
9439 }
9440 
9441 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9442   SDValue N0 = N->getOperand(0);
9443   EVT VT = N->getValueType(0);
9444 
9445   // fold (ftrunc c1) -> ftrunc(c1)
9446   if (isConstantFPBuildVectorOrConstantFP(N0))
9447     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9448 
9449   return SDValue();
9450 }
9451 
9452 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9453   SDValue N0 = N->getOperand(0);
9454   EVT VT = N->getValueType(0);
9455 
9456   // fold (ffloor c1) -> ffloor(c1)
9457   if (isConstantFPBuildVectorOrConstantFP(N0))
9458     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9459 
9460   return SDValue();
9461 }
9462 
9463 // FIXME: FNEG and FABS have a lot in common; refactor.
9464 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9465   SDValue N0 = N->getOperand(0);
9466   EVT VT = N->getValueType(0);
9467 
9468   // Constant fold FNEG.
9469   if (isConstantFPBuildVectorOrConstantFP(N0))
9470     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9471 
9472   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9473                          &DAG.getTarget().Options))
9474     return GetNegatedExpression(N0, DAG, LegalOperations);
9475 
9476   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9477   // constant pool values.
9478   if (!TLI.isFNegFree(VT) &&
9479       N0.getOpcode() == ISD::BITCAST &&
9480       N0.getNode()->hasOneUse()) {
9481     SDValue Int = N0.getOperand(0);
9482     EVT IntVT = Int.getValueType();
9483     if (IntVT.isInteger() && !IntVT.isVector()) {
9484       APInt SignMask;
9485       if (N0.getValueType().isVector()) {
9486         // For a vector, get a mask such as 0x80... per scalar element
9487         // and splat it.
9488         SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits());
9489         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9490       } else {
9491         // For a scalar, just generate 0x80...
9492         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9493       }
9494       SDLoc DL0(N0);
9495       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9496                         DAG.getConstant(SignMask, DL0, IntVT));
9497       AddToWorklist(Int.getNode());
9498       return DAG.getBitcast(VT, Int);
9499     }
9500   }
9501 
9502   // (fneg (fmul c, x)) -> (fmul -c, x)
9503   if (N0.getOpcode() == ISD::FMUL &&
9504       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9505     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9506     if (CFP1) {
9507       APFloat CVal = CFP1->getValueAPF();
9508       CVal.changeSign();
9509       if (Level >= AfterLegalizeDAG &&
9510           (TLI.isFPImmLegal(CVal, VT) ||
9511            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9512         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9513                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9514                                        N0.getOperand(1)),
9515                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9516     }
9517   }
9518 
9519   return SDValue();
9520 }
9521 
9522 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9523   SDValue N0 = N->getOperand(0);
9524   SDValue N1 = N->getOperand(1);
9525   EVT VT = N->getValueType(0);
9526   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9527   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9528 
9529   if (N0CFP && N1CFP) {
9530     const APFloat &C0 = N0CFP->getValueAPF();
9531     const APFloat &C1 = N1CFP->getValueAPF();
9532     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9533   }
9534 
9535   // Canonicalize to constant on RHS.
9536   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9537      !isConstantFPBuildVectorOrConstantFP(N1))
9538     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9539 
9540   return SDValue();
9541 }
9542 
9543 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9544   SDValue N0 = N->getOperand(0);
9545   SDValue N1 = N->getOperand(1);
9546   EVT VT = N->getValueType(0);
9547   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9548   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9549 
9550   if (N0CFP && N1CFP) {
9551     const APFloat &C0 = N0CFP->getValueAPF();
9552     const APFloat &C1 = N1CFP->getValueAPF();
9553     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9554   }
9555 
9556   // Canonicalize to constant on RHS.
9557   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9558      !isConstantFPBuildVectorOrConstantFP(N1))
9559     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9560 
9561   return SDValue();
9562 }
9563 
9564 SDValue DAGCombiner::visitFABS(SDNode *N) {
9565   SDValue N0 = N->getOperand(0);
9566   EVT VT = N->getValueType(0);
9567 
9568   // fold (fabs c1) -> fabs(c1)
9569   if (isConstantFPBuildVectorOrConstantFP(N0))
9570     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9571 
9572   // fold (fabs (fabs x)) -> (fabs x)
9573   if (N0.getOpcode() == ISD::FABS)
9574     return N->getOperand(0);
9575 
9576   // fold (fabs (fneg x)) -> (fabs x)
9577   // fold (fabs (fcopysign x, y)) -> (fabs x)
9578   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9579     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9580 
9581   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9582   // constant pool values.
9583   if (!TLI.isFAbsFree(VT) &&
9584       N0.getOpcode() == ISD::BITCAST &&
9585       N0.getNode()->hasOneUse()) {
9586     SDValue Int = N0.getOperand(0);
9587     EVT IntVT = Int.getValueType();
9588     if (IntVT.isInteger() && !IntVT.isVector()) {
9589       APInt SignMask;
9590       if (N0.getValueType().isVector()) {
9591         // For a vector, get a mask such as 0x7f... per scalar element
9592         // and splat it.
9593         SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits());
9594         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9595       } else {
9596         // For a scalar, just generate 0x7f...
9597         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9598       }
9599       SDLoc DL(N0);
9600       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9601                         DAG.getConstant(SignMask, DL, IntVT));
9602       AddToWorklist(Int.getNode());
9603       return DAG.getBitcast(N->getValueType(0), Int);
9604     }
9605   }
9606 
9607   return SDValue();
9608 }
9609 
9610 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9611   SDValue Chain = N->getOperand(0);
9612   SDValue N1 = N->getOperand(1);
9613   SDValue N2 = N->getOperand(2);
9614 
9615   // If N is a constant we could fold this into a fallthrough or unconditional
9616   // branch. However that doesn't happen very often in normal code, because
9617   // Instcombine/SimplifyCFG should have handled the available opportunities.
9618   // If we did this folding here, it would be necessary to update the
9619   // MachineBasicBlock CFG, which is awkward.
9620 
9621   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9622   // on the target.
9623   if (N1.getOpcode() == ISD::SETCC &&
9624       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9625                                    N1.getOperand(0).getValueType())) {
9626     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9627                        Chain, N1.getOperand(2),
9628                        N1.getOperand(0), N1.getOperand(1), N2);
9629   }
9630 
9631   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9632       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9633        (N1.getOperand(0).hasOneUse() &&
9634         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9635     SDNode *Trunc = nullptr;
9636     if (N1.getOpcode() == ISD::TRUNCATE) {
9637       // Look pass the truncate.
9638       Trunc = N1.getNode();
9639       N1 = N1.getOperand(0);
9640     }
9641 
9642     // Match this pattern so that we can generate simpler code:
9643     //
9644     //   %a = ...
9645     //   %b = and i32 %a, 2
9646     //   %c = srl i32 %b, 1
9647     //   brcond i32 %c ...
9648     //
9649     // into
9650     //
9651     //   %a = ...
9652     //   %b = and i32 %a, 2
9653     //   %c = setcc eq %b, 0
9654     //   brcond %c ...
9655     //
9656     // This applies only when the AND constant value has one bit set and the
9657     // SRL constant is equal to the log2 of the AND constant. The back-end is
9658     // smart enough to convert the result into a TEST/JMP sequence.
9659     SDValue Op0 = N1.getOperand(0);
9660     SDValue Op1 = N1.getOperand(1);
9661 
9662     if (Op0.getOpcode() == ISD::AND &&
9663         Op1.getOpcode() == ISD::Constant) {
9664       SDValue AndOp1 = Op0.getOperand(1);
9665 
9666       if (AndOp1.getOpcode() == ISD::Constant) {
9667         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9668 
9669         if (AndConst.isPowerOf2() &&
9670             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9671           SDLoc DL(N);
9672           SDValue SetCC =
9673             DAG.getSetCC(DL,
9674                          getSetCCResultType(Op0.getValueType()),
9675                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9676                          ISD::SETNE);
9677 
9678           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9679                                           MVT::Other, Chain, SetCC, N2);
9680           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9681           // will convert it back to (X & C1) >> C2.
9682           CombineTo(N, NewBRCond, false);
9683           // Truncate is dead.
9684           if (Trunc)
9685             deleteAndRecombine(Trunc);
9686           // Replace the uses of SRL with SETCC
9687           WorklistRemover DeadNodes(*this);
9688           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9689           deleteAndRecombine(N1.getNode());
9690           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9691         }
9692       }
9693     }
9694 
9695     if (Trunc)
9696       // Restore N1 if the above transformation doesn't match.
9697       N1 = N->getOperand(1);
9698   }
9699 
9700   // Transform br(xor(x, y)) -> br(x != y)
9701   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9702   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9703     SDNode *TheXor = N1.getNode();
9704     SDValue Op0 = TheXor->getOperand(0);
9705     SDValue Op1 = TheXor->getOperand(1);
9706     if (Op0.getOpcode() == Op1.getOpcode()) {
9707       // Avoid missing important xor optimizations.
9708       if (SDValue Tmp = visitXOR(TheXor)) {
9709         if (Tmp.getNode() != TheXor) {
9710           DEBUG(dbgs() << "\nReplacing.8 ";
9711                 TheXor->dump(&DAG);
9712                 dbgs() << "\nWith: ";
9713                 Tmp.getNode()->dump(&DAG);
9714                 dbgs() << '\n');
9715           WorklistRemover DeadNodes(*this);
9716           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9717           deleteAndRecombine(TheXor);
9718           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9719                              MVT::Other, Chain, Tmp, N2);
9720         }
9721 
9722         // visitXOR has changed XOR's operands or replaced the XOR completely,
9723         // bail out.
9724         return SDValue(N, 0);
9725       }
9726     }
9727 
9728     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9729       bool Equal = false;
9730       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9731           Op0.getOpcode() == ISD::XOR) {
9732         TheXor = Op0.getNode();
9733         Equal = true;
9734       }
9735 
9736       EVT SetCCVT = N1.getValueType();
9737       if (LegalTypes)
9738         SetCCVT = getSetCCResultType(SetCCVT);
9739       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9740                                    SetCCVT,
9741                                    Op0, Op1,
9742                                    Equal ? ISD::SETEQ : ISD::SETNE);
9743       // Replace the uses of XOR with SETCC
9744       WorklistRemover DeadNodes(*this);
9745       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9746       deleteAndRecombine(N1.getNode());
9747       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9748                          MVT::Other, Chain, SetCC, N2);
9749     }
9750   }
9751 
9752   return SDValue();
9753 }
9754 
9755 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9756 //
9757 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9758   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9759   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9760 
9761   // If N is a constant we could fold this into a fallthrough or unconditional
9762   // branch. However that doesn't happen very often in normal code, because
9763   // Instcombine/SimplifyCFG should have handled the available opportunities.
9764   // If we did this folding here, it would be necessary to update the
9765   // MachineBasicBlock CFG, which is awkward.
9766 
9767   // Use SimplifySetCC to simplify SETCC's.
9768   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9769                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9770                                false);
9771   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9772 
9773   // fold to a simpler setcc
9774   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9775     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9776                        N->getOperand(0), Simp.getOperand(2),
9777                        Simp.getOperand(0), Simp.getOperand(1),
9778                        N->getOperand(4));
9779 
9780   return SDValue();
9781 }
9782 
9783 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9784 /// and that N may be folded in the load / store addressing mode.
9785 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9786                                     SelectionDAG &DAG,
9787                                     const TargetLowering &TLI) {
9788   EVT VT;
9789   unsigned AS;
9790 
9791   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9792     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9793       return false;
9794     VT = LD->getMemoryVT();
9795     AS = LD->getAddressSpace();
9796   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9797     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9798       return false;
9799     VT = ST->getMemoryVT();
9800     AS = ST->getAddressSpace();
9801   } else
9802     return false;
9803 
9804   TargetLowering::AddrMode AM;
9805   if (N->getOpcode() == ISD::ADD) {
9806     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9807     if (Offset)
9808       // [reg +/- imm]
9809       AM.BaseOffs = Offset->getSExtValue();
9810     else
9811       // [reg +/- reg]
9812       AM.Scale = 1;
9813   } else if (N->getOpcode() == ISD::SUB) {
9814     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9815     if (Offset)
9816       // [reg +/- imm]
9817       AM.BaseOffs = -Offset->getSExtValue();
9818     else
9819       // [reg +/- reg]
9820       AM.Scale = 1;
9821   } else
9822     return false;
9823 
9824   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9825                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9826 }
9827 
9828 /// Try turning a load/store into a pre-indexed load/store when the base
9829 /// pointer is an add or subtract and it has other uses besides the load/store.
9830 /// After the transformation, the new indexed load/store has effectively folded
9831 /// the add/subtract in and all of its other uses are redirected to the
9832 /// new load/store.
9833 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9834   if (Level < AfterLegalizeDAG)
9835     return false;
9836 
9837   bool isLoad = true;
9838   SDValue Ptr;
9839   EVT VT;
9840   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9841     if (LD->isIndexed())
9842       return false;
9843     VT = LD->getMemoryVT();
9844     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9845         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9846       return false;
9847     Ptr = LD->getBasePtr();
9848   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9849     if (ST->isIndexed())
9850       return false;
9851     VT = ST->getMemoryVT();
9852     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9853         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9854       return false;
9855     Ptr = ST->getBasePtr();
9856     isLoad = false;
9857   } else {
9858     return false;
9859   }
9860 
9861   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9862   // out.  There is no reason to make this a preinc/predec.
9863   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9864       Ptr.getNode()->hasOneUse())
9865     return false;
9866 
9867   // Ask the target to do addressing mode selection.
9868   SDValue BasePtr;
9869   SDValue Offset;
9870   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9871   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9872     return false;
9873 
9874   // Backends without true r+i pre-indexed forms may need to pass a
9875   // constant base with a variable offset so that constant coercion
9876   // will work with the patterns in canonical form.
9877   bool Swapped = false;
9878   if (isa<ConstantSDNode>(BasePtr)) {
9879     std::swap(BasePtr, Offset);
9880     Swapped = true;
9881   }
9882 
9883   // Don't create a indexed load / store with zero offset.
9884   if (isNullConstant(Offset))
9885     return false;
9886 
9887   // Try turning it into a pre-indexed load / store except when:
9888   // 1) The new base ptr is a frame index.
9889   // 2) If N is a store and the new base ptr is either the same as or is a
9890   //    predecessor of the value being stored.
9891   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9892   //    that would create a cycle.
9893   // 4) All uses are load / store ops that use it as old base ptr.
9894 
9895   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9896   // (plus the implicit offset) to a register to preinc anyway.
9897   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9898     return false;
9899 
9900   // Check #2.
9901   if (!isLoad) {
9902     SDValue Val = cast<StoreSDNode>(N)->getValue();
9903     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9904       return false;
9905   }
9906 
9907   // Caches for hasPredecessorHelper.
9908   SmallPtrSet<const SDNode *, 32> Visited;
9909   SmallVector<const SDNode *, 16> Worklist;
9910   Worklist.push_back(N);
9911 
9912   // If the offset is a constant, there may be other adds of constants that
9913   // can be folded with this one. We should do this to avoid having to keep
9914   // a copy of the original base pointer.
9915   SmallVector<SDNode *, 16> OtherUses;
9916   if (isa<ConstantSDNode>(Offset))
9917     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9918                               UE = BasePtr.getNode()->use_end();
9919          UI != UE; ++UI) {
9920       SDUse &Use = UI.getUse();
9921       // Skip the use that is Ptr and uses of other results from BasePtr's
9922       // node (important for nodes that return multiple results).
9923       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9924         continue;
9925 
9926       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9927         continue;
9928 
9929       if (Use.getUser()->getOpcode() != ISD::ADD &&
9930           Use.getUser()->getOpcode() != ISD::SUB) {
9931         OtherUses.clear();
9932         break;
9933       }
9934 
9935       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9936       if (!isa<ConstantSDNode>(Op1)) {
9937         OtherUses.clear();
9938         break;
9939       }
9940 
9941       // FIXME: In some cases, we can be smarter about this.
9942       if (Op1.getValueType() != Offset.getValueType()) {
9943         OtherUses.clear();
9944         break;
9945       }
9946 
9947       OtherUses.push_back(Use.getUser());
9948     }
9949 
9950   if (Swapped)
9951     std::swap(BasePtr, Offset);
9952 
9953   // Now check for #3 and #4.
9954   bool RealUse = false;
9955 
9956   for (SDNode *Use : Ptr.getNode()->uses()) {
9957     if (Use == N)
9958       continue;
9959     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9960       return false;
9961 
9962     // If Ptr may be folded in addressing mode of other use, then it's
9963     // not profitable to do this transformation.
9964     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9965       RealUse = true;
9966   }
9967 
9968   if (!RealUse)
9969     return false;
9970 
9971   SDValue Result;
9972   if (isLoad)
9973     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9974                                 BasePtr, Offset, AM);
9975   else
9976     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9977                                  BasePtr, Offset, AM);
9978   ++PreIndexedNodes;
9979   ++NodesCombined;
9980   DEBUG(dbgs() << "\nReplacing.4 ";
9981         N->dump(&DAG);
9982         dbgs() << "\nWith: ";
9983         Result.getNode()->dump(&DAG);
9984         dbgs() << '\n');
9985   WorklistRemover DeadNodes(*this);
9986   if (isLoad) {
9987     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9988     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9989   } else {
9990     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9991   }
9992 
9993   // Finally, since the node is now dead, remove it from the graph.
9994   deleteAndRecombine(N);
9995 
9996   if (Swapped)
9997     std::swap(BasePtr, Offset);
9998 
9999   // Replace other uses of BasePtr that can be updated to use Ptr
10000   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
10001     unsigned OffsetIdx = 1;
10002     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
10003       OffsetIdx = 0;
10004     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
10005            BasePtr.getNode() && "Expected BasePtr operand");
10006 
10007     // We need to replace ptr0 in the following expression:
10008     //   x0 * offset0 + y0 * ptr0 = t0
10009     // knowing that
10010     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
10011     //
10012     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
10013     // indexed load/store and the expresion that needs to be re-written.
10014     //
10015     // Therefore, we have:
10016     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
10017 
10018     ConstantSDNode *CN =
10019       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
10020     int X0, X1, Y0, Y1;
10021     const APInt &Offset0 = CN->getAPIntValue();
10022     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
10023 
10024     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
10025     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
10026     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
10027     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
10028 
10029     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
10030 
10031     APInt CNV = Offset0;
10032     if (X0 < 0) CNV = -CNV;
10033     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
10034     else CNV = CNV - Offset1;
10035 
10036     SDLoc DL(OtherUses[i]);
10037 
10038     // We can now generate the new expression.
10039     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
10040     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
10041 
10042     SDValue NewUse = DAG.getNode(Opcode,
10043                                  DL,
10044                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
10045     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
10046     deleteAndRecombine(OtherUses[i]);
10047   }
10048 
10049   // Replace the uses of Ptr with uses of the updated base value.
10050   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
10051   deleteAndRecombine(Ptr.getNode());
10052 
10053   return true;
10054 }
10055 
10056 /// Try to combine a load/store with a add/sub of the base pointer node into a
10057 /// post-indexed load/store. The transformation folded the add/subtract into the
10058 /// new indexed load/store effectively and all of its uses are redirected to the
10059 /// new load/store.
10060 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
10061   if (Level < AfterLegalizeDAG)
10062     return false;
10063 
10064   bool isLoad = true;
10065   SDValue Ptr;
10066   EVT VT;
10067   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
10068     if (LD->isIndexed())
10069       return false;
10070     VT = LD->getMemoryVT();
10071     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
10072         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
10073       return false;
10074     Ptr = LD->getBasePtr();
10075   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
10076     if (ST->isIndexed())
10077       return false;
10078     VT = ST->getMemoryVT();
10079     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
10080         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
10081       return false;
10082     Ptr = ST->getBasePtr();
10083     isLoad = false;
10084   } else {
10085     return false;
10086   }
10087 
10088   if (Ptr.getNode()->hasOneUse())
10089     return false;
10090 
10091   for (SDNode *Op : Ptr.getNode()->uses()) {
10092     if (Op == N ||
10093         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10094       continue;
10095 
10096     SDValue BasePtr;
10097     SDValue Offset;
10098     ISD::MemIndexedMode AM = ISD::UNINDEXED;
10099     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10100       // Don't create a indexed load / store with zero offset.
10101       if (isNullConstant(Offset))
10102         continue;
10103 
10104       // Try turning it into a post-indexed load / store except when
10105       // 1) All uses are load / store ops that use it as base ptr (and
10106       //    it may be folded as addressing mmode).
10107       // 2) Op must be independent of N, i.e. Op is neither a predecessor
10108       //    nor a successor of N. Otherwise, if Op is folded that would
10109       //    create a cycle.
10110 
10111       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10112         continue;
10113 
10114       // Check for #1.
10115       bool TryNext = false;
10116       for (SDNode *Use : BasePtr.getNode()->uses()) {
10117         if (Use == Ptr.getNode())
10118           continue;
10119 
10120         // If all the uses are load / store addresses, then don't do the
10121         // transformation.
10122         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10123           bool RealUse = false;
10124           for (SDNode *UseUse : Use->uses()) {
10125             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10126               RealUse = true;
10127           }
10128 
10129           if (!RealUse) {
10130             TryNext = true;
10131             break;
10132           }
10133         }
10134       }
10135 
10136       if (TryNext)
10137         continue;
10138 
10139       // Check for #2
10140       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10141         SDValue Result = isLoad
10142           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10143                                BasePtr, Offset, AM)
10144           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10145                                 BasePtr, Offset, AM);
10146         ++PostIndexedNodes;
10147         ++NodesCombined;
10148         DEBUG(dbgs() << "\nReplacing.5 ";
10149               N->dump(&DAG);
10150               dbgs() << "\nWith: ";
10151               Result.getNode()->dump(&DAG);
10152               dbgs() << '\n');
10153         WorklistRemover DeadNodes(*this);
10154         if (isLoad) {
10155           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10156           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10157         } else {
10158           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10159         }
10160 
10161         // Finally, since the node is now dead, remove it from the graph.
10162         deleteAndRecombine(N);
10163 
10164         // Replace the uses of Use with uses of the updated base value.
10165         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10166                                       Result.getValue(isLoad ? 1 : 0));
10167         deleteAndRecombine(Op);
10168         return true;
10169       }
10170     }
10171   }
10172 
10173   return false;
10174 }
10175 
10176 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10177 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10178   ISD::MemIndexedMode AM = LD->getAddressingMode();
10179   assert(AM != ISD::UNINDEXED);
10180   SDValue BP = LD->getOperand(1);
10181   SDValue Inc = LD->getOperand(2);
10182 
10183   // Some backends use TargetConstants for load offsets, but don't expect
10184   // TargetConstants in general ADD nodes. We can convert these constants into
10185   // regular Constants (if the constant is not opaque).
10186   assert((Inc.getOpcode() != ISD::TargetConstant ||
10187           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10188          "Cannot split out indexing using opaque target constants");
10189   if (Inc.getOpcode() == ISD::TargetConstant) {
10190     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10191     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10192                           ConstInc->getValueType(0));
10193   }
10194 
10195   unsigned Opc =
10196       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10197   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10198 }
10199 
10200 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10201   LoadSDNode *LD  = cast<LoadSDNode>(N);
10202   SDValue Chain = LD->getChain();
10203   SDValue Ptr   = LD->getBasePtr();
10204 
10205   // If load is not volatile and there are no uses of the loaded value (and
10206   // the updated indexed value in case of indexed loads), change uses of the
10207   // chain value into uses of the chain input (i.e. delete the dead load).
10208   if (!LD->isVolatile()) {
10209     if (N->getValueType(1) == MVT::Other) {
10210       // Unindexed loads.
10211       if (!N->hasAnyUseOfValue(0)) {
10212         // It's not safe to use the two value CombineTo variant here. e.g.
10213         // v1, chain2 = load chain1, loc
10214         // v2, chain3 = load chain2, loc
10215         // v3         = add v2, c
10216         // Now we replace use of chain2 with chain1.  This makes the second load
10217         // isomorphic to the one we are deleting, and thus makes this load live.
10218         DEBUG(dbgs() << "\nReplacing.6 ";
10219               N->dump(&DAG);
10220               dbgs() << "\nWith chain: ";
10221               Chain.getNode()->dump(&DAG);
10222               dbgs() << "\n");
10223         WorklistRemover DeadNodes(*this);
10224         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10225 
10226         if (N->use_empty())
10227           deleteAndRecombine(N);
10228 
10229         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10230       }
10231     } else {
10232       // Indexed loads.
10233       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10234 
10235       // If this load has an opaque TargetConstant offset, then we cannot split
10236       // the indexing into an add/sub directly (that TargetConstant may not be
10237       // valid for a different type of node, and we cannot convert an opaque
10238       // target constant into a regular constant).
10239       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10240                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10241 
10242       if (!N->hasAnyUseOfValue(0) &&
10243           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10244         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10245         SDValue Index;
10246         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10247           Index = SplitIndexingFromLoad(LD);
10248           // Try to fold the base pointer arithmetic into subsequent loads and
10249           // stores.
10250           AddUsersToWorklist(N);
10251         } else
10252           Index = DAG.getUNDEF(N->getValueType(1));
10253         DEBUG(dbgs() << "\nReplacing.7 ";
10254               N->dump(&DAG);
10255               dbgs() << "\nWith: ";
10256               Undef.getNode()->dump(&DAG);
10257               dbgs() << " and 2 other values\n");
10258         WorklistRemover DeadNodes(*this);
10259         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10260         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10261         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10262         deleteAndRecombine(N);
10263         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10264       }
10265     }
10266   }
10267 
10268   // If this load is directly stored, replace the load value with the stored
10269   // value.
10270   // TODO: Handle store large -> read small portion.
10271   // TODO: Handle TRUNCSTORE/LOADEXT
10272   if (OptLevel != CodeGenOpt::None &&
10273       ISD::isNormalLoad(N) && !LD->isVolatile()) {
10274     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10275       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10276       if (PrevST->getBasePtr() == Ptr &&
10277           PrevST->getValue().getValueType() == N->getValueType(0))
10278       return CombineTo(N, Chain.getOperand(1), Chain);
10279     }
10280   }
10281 
10282   // Try to infer better alignment information than the load already has.
10283   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10284     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10285       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10286         SDValue NewLoad = DAG.getExtLoad(
10287             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
10288             LD->getPointerInfo(), LD->getMemoryVT(), Align,
10289             LD->getMemOperand()->getFlags(), LD->getAAInfo());
10290         if (NewLoad.getNode() != N)
10291           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10292       }
10293     }
10294   }
10295 
10296   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10297                                                   : DAG.getSubtarget().useAA();
10298 #ifndef NDEBUG
10299   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10300       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10301     UseAA = false;
10302 #endif
10303   if (UseAA && LD->isUnindexed()) {
10304     // Walk up chain skipping non-aliasing memory nodes.
10305     SDValue BetterChain = FindBetterChain(N, Chain);
10306 
10307     // If there is a better chain.
10308     if (Chain != BetterChain) {
10309       SDValue ReplLoad;
10310 
10311       // Replace the chain to void dependency.
10312       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10313         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10314                                BetterChain, Ptr, LD->getMemOperand());
10315       } else {
10316         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10317                                   LD->getValueType(0),
10318                                   BetterChain, Ptr, LD->getMemoryVT(),
10319                                   LD->getMemOperand());
10320       }
10321 
10322       // Create token factor to keep old chain connected.
10323       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10324                                   MVT::Other, Chain, ReplLoad.getValue(1));
10325 
10326       // Make sure the new and old chains are cleaned up.
10327       AddToWorklist(Token.getNode());
10328 
10329       // Replace uses with load result and token factor. Don't add users
10330       // to work list.
10331       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10332     }
10333   }
10334 
10335   // Try transforming N to an indexed load.
10336   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10337     return SDValue(N, 0);
10338 
10339   // Try to slice up N to more direct loads if the slices are mapped to
10340   // different register banks or pairing can take place.
10341   if (SliceUpLoad(N))
10342     return SDValue(N, 0);
10343 
10344   return SDValue();
10345 }
10346 
10347 namespace {
10348 /// \brief Helper structure used to slice a load in smaller loads.
10349 /// Basically a slice is obtained from the following sequence:
10350 /// Origin = load Ty1, Base
10351 /// Shift = srl Ty1 Origin, CstTy Amount
10352 /// Inst = trunc Shift to Ty2
10353 ///
10354 /// Then, it will be rewriten into:
10355 /// Slice = load SliceTy, Base + SliceOffset
10356 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10357 ///
10358 /// SliceTy is deduced from the number of bits that are actually used to
10359 /// build Inst.
10360 struct LoadedSlice {
10361   /// \brief Helper structure used to compute the cost of a slice.
10362   struct Cost {
10363     /// Are we optimizing for code size.
10364     bool ForCodeSize;
10365     /// Various cost.
10366     unsigned Loads;
10367     unsigned Truncates;
10368     unsigned CrossRegisterBanksCopies;
10369     unsigned ZExts;
10370     unsigned Shift;
10371 
10372     Cost(bool ForCodeSize = false)
10373         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10374           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10375 
10376     /// \brief Get the cost of one isolated slice.
10377     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10378         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10379           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10380       EVT TruncType = LS.Inst->getValueType(0);
10381       EVT LoadedType = LS.getLoadedType();
10382       if (TruncType != LoadedType &&
10383           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10384         ZExts = 1;
10385     }
10386 
10387     /// \brief Account for slicing gain in the current cost.
10388     /// Slicing provide a few gains like removing a shift or a
10389     /// truncate. This method allows to grow the cost of the original
10390     /// load with the gain from this slice.
10391     void addSliceGain(const LoadedSlice &LS) {
10392       // Each slice saves a truncate.
10393       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10394       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10395                               LS.Inst->getValueType(0)))
10396         ++Truncates;
10397       // If there is a shift amount, this slice gets rid of it.
10398       if (LS.Shift)
10399         ++Shift;
10400       // If this slice can merge a cross register bank copy, account for it.
10401       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10402         ++CrossRegisterBanksCopies;
10403     }
10404 
10405     Cost &operator+=(const Cost &RHS) {
10406       Loads += RHS.Loads;
10407       Truncates += RHS.Truncates;
10408       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10409       ZExts += RHS.ZExts;
10410       Shift += RHS.Shift;
10411       return *this;
10412     }
10413 
10414     bool operator==(const Cost &RHS) const {
10415       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10416              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10417              ZExts == RHS.ZExts && Shift == RHS.Shift;
10418     }
10419 
10420     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10421 
10422     bool operator<(const Cost &RHS) const {
10423       // Assume cross register banks copies are as expensive as loads.
10424       // FIXME: Do we want some more target hooks?
10425       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10426       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10427       // Unless we are optimizing for code size, consider the
10428       // expensive operation first.
10429       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10430         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10431       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10432              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10433     }
10434 
10435     bool operator>(const Cost &RHS) const { return RHS < *this; }
10436 
10437     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10438 
10439     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10440   };
10441   // The last instruction that represent the slice. This should be a
10442   // truncate instruction.
10443   SDNode *Inst;
10444   // The original load instruction.
10445   LoadSDNode *Origin;
10446   // The right shift amount in bits from the original load.
10447   unsigned Shift;
10448   // The DAG from which Origin came from.
10449   // This is used to get some contextual information about legal types, etc.
10450   SelectionDAG *DAG;
10451 
10452   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10453               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10454       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10455 
10456   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10457   /// \return Result is \p BitWidth and has used bits set to 1 and
10458   ///         not used bits set to 0.
10459   APInt getUsedBits() const {
10460     // Reproduce the trunc(lshr) sequence:
10461     // - Start from the truncated value.
10462     // - Zero extend to the desired bit width.
10463     // - Shift left.
10464     assert(Origin && "No original load to compare against.");
10465     unsigned BitWidth = Origin->getValueSizeInBits(0);
10466     assert(Inst && "This slice is not bound to an instruction");
10467     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10468            "Extracted slice is bigger than the whole type!");
10469     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10470     UsedBits.setAllBits();
10471     UsedBits = UsedBits.zext(BitWidth);
10472     UsedBits <<= Shift;
10473     return UsedBits;
10474   }
10475 
10476   /// \brief Get the size of the slice to be loaded in bytes.
10477   unsigned getLoadedSize() const {
10478     unsigned SliceSize = getUsedBits().countPopulation();
10479     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10480     return SliceSize / 8;
10481   }
10482 
10483   /// \brief Get the type that will be loaded for this slice.
10484   /// Note: This may not be the final type for the slice.
10485   EVT getLoadedType() const {
10486     assert(DAG && "Missing context");
10487     LLVMContext &Ctxt = *DAG->getContext();
10488     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10489   }
10490 
10491   /// \brief Get the alignment of the load used for this slice.
10492   unsigned getAlignment() const {
10493     unsigned Alignment = Origin->getAlignment();
10494     unsigned Offset = getOffsetFromBase();
10495     if (Offset != 0)
10496       Alignment = MinAlign(Alignment, Alignment + Offset);
10497     return Alignment;
10498   }
10499 
10500   /// \brief Check if this slice can be rewritten with legal operations.
10501   bool isLegal() const {
10502     // An invalid slice is not legal.
10503     if (!Origin || !Inst || !DAG)
10504       return false;
10505 
10506     // Offsets are for indexed load only, we do not handle that.
10507     if (!Origin->getOffset().isUndef())
10508       return false;
10509 
10510     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10511 
10512     // Check that the type is legal.
10513     EVT SliceType = getLoadedType();
10514     if (!TLI.isTypeLegal(SliceType))
10515       return false;
10516 
10517     // Check that the load is legal for this type.
10518     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10519       return false;
10520 
10521     // Check that the offset can be computed.
10522     // 1. Check its type.
10523     EVT PtrType = Origin->getBasePtr().getValueType();
10524     if (PtrType == MVT::Untyped || PtrType.isExtended())
10525       return false;
10526 
10527     // 2. Check that it fits in the immediate.
10528     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10529       return false;
10530 
10531     // 3. Check that the computation is legal.
10532     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10533       return false;
10534 
10535     // Check that the zext is legal if it needs one.
10536     EVT TruncateType = Inst->getValueType(0);
10537     if (TruncateType != SliceType &&
10538         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10539       return false;
10540 
10541     return true;
10542   }
10543 
10544   /// \brief Get the offset in bytes of this slice in the original chunk of
10545   /// bits.
10546   /// \pre DAG != nullptr.
10547   uint64_t getOffsetFromBase() const {
10548     assert(DAG && "Missing context.");
10549     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10550     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10551     uint64_t Offset = Shift / 8;
10552     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10553     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10554            "The size of the original loaded type is not a multiple of a"
10555            " byte.");
10556     // If Offset is bigger than TySizeInBytes, it means we are loading all
10557     // zeros. This should have been optimized before in the process.
10558     assert(TySizeInBytes > Offset &&
10559            "Invalid shift amount for given loaded size");
10560     if (IsBigEndian)
10561       Offset = TySizeInBytes - Offset - getLoadedSize();
10562     return Offset;
10563   }
10564 
10565   /// \brief Generate the sequence of instructions to load the slice
10566   /// represented by this object and redirect the uses of this slice to
10567   /// this new sequence of instructions.
10568   /// \pre this->Inst && this->Origin are valid Instructions and this
10569   /// object passed the legal check: LoadedSlice::isLegal returned true.
10570   /// \return The last instruction of the sequence used to load the slice.
10571   SDValue loadSlice() const {
10572     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10573     const SDValue &OldBaseAddr = Origin->getBasePtr();
10574     SDValue BaseAddr = OldBaseAddr;
10575     // Get the offset in that chunk of bytes w.r.t. the endianess.
10576     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10577     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10578     if (Offset) {
10579       // BaseAddr = BaseAddr + Offset.
10580       EVT ArithType = BaseAddr.getValueType();
10581       SDLoc DL(Origin);
10582       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10583                               DAG->getConstant(Offset, DL, ArithType));
10584     }
10585 
10586     // Create the type of the loaded slice according to its size.
10587     EVT SliceType = getLoadedType();
10588 
10589     // Create the load for the slice.
10590     SDValue LastInst =
10591         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10592                      Origin->getPointerInfo().getWithOffset(Offset),
10593                      getAlignment(), Origin->getMemOperand()->getFlags());
10594     // If the final type is not the same as the loaded type, this means that
10595     // we have to pad with zero. Create a zero extend for that.
10596     EVT FinalType = Inst->getValueType(0);
10597     if (SliceType != FinalType)
10598       LastInst =
10599           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10600     return LastInst;
10601   }
10602 
10603   /// \brief Check if this slice can be merged with an expensive cross register
10604   /// bank copy. E.g.,
10605   /// i = load i32
10606   /// f = bitcast i32 i to float
10607   bool canMergeExpensiveCrossRegisterBankCopy() const {
10608     if (!Inst || !Inst->hasOneUse())
10609       return false;
10610     SDNode *Use = *Inst->use_begin();
10611     if (Use->getOpcode() != ISD::BITCAST)
10612       return false;
10613     assert(DAG && "Missing context");
10614     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10615     EVT ResVT = Use->getValueType(0);
10616     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10617     const TargetRegisterClass *ArgRC =
10618         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10619     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10620       return false;
10621 
10622     // At this point, we know that we perform a cross-register-bank copy.
10623     // Check if it is expensive.
10624     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10625     // Assume bitcasts are cheap, unless both register classes do not
10626     // explicitly share a common sub class.
10627     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10628       return false;
10629 
10630     // Check if it will be merged with the load.
10631     // 1. Check the alignment constraint.
10632     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10633         ResVT.getTypeForEVT(*DAG->getContext()));
10634 
10635     if (RequiredAlignment > getAlignment())
10636       return false;
10637 
10638     // 2. Check that the load is a legal operation for that type.
10639     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10640       return false;
10641 
10642     // 3. Check that we do not have a zext in the way.
10643     if (Inst->getValueType(0) != getLoadedType())
10644       return false;
10645 
10646     return true;
10647   }
10648 };
10649 }
10650 
10651 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10652 /// \p UsedBits looks like 0..0 1..1 0..0.
10653 static bool areUsedBitsDense(const APInt &UsedBits) {
10654   // If all the bits are one, this is dense!
10655   if (UsedBits.isAllOnesValue())
10656     return true;
10657 
10658   // Get rid of the unused bits on the right.
10659   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10660   // Get rid of the unused bits on the left.
10661   if (NarrowedUsedBits.countLeadingZeros())
10662     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10663   // Check that the chunk of bits is completely used.
10664   return NarrowedUsedBits.isAllOnesValue();
10665 }
10666 
10667 /// \brief Check whether or not \p First and \p Second are next to each other
10668 /// in memory. This means that there is no hole between the bits loaded
10669 /// by \p First and the bits loaded by \p Second.
10670 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10671                                      const LoadedSlice &Second) {
10672   assert(First.Origin == Second.Origin && First.Origin &&
10673          "Unable to match different memory origins.");
10674   APInt UsedBits = First.getUsedBits();
10675   assert((UsedBits & Second.getUsedBits()) == 0 &&
10676          "Slices are not supposed to overlap.");
10677   UsedBits |= Second.getUsedBits();
10678   return areUsedBitsDense(UsedBits);
10679 }
10680 
10681 /// \brief Adjust the \p GlobalLSCost according to the target
10682 /// paring capabilities and the layout of the slices.
10683 /// \pre \p GlobalLSCost should account for at least as many loads as
10684 /// there is in the slices in \p LoadedSlices.
10685 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10686                                  LoadedSlice::Cost &GlobalLSCost) {
10687   unsigned NumberOfSlices = LoadedSlices.size();
10688   // If there is less than 2 elements, no pairing is possible.
10689   if (NumberOfSlices < 2)
10690     return;
10691 
10692   // Sort the slices so that elements that are likely to be next to each
10693   // other in memory are next to each other in the list.
10694   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10695             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10696     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10697     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10698   });
10699   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10700   // First (resp. Second) is the first (resp. Second) potentially candidate
10701   // to be placed in a paired load.
10702   const LoadedSlice *First = nullptr;
10703   const LoadedSlice *Second = nullptr;
10704   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10705                 // Set the beginning of the pair.
10706                                                            First = Second) {
10707 
10708     Second = &LoadedSlices[CurrSlice];
10709 
10710     // If First is NULL, it means we start a new pair.
10711     // Get to the next slice.
10712     if (!First)
10713       continue;
10714 
10715     EVT LoadedType = First->getLoadedType();
10716 
10717     // If the types of the slices are different, we cannot pair them.
10718     if (LoadedType != Second->getLoadedType())
10719       continue;
10720 
10721     // Check if the target supplies paired loads for this type.
10722     unsigned RequiredAlignment = 0;
10723     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10724       // move to the next pair, this type is hopeless.
10725       Second = nullptr;
10726       continue;
10727     }
10728     // Check if we meet the alignment requirement.
10729     if (RequiredAlignment > First->getAlignment())
10730       continue;
10731 
10732     // Check that both loads are next to each other in memory.
10733     if (!areSlicesNextToEachOther(*First, *Second))
10734       continue;
10735 
10736     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10737     --GlobalLSCost.Loads;
10738     // Move to the next pair.
10739     Second = nullptr;
10740   }
10741 }
10742 
10743 /// \brief Check the profitability of all involved LoadedSlice.
10744 /// Currently, it is considered profitable if there is exactly two
10745 /// involved slices (1) which are (2) next to each other in memory, and
10746 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10747 ///
10748 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10749 /// the elements themselves.
10750 ///
10751 /// FIXME: When the cost model will be mature enough, we can relax
10752 /// constraints (1) and (2).
10753 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10754                                 const APInt &UsedBits, bool ForCodeSize) {
10755   unsigned NumberOfSlices = LoadedSlices.size();
10756   if (StressLoadSlicing)
10757     return NumberOfSlices > 1;
10758 
10759   // Check (1).
10760   if (NumberOfSlices != 2)
10761     return false;
10762 
10763   // Check (2).
10764   if (!areUsedBitsDense(UsedBits))
10765     return false;
10766 
10767   // Check (3).
10768   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10769   // The original code has one big load.
10770   OrigCost.Loads = 1;
10771   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10772     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10773     // Accumulate the cost of all the slices.
10774     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10775     GlobalSlicingCost += SliceCost;
10776 
10777     // Account as cost in the original configuration the gain obtained
10778     // with the current slices.
10779     OrigCost.addSliceGain(LS);
10780   }
10781 
10782   // If the target supports paired load, adjust the cost accordingly.
10783   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10784   return OrigCost > GlobalSlicingCost;
10785 }
10786 
10787 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10788 /// operations, split it in the various pieces being extracted.
10789 ///
10790 /// This sort of thing is introduced by SROA.
10791 /// This slicing takes care not to insert overlapping loads.
10792 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10793 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10794   if (Level < AfterLegalizeDAG)
10795     return false;
10796 
10797   LoadSDNode *LD = cast<LoadSDNode>(N);
10798   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10799       !LD->getValueType(0).isInteger())
10800     return false;
10801 
10802   // Keep track of already used bits to detect overlapping values.
10803   // In that case, we will just abort the transformation.
10804   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10805 
10806   SmallVector<LoadedSlice, 4> LoadedSlices;
10807 
10808   // Check if this load is used as several smaller chunks of bits.
10809   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10810   // of computation for each trunc.
10811   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10812        UI != UIEnd; ++UI) {
10813     // Skip the uses of the chain.
10814     if (UI.getUse().getResNo() != 0)
10815       continue;
10816 
10817     SDNode *User = *UI;
10818     unsigned Shift = 0;
10819 
10820     // Check if this is a trunc(lshr).
10821     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10822         isa<ConstantSDNode>(User->getOperand(1))) {
10823       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10824       User = *User->use_begin();
10825     }
10826 
10827     // At this point, User is a Truncate, iff we encountered, trunc or
10828     // trunc(lshr).
10829     if (User->getOpcode() != ISD::TRUNCATE)
10830       return false;
10831 
10832     // The width of the type must be a power of 2 and greater than 8-bits.
10833     // Otherwise the load cannot be represented in LLVM IR.
10834     // Moreover, if we shifted with a non-8-bits multiple, the slice
10835     // will be across several bytes. We do not support that.
10836     unsigned Width = User->getValueSizeInBits(0);
10837     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10838       return 0;
10839 
10840     // Build the slice for this chain of computations.
10841     LoadedSlice LS(User, LD, Shift, &DAG);
10842     APInt CurrentUsedBits = LS.getUsedBits();
10843 
10844     // Check if this slice overlaps with another.
10845     if ((CurrentUsedBits & UsedBits) != 0)
10846       return false;
10847     // Update the bits used globally.
10848     UsedBits |= CurrentUsedBits;
10849 
10850     // Check if the new slice would be legal.
10851     if (!LS.isLegal())
10852       return false;
10853 
10854     // Record the slice.
10855     LoadedSlices.push_back(LS);
10856   }
10857 
10858   // Abort slicing if it does not seem to be profitable.
10859   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10860     return false;
10861 
10862   ++SlicedLoads;
10863 
10864   // Rewrite each chain to use an independent load.
10865   // By construction, each chain can be represented by a unique load.
10866 
10867   // Prepare the argument for the new token factor for all the slices.
10868   SmallVector<SDValue, 8> ArgChains;
10869   for (SmallVectorImpl<LoadedSlice>::const_iterator
10870            LSIt = LoadedSlices.begin(),
10871            LSItEnd = LoadedSlices.end();
10872        LSIt != LSItEnd; ++LSIt) {
10873     SDValue SliceInst = LSIt->loadSlice();
10874     CombineTo(LSIt->Inst, SliceInst, true);
10875     if (SliceInst.getOpcode() != ISD::LOAD)
10876       SliceInst = SliceInst.getOperand(0);
10877     assert(SliceInst->getOpcode() == ISD::LOAD &&
10878            "It takes more than a zext to get to the loaded slice!!");
10879     ArgChains.push_back(SliceInst.getValue(1));
10880   }
10881 
10882   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10883                               ArgChains);
10884   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10885   return true;
10886 }
10887 
10888 /// Check to see if V is (and load (ptr), imm), where the load is having
10889 /// specific bytes cleared out.  If so, return the byte size being masked out
10890 /// and the shift amount.
10891 static std::pair<unsigned, unsigned>
10892 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10893   std::pair<unsigned, unsigned> Result(0, 0);
10894 
10895   // Check for the structure we're looking for.
10896   if (V->getOpcode() != ISD::AND ||
10897       !isa<ConstantSDNode>(V->getOperand(1)) ||
10898       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10899     return Result;
10900 
10901   // Check the chain and pointer.
10902   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10903   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10904 
10905   // The store should be chained directly to the load or be an operand of a
10906   // tokenfactor.
10907   if (LD == Chain.getNode())
10908     ; // ok.
10909   else if (Chain->getOpcode() != ISD::TokenFactor)
10910     return Result; // Fail.
10911   else {
10912     bool isOk = false;
10913     for (const SDValue &ChainOp : Chain->op_values())
10914       if (ChainOp.getNode() == LD) {
10915         isOk = true;
10916         break;
10917       }
10918     if (!isOk) return Result;
10919   }
10920 
10921   // This only handles simple types.
10922   if (V.getValueType() != MVT::i16 &&
10923       V.getValueType() != MVT::i32 &&
10924       V.getValueType() != MVT::i64)
10925     return Result;
10926 
10927   // Check the constant mask.  Invert it so that the bits being masked out are
10928   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10929   // follow the sign bit for uniformity.
10930   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10931   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10932   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10933   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10934   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10935   if (NotMaskLZ == 64) return Result;  // All zero mask.
10936 
10937   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10938   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10939     return Result;
10940 
10941   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10942   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10943     NotMaskLZ -= 64-V.getValueSizeInBits();
10944 
10945   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10946   switch (MaskedBytes) {
10947   case 1:
10948   case 2:
10949   case 4: break;
10950   default: return Result; // All one mask, or 5-byte mask.
10951   }
10952 
10953   // Verify that the first bit starts at a multiple of mask so that the access
10954   // is aligned the same as the access width.
10955   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10956 
10957   Result.first = MaskedBytes;
10958   Result.second = NotMaskTZ/8;
10959   return Result;
10960 }
10961 
10962 
10963 /// Check to see if IVal is something that provides a value as specified by
10964 /// MaskInfo. If so, replace the specified store with a narrower store of
10965 /// truncated IVal.
10966 static SDNode *
10967 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10968                                 SDValue IVal, StoreSDNode *St,
10969                                 DAGCombiner *DC) {
10970   unsigned NumBytes = MaskInfo.first;
10971   unsigned ByteShift = MaskInfo.second;
10972   SelectionDAG &DAG = DC->getDAG();
10973 
10974   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10975   // that uses this.  If not, this is not a replacement.
10976   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10977                                   ByteShift*8, (ByteShift+NumBytes)*8);
10978   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10979 
10980   // Check that it is legal on the target to do this.  It is legal if the new
10981   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10982   // legalization.
10983   MVT VT = MVT::getIntegerVT(NumBytes*8);
10984   if (!DC->isTypeLegal(VT))
10985     return nullptr;
10986 
10987   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10988   // shifted by ByteShift and truncated down to NumBytes.
10989   if (ByteShift) {
10990     SDLoc DL(IVal);
10991     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10992                        DAG.getConstant(ByteShift*8, DL,
10993                                     DC->getShiftAmountTy(IVal.getValueType())));
10994   }
10995 
10996   // Figure out the offset for the store and the alignment of the access.
10997   unsigned StOffset;
10998   unsigned NewAlign = St->getAlignment();
10999 
11000   if (DAG.getDataLayout().isLittleEndian())
11001     StOffset = ByteShift;
11002   else
11003     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
11004 
11005   SDValue Ptr = St->getBasePtr();
11006   if (StOffset) {
11007     SDLoc DL(IVal);
11008     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11009                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11010     NewAlign = MinAlign(NewAlign, StOffset);
11011   }
11012 
11013   // Truncate down to the new size.
11014   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
11015 
11016   ++OpsNarrowed;
11017   return DAG
11018       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
11019                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
11020       .getNode();
11021 }
11022 
11023 
11024 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11025 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
11026 /// narrowing the load and store if it would end up being a win for performance
11027 /// or code size.
11028 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
11029   StoreSDNode *ST  = cast<StoreSDNode>(N);
11030   if (ST->isVolatile())
11031     return SDValue();
11032 
11033   SDValue Chain = ST->getChain();
11034   SDValue Value = ST->getValue();
11035   SDValue Ptr   = ST->getBasePtr();
11036   EVT VT = Value.getValueType();
11037 
11038   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
11039     return SDValue();
11040 
11041   unsigned Opc = Value.getOpcode();
11042 
11043   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
11044   // is a byte mask indicating a consecutive number of bytes, check to see if
11045   // Y is known to provide just those bytes.  If so, we try to replace the
11046   // load + replace + store sequence with a single (narrower) store, which makes
11047   // the load dead.
11048   if (Opc == ISD::OR) {
11049     std::pair<unsigned, unsigned> MaskedLoad;
11050     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
11051     if (MaskedLoad.first)
11052       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11053                                                   Value.getOperand(1), ST,this))
11054         return SDValue(NewST, 0);
11055 
11056     // Or is commutative, so try swapping X and Y.
11057     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
11058     if (MaskedLoad.first)
11059       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11060                                                   Value.getOperand(0), ST,this))
11061         return SDValue(NewST, 0);
11062   }
11063 
11064   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
11065       Value.getOperand(1).getOpcode() != ISD::Constant)
11066     return SDValue();
11067 
11068   SDValue N0 = Value.getOperand(0);
11069   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11070       Chain == SDValue(N0.getNode(), 1)) {
11071     LoadSDNode *LD = cast<LoadSDNode>(N0);
11072     if (LD->getBasePtr() != Ptr ||
11073         LD->getPointerInfo().getAddrSpace() !=
11074         ST->getPointerInfo().getAddrSpace())
11075       return SDValue();
11076 
11077     // Find the type to narrow it the load / op / store to.
11078     SDValue N1 = Value.getOperand(1);
11079     unsigned BitWidth = N1.getValueSizeInBits();
11080     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
11081     if (Opc == ISD::AND)
11082       Imm ^= APInt::getAllOnesValue(BitWidth);
11083     if (Imm == 0 || Imm.isAllOnesValue())
11084       return SDValue();
11085     unsigned ShAmt = Imm.countTrailingZeros();
11086     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
11087     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
11088     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11089     // The narrowing should be profitable, the load/store operation should be
11090     // legal (or custom) and the store size should be equal to the NewVT width.
11091     while (NewBW < BitWidth &&
11092            (NewVT.getStoreSizeInBits() != NewBW ||
11093             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11094             !TLI.isNarrowingProfitable(VT, NewVT))) {
11095       NewBW = NextPowerOf2(NewBW);
11096       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11097     }
11098     if (NewBW >= BitWidth)
11099       return SDValue();
11100 
11101     // If the lsb changed does not start at the type bitwidth boundary,
11102     // start at the previous one.
11103     if (ShAmt % NewBW)
11104       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11105     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11106                                    std::min(BitWidth, ShAmt + NewBW));
11107     if ((Imm & Mask) == Imm) {
11108       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11109       if (Opc == ISD::AND)
11110         NewImm ^= APInt::getAllOnesValue(NewBW);
11111       uint64_t PtrOff = ShAmt / 8;
11112       // For big endian targets, we need to adjust the offset to the pointer to
11113       // load the correct bytes.
11114       if (DAG.getDataLayout().isBigEndian())
11115         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11116 
11117       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11118       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11119       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11120         return SDValue();
11121 
11122       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11123                                    Ptr.getValueType(), Ptr,
11124                                    DAG.getConstant(PtrOff, SDLoc(LD),
11125                                                    Ptr.getValueType()));
11126       SDValue NewLD =
11127           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11128                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11129                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
11130       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11131                                    DAG.getConstant(NewImm, SDLoc(Value),
11132                                                    NewVT));
11133       SDValue NewST =
11134           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11135                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11136 
11137       AddToWorklist(NewPtr.getNode());
11138       AddToWorklist(NewLD.getNode());
11139       AddToWorklist(NewVal.getNode());
11140       WorklistRemover DeadNodes(*this);
11141       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11142       ++OpsNarrowed;
11143       return NewST;
11144     }
11145   }
11146 
11147   return SDValue();
11148 }
11149 
11150 /// For a given floating point load / store pair, if the load value isn't used
11151 /// by any other operations, then consider transforming the pair to integer
11152 /// load / store operations if the target deems the transformation profitable.
11153 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11154   StoreSDNode *ST  = cast<StoreSDNode>(N);
11155   SDValue Chain = ST->getChain();
11156   SDValue Value = ST->getValue();
11157   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11158       Value.hasOneUse() &&
11159       Chain == SDValue(Value.getNode(), 1)) {
11160     LoadSDNode *LD = cast<LoadSDNode>(Value);
11161     EVT VT = LD->getMemoryVT();
11162     if (!VT.isFloatingPoint() ||
11163         VT != ST->getMemoryVT() ||
11164         LD->isNonTemporal() ||
11165         ST->isNonTemporal() ||
11166         LD->getPointerInfo().getAddrSpace() != 0 ||
11167         ST->getPointerInfo().getAddrSpace() != 0)
11168       return SDValue();
11169 
11170     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11171     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11172         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11173         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11174         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11175       return SDValue();
11176 
11177     unsigned LDAlign = LD->getAlignment();
11178     unsigned STAlign = ST->getAlignment();
11179     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11180     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11181     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11182       return SDValue();
11183 
11184     SDValue NewLD =
11185         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
11186                     LD->getPointerInfo(), LDAlign);
11187 
11188     SDValue NewST =
11189         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
11190                      ST->getPointerInfo(), STAlign);
11191 
11192     AddToWorklist(NewLD.getNode());
11193     AddToWorklist(NewST.getNode());
11194     WorklistRemover DeadNodes(*this);
11195     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11196     ++LdStFP2Int;
11197     return NewST;
11198   }
11199 
11200   return SDValue();
11201 }
11202 
11203 namespace {
11204 /// Helper struct to parse and store a memory address as base + index + offset.
11205 /// We ignore sign extensions when it is safe to do so.
11206 /// The following two expressions are not equivalent. To differentiate we need
11207 /// to store whether there was a sign extension involved in the index
11208 /// computation.
11209 ///  (load (i64 add (i64 copyfromreg %c)
11210 ///                 (i64 signextend (add (i8 load %index)
11211 ///                                      (i8 1))))
11212 /// vs
11213 ///
11214 /// (load (i64 add (i64 copyfromreg %c)
11215 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11216 ///                                         (i32 1)))))
11217 struct BaseIndexOffset {
11218   SDValue Base;
11219   SDValue Index;
11220   int64_t Offset;
11221   bool IsIndexSignExt;
11222 
11223   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11224 
11225   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11226                   bool IsIndexSignExt) :
11227     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11228 
11229   bool equalBaseIndex(const BaseIndexOffset &Other) {
11230     return Other.Base == Base && Other.Index == Index &&
11231       Other.IsIndexSignExt == IsIndexSignExt;
11232   }
11233 
11234   /// Parses tree in Ptr for base, index, offset addresses.
11235   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11236     bool IsIndexSignExt = false;
11237 
11238     // Split up a folded GlobalAddress+Offset into its component parts.
11239     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11240       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11241         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11242                                                     SDLoc(GA),
11243                                                     GA->getValueType(0),
11244                                                     /*Offset=*/0,
11245                                                     /*isTargetGA=*/false,
11246                                                     GA->getTargetFlags()),
11247                                SDValue(),
11248                                GA->getOffset(),
11249                                IsIndexSignExt);
11250       }
11251 
11252     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11253     // instruction, then it could be just the BASE or everything else we don't
11254     // know how to handle. Just use Ptr as BASE and give up.
11255     if (Ptr->getOpcode() != ISD::ADD)
11256       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11257 
11258     // We know that we have at least an ADD instruction. Try to pattern match
11259     // the simple case of BASE + OFFSET.
11260     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11261       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11262       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11263                               IsIndexSignExt);
11264     }
11265 
11266     // Inside a loop the current BASE pointer is calculated using an ADD and a
11267     // MUL instruction. In this case Ptr is the actual BASE pointer.
11268     // (i64 add (i64 %array_ptr)
11269     //          (i64 mul (i64 %induction_var)
11270     //                   (i64 %element_size)))
11271     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11272       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11273 
11274     // Look at Base + Index + Offset cases.
11275     SDValue Base = Ptr->getOperand(0);
11276     SDValue IndexOffset = Ptr->getOperand(1);
11277 
11278     // Skip signextends.
11279     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11280       IndexOffset = IndexOffset->getOperand(0);
11281       IsIndexSignExt = true;
11282     }
11283 
11284     // Either the case of Base + Index (no offset) or something else.
11285     if (IndexOffset->getOpcode() != ISD::ADD)
11286       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11287 
11288     // Now we have the case of Base + Index + offset.
11289     SDValue Index = IndexOffset->getOperand(0);
11290     SDValue Offset = IndexOffset->getOperand(1);
11291 
11292     if (!isa<ConstantSDNode>(Offset))
11293       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11294 
11295     // Ignore signextends.
11296     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11297       Index = Index->getOperand(0);
11298       IsIndexSignExt = true;
11299     } else IsIndexSignExt = false;
11300 
11301     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11302     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11303   }
11304 };
11305 } // namespace
11306 
11307 // This is a helper function for visitMUL to check the profitability
11308 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11309 // MulNode is the original multiply, AddNode is (add x, c1),
11310 // and ConstNode is c2.
11311 //
11312 // If the (add x, c1) has multiple uses, we could increase
11313 // the number of adds if we make this transformation.
11314 // It would only be worth doing this if we can remove a
11315 // multiply in the process. Check for that here.
11316 // To illustrate:
11317 //     (A + c1) * c3
11318 //     (A + c2) * c3
11319 // We're checking for cases where we have common "c3 * A" expressions.
11320 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11321                                               SDValue &AddNode,
11322                                               SDValue &ConstNode) {
11323   APInt Val;
11324 
11325   // If the add only has one use, this would be OK to do.
11326   if (AddNode.getNode()->hasOneUse())
11327     return true;
11328 
11329   // Walk all the users of the constant with which we're multiplying.
11330   for (SDNode *Use : ConstNode->uses()) {
11331 
11332     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11333       continue;
11334 
11335     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11336       SDNode *OtherOp;
11337       SDNode *MulVar = AddNode.getOperand(0).getNode();
11338 
11339       // OtherOp is what we're multiplying against the constant.
11340       if (Use->getOperand(0) == ConstNode)
11341         OtherOp = Use->getOperand(1).getNode();
11342       else
11343         OtherOp = Use->getOperand(0).getNode();
11344 
11345       // Check to see if multiply is with the same operand of our "add".
11346       //
11347       //     ConstNode  = CONST
11348       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11349       //     ...
11350       //     AddNode  = (A + c1)  <-- MulVar is A.
11351       //         = AddNode * ConstNode   <-- current visiting instruction.
11352       //
11353       // If we make this transformation, we will have a common
11354       // multiply (ConstNode * A) that we can save.
11355       if (OtherOp == MulVar)
11356         return true;
11357 
11358       // Now check to see if a future expansion will give us a common
11359       // multiply.
11360       //
11361       //     ConstNode  = CONST
11362       //     AddNode    = (A + c1)
11363       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11364       //     ...
11365       //     OtherOp = (A + c2)
11366       //     Use     = OtherOp * ConstNode <-- visiting Use.
11367       //
11368       // If we make this transformation, we will have a common
11369       // multiply (CONST * A) after we also do the same transformation
11370       // to the "t2" instruction.
11371       if (OtherOp->getOpcode() == ISD::ADD &&
11372           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11373           OtherOp->getOperand(0).getNode() == MulVar)
11374         return true;
11375     }
11376   }
11377 
11378   // Didn't find a case where this would be profitable.
11379   return false;
11380 }
11381 
11382 SDValue DAGCombiner::getMergedConstantVectorStore(
11383     SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11384     SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11385   SmallVector<SDValue, 8> BuildVector;
11386 
11387   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11388     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11389     Chains.push_back(St->getChain());
11390     BuildVector.push_back(St->getValue());
11391   }
11392 
11393   return DAG.getBuildVector(Ty, SL, BuildVector);
11394 }
11395 
11396 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11397                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11398                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11399   // Make sure we have something to merge.
11400   if (NumStores < 2)
11401     return false;
11402 
11403   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11404   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11405   unsigned LatestNodeUsed = 0;
11406 
11407   for (unsigned i=0; i < NumStores; ++i) {
11408     // Find a chain for the new wide-store operand. Notice that some
11409     // of the store nodes that we found may not be selected for inclusion
11410     // in the wide store. The chain we use needs to be the chain of the
11411     // latest store node which is *used* and replaced by the wide store.
11412     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11413       LatestNodeUsed = i;
11414   }
11415 
11416   SmallVector<SDValue, 8> Chains;
11417 
11418   // The latest Node in the DAG.
11419   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11420   SDLoc DL(StoreNodes[0].MemNode);
11421 
11422   SDValue StoredVal;
11423   if (UseVector) {
11424     bool IsVec = MemVT.isVector();
11425     unsigned Elts = NumStores;
11426     if (IsVec) {
11427       // When merging vector stores, get the total number of elements.
11428       Elts *= MemVT.getVectorNumElements();
11429     }
11430     // Get the type for the merged vector store.
11431     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11432     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11433 
11434     if (IsConstantSrc) {
11435       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11436     } else {
11437       SmallVector<SDValue, 8> Ops;
11438       for (unsigned i = 0; i < NumStores; ++i) {
11439         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11440         SDValue Val = St->getValue();
11441         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11442         if (Val.getValueType() != MemVT)
11443           return false;
11444         Ops.push_back(Val);
11445         Chains.push_back(St->getChain());
11446       }
11447 
11448       // Build the extracted vector elements back into a vector.
11449       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11450                               DL, Ty, Ops);    }
11451   } else {
11452     // We should always use a vector store when merging extracted vector
11453     // elements, so this path implies a store of constants.
11454     assert(IsConstantSrc && "Merged vector elements should use vector store");
11455 
11456     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11457     APInt StoreInt(SizeInBits, 0);
11458 
11459     // Construct a single integer constant which is made of the smaller
11460     // constant inputs.
11461     bool IsLE = DAG.getDataLayout().isLittleEndian();
11462     for (unsigned i = 0; i < NumStores; ++i) {
11463       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11464       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11465       Chains.push_back(St->getChain());
11466 
11467       SDValue Val = St->getValue();
11468       StoreInt <<= ElementSizeBytes * 8;
11469       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11470         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11471       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11472         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11473       } else {
11474         llvm_unreachable("Invalid constant element type");
11475       }
11476     }
11477 
11478     // Create the new Load and Store operations.
11479     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11480     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11481   }
11482 
11483   assert(!Chains.empty());
11484 
11485   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11486   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11487                                   FirstInChain->getBasePtr(),
11488                                   FirstInChain->getPointerInfo(),
11489                                   FirstInChain->getAlignment());
11490 
11491   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11492                                                   : DAG.getSubtarget().useAA();
11493   if (UseAA) {
11494     // Replace all merged stores with the new store.
11495     for (unsigned i = 0; i < NumStores; ++i)
11496       CombineTo(StoreNodes[i].MemNode, NewStore);
11497   } else {
11498     // Replace the last store with the new store.
11499     CombineTo(LatestOp, NewStore);
11500     // Erase all other stores.
11501     for (unsigned i = 0; i < NumStores; ++i) {
11502       if (StoreNodes[i].MemNode == LatestOp)
11503         continue;
11504       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11505       // ReplaceAllUsesWith will replace all uses that existed when it was
11506       // called, but graph optimizations may cause new ones to appear. For
11507       // example, the case in pr14333 looks like
11508       //
11509       //  St's chain -> St -> another store -> X
11510       //
11511       // And the only difference from St to the other store is the chain.
11512       // When we change it's chain to be St's chain they become identical,
11513       // get CSEed and the net result is that X is now a use of St.
11514       // Since we know that St is redundant, just iterate.
11515       while (!St->use_empty())
11516         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11517       deleteAndRecombine(St);
11518     }
11519   }
11520 
11521   return true;
11522 }
11523 
11524 void DAGCombiner::getStoreMergeAndAliasCandidates(
11525     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11526     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11527   // This holds the base pointer, index, and the offset in bytes from the base
11528   // pointer.
11529   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11530 
11531   // We must have a base and an offset.
11532   if (!BasePtr.Base.getNode())
11533     return;
11534 
11535   // Do not handle stores to undef base pointers.
11536   if (BasePtr.Base.isUndef())
11537     return;
11538 
11539   // Walk up the chain and look for nodes with offsets from the same
11540   // base pointer. Stop when reaching an instruction with a different kind
11541   // or instruction which has a different base pointer.
11542   EVT MemVT = St->getMemoryVT();
11543   unsigned Seq = 0;
11544   StoreSDNode *Index = St;
11545 
11546 
11547   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11548                                                   : DAG.getSubtarget().useAA();
11549 
11550   if (UseAA) {
11551     // Look at other users of the same chain. Stores on the same chain do not
11552     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11553     // to be on the same chain, so don't bother looking at adjacent chains.
11554 
11555     SDValue Chain = St->getChain();
11556     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11557       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11558         if (I.getOperandNo() != 0)
11559           continue;
11560 
11561         if (OtherST->isVolatile() || OtherST->isIndexed())
11562           continue;
11563 
11564         if (OtherST->getMemoryVT() != MemVT)
11565           continue;
11566 
11567         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11568 
11569         if (Ptr.equalBaseIndex(BasePtr))
11570           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11571       }
11572     }
11573 
11574     return;
11575   }
11576 
11577   while (Index) {
11578     // If the chain has more than one use, then we can't reorder the mem ops.
11579     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11580       break;
11581 
11582     // Find the base pointer and offset for this memory node.
11583     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11584 
11585     // Check that the base pointer is the same as the original one.
11586     if (!Ptr.equalBaseIndex(BasePtr))
11587       break;
11588 
11589     // The memory operands must not be volatile.
11590     if (Index->isVolatile() || Index->isIndexed())
11591       break;
11592 
11593     // No truncation.
11594     if (Index->isTruncatingStore())
11595       break;
11596 
11597     // The stored memory type must be the same.
11598     if (Index->getMemoryVT() != MemVT)
11599       break;
11600 
11601     // We do not allow under-aligned stores in order to prevent
11602     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11603     // be irrelevant here; what MATTERS is that we not move memory
11604     // operations that potentially overlap past each-other.
11605     if (Index->getAlignment() < MemVT.getStoreSize())
11606       break;
11607 
11608     // We found a potential memory operand to merge.
11609     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11610 
11611     // Find the next memory operand in the chain. If the next operand in the
11612     // chain is a store then move up and continue the scan with the next
11613     // memory operand. If the next operand is a load save it and use alias
11614     // information to check if it interferes with anything.
11615     SDNode *NextInChain = Index->getChain().getNode();
11616     while (1) {
11617       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11618         // We found a store node. Use it for the next iteration.
11619         Index = STn;
11620         break;
11621       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11622         if (Ldn->isVolatile()) {
11623           Index = nullptr;
11624           break;
11625         }
11626 
11627         // Save the load node for later. Continue the scan.
11628         AliasLoadNodes.push_back(Ldn);
11629         NextInChain = Ldn->getChain().getNode();
11630         continue;
11631       } else {
11632         Index = nullptr;
11633         break;
11634       }
11635     }
11636   }
11637 }
11638 
11639 // We need to check that merging these stores does not cause a loop
11640 // in the DAG. Any store candidate may depend on another candidate
11641 // indirectly through its operand (we already consider dependencies
11642 // through the chain). Check in parallel by searching up from
11643 // non-chain operands of candidates.
11644 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11645     SmallVectorImpl<MemOpLink> &StoreNodes) {
11646   SmallPtrSet<const SDNode *, 16> Visited;
11647   SmallVector<const SDNode *, 8> Worklist;
11648   // search ops of store candidates
11649   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11650     SDNode *n = StoreNodes[i].MemNode;
11651     // Potential loops may happen only through non-chain operands
11652     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11653       Worklist.push_back(n->getOperand(j).getNode());
11654   }
11655   // search through DAG. We can stop early if we find a storenode
11656   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11657     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11658       return false;
11659   }
11660   return true;
11661 }
11662 
11663 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11664   if (OptLevel == CodeGenOpt::None)
11665     return false;
11666 
11667   EVT MemVT = St->getMemoryVT();
11668   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11669   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11670       Attribute::NoImplicitFloat);
11671 
11672   // This function cannot currently deal with non-byte-sized memory sizes.
11673   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11674     return false;
11675 
11676   if (!MemVT.isSimple())
11677     return false;
11678 
11679   // Perform an early exit check. Do not bother looking at stored values that
11680   // are not constants, loads, or extracted vector elements.
11681   SDValue StoredVal = St->getValue();
11682   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11683   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11684                        isa<ConstantFPSDNode>(StoredVal);
11685   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11686                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11687 
11688   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11689     return false;
11690 
11691   // Don't merge vectors into wider vectors if the source data comes from loads.
11692   // TODO: This restriction can be lifted by using logic similar to the
11693   // ExtractVecSrc case.
11694   if (MemVT.isVector() && IsLoadSrc)
11695     return false;
11696 
11697   // Only look at ends of store sequences.
11698   SDValue Chain = SDValue(St, 0);
11699   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11700     return false;
11701 
11702   // Save the LoadSDNodes that we find in the chain.
11703   // We need to make sure that these nodes do not interfere with
11704   // any of the store nodes.
11705   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11706 
11707   // Save the StoreSDNodes that we find in the chain.
11708   SmallVector<MemOpLink, 8> StoreNodes;
11709 
11710   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11711 
11712   // Check if there is anything to merge.
11713   if (StoreNodes.size() < 2)
11714     return false;
11715 
11716   // only do dependence check in AA case
11717   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11718                                                   : DAG.getSubtarget().useAA();
11719   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11720     return false;
11721 
11722   // Sort the memory operands according to their distance from the
11723   // base pointer.  As a secondary criteria: make sure stores coming
11724   // later in the code come first in the list. This is important for
11725   // the non-UseAA case, because we're merging stores into the FINAL
11726   // store along a chain which potentially contains aliasing stores.
11727   // Thus, if there are multiple stores to the same address, the last
11728   // one can be considered for merging but not the others.
11729   std::sort(StoreNodes.begin(), StoreNodes.end(),
11730             [](MemOpLink LHS, MemOpLink RHS) {
11731     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11732            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11733             LHS.SequenceNum < RHS.SequenceNum);
11734   });
11735 
11736   // Scan the memory operations on the chain and find the first non-consecutive
11737   // store memory address.
11738   unsigned LastConsecutiveStore = 0;
11739   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11740   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11741 
11742     // Check that the addresses are consecutive starting from the second
11743     // element in the list of stores.
11744     if (i > 0) {
11745       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11746       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11747         break;
11748     }
11749 
11750     // Check if this store interferes with any of the loads that we found.
11751     // If we find a load that alias with this store. Stop the sequence.
11752     if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) {
11753           return isAlias(Ldn, StoreNodes[i].MemNode);
11754         }))
11755       break;
11756 
11757     // Mark this node as useful.
11758     LastConsecutiveStore = i;
11759   }
11760 
11761   // The node with the lowest store address.
11762   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11763   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11764   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11765   LLVMContext &Context = *DAG.getContext();
11766   const DataLayout &DL = DAG.getDataLayout();
11767 
11768   // Store the constants into memory as one consecutive store.
11769   if (IsConstantSrc) {
11770     unsigned LastLegalType = 0;
11771     unsigned LastLegalVectorType = 0;
11772     bool NonZero = false;
11773     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11774       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11775       SDValue StoredVal = St->getValue();
11776 
11777       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11778         NonZero |= !C->isNullValue();
11779       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11780         NonZero |= !C->getConstantFPValue()->isNullValue();
11781       } else {
11782         // Non-constant.
11783         break;
11784       }
11785 
11786       // Find a legal type for the constant store.
11787       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11788       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11789       bool IsFast;
11790       if (TLI.isTypeLegal(StoreTy) &&
11791           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11792                                  FirstStoreAlign, &IsFast) && IsFast) {
11793         LastLegalType = i+1;
11794       // Or check whether a truncstore is legal.
11795       } else if (TLI.getTypeAction(Context, StoreTy) ==
11796                  TargetLowering::TypePromoteInteger) {
11797         EVT LegalizedStoredValueTy =
11798           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11799         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11800             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11801                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11802             IsFast) {
11803           LastLegalType = i + 1;
11804         }
11805       }
11806 
11807       // We only use vectors if the constant is known to be zero or the target
11808       // allows it and the function is not marked with the noimplicitfloat
11809       // attribute.
11810       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11811                                                         FirstStoreAS)) &&
11812           !NoVectors) {
11813         // Find a legal type for the vector store.
11814         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11815         if (TLI.isTypeLegal(Ty) &&
11816             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11817                                    FirstStoreAlign, &IsFast) && IsFast)
11818           LastLegalVectorType = i + 1;
11819       }
11820     }
11821 
11822     // Check if we found a legal integer type to store.
11823     if (LastLegalType == 0 && LastLegalVectorType == 0)
11824       return false;
11825 
11826     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11827     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11828 
11829     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11830                                            true, UseVector);
11831   }
11832 
11833   // When extracting multiple vector elements, try to store them
11834   // in one vector store rather than a sequence of scalar stores.
11835   if (IsExtractVecSrc) {
11836     unsigned NumStoresToMerge = 0;
11837     bool IsVec = MemVT.isVector();
11838     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11839       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11840       unsigned StoreValOpcode = St->getValue().getOpcode();
11841       // This restriction could be loosened.
11842       // Bail out if any stored values are not elements extracted from a vector.
11843       // It should be possible to handle mixed sources, but load sources need
11844       // more careful handling (see the block of code below that handles
11845       // consecutive loads).
11846       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11847           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11848         return false;
11849 
11850       // Find a legal type for the vector store.
11851       unsigned Elts = i + 1;
11852       if (IsVec) {
11853         // When merging vector stores, get the total number of elements.
11854         Elts *= MemVT.getVectorNumElements();
11855       }
11856       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11857       bool IsFast;
11858       if (TLI.isTypeLegal(Ty) &&
11859           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11860                                  FirstStoreAlign, &IsFast) && IsFast)
11861         NumStoresToMerge = i + 1;
11862     }
11863 
11864     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11865                                            false, true);
11866   }
11867 
11868   // Below we handle the case of multiple consecutive stores that
11869   // come from multiple consecutive loads. We merge them into a single
11870   // wide load and a single wide store.
11871 
11872   // Look for load nodes which are used by the stored values.
11873   SmallVector<MemOpLink, 8> LoadNodes;
11874 
11875   // Find acceptable loads. Loads need to have the same chain (token factor),
11876   // must not be zext, volatile, indexed, and they must be consecutive.
11877   BaseIndexOffset LdBasePtr;
11878   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11879     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11880     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11881     if (!Ld) break;
11882 
11883     // Loads must only have one use.
11884     if (!Ld->hasNUsesOfValue(1, 0))
11885       break;
11886 
11887     // The memory operands must not be volatile.
11888     if (Ld->isVolatile() || Ld->isIndexed())
11889       break;
11890 
11891     // We do not accept ext loads.
11892     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11893       break;
11894 
11895     // The stored memory type must be the same.
11896     if (Ld->getMemoryVT() != MemVT)
11897       break;
11898 
11899     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11900     // If this is not the first ptr that we check.
11901     if (LdBasePtr.Base.getNode()) {
11902       // The base ptr must be the same.
11903       if (!LdPtr.equalBaseIndex(LdBasePtr))
11904         break;
11905     } else {
11906       // Check that all other base pointers are the same as this one.
11907       LdBasePtr = LdPtr;
11908     }
11909 
11910     // We found a potential memory operand to merge.
11911     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11912   }
11913 
11914   if (LoadNodes.size() < 2)
11915     return false;
11916 
11917   // If we have load/store pair instructions and we only have two values,
11918   // don't bother.
11919   unsigned RequiredAlignment;
11920   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11921       St->getAlignment() >= RequiredAlignment)
11922     return false;
11923 
11924   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11925   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11926   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11927 
11928   // Scan the memory operations on the chain and find the first non-consecutive
11929   // load memory address. These variables hold the index in the store node
11930   // array.
11931   unsigned LastConsecutiveLoad = 0;
11932   // This variable refers to the size and not index in the array.
11933   unsigned LastLegalVectorType = 0;
11934   unsigned LastLegalIntegerType = 0;
11935   StartAddress = LoadNodes[0].OffsetFromBase;
11936   SDValue FirstChain = FirstLoad->getChain();
11937   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11938     // All loads must share the same chain.
11939     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11940       break;
11941 
11942     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11943     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11944       break;
11945     LastConsecutiveLoad = i;
11946     // Find a legal type for the vector store.
11947     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11948     bool IsFastSt, IsFastLd;
11949     if (TLI.isTypeLegal(StoreTy) &&
11950         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11951                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11952         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11953                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11954       LastLegalVectorType = i + 1;
11955     }
11956 
11957     // Find a legal type for the integer store.
11958     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11959     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11960     if (TLI.isTypeLegal(StoreTy) &&
11961         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11962                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11963         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11964                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11965       LastLegalIntegerType = i + 1;
11966     // Or check whether a truncstore and extload is legal.
11967     else if (TLI.getTypeAction(Context, StoreTy) ==
11968              TargetLowering::TypePromoteInteger) {
11969       EVT LegalizedStoredValueTy =
11970         TLI.getTypeToTransformTo(Context, StoreTy);
11971       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11972           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11973           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11974           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11975           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11976                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11977           IsFastSt &&
11978           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11979                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11980           IsFastLd)
11981         LastLegalIntegerType = i+1;
11982     }
11983   }
11984 
11985   // Only use vector types if the vector type is larger than the integer type.
11986   // If they are the same, use integers.
11987   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11988   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11989 
11990   // We add +1 here because the LastXXX variables refer to location while
11991   // the NumElem refers to array/index size.
11992   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11993   NumElem = std::min(LastLegalType, NumElem);
11994 
11995   if (NumElem < 2)
11996     return false;
11997 
11998   // Collect the chains from all merged stores.
11999   SmallVector<SDValue, 8> MergeStoreChains;
12000   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
12001 
12002   // The latest Node in the DAG.
12003   unsigned LatestNodeUsed = 0;
12004   for (unsigned i=1; i<NumElem; ++i) {
12005     // Find a chain for the new wide-store operand. Notice that some
12006     // of the store nodes that we found may not be selected for inclusion
12007     // in the wide store. The chain we use needs to be the chain of the
12008     // latest store node which is *used* and replaced by the wide store.
12009     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
12010       LatestNodeUsed = i;
12011 
12012     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
12013   }
12014 
12015   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
12016 
12017   // Find if it is better to use vectors or integers to load and store
12018   // to memory.
12019   EVT JointMemOpVT;
12020   if (UseVectorTy) {
12021     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12022   } else {
12023     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12024     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12025   }
12026 
12027   SDLoc LoadDL(LoadNodes[0].MemNode);
12028   SDLoc StoreDL(StoreNodes[0].MemNode);
12029 
12030   // The merged loads are required to have the same incoming chain, so
12031   // using the first's chain is acceptable.
12032   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12033                                 FirstLoad->getBasePtr(),
12034                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
12035 
12036   SDValue NewStoreChain =
12037     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
12038 
12039   SDValue NewStore =
12040       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12041                    FirstInChain->getPointerInfo(), FirstStoreAlign);
12042 
12043   // Transfer chain users from old loads to the new load.
12044   for (unsigned i = 0; i < NumElem; ++i) {
12045     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12046     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12047                                   SDValue(NewLoad.getNode(), 1));
12048   }
12049 
12050   if (UseAA) {
12051     // Replace the all stores with the new store.
12052     for (unsigned i = 0; i < NumElem; ++i)
12053       CombineTo(StoreNodes[i].MemNode, NewStore);
12054   } else {
12055     // Replace the last store with the new store.
12056     CombineTo(LatestOp, NewStore);
12057     // Erase all other stores.
12058     for (unsigned i = 0; i < NumElem; ++i) {
12059       // Remove all Store nodes.
12060       if (StoreNodes[i].MemNode == LatestOp)
12061         continue;
12062       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12063       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
12064       deleteAndRecombine(St);
12065     }
12066   }
12067 
12068   return true;
12069 }
12070 
12071 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12072   SDLoc SL(ST);
12073   SDValue ReplStore;
12074 
12075   // Replace the chain to avoid dependency.
12076   if (ST->isTruncatingStore()) {
12077     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12078                                   ST->getBasePtr(), ST->getMemoryVT(),
12079                                   ST->getMemOperand());
12080   } else {
12081     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12082                              ST->getMemOperand());
12083   }
12084 
12085   // Create token to keep both nodes around.
12086   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12087                               MVT::Other, ST->getChain(), ReplStore);
12088 
12089   // Make sure the new and old chains are cleaned up.
12090   AddToWorklist(Token.getNode());
12091 
12092   // Don't add users to work list.
12093   return CombineTo(ST, Token, false);
12094 }
12095 
12096 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12097   SDValue Value = ST->getValue();
12098   if (Value.getOpcode() == ISD::TargetConstantFP)
12099     return SDValue();
12100 
12101   SDLoc DL(ST);
12102 
12103   SDValue Chain = ST->getChain();
12104   SDValue Ptr = ST->getBasePtr();
12105 
12106   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12107 
12108   // NOTE: If the original store is volatile, this transform must not increase
12109   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12110   // processor operation but an i64 (which is not legal) requires two.  So the
12111   // transform should not be done in this case.
12112 
12113   SDValue Tmp;
12114   switch (CFP->getSimpleValueType(0).SimpleTy) {
12115   default:
12116     llvm_unreachable("Unknown FP type");
12117   case MVT::f16:    // We don't do this for these yet.
12118   case MVT::f80:
12119   case MVT::f128:
12120   case MVT::ppcf128:
12121     return SDValue();
12122   case MVT::f32:
12123     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12124         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12125       ;
12126       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12127                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12128                             MVT::i32);
12129       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12130     }
12131 
12132     return SDValue();
12133   case MVT::f64:
12134     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12135          !ST->isVolatile()) ||
12136         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12137       ;
12138       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12139                             getZExtValue(), SDLoc(CFP), MVT::i64);
12140       return DAG.getStore(Chain, DL, Tmp,
12141                           Ptr, ST->getMemOperand());
12142     }
12143 
12144     if (!ST->isVolatile() &&
12145         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12146       // Many FP stores are not made apparent until after legalize, e.g. for
12147       // argument passing.  Since this is so common, custom legalize the
12148       // 64-bit integer store into two 32-bit stores.
12149       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12150       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12151       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12152       if (DAG.getDataLayout().isBigEndian())
12153         std::swap(Lo, Hi);
12154 
12155       unsigned Alignment = ST->getAlignment();
12156       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12157       AAMDNodes AAInfo = ST->getAAInfo();
12158 
12159       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12160                                  ST->getAlignment(), MMOFlags, AAInfo);
12161       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12162                         DAG.getConstant(4, DL, Ptr.getValueType()));
12163       Alignment = MinAlign(Alignment, 4U);
12164       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12165                                  ST->getPointerInfo().getWithOffset(4),
12166                                  Alignment, MMOFlags, AAInfo);
12167       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12168                          St0, St1);
12169     }
12170 
12171     return SDValue();
12172   }
12173 }
12174 
12175 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12176   StoreSDNode *ST  = cast<StoreSDNode>(N);
12177   SDValue Chain = ST->getChain();
12178   SDValue Value = ST->getValue();
12179   SDValue Ptr   = ST->getBasePtr();
12180 
12181   // If this is a store of a bit convert, store the input value if the
12182   // resultant store does not need a higher alignment than the original.
12183   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12184       ST->isUnindexed()) {
12185     EVT SVT = Value.getOperand(0).getValueType();
12186     if (((!LegalOperations && !ST->isVolatile()) ||
12187          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12188         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12189       unsigned OrigAlign = ST->getAlignment();
12190       bool Fast = false;
12191       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12192                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12193           Fast) {
12194         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12195                             ST->getPointerInfo(), OrigAlign,
12196                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
12197       }
12198     }
12199   }
12200 
12201   // Turn 'store undef, Ptr' -> nothing.
12202   if (Value.isUndef() && ST->isUnindexed())
12203     return Chain;
12204 
12205   // Try to infer better alignment information than the store already has.
12206   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12207     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12208       if (Align > ST->getAlignment()) {
12209         SDValue NewStore =
12210             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12211                               ST->getMemoryVT(), Align,
12212                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
12213         if (NewStore.getNode() != N)
12214           return CombineTo(ST, NewStore, true);
12215       }
12216     }
12217   }
12218 
12219   // Try transforming a pair floating point load / store ops to integer
12220   // load / store ops.
12221   if (SDValue NewST = TransformFPLoadStorePair(N))
12222     return NewST;
12223 
12224   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12225                                                   : DAG.getSubtarget().useAA();
12226 #ifndef NDEBUG
12227   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12228       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12229     UseAA = false;
12230 #endif
12231   if (UseAA && ST->isUnindexed()) {
12232     // FIXME: We should do this even without AA enabled. AA will just allow
12233     // FindBetterChain to work in more situations. The problem with this is that
12234     // any combine that expects memory operations to be on consecutive chains
12235     // first needs to be updated to look for users of the same chain.
12236 
12237     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12238     // adjacent stores.
12239     if (findBetterNeighborChains(ST)) {
12240       // replaceStoreChain uses CombineTo, which handled all of the worklist
12241       // manipulation. Return the original node to not do anything else.
12242       return SDValue(ST, 0);
12243     }
12244     Chain = ST->getChain();
12245   }
12246 
12247   // Try transforming N to an indexed store.
12248   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12249     return SDValue(N, 0);
12250 
12251   // FIXME: is there such a thing as a truncating indexed store?
12252   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12253       Value.getValueType().isInteger()) {
12254     // See if we can simplify the input to this truncstore with knowledge that
12255     // only the low bits are being used.  For example:
12256     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12257     SDValue Shorter = GetDemandedBits(
12258         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12259                                     ST->getMemoryVT().getScalarSizeInBits()));
12260     AddToWorklist(Value.getNode());
12261     if (Shorter.getNode())
12262       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12263                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12264 
12265     // Otherwise, see if we can simplify the operation with
12266     // SimplifyDemandedBits, which only works if the value has a single use.
12267     if (SimplifyDemandedBits(
12268             Value,
12269             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12270                                  ST->getMemoryVT().getScalarSizeInBits())))
12271       return SDValue(N, 0);
12272   }
12273 
12274   // If this is a load followed by a store to the same location, then the store
12275   // is dead/noop.
12276   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12277     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12278         ST->isUnindexed() && !ST->isVolatile() &&
12279         // There can't be any side effects between the load and store, such as
12280         // a call or store.
12281         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12282       // The store is dead, remove it.
12283       return Chain;
12284     }
12285   }
12286 
12287   // If this is a store followed by a store with the same value to the same
12288   // location, then the store is dead/noop.
12289   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12290     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12291         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12292         ST1->isUnindexed() && !ST1->isVolatile()) {
12293       // The store is dead, remove it.
12294       return Chain;
12295     }
12296   }
12297 
12298   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12299   // truncating store.  We can do this even if this is already a truncstore.
12300   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12301       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12302       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12303                             ST->getMemoryVT())) {
12304     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12305                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12306   }
12307 
12308   // Only perform this optimization before the types are legal, because we
12309   // don't want to perform this optimization on every DAGCombine invocation.
12310   if (!LegalTypes) {
12311     bool EverChanged = false;
12312 
12313     do {
12314       // There can be multiple store sequences on the same chain.
12315       // Keep trying to merge store sequences until we are unable to do so
12316       // or until we merge the last store on the chain.
12317       bool Changed = MergeConsecutiveStores(ST);
12318       EverChanged |= Changed;
12319       if (!Changed) break;
12320     } while (ST->getOpcode() != ISD::DELETED_NODE);
12321 
12322     if (EverChanged)
12323       return SDValue(N, 0);
12324   }
12325 
12326   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12327   //
12328   // Make sure to do this only after attempting to merge stores in order to
12329   //  avoid changing the types of some subset of stores due to visit order,
12330   //  preventing their merging.
12331   if (isa<ConstantFPSDNode>(Value)) {
12332     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12333       return NewSt;
12334   }
12335 
12336   if (SDValue NewSt = splitMergedValStore(ST))
12337     return NewSt;
12338 
12339   return ReduceLoadOpStoreWidth(N);
12340 }
12341 
12342 /// For the instruction sequence of store below, F and I values
12343 /// are bundled together as an i64 value before being stored into memory.
12344 /// Sometimes it is more efficent to generate separate stores for F and I,
12345 /// which can remove the bitwise instructions or sink them to colder places.
12346 ///
12347 ///   (store (or (zext (bitcast F to i32) to i64),
12348 ///              (shl (zext I to i64), 32)), addr)  -->
12349 ///   (store F, addr) and (store I, addr+4)
12350 ///
12351 /// Similarly, splitting for other merged store can also be beneficial, like:
12352 /// For pair of {i32, i32}, i64 store --> two i32 stores.
12353 /// For pair of {i32, i16}, i64 store --> two i32 stores.
12354 /// For pair of {i16, i16}, i32 store --> two i16 stores.
12355 /// For pair of {i16, i8},  i32 store --> two i16 stores.
12356 /// For pair of {i8, i8},   i16 store --> two i8 stores.
12357 ///
12358 /// We allow each target to determine specifically which kind of splitting is
12359 /// supported.
12360 ///
12361 /// The store patterns are commonly seen from the simple code snippet below
12362 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
12363 ///   void goo(const std::pair<int, float> &);
12364 ///   hoo() {
12365 ///     ...
12366 ///     goo(std::make_pair(tmp, ftmp));
12367 ///     ...
12368 ///   }
12369 ///
12370 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
12371   if (OptLevel == CodeGenOpt::None)
12372     return SDValue();
12373 
12374   SDValue Val = ST->getValue();
12375   SDLoc DL(ST);
12376 
12377   // Match OR operand.
12378   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
12379     return SDValue();
12380 
12381   // Match SHL operand and get Lower and Higher parts of Val.
12382   SDValue Op1 = Val.getOperand(0);
12383   SDValue Op2 = Val.getOperand(1);
12384   SDValue Lo, Hi;
12385   if (Op1.getOpcode() != ISD::SHL) {
12386     std::swap(Op1, Op2);
12387     if (Op1.getOpcode() != ISD::SHL)
12388       return SDValue();
12389   }
12390   Lo = Op2;
12391   Hi = Op1.getOperand(0);
12392   if (!Op1.hasOneUse())
12393     return SDValue();
12394 
12395   // Match shift amount to HalfValBitSize.
12396   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
12397   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
12398   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
12399     return SDValue();
12400 
12401   // Lo and Hi are zero-extended from int with size less equal than 32
12402   // to i64.
12403   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
12404       !Lo.getOperand(0).getValueType().isScalarInteger() ||
12405       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
12406       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
12407       !Hi.getOperand(0).getValueType().isScalarInteger() ||
12408       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
12409     return SDValue();
12410 
12411   if (!TLI.isMultiStoresCheaperThanBitsMerge(Lo.getOperand(0),
12412                                              Hi.getOperand(0)))
12413     return SDValue();
12414 
12415   // Start to split store.
12416   unsigned Alignment = ST->getAlignment();
12417   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12418   AAMDNodes AAInfo = ST->getAAInfo();
12419 
12420   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
12421   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
12422   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
12423   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
12424 
12425   SDValue Chain = ST->getChain();
12426   SDValue Ptr = ST->getBasePtr();
12427   // Lower value store.
12428   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12429                              ST->getAlignment(), MMOFlags, AAInfo);
12430   Ptr =
12431       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12432                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
12433   // Higher value store.
12434   SDValue St1 =
12435       DAG.getStore(St0, DL, Hi, Ptr,
12436                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
12437                    Alignment / 2, MMOFlags, AAInfo);
12438   return St1;
12439 }
12440 
12441 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12442   SDValue InVec = N->getOperand(0);
12443   SDValue InVal = N->getOperand(1);
12444   SDValue EltNo = N->getOperand(2);
12445   SDLoc DL(N);
12446 
12447   // If the inserted element is an UNDEF, just use the input vector.
12448   if (InVal.isUndef())
12449     return InVec;
12450 
12451   EVT VT = InVec.getValueType();
12452 
12453   // If we can't generate a legal BUILD_VECTOR, exit
12454   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12455     return SDValue();
12456 
12457   // Check that we know which element is being inserted
12458   if (!isa<ConstantSDNode>(EltNo))
12459     return SDValue();
12460   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12461 
12462   // Canonicalize insert_vector_elt dag nodes.
12463   // Example:
12464   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12465   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12466   //
12467   // Do this only if the child insert_vector node has one use; also
12468   // do this only if indices are both constants and Idx1 < Idx0.
12469   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12470       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12471     unsigned OtherElt =
12472       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12473     if (Elt < OtherElt) {
12474       // Swap nodes.
12475       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
12476                                   InVec.getOperand(0), InVal, EltNo);
12477       AddToWorklist(NewOp.getNode());
12478       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12479                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12480     }
12481   }
12482 
12483   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12484   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12485   // vector elements.
12486   SmallVector<SDValue, 8> Ops;
12487   // Do not combine these two vectors if the output vector will not replace
12488   // the input vector.
12489   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12490     Ops.append(InVec.getNode()->op_begin(),
12491                InVec.getNode()->op_end());
12492   } else if (InVec.isUndef()) {
12493     unsigned NElts = VT.getVectorNumElements();
12494     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12495   } else {
12496     return SDValue();
12497   }
12498 
12499   // Insert the element
12500   if (Elt < Ops.size()) {
12501     // All the operands of BUILD_VECTOR must have the same type;
12502     // we enforce that here.
12503     EVT OpVT = Ops[0].getValueType();
12504     if (InVal.getValueType() != OpVT)
12505       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12506                 DAG.getNode(ISD::ANY_EXTEND, DL, OpVT, InVal) :
12507                 DAG.getNode(ISD::TRUNCATE, DL, OpVT, InVal);
12508     Ops[Elt] = InVal;
12509   }
12510 
12511   // Return the new vector
12512   return DAG.getBuildVector(VT, DL, Ops);
12513 }
12514 
12515 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12516     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12517   assert(!OriginalLoad->isVolatile());
12518 
12519   EVT ResultVT = EVE->getValueType(0);
12520   EVT VecEltVT = InVecVT.getVectorElementType();
12521   unsigned Align = OriginalLoad->getAlignment();
12522   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12523       VecEltVT.getTypeForEVT(*DAG.getContext()));
12524 
12525   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12526     return SDValue();
12527 
12528   Align = NewAlign;
12529 
12530   SDValue NewPtr = OriginalLoad->getBasePtr();
12531   SDValue Offset;
12532   EVT PtrType = NewPtr.getValueType();
12533   MachinePointerInfo MPI;
12534   SDLoc DL(EVE);
12535   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12536     int Elt = ConstEltNo->getZExtValue();
12537     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12538     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12539     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12540   } else {
12541     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12542     Offset = DAG.getNode(
12543         ISD::MUL, DL, PtrType, Offset,
12544         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12545     MPI = OriginalLoad->getPointerInfo();
12546   }
12547   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12548 
12549   // The replacement we need to do here is a little tricky: we need to
12550   // replace an extractelement of a load with a load.
12551   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12552   // Note that this replacement assumes that the extractvalue is the only
12553   // use of the load; that's okay because we don't want to perform this
12554   // transformation in other cases anyway.
12555   SDValue Load;
12556   SDValue Chain;
12557   if (ResultVT.bitsGT(VecEltVT)) {
12558     // If the result type of vextract is wider than the load, then issue an
12559     // extending load instead.
12560     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12561                                                   VecEltVT)
12562                                    ? ISD::ZEXTLOAD
12563                                    : ISD::EXTLOAD;
12564     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
12565                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
12566                           Align, OriginalLoad->getMemOperand()->getFlags(),
12567                           OriginalLoad->getAAInfo());
12568     Chain = Load.getValue(1);
12569   } else {
12570     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
12571                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
12572                        OriginalLoad->getAAInfo());
12573     Chain = Load.getValue(1);
12574     if (ResultVT.bitsLT(VecEltVT))
12575       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12576     else
12577       Load = DAG.getBitcast(ResultVT, Load);
12578   }
12579   WorklistRemover DeadNodes(*this);
12580   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12581   SDValue To[] = { Load, Chain };
12582   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12583   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12584   // worklist explicitly as well.
12585   AddToWorklist(Load.getNode());
12586   AddUsersToWorklist(Load.getNode()); // Add users too
12587   // Make sure to revisit this node to clean it up; it will usually be dead.
12588   AddToWorklist(EVE);
12589   ++OpsNarrowed;
12590   return SDValue(EVE, 0);
12591 }
12592 
12593 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12594   // (vextract (scalar_to_vector val, 0) -> val
12595   SDValue InVec = N->getOperand(0);
12596   EVT VT = InVec.getValueType();
12597   EVT NVT = N->getValueType(0);
12598 
12599   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12600     // Check if the result type doesn't match the inserted element type. A
12601     // SCALAR_TO_VECTOR may truncate the inserted element and the
12602     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12603     SDValue InOp = InVec.getOperand(0);
12604     if (InOp.getValueType() != NVT) {
12605       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12606       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12607     }
12608     return InOp;
12609   }
12610 
12611   SDValue EltNo = N->getOperand(1);
12612   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12613 
12614   // extract_vector_elt (build_vector x, y), 1 -> y
12615   if (ConstEltNo &&
12616       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12617       TLI.isTypeLegal(VT) &&
12618       (InVec.hasOneUse() ||
12619        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12620     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12621     EVT InEltVT = Elt.getValueType();
12622 
12623     // Sometimes build_vector's scalar input types do not match result type.
12624     if (NVT == InEltVT)
12625       return Elt;
12626 
12627     // TODO: It may be useful to truncate if free if the build_vector implicitly
12628     // converts.
12629   }
12630 
12631   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12632   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12633       ConstEltNo->isNullValue() && VT.isInteger()) {
12634     SDValue BCSrc = InVec.getOperand(0);
12635     if (BCSrc.getValueType().isScalarInteger())
12636       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12637   }
12638 
12639   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
12640   //
12641   // This only really matters if the index is non-constant since other combines
12642   // on the constant elements already work.
12643   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12644       EltNo == InVec.getOperand(2)) {
12645     SDValue Elt = InVec.getOperand(1);
12646     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
12647   }
12648 
12649   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12650   // We only perform this optimization before the op legalization phase because
12651   // we may introduce new vector instructions which are not backed by TD
12652   // patterns. For example on AVX, extracting elements from a wide vector
12653   // without using extract_subvector. However, if we can find an underlying
12654   // scalar value, then we can always use that.
12655   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12656     int NumElem = VT.getVectorNumElements();
12657     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12658     // Find the new index to extract from.
12659     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12660 
12661     // Extracting an undef index is undef.
12662     if (OrigElt == -1)
12663       return DAG.getUNDEF(NVT);
12664 
12665     // Select the right vector half to extract from.
12666     SDValue SVInVec;
12667     if (OrigElt < NumElem) {
12668       SVInVec = InVec->getOperand(0);
12669     } else {
12670       SVInVec = InVec->getOperand(1);
12671       OrigElt -= NumElem;
12672     }
12673 
12674     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12675       SDValue InOp = SVInVec.getOperand(OrigElt);
12676       if (InOp.getValueType() != NVT) {
12677         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12678         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12679       }
12680 
12681       return InOp;
12682     }
12683 
12684     // FIXME: We should handle recursing on other vector shuffles and
12685     // scalar_to_vector here as well.
12686 
12687     if (!LegalOperations) {
12688       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12689       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12690                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12691     }
12692   }
12693 
12694   bool BCNumEltsChanged = false;
12695   EVT ExtVT = VT.getVectorElementType();
12696   EVT LVT = ExtVT;
12697 
12698   // If the result of load has to be truncated, then it's not necessarily
12699   // profitable.
12700   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12701     return SDValue();
12702 
12703   if (InVec.getOpcode() == ISD::BITCAST) {
12704     // Don't duplicate a load with other uses.
12705     if (!InVec.hasOneUse())
12706       return SDValue();
12707 
12708     EVT BCVT = InVec.getOperand(0).getValueType();
12709     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12710       return SDValue();
12711     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12712       BCNumEltsChanged = true;
12713     InVec = InVec.getOperand(0);
12714     ExtVT = BCVT.getVectorElementType();
12715   }
12716 
12717   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12718   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12719       ISD::isNormalLoad(InVec.getNode()) &&
12720       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12721     SDValue Index = N->getOperand(1);
12722     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
12723       if (!OrigLoad->isVolatile()) {
12724         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12725                                                              OrigLoad);
12726       }
12727     }
12728   }
12729 
12730   // Perform only after legalization to ensure build_vector / vector_shuffle
12731   // optimizations have already been done.
12732   if (!LegalOperations) return SDValue();
12733 
12734   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12735   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12736   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12737 
12738   if (ConstEltNo) {
12739     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12740 
12741     LoadSDNode *LN0 = nullptr;
12742     const ShuffleVectorSDNode *SVN = nullptr;
12743     if (ISD::isNormalLoad(InVec.getNode())) {
12744       LN0 = cast<LoadSDNode>(InVec);
12745     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12746                InVec.getOperand(0).getValueType() == ExtVT &&
12747                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12748       // Don't duplicate a load with other uses.
12749       if (!InVec.hasOneUse())
12750         return SDValue();
12751 
12752       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12753     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12754       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12755       // =>
12756       // (load $addr+1*size)
12757 
12758       // Don't duplicate a load with other uses.
12759       if (!InVec.hasOneUse())
12760         return SDValue();
12761 
12762       // If the bit convert changed the number of elements, it is unsafe
12763       // to examine the mask.
12764       if (BCNumEltsChanged)
12765         return SDValue();
12766 
12767       // Select the input vector, guarding against out of range extract vector.
12768       unsigned NumElems = VT.getVectorNumElements();
12769       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12770       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12771 
12772       if (InVec.getOpcode() == ISD::BITCAST) {
12773         // Don't duplicate a load with other uses.
12774         if (!InVec.hasOneUse())
12775           return SDValue();
12776 
12777         InVec = InVec.getOperand(0);
12778       }
12779       if (ISD::isNormalLoad(InVec.getNode())) {
12780         LN0 = cast<LoadSDNode>(InVec);
12781         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12782         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12783       }
12784     }
12785 
12786     // Make sure we found a non-volatile load and the extractelement is
12787     // the only use.
12788     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12789       return SDValue();
12790 
12791     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12792     if (Elt == -1)
12793       return DAG.getUNDEF(LVT);
12794 
12795     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12796   }
12797 
12798   return SDValue();
12799 }
12800 
12801 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12802 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12803   // We perform this optimization post type-legalization because
12804   // the type-legalizer often scalarizes integer-promoted vectors.
12805   // Performing this optimization before may create bit-casts which
12806   // will be type-legalized to complex code sequences.
12807   // We perform this optimization only before the operation legalizer because we
12808   // may introduce illegal operations.
12809   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12810     return SDValue();
12811 
12812   unsigned NumInScalars = N->getNumOperands();
12813   SDLoc DL(N);
12814   EVT VT = N->getValueType(0);
12815 
12816   // Check to see if this is a BUILD_VECTOR of a bunch of values
12817   // which come from any_extend or zero_extend nodes. If so, we can create
12818   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12819   // optimizations. We do not handle sign-extend because we can't fill the sign
12820   // using shuffles.
12821   EVT SourceType = MVT::Other;
12822   bool AllAnyExt = true;
12823 
12824   for (unsigned i = 0; i != NumInScalars; ++i) {
12825     SDValue In = N->getOperand(i);
12826     // Ignore undef inputs.
12827     if (In.isUndef()) continue;
12828 
12829     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12830     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12831 
12832     // Abort if the element is not an extension.
12833     if (!ZeroExt && !AnyExt) {
12834       SourceType = MVT::Other;
12835       break;
12836     }
12837 
12838     // The input is a ZeroExt or AnyExt. Check the original type.
12839     EVT InTy = In.getOperand(0).getValueType();
12840 
12841     // Check that all of the widened source types are the same.
12842     if (SourceType == MVT::Other)
12843       // First time.
12844       SourceType = InTy;
12845     else if (InTy != SourceType) {
12846       // Multiple income types. Abort.
12847       SourceType = MVT::Other;
12848       break;
12849     }
12850 
12851     // Check if all of the extends are ANY_EXTENDs.
12852     AllAnyExt &= AnyExt;
12853   }
12854 
12855   // In order to have valid types, all of the inputs must be extended from the
12856   // same source type and all of the inputs must be any or zero extend.
12857   // Scalar sizes must be a power of two.
12858   EVT OutScalarTy = VT.getScalarType();
12859   bool ValidTypes = SourceType != MVT::Other &&
12860                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12861                  isPowerOf2_32(SourceType.getSizeInBits());
12862 
12863   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12864   // turn into a single shuffle instruction.
12865   if (!ValidTypes)
12866     return SDValue();
12867 
12868   bool isLE = DAG.getDataLayout().isLittleEndian();
12869   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12870   assert(ElemRatio > 1 && "Invalid element size ratio");
12871   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12872                                DAG.getConstant(0, DL, SourceType);
12873 
12874   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12875   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12876 
12877   // Populate the new build_vector
12878   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12879     SDValue Cast = N->getOperand(i);
12880     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12881             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12882             Cast.isUndef()) && "Invalid cast opcode");
12883     SDValue In;
12884     if (Cast.isUndef())
12885       In = DAG.getUNDEF(SourceType);
12886     else
12887       In = Cast->getOperand(0);
12888     unsigned Index = isLE ? (i * ElemRatio) :
12889                             (i * ElemRatio + (ElemRatio - 1));
12890 
12891     assert(Index < Ops.size() && "Invalid index");
12892     Ops[Index] = In;
12893   }
12894 
12895   // The type of the new BUILD_VECTOR node.
12896   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12897   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12898          "Invalid vector size");
12899   // Check if the new vector type is legal.
12900   if (!isTypeLegal(VecVT)) return SDValue();
12901 
12902   // Make the new BUILD_VECTOR.
12903   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
12904 
12905   // The new BUILD_VECTOR node has the potential to be further optimized.
12906   AddToWorklist(BV.getNode());
12907   // Bitcast to the desired type.
12908   return DAG.getBitcast(VT, BV);
12909 }
12910 
12911 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12912   EVT VT = N->getValueType(0);
12913 
12914   unsigned NumInScalars = N->getNumOperands();
12915   SDLoc DL(N);
12916 
12917   EVT SrcVT = MVT::Other;
12918   unsigned Opcode = ISD::DELETED_NODE;
12919   unsigned NumDefs = 0;
12920 
12921   for (unsigned i = 0; i != NumInScalars; ++i) {
12922     SDValue In = N->getOperand(i);
12923     unsigned Opc = In.getOpcode();
12924 
12925     if (Opc == ISD::UNDEF)
12926       continue;
12927 
12928     // If all scalar values are floats and converted from integers.
12929     if (Opcode == ISD::DELETED_NODE &&
12930         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12931       Opcode = Opc;
12932     }
12933 
12934     if (Opc != Opcode)
12935       return SDValue();
12936 
12937     EVT InVT = In.getOperand(0).getValueType();
12938 
12939     // If all scalar values are typed differently, bail out. It's chosen to
12940     // simplify BUILD_VECTOR of integer types.
12941     if (SrcVT == MVT::Other)
12942       SrcVT = InVT;
12943     if (SrcVT != InVT)
12944       return SDValue();
12945     NumDefs++;
12946   }
12947 
12948   // If the vector has just one element defined, it's not worth to fold it into
12949   // a vectorized one.
12950   if (NumDefs < 2)
12951     return SDValue();
12952 
12953   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12954          && "Should only handle conversion from integer to float.");
12955   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12956 
12957   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12958 
12959   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12960     return SDValue();
12961 
12962   // Just because the floating-point vector type is legal does not necessarily
12963   // mean that the corresponding integer vector type is.
12964   if (!isTypeLegal(NVT))
12965     return SDValue();
12966 
12967   SmallVector<SDValue, 8> Opnds;
12968   for (unsigned i = 0; i != NumInScalars; ++i) {
12969     SDValue In = N->getOperand(i);
12970 
12971     if (In.isUndef())
12972       Opnds.push_back(DAG.getUNDEF(SrcVT));
12973     else
12974       Opnds.push_back(In.getOperand(0));
12975   }
12976   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
12977   AddToWorklist(BV.getNode());
12978 
12979   return DAG.getNode(Opcode, DL, VT, BV);
12980 }
12981 
12982 SDValue DAGCombiner::createBuildVecShuffle(SDLoc DL, SDNode *N,
12983                                            ArrayRef<int> VectorMask,
12984                                            SDValue VecIn1, SDValue VecIn2,
12985                                            unsigned LeftIdx) {
12986   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12987   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
12988 
12989   EVT VT = N->getValueType(0);
12990   EVT InVT1 = VecIn1.getValueType();
12991   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
12992 
12993   unsigned Vec2Offset = InVT1.getVectorNumElements();
12994   unsigned NumElems = VT.getVectorNumElements();
12995   unsigned ShuffleNumElems = NumElems;
12996 
12997   // We can't generate a shuffle node with mismatched input and output types.
12998   // Try to make the types match the type of the output.
12999   if (InVT1 != VT || InVT2 != VT) {
13000     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13001       // If the output vector length is a multiple of both input lengths,
13002       // we can concatenate them and pad the rest with undefs.
13003       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13004       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13005       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13006       ConcatOps[0] = VecIn1;
13007       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13008       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13009       VecIn2 = SDValue();
13010     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13011       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13012         return SDValue();
13013 
13014       if (!VecIn2.getNode()) {
13015         // If we only have one input vector, and it's twice the size of the
13016         // output, split it in two.
13017         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13018                              DAG.getConstant(NumElems, DL, IdxTy));
13019         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13020         // Since we now have shorter input vectors, adjust the offset of the
13021         // second vector's start.
13022         Vec2Offset = NumElems;
13023       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13024         // VecIn1 is wider than the output, and we have another, possibly
13025         // smaller input. Pad the smaller input with undefs, shuffle at the
13026         // input vector width, and extract the output.
13027         // The shuffle type is different than VT, so check legality again.
13028         if (LegalOperations &&
13029             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13030           return SDValue();
13031 
13032         if (InVT1 != InVT2)
13033           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13034                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13035         ShuffleNumElems = NumElems * 2;
13036       } else {
13037         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13038         // than VecIn1. We can't handle this for now - this case will disappear
13039         // when we start sorting the vectors by type.
13040         return SDValue();
13041       }
13042     } else {
13043       // TODO: Support cases where the length mismatch isn't exactly by a
13044       // factor of 2.
13045       // TODO: Move this check upwards, so that if we have bad type
13046       // mismatches, we don't create any DAG nodes.
13047       return SDValue();
13048     }
13049   }
13050 
13051   // Initialize mask to undef.
13052   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13053 
13054   // Only need to run up to the number of elements actually used, not the
13055   // total number of elements in the shuffle - if we are shuffling a wider
13056   // vector, the high lanes should be set to undef.
13057   for (unsigned i = 0; i != NumElems; ++i) {
13058     if (VectorMask[i] <= 0)
13059       continue;
13060 
13061     SDValue Extract = N->getOperand(i);
13062     unsigned ExtIndex =
13063         cast<ConstantSDNode>(Extract.getOperand(1))->getZExtValue();
13064 
13065     if (VectorMask[i] == (int)LeftIdx) {
13066       Mask[i] = ExtIndex;
13067     } else if (VectorMask[i] == (int)LeftIdx + 1) {
13068       Mask[i] = Vec2Offset + ExtIndex;
13069     }
13070   }
13071 
13072   // The type the input vectors may have changed above.
13073   InVT1 = VecIn1.getValueType();
13074 
13075   // If we already have a VecIn2, it should have the same type as VecIn1.
13076   // If we don't, get an undef/zero vector of the appropriate type.
13077   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13078   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13079 
13080   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13081   if (ShuffleNumElems > NumElems)
13082     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13083 
13084   return Shuffle;
13085 }
13086 
13087 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13088 // operations. If the types of the vectors we're extracting from allow it,
13089 // turn this into a vector_shuffle node.
13090 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13091   SDLoc DL(N);
13092   EVT VT = N->getValueType(0);
13093 
13094   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13095   if (!isTypeLegal(VT))
13096     return SDValue();
13097 
13098   // May only combine to shuffle after legalize if shuffle is legal.
13099   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13100     return SDValue();
13101 
13102   bool UsesZeroVector = false;
13103   unsigned NumElems = N->getNumOperands();
13104 
13105   // Record, for each element of the newly built vector, which input vector
13106   // that element comes from. -1 stands for undef, 0 for the zero vector,
13107   // and positive values for the input vectors.
13108   // VectorMask maps each element to its vector number, and VecIn maps vector
13109   // numbers to their initial SDValues.
13110 
13111   SmallVector<int, 8> VectorMask(NumElems, -1);
13112   SmallVector<SDValue, 8> VecIn;
13113   VecIn.push_back(SDValue());
13114 
13115   for (unsigned i = 0; i != NumElems; ++i) {
13116     SDValue Op = N->getOperand(i);
13117 
13118     if (Op.isUndef())
13119       continue;
13120 
13121     // See if we can use a blend with a zero vector.
13122     // TODO: Should we generalize this to a blend with an arbitrary constant
13123     // vector?
13124     if (isNullConstant(Op) || isNullFPConstant(Op)) {
13125       UsesZeroVector = true;
13126       VectorMask[i] = 0;
13127       continue;
13128     }
13129 
13130     // Not an undef or zero. If the input is something other than an
13131     // EXTRACT_VECTOR_ELT with a constant index, bail out.
13132     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13133         !isa<ConstantSDNode>(Op.getOperand(1)))
13134       return SDValue();
13135 
13136     SDValue ExtractedFromVec = Op.getOperand(0);
13137 
13138     // All inputs must have the same element type as the output.
13139     if (VT.getVectorElementType() !=
13140         ExtractedFromVec.getValueType().getVectorElementType())
13141       return SDValue();
13142 
13143     // Have we seen this input vector before?
13144     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13145     // a map back from SDValues to numbers isn't worth it.
13146     unsigned Idx = std::distance(
13147         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13148     if (Idx == VecIn.size())
13149       VecIn.push_back(ExtractedFromVec);
13150 
13151     VectorMask[i] = Idx;
13152   }
13153 
13154   // If we didn't find at least one input vector, bail out.
13155   if (VecIn.size() < 2)
13156     return SDValue();
13157 
13158   // TODO: We want to sort the vectors by descending length, so that adjacent
13159   // pairs have similar length, and the longer vector is always first in the
13160   // pair.
13161 
13162   // TODO: Should this fire if some of the input vectors has illegal type (like
13163   // it does now), or should we let legalization run its course first?
13164 
13165   // Shuffle phase:
13166   // Take pairs of vectors, and shuffle them so that the result has elements
13167   // from these vectors in the correct places.
13168   // For example, given:
13169   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13170   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13171   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13172   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13173   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13174   // We will generate:
13175   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13176   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13177   SmallVector<SDValue, 4> Shuffles;
13178   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13179     unsigned LeftIdx = 2 * In + 1;
13180     SDValue VecLeft = VecIn[LeftIdx];
13181     SDValue VecRight =
13182         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13183 
13184     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13185                                                 VecRight, LeftIdx))
13186       Shuffles.push_back(Shuffle);
13187     else
13188       return SDValue();
13189   }
13190 
13191   // If we need the zero vector as an "ingredient" in the blend tree, add it
13192   // to the list of shuffles.
13193   if (UsesZeroVector)
13194     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13195                                       : DAG.getConstantFP(0.0, DL, VT));
13196 
13197   // If we only have one shuffle, we're done.
13198   if (Shuffles.size() == 1)
13199     return Shuffles[0];
13200 
13201   // Update the vector mask to point to the post-shuffle vectors.
13202   for (int &Vec : VectorMask)
13203     if (Vec == 0)
13204       Vec = Shuffles.size() - 1;
13205     else
13206       Vec = (Vec - 1) / 2;
13207 
13208   // More than one shuffle. Generate a binary tree of blends, e.g. if from
13209   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13210   // generate:
13211   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13212   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13213   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13214   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13215   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13216   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13217   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13218 
13219   // Make sure the initial size of the shuffle list is even.
13220   if (Shuffles.size() % 2)
13221     Shuffles.push_back(DAG.getUNDEF(VT));
13222 
13223   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13224     if (CurSize % 2) {
13225       Shuffles[CurSize] = DAG.getUNDEF(VT);
13226       CurSize++;
13227     }
13228     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13229       int Left = 2 * In;
13230       int Right = 2 * In + 1;
13231       SmallVector<int, 8> Mask(NumElems, -1);
13232       for (unsigned i = 0; i != NumElems; ++i) {
13233         if (VectorMask[i] == Left) {
13234           Mask[i] = i;
13235           VectorMask[i] = In;
13236         } else if (VectorMask[i] == Right) {
13237           Mask[i] = i + NumElems;
13238           VectorMask[i] = In;
13239         }
13240       }
13241 
13242       Shuffles[In] =
13243           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13244     }
13245   }
13246 
13247   return Shuffles[0];
13248 }
13249 
13250 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13251   EVT VT = N->getValueType(0);
13252 
13253   // A vector built entirely of undefs is undef.
13254   if (ISD::allOperandsUndef(N))
13255     return DAG.getUNDEF(VT);
13256 
13257   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13258     return V;
13259 
13260   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13261     return V;
13262 
13263   if (SDValue V = reduceBuildVecToShuffle(N))
13264     return V;
13265 
13266   return SDValue();
13267 }
13268 
13269 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13271   EVT OpVT = N->getOperand(0).getValueType();
13272 
13273   // If the operands are legal vectors, leave them alone.
13274   if (TLI.isTypeLegal(OpVT))
13275     return SDValue();
13276 
13277   SDLoc DL(N);
13278   EVT VT = N->getValueType(0);
13279   SmallVector<SDValue, 8> Ops;
13280 
13281   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13282   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13283 
13284   // Keep track of what we encounter.
13285   bool AnyInteger = false;
13286   bool AnyFP = false;
13287   for (const SDValue &Op : N->ops()) {
13288     if (ISD::BITCAST == Op.getOpcode() &&
13289         !Op.getOperand(0).getValueType().isVector())
13290       Ops.push_back(Op.getOperand(0));
13291     else if (ISD::UNDEF == Op.getOpcode())
13292       Ops.push_back(ScalarUndef);
13293     else
13294       return SDValue();
13295 
13296     // Note whether we encounter an integer or floating point scalar.
13297     // If it's neither, bail out, it could be something weird like x86mmx.
13298     EVT LastOpVT = Ops.back().getValueType();
13299     if (LastOpVT.isFloatingPoint())
13300       AnyFP = true;
13301     else if (LastOpVT.isInteger())
13302       AnyInteger = true;
13303     else
13304       return SDValue();
13305   }
13306 
13307   // If any of the operands is a floating point scalar bitcast to a vector,
13308   // use floating point types throughout, and bitcast everything.
13309   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
13310   if (AnyFP) {
13311     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
13312     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13313     if (AnyInteger) {
13314       for (SDValue &Op : Ops) {
13315         if (Op.getValueType() == SVT)
13316           continue;
13317         if (Op.isUndef())
13318           Op = ScalarUndef;
13319         else
13320           Op = DAG.getBitcast(SVT, Op);
13321       }
13322     }
13323   }
13324 
13325   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
13326                                VT.getSizeInBits() / SVT.getSizeInBits());
13327   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
13328 }
13329 
13330 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
13331 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
13332 // most two distinct vectors the same size as the result, attempt to turn this
13333 // into a legal shuffle.
13334 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
13335   EVT VT = N->getValueType(0);
13336   EVT OpVT = N->getOperand(0).getValueType();
13337   int NumElts = VT.getVectorNumElements();
13338   int NumOpElts = OpVT.getVectorNumElements();
13339 
13340   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
13341   SmallVector<int, 8> Mask;
13342 
13343   for (SDValue Op : N->ops()) {
13344     // Peek through any bitcast.
13345     while (Op.getOpcode() == ISD::BITCAST)
13346       Op = Op.getOperand(0);
13347 
13348     // UNDEF nodes convert to UNDEF shuffle mask values.
13349     if (Op.isUndef()) {
13350       Mask.append((unsigned)NumOpElts, -1);
13351       continue;
13352     }
13353 
13354     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13355       return SDValue();
13356 
13357     // What vector are we extracting the subvector from and at what index?
13358     SDValue ExtVec = Op.getOperand(0);
13359 
13360     // We want the EVT of the original extraction to correctly scale the
13361     // extraction index.
13362     EVT ExtVT = ExtVec.getValueType();
13363 
13364     // Peek through any bitcast.
13365     while (ExtVec.getOpcode() == ISD::BITCAST)
13366       ExtVec = ExtVec.getOperand(0);
13367 
13368     // UNDEF nodes convert to UNDEF shuffle mask values.
13369     if (ExtVec.isUndef()) {
13370       Mask.append((unsigned)NumOpElts, -1);
13371       continue;
13372     }
13373 
13374     if (!isa<ConstantSDNode>(Op.getOperand(1)))
13375       return SDValue();
13376     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13377 
13378     // Ensure that we are extracting a subvector from a vector the same
13379     // size as the result.
13380     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13381       return SDValue();
13382 
13383     // Scale the subvector index to account for any bitcast.
13384     int NumExtElts = ExtVT.getVectorNumElements();
13385     if (0 == (NumExtElts % NumElts))
13386       ExtIdx /= (NumExtElts / NumElts);
13387     else if (0 == (NumElts % NumExtElts))
13388       ExtIdx *= (NumElts / NumExtElts);
13389     else
13390       return SDValue();
13391 
13392     // At most we can reference 2 inputs in the final shuffle.
13393     if (SV0.isUndef() || SV0 == ExtVec) {
13394       SV0 = ExtVec;
13395       for (int i = 0; i != NumOpElts; ++i)
13396         Mask.push_back(i + ExtIdx);
13397     } else if (SV1.isUndef() || SV1 == ExtVec) {
13398       SV1 = ExtVec;
13399       for (int i = 0; i != NumOpElts; ++i)
13400         Mask.push_back(i + ExtIdx + NumElts);
13401     } else {
13402       return SDValue();
13403     }
13404   }
13405 
13406   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13407     return SDValue();
13408 
13409   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13410                               DAG.getBitcast(VT, SV1), Mask);
13411 }
13412 
13413 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13414   // If we only have one input vector, we don't need to do any concatenation.
13415   if (N->getNumOperands() == 1)
13416     return N->getOperand(0);
13417 
13418   // Check if all of the operands are undefs.
13419   EVT VT = N->getValueType(0);
13420   if (ISD::allOperandsUndef(N))
13421     return DAG.getUNDEF(VT);
13422 
13423   // Optimize concat_vectors where all but the first of the vectors are undef.
13424   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13425         return Op.isUndef();
13426       })) {
13427     SDValue In = N->getOperand(0);
13428     assert(In.getValueType().isVector() && "Must concat vectors");
13429 
13430     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13431     if (In->getOpcode() == ISD::BITCAST &&
13432         !In->getOperand(0)->getValueType(0).isVector()) {
13433       SDValue Scalar = In->getOperand(0);
13434 
13435       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13436       // look through the trunc so we can still do the transform:
13437       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13438       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13439           !TLI.isTypeLegal(Scalar.getValueType()) &&
13440           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13441         Scalar = Scalar->getOperand(0);
13442 
13443       EVT SclTy = Scalar->getValueType(0);
13444 
13445       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13446         return SDValue();
13447 
13448       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13449                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13450       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13451         return SDValue();
13452 
13453       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
13454       return DAG.getBitcast(VT, Res);
13455     }
13456   }
13457 
13458   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13459   // We have already tested above for an UNDEF only concatenation.
13460   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13461   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13462   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13463     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13464   };
13465   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13466     SmallVector<SDValue, 8> Opnds;
13467     EVT SVT = VT.getScalarType();
13468 
13469     EVT MinVT = SVT;
13470     if (!SVT.isFloatingPoint()) {
13471       // If BUILD_VECTOR are from built from integer, they may have different
13472       // operand types. Get the smallest type and truncate all operands to it.
13473       bool FoundMinVT = false;
13474       for (const SDValue &Op : N->ops())
13475         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13476           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13477           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13478           FoundMinVT = true;
13479         }
13480       assert(FoundMinVT && "Concat vector type mismatch");
13481     }
13482 
13483     for (const SDValue &Op : N->ops()) {
13484       EVT OpVT = Op.getValueType();
13485       unsigned NumElts = OpVT.getVectorNumElements();
13486 
13487       if (ISD::UNDEF == Op.getOpcode())
13488         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13489 
13490       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13491         if (SVT.isFloatingPoint()) {
13492           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13493           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13494         } else {
13495           for (unsigned i = 0; i != NumElts; ++i)
13496             Opnds.push_back(
13497                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13498         }
13499       }
13500     }
13501 
13502     assert(VT.getVectorNumElements() == Opnds.size() &&
13503            "Concat vector type mismatch");
13504     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13505   }
13506 
13507   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13508   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13509     return V;
13510 
13511   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13512   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13513     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13514       return V;
13515 
13516   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13517   // nodes often generate nop CONCAT_VECTOR nodes.
13518   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13519   // place the incoming vectors at the exact same location.
13520   SDValue SingleSource = SDValue();
13521   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13522 
13523   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13524     SDValue Op = N->getOperand(i);
13525 
13526     if (Op.isUndef())
13527       continue;
13528 
13529     // Check if this is the identity extract:
13530     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13531       return SDValue();
13532 
13533     // Find the single incoming vector for the extract_subvector.
13534     if (SingleSource.getNode()) {
13535       if (Op.getOperand(0) != SingleSource)
13536         return SDValue();
13537     } else {
13538       SingleSource = Op.getOperand(0);
13539 
13540       // Check the source type is the same as the type of the result.
13541       // If not, this concat may extend the vector, so we can not
13542       // optimize it away.
13543       if (SingleSource.getValueType() != N->getValueType(0))
13544         return SDValue();
13545     }
13546 
13547     unsigned IdentityIndex = i * PartNumElem;
13548     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13549     // The extract index must be constant.
13550     if (!CS)
13551       return SDValue();
13552 
13553     // Check that we are reading from the identity index.
13554     if (CS->getZExtValue() != IdentityIndex)
13555       return SDValue();
13556   }
13557 
13558   if (SingleSource.getNode())
13559     return SingleSource;
13560 
13561   return SDValue();
13562 }
13563 
13564 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13565   EVT NVT = N->getValueType(0);
13566   SDValue V = N->getOperand(0);
13567 
13568   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13569     // Combine:
13570     //    (extract_subvec (concat V1, V2, ...), i)
13571     // Into:
13572     //    Vi if possible
13573     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13574     // type.
13575     if (V->getOperand(0).getValueType() != NVT)
13576       return SDValue();
13577     unsigned Idx = N->getConstantOperandVal(1);
13578     unsigned NumElems = NVT.getVectorNumElements();
13579     assert((Idx % NumElems) == 0 &&
13580            "IDX in concat is not a multiple of the result vector length.");
13581     return V->getOperand(Idx / NumElems);
13582   }
13583 
13584   // Skip bitcasting
13585   if (V->getOpcode() == ISD::BITCAST)
13586     V = V.getOperand(0);
13587 
13588   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13589     // Handle only simple case where vector being inserted and vector
13590     // being extracted are of same type, and are half size of larger vectors.
13591     EVT BigVT = V->getOperand(0).getValueType();
13592     EVT SmallVT = V->getOperand(1).getValueType();
13593     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13594       return SDValue();
13595 
13596     // Only handle cases where both indexes are constants with the same type.
13597     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13598     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13599 
13600     if (InsIdx && ExtIdx &&
13601         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13602         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13603       // Combine:
13604       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13605       // Into:
13606       //    indices are equal or bit offsets are equal => V1
13607       //    otherwise => (extract_subvec V1, ExtIdx)
13608       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
13609           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
13610         return DAG.getBitcast(NVT, V->getOperand(1));
13611       return DAG.getNode(
13612           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
13613           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13614           N->getOperand(1));
13615     }
13616   }
13617 
13618   return SDValue();
13619 }
13620 
13621 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13622                                                  SDValue V, SelectionDAG &DAG) {
13623   SDLoc DL(V);
13624   EVT VT = V.getValueType();
13625 
13626   switch (V.getOpcode()) {
13627   default:
13628     return V;
13629 
13630   case ISD::CONCAT_VECTORS: {
13631     EVT OpVT = V->getOperand(0).getValueType();
13632     int OpSize = OpVT.getVectorNumElements();
13633     SmallBitVector OpUsedElements(OpSize, false);
13634     bool FoundSimplification = false;
13635     SmallVector<SDValue, 4> NewOps;
13636     NewOps.reserve(V->getNumOperands());
13637     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13638       SDValue Op = V->getOperand(i);
13639       bool OpUsed = false;
13640       for (int j = 0; j < OpSize; ++j)
13641         if (UsedElements[i * OpSize + j]) {
13642           OpUsedElements[j] = true;
13643           OpUsed = true;
13644         }
13645       NewOps.push_back(
13646           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13647                  : DAG.getUNDEF(OpVT));
13648       FoundSimplification |= Op == NewOps.back();
13649       OpUsedElements.reset();
13650     }
13651     if (FoundSimplification)
13652       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13653     return V;
13654   }
13655 
13656   case ISD::INSERT_SUBVECTOR: {
13657     SDValue BaseV = V->getOperand(0);
13658     SDValue SubV = V->getOperand(1);
13659     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13660     if (!IdxN)
13661       return V;
13662 
13663     int SubSize = SubV.getValueType().getVectorNumElements();
13664     int Idx = IdxN->getZExtValue();
13665     bool SubVectorUsed = false;
13666     SmallBitVector SubUsedElements(SubSize, false);
13667     for (int i = 0; i < SubSize; ++i)
13668       if (UsedElements[i + Idx]) {
13669         SubVectorUsed = true;
13670         SubUsedElements[i] = true;
13671         UsedElements[i + Idx] = false;
13672       }
13673 
13674     // Now recurse on both the base and sub vectors.
13675     SDValue SimplifiedSubV =
13676         SubVectorUsed
13677             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13678             : DAG.getUNDEF(SubV.getValueType());
13679     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13680     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13681       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13682                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13683     return V;
13684   }
13685   }
13686 }
13687 
13688 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13689                                        SDValue N1, SelectionDAG &DAG) {
13690   EVT VT = SVN->getValueType(0);
13691   int NumElts = VT.getVectorNumElements();
13692   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13693   for (int M : SVN->getMask())
13694     if (M >= 0 && M < NumElts)
13695       N0UsedElements[M] = true;
13696     else if (M >= NumElts)
13697       N1UsedElements[M - NumElts] = true;
13698 
13699   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13700   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13701   if (S0 == N0 && S1 == N1)
13702     return SDValue();
13703 
13704   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13705 }
13706 
13707 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13708 // or turn a shuffle of a single concat into simpler shuffle then concat.
13709 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13710   EVT VT = N->getValueType(0);
13711   unsigned NumElts = VT.getVectorNumElements();
13712 
13713   SDValue N0 = N->getOperand(0);
13714   SDValue N1 = N->getOperand(1);
13715   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13716 
13717   SmallVector<SDValue, 4> Ops;
13718   EVT ConcatVT = N0.getOperand(0).getValueType();
13719   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13720   unsigned NumConcats = NumElts / NumElemsPerConcat;
13721 
13722   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13723   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13724   // half vector elements.
13725   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13726       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13727                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13728     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13729                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13730     N1 = DAG.getUNDEF(ConcatVT);
13731     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13732   }
13733 
13734   // Look at every vector that's inserted. We're looking for exact
13735   // subvector-sized copies from a concatenated vector
13736   for (unsigned I = 0; I != NumConcats; ++I) {
13737     // Make sure we're dealing with a copy.
13738     unsigned Begin = I * NumElemsPerConcat;
13739     bool AllUndef = true, NoUndef = true;
13740     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13741       if (SVN->getMaskElt(J) >= 0)
13742         AllUndef = false;
13743       else
13744         NoUndef = false;
13745     }
13746 
13747     if (NoUndef) {
13748       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13749         return SDValue();
13750 
13751       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13752         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13753           return SDValue();
13754 
13755       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13756       if (FirstElt < N0.getNumOperands())
13757         Ops.push_back(N0.getOperand(FirstElt));
13758       else
13759         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13760 
13761     } else if (AllUndef) {
13762       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13763     } else { // Mixed with general masks and undefs, can't do optimization.
13764       return SDValue();
13765     }
13766   }
13767 
13768   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13769 }
13770 
13771 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13772   EVT VT = N->getValueType(0);
13773   unsigned NumElts = VT.getVectorNumElements();
13774 
13775   SDValue N0 = N->getOperand(0);
13776   SDValue N1 = N->getOperand(1);
13777 
13778   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13779 
13780   // Canonicalize shuffle undef, undef -> undef
13781   if (N0.isUndef() && N1.isUndef())
13782     return DAG.getUNDEF(VT);
13783 
13784   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13785 
13786   // Canonicalize shuffle v, v -> v, undef
13787   if (N0 == N1) {
13788     SmallVector<int, 8> NewMask;
13789     for (unsigned i = 0; i != NumElts; ++i) {
13790       int Idx = SVN->getMaskElt(i);
13791       if (Idx >= (int)NumElts) Idx -= NumElts;
13792       NewMask.push_back(Idx);
13793     }
13794     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
13795   }
13796 
13797   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13798   if (N0.isUndef())
13799     return DAG.getCommutedVectorShuffle(*SVN);
13800 
13801   // Remove references to rhs if it is undef
13802   if (N1.isUndef()) {
13803     bool Changed = false;
13804     SmallVector<int, 8> NewMask;
13805     for (unsigned i = 0; i != NumElts; ++i) {
13806       int Idx = SVN->getMaskElt(i);
13807       if (Idx >= (int)NumElts) {
13808         Idx = -1;
13809         Changed = true;
13810       }
13811       NewMask.push_back(Idx);
13812     }
13813     if (Changed)
13814       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
13815   }
13816 
13817   // If it is a splat, check if the argument vector is another splat or a
13818   // build_vector.
13819   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13820     SDNode *V = N0.getNode();
13821 
13822     // If this is a bit convert that changes the element type of the vector but
13823     // not the number of vector elements, look through it.  Be careful not to
13824     // look though conversions that change things like v4f32 to v2f64.
13825     if (V->getOpcode() == ISD::BITCAST) {
13826       SDValue ConvInput = V->getOperand(0);
13827       if (ConvInput.getValueType().isVector() &&
13828           ConvInput.getValueType().getVectorNumElements() == NumElts)
13829         V = ConvInput.getNode();
13830     }
13831 
13832     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13833       assert(V->getNumOperands() == NumElts &&
13834              "BUILD_VECTOR has wrong number of operands");
13835       SDValue Base;
13836       bool AllSame = true;
13837       for (unsigned i = 0; i != NumElts; ++i) {
13838         if (!V->getOperand(i).isUndef()) {
13839           Base = V->getOperand(i);
13840           break;
13841         }
13842       }
13843       // Splat of <u, u, u, u>, return <u, u, u, u>
13844       if (!Base.getNode())
13845         return N0;
13846       for (unsigned i = 0; i != NumElts; ++i) {
13847         if (V->getOperand(i) != Base) {
13848           AllSame = false;
13849           break;
13850         }
13851       }
13852       // Splat of <x, x, x, x>, return <x, x, x, x>
13853       if (AllSame)
13854         return N0;
13855 
13856       // Canonicalize any other splat as a build_vector.
13857       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13858       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13859       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13860 
13861       // We may have jumped through bitcasts, so the type of the
13862       // BUILD_VECTOR may not match the type of the shuffle.
13863       if (V->getValueType(0) != VT)
13864         NewBV = DAG.getBitcast(VT, NewBV);
13865       return NewBV;
13866     }
13867   }
13868 
13869   // There are various patterns used to build up a vector from smaller vectors,
13870   // subvectors, or elements. Scan chains of these and replace unused insertions
13871   // or components with undef.
13872   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13873     return S;
13874 
13875   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13876       Level < AfterLegalizeVectorOps &&
13877       (N1.isUndef() ||
13878       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13879        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13880     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13881       return V;
13882   }
13883 
13884   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13885   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13886   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13887     SmallVector<SDValue, 8> Ops;
13888     for (int M : SVN->getMask()) {
13889       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13890       if (M >= 0) {
13891         int Idx = M % NumElts;
13892         SDValue &S = (M < (int)NumElts ? N0 : N1);
13893         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13894           Op = S.getOperand(Idx);
13895         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13896           if (Idx == 0)
13897             Op = S.getOperand(0);
13898         } else {
13899           // Operand can't be combined - bail out.
13900           break;
13901         }
13902       }
13903       Ops.push_back(Op);
13904     }
13905     if (Ops.size() == VT.getVectorNumElements()) {
13906       // BUILD_VECTOR requires all inputs to be of the same type, find the
13907       // maximum type and extend them all.
13908       EVT SVT = VT.getScalarType();
13909       if (SVT.isInteger())
13910         for (SDValue &Op : Ops)
13911           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13912       if (SVT != VT.getScalarType())
13913         for (SDValue &Op : Ops)
13914           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13915                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13916                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13917       return DAG.getBuildVector(VT, SDLoc(N), Ops);
13918     }
13919   }
13920 
13921   // If this shuffle only has a single input that is a bitcasted shuffle,
13922   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13923   // back to their original types.
13924   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13925       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13926       TLI.isTypeLegal(VT)) {
13927 
13928     // Peek through the bitcast only if there is one user.
13929     SDValue BC0 = N0;
13930     while (BC0.getOpcode() == ISD::BITCAST) {
13931       if (!BC0.hasOneUse())
13932         break;
13933       BC0 = BC0.getOperand(0);
13934     }
13935 
13936     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13937       if (Scale == 1)
13938         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13939 
13940       SmallVector<int, 8> NewMask;
13941       for (int M : Mask)
13942         for (int s = 0; s != Scale; ++s)
13943           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13944       return NewMask;
13945     };
13946 
13947     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13948       EVT SVT = VT.getScalarType();
13949       EVT InnerVT = BC0->getValueType(0);
13950       EVT InnerSVT = InnerVT.getScalarType();
13951 
13952       // Determine which shuffle works with the smaller scalar type.
13953       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13954       EVT ScaleSVT = ScaleVT.getScalarType();
13955 
13956       if (TLI.isTypeLegal(ScaleVT) &&
13957           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13958           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13959 
13960         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13961         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13962 
13963         // Scale the shuffle masks to the smaller scalar type.
13964         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13965         SmallVector<int, 8> InnerMask =
13966             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13967         SmallVector<int, 8> OuterMask =
13968             ScaleShuffleMask(SVN->getMask(), OuterScale);
13969 
13970         // Merge the shuffle masks.
13971         SmallVector<int, 8> NewMask;
13972         for (int M : OuterMask)
13973           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13974 
13975         // Test for shuffle mask legality over both commutations.
13976         SDValue SV0 = BC0->getOperand(0);
13977         SDValue SV1 = BC0->getOperand(1);
13978         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13979         if (!LegalMask) {
13980           std::swap(SV0, SV1);
13981           ShuffleVectorSDNode::commuteMask(NewMask);
13982           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13983         }
13984 
13985         if (LegalMask) {
13986           SV0 = DAG.getBitcast(ScaleVT, SV0);
13987           SV1 = DAG.getBitcast(ScaleVT, SV1);
13988           return DAG.getBitcast(
13989               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13990         }
13991       }
13992     }
13993   }
13994 
13995   // Canonicalize shuffles according to rules:
13996   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13997   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13998   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13999   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
14000       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
14001       TLI.isTypeLegal(VT)) {
14002     // The incoming shuffle must be of the same type as the result of the
14003     // current shuffle.
14004     assert(N1->getOperand(0).getValueType() == VT &&
14005            "Shuffle types don't match");
14006 
14007     SDValue SV0 = N1->getOperand(0);
14008     SDValue SV1 = N1->getOperand(1);
14009     bool HasSameOp0 = N0 == SV0;
14010     bool IsSV1Undef = SV1.isUndef();
14011     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
14012       // Commute the operands of this shuffle so that next rule
14013       // will trigger.
14014       return DAG.getCommutedVectorShuffle(*SVN);
14015   }
14016 
14017   // Try to fold according to rules:
14018   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14019   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14020   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14021   // Don't try to fold shuffles with illegal type.
14022   // Only fold if this shuffle is the only user of the other shuffle.
14023   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
14024       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
14025     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
14026 
14027     // The incoming shuffle must be of the same type as the result of the
14028     // current shuffle.
14029     assert(OtherSV->getOperand(0).getValueType() == VT &&
14030            "Shuffle types don't match");
14031 
14032     SDValue SV0, SV1;
14033     SmallVector<int, 4> Mask;
14034     // Compute the combined shuffle mask for a shuffle with SV0 as the first
14035     // operand, and SV1 as the second operand.
14036     for (unsigned i = 0; i != NumElts; ++i) {
14037       int Idx = SVN->getMaskElt(i);
14038       if (Idx < 0) {
14039         // Propagate Undef.
14040         Mask.push_back(Idx);
14041         continue;
14042       }
14043 
14044       SDValue CurrentVec;
14045       if (Idx < (int)NumElts) {
14046         // This shuffle index refers to the inner shuffle N0. Lookup the inner
14047         // shuffle mask to identify which vector is actually referenced.
14048         Idx = OtherSV->getMaskElt(Idx);
14049         if (Idx < 0) {
14050           // Propagate Undef.
14051           Mask.push_back(Idx);
14052           continue;
14053         }
14054 
14055         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
14056                                            : OtherSV->getOperand(1);
14057       } else {
14058         // This shuffle index references an element within N1.
14059         CurrentVec = N1;
14060       }
14061 
14062       // Simple case where 'CurrentVec' is UNDEF.
14063       if (CurrentVec.isUndef()) {
14064         Mask.push_back(-1);
14065         continue;
14066       }
14067 
14068       // Canonicalize the shuffle index. We don't know yet if CurrentVec
14069       // will be the first or second operand of the combined shuffle.
14070       Idx = Idx % NumElts;
14071       if (!SV0.getNode() || SV0 == CurrentVec) {
14072         // Ok. CurrentVec is the left hand side.
14073         // Update the mask accordingly.
14074         SV0 = CurrentVec;
14075         Mask.push_back(Idx);
14076         continue;
14077       }
14078 
14079       // Bail out if we cannot convert the shuffle pair into a single shuffle.
14080       if (SV1.getNode() && SV1 != CurrentVec)
14081         return SDValue();
14082 
14083       // Ok. CurrentVec is the right hand side.
14084       // Update the mask accordingly.
14085       SV1 = CurrentVec;
14086       Mask.push_back(Idx + NumElts);
14087     }
14088 
14089     // Check if all indices in Mask are Undef. In case, propagate Undef.
14090     bool isUndefMask = true;
14091     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
14092       isUndefMask &= Mask[i] < 0;
14093 
14094     if (isUndefMask)
14095       return DAG.getUNDEF(VT);
14096 
14097     if (!SV0.getNode())
14098       SV0 = DAG.getUNDEF(VT);
14099     if (!SV1.getNode())
14100       SV1 = DAG.getUNDEF(VT);
14101 
14102     // Avoid introducing shuffles with illegal mask.
14103     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14104       ShuffleVectorSDNode::commuteMask(Mask);
14105 
14106       if (!TLI.isShuffleMaskLegal(Mask, VT))
14107         return SDValue();
14108 
14109       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14110       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14111       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14112       std::swap(SV0, SV1);
14113     }
14114 
14115     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14116     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14117     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14118     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14119   }
14120 
14121   return SDValue();
14122 }
14123 
14124 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14125   SDValue InVal = N->getOperand(0);
14126   EVT VT = N->getValueType(0);
14127 
14128   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14129   // with a VECTOR_SHUFFLE.
14130   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14131     SDValue InVec = InVal->getOperand(0);
14132     SDValue EltNo = InVal->getOperand(1);
14133 
14134     // FIXME: We could support implicit truncation if the shuffle can be
14135     // scaled to a smaller vector scalar type.
14136     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
14137     if (C0 && VT == InVec.getValueType() &&
14138         VT.getScalarType() == InVal.getValueType()) {
14139       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
14140       int Elt = C0->getZExtValue();
14141       NewMask[0] = Elt;
14142 
14143       if (TLI.isShuffleMaskLegal(NewMask, VT))
14144         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
14145                                     NewMask);
14146     }
14147   }
14148 
14149   return SDValue();
14150 }
14151 
14152 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
14153   EVT VT = N->getValueType(0);
14154   SDValue N0 = N->getOperand(0);
14155   SDValue N1 = N->getOperand(1);
14156   SDValue N2 = N->getOperand(2);
14157 
14158   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
14159   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
14160   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
14161   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
14162       N0.getOperand(1).getValueType() == N1.getValueType() &&
14163       N0.getOperand(2) == N2)
14164     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
14165                        N1, N2);
14166 
14167   if (N0.getValueType() != N1.getValueType())
14168     return SDValue();
14169 
14170   // If the input vector is a concatenation, and the insert replaces
14171   // one of the halves, we can optimize into a single concat_vectors.
14172   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
14173       N2.getOpcode() == ISD::Constant) {
14174     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
14175 
14176     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14177     // (concat_vectors Z, Y)
14178     if (InsIdx == 0)
14179       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
14180                          N0.getOperand(1));
14181 
14182     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14183     // (concat_vectors X, Z)
14184     if (InsIdx == VT.getVectorNumElements() / 2)
14185       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
14186                          N1);
14187   }
14188 
14189   return SDValue();
14190 }
14191 
14192 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
14193   SDValue N0 = N->getOperand(0);
14194 
14195   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
14196   if (N0->getOpcode() == ISD::FP16_TO_FP)
14197     return N0->getOperand(0);
14198 
14199   return SDValue();
14200 }
14201 
14202 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
14203   SDValue N0 = N->getOperand(0);
14204 
14205   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
14206   if (N0->getOpcode() == ISD::AND) {
14207     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
14208     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
14209       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
14210                          N0.getOperand(0));
14211     }
14212   }
14213 
14214   return SDValue();
14215 }
14216 
14217 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
14218 /// with the destination vector and a zero vector.
14219 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
14220 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
14221 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
14222   EVT VT = N->getValueType(0);
14223   SDValue LHS = N->getOperand(0);
14224   SDValue RHS = N->getOperand(1);
14225   SDLoc DL(N);
14226 
14227   // Make sure we're not running after operation legalization where it
14228   // may have custom lowered the vector shuffles.
14229   if (LegalOperations)
14230     return SDValue();
14231 
14232   if (N->getOpcode() != ISD::AND)
14233     return SDValue();
14234 
14235   if (RHS.getOpcode() == ISD::BITCAST)
14236     RHS = RHS.getOperand(0);
14237 
14238   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
14239     return SDValue();
14240 
14241   EVT RVT = RHS.getValueType();
14242   unsigned NumElts = RHS.getNumOperands();
14243 
14244   // Attempt to create a valid clear mask, splitting the mask into
14245   // sub elements and checking to see if each is
14246   // all zeros or all ones - suitable for shuffle masking.
14247   auto BuildClearMask = [&](int Split) {
14248     int NumSubElts = NumElts * Split;
14249     int NumSubBits = RVT.getScalarSizeInBits() / Split;
14250 
14251     SmallVector<int, 8> Indices;
14252     for (int i = 0; i != NumSubElts; ++i) {
14253       int EltIdx = i / Split;
14254       int SubIdx = i % Split;
14255       SDValue Elt = RHS.getOperand(EltIdx);
14256       if (Elt.isUndef()) {
14257         Indices.push_back(-1);
14258         continue;
14259       }
14260 
14261       APInt Bits;
14262       if (isa<ConstantSDNode>(Elt))
14263         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
14264       else if (isa<ConstantFPSDNode>(Elt))
14265         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
14266       else
14267         return SDValue();
14268 
14269       // Extract the sub element from the constant bit mask.
14270       if (DAG.getDataLayout().isBigEndian()) {
14271         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
14272       } else {
14273         Bits = Bits.lshr(SubIdx * NumSubBits);
14274       }
14275 
14276       if (Split > 1)
14277         Bits = Bits.trunc(NumSubBits);
14278 
14279       if (Bits.isAllOnesValue())
14280         Indices.push_back(i);
14281       else if (Bits == 0)
14282         Indices.push_back(i + NumSubElts);
14283       else
14284         return SDValue();
14285     }
14286 
14287     // Let's see if the target supports this vector_shuffle.
14288     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
14289     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
14290     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
14291       return SDValue();
14292 
14293     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
14294     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
14295                                                    DAG.getBitcast(ClearVT, LHS),
14296                                                    Zero, Indices));
14297   };
14298 
14299   // Determine maximum split level (byte level masking).
14300   int MaxSplit = 1;
14301   if (RVT.getScalarSizeInBits() % 8 == 0)
14302     MaxSplit = RVT.getScalarSizeInBits() / 8;
14303 
14304   for (int Split = 1; Split <= MaxSplit; ++Split)
14305     if (RVT.getScalarSizeInBits() % Split == 0)
14306       if (SDValue S = BuildClearMask(Split))
14307         return S;
14308 
14309   return SDValue();
14310 }
14311 
14312 /// Visit a binary vector operation, like ADD.
14313 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
14314   assert(N->getValueType(0).isVector() &&
14315          "SimplifyVBinOp only works on vectors!");
14316 
14317   SDValue LHS = N->getOperand(0);
14318   SDValue RHS = N->getOperand(1);
14319   SDValue Ops[] = {LHS, RHS};
14320 
14321   // See if we can constant fold the vector operation.
14322   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
14323           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
14324     return Fold;
14325 
14326   // Try to convert a constant mask AND into a shuffle clear mask.
14327   if (SDValue Shuffle = XformToShuffleWithZero(N))
14328     return Shuffle;
14329 
14330   // Type legalization might introduce new shuffles in the DAG.
14331   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
14332   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
14333   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
14334       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
14335       LHS.getOperand(1).isUndef() &&
14336       RHS.getOperand(1).isUndef()) {
14337     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
14338     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
14339 
14340     if (SVN0->getMask().equals(SVN1->getMask())) {
14341       EVT VT = N->getValueType(0);
14342       SDValue UndefVector = LHS.getOperand(1);
14343       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
14344                                      LHS.getOperand(0), RHS.getOperand(0),
14345                                      N->getFlags());
14346       AddUsersToWorklist(N);
14347       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
14348                                   SVN0->getMask());
14349     }
14350   }
14351 
14352   return SDValue();
14353 }
14354 
14355 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
14356                                     SDValue N2) {
14357   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
14358 
14359   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
14360                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
14361 
14362   // If we got a simplified select_cc node back from SimplifySelectCC, then
14363   // break it down into a new SETCC node, and a new SELECT node, and then return
14364   // the SELECT node, since we were called with a SELECT node.
14365   if (SCC.getNode()) {
14366     // Check to see if we got a select_cc back (to turn into setcc/select).
14367     // Otherwise, just return whatever node we got back, like fabs.
14368     if (SCC.getOpcode() == ISD::SELECT_CC) {
14369       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
14370                                   N0.getValueType(),
14371                                   SCC.getOperand(0), SCC.getOperand(1),
14372                                   SCC.getOperand(4));
14373       AddToWorklist(SETCC.getNode());
14374       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14375                            SCC.getOperand(2), SCC.getOperand(3));
14376     }
14377 
14378     return SCC;
14379   }
14380   return SDValue();
14381 }
14382 
14383 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14384 /// being selected between, see if we can simplify the select.  Callers of this
14385 /// should assume that TheSelect is deleted if this returns true.  As such, they
14386 /// should return the appropriate thing (e.g. the node) back to the top-level of
14387 /// the DAG combiner loop to avoid it being looked at.
14388 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14389                                     SDValue RHS) {
14390 
14391   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14392   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14393   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14394     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14395       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14396       SDValue Sqrt = RHS;
14397       ISD::CondCode CC;
14398       SDValue CmpLHS;
14399       const ConstantFPSDNode *Zero = nullptr;
14400 
14401       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14402         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14403         CmpLHS = TheSelect->getOperand(0);
14404         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14405       } else {
14406         // SELECT or VSELECT
14407         SDValue Cmp = TheSelect->getOperand(0);
14408         if (Cmp.getOpcode() == ISD::SETCC) {
14409           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14410           CmpLHS = Cmp.getOperand(0);
14411           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14412         }
14413       }
14414       if (Zero && Zero->isZero() &&
14415           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14416           CC == ISD::SETULT || CC == ISD::SETLT)) {
14417         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14418         CombineTo(TheSelect, Sqrt);
14419         return true;
14420       }
14421     }
14422   }
14423   // Cannot simplify select with vector condition
14424   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14425 
14426   // If this is a select from two identical things, try to pull the operation
14427   // through the select.
14428   if (LHS.getOpcode() != RHS.getOpcode() ||
14429       !LHS.hasOneUse() || !RHS.hasOneUse())
14430     return false;
14431 
14432   // If this is a load and the token chain is identical, replace the select
14433   // of two loads with a load through a select of the address to load from.
14434   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14435   // constants have been dropped into the constant pool.
14436   if (LHS.getOpcode() == ISD::LOAD) {
14437     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14438     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14439 
14440     // Token chains must be identical.
14441     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14442         // Do not let this transformation reduce the number of volatile loads.
14443         LLD->isVolatile() || RLD->isVolatile() ||
14444         // FIXME: If either is a pre/post inc/dec load,
14445         // we'd need to split out the address adjustment.
14446         LLD->isIndexed() || RLD->isIndexed() ||
14447         // If this is an EXTLOAD, the VT's must match.
14448         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14449         // If this is an EXTLOAD, the kind of extension must match.
14450         (LLD->getExtensionType() != RLD->getExtensionType() &&
14451          // The only exception is if one of the extensions is anyext.
14452          LLD->getExtensionType() != ISD::EXTLOAD &&
14453          RLD->getExtensionType() != ISD::EXTLOAD) ||
14454         // FIXME: this discards src value information.  This is
14455         // over-conservative. It would be beneficial to be able to remember
14456         // both potential memory locations.  Since we are discarding
14457         // src value info, don't do the transformation if the memory
14458         // locations are not in the default address space.
14459         LLD->getPointerInfo().getAddrSpace() != 0 ||
14460         RLD->getPointerInfo().getAddrSpace() != 0 ||
14461         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14462                                       LLD->getBasePtr().getValueType()))
14463       return false;
14464 
14465     // Check that the select condition doesn't reach either load.  If so,
14466     // folding this will induce a cycle into the DAG.  If not, this is safe to
14467     // xform, so create a select of the addresses.
14468     SDValue Addr;
14469     if (TheSelect->getOpcode() == ISD::SELECT) {
14470       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14471       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14472           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14473         return false;
14474       // The loads must not depend on one another.
14475       if (LLD->isPredecessorOf(RLD) ||
14476           RLD->isPredecessorOf(LLD))
14477         return false;
14478       Addr = DAG.getSelect(SDLoc(TheSelect),
14479                            LLD->getBasePtr().getValueType(),
14480                            TheSelect->getOperand(0), LLD->getBasePtr(),
14481                            RLD->getBasePtr());
14482     } else {  // Otherwise SELECT_CC
14483       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14484       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14485 
14486       if ((LLD->hasAnyUseOfValue(1) &&
14487            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14488           (RLD->hasAnyUseOfValue(1) &&
14489            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14490         return false;
14491 
14492       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14493                          LLD->getBasePtr().getValueType(),
14494                          TheSelect->getOperand(0),
14495                          TheSelect->getOperand(1),
14496                          LLD->getBasePtr(), RLD->getBasePtr(),
14497                          TheSelect->getOperand(4));
14498     }
14499 
14500     SDValue Load;
14501     // It is safe to replace the two loads if they have different alignments,
14502     // but the new load must be the minimum (most restrictive) alignment of the
14503     // inputs.
14504     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14505     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
14506     if (!RLD->isInvariant())
14507       MMOFlags &= ~MachineMemOperand::MOInvariant;
14508     if (!RLD->isDereferenceable())
14509       MMOFlags &= ~MachineMemOperand::MODereferenceable;
14510     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14511       // FIXME: Discards pointer and AA info.
14512       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
14513                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
14514                          MMOFlags);
14515     } else {
14516       // FIXME: Discards pointer and AA info.
14517       Load = DAG.getExtLoad(
14518           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
14519                                                   : LLD->getExtensionType(),
14520           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
14521           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
14522     }
14523 
14524     // Users of the select now use the result of the load.
14525     CombineTo(TheSelect, Load);
14526 
14527     // Users of the old loads now use the new load's chain.  We know the
14528     // old-load value is dead now.
14529     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14530     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14531     return true;
14532   }
14533 
14534   return false;
14535 }
14536 
14537 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14538 /// where 'cond' is the comparison specified by CC.
14539 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
14540                                       SDValue N2, SDValue N3, ISD::CondCode CC,
14541                                       bool NotExtCompare) {
14542   // (x ? y : y) -> y.
14543   if (N2 == N3) return N2;
14544 
14545   EVT VT = N2.getValueType();
14546   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14547   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14548 
14549   // Determine if the condition we're dealing with is constant
14550   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14551                               N0, N1, CC, DL, false);
14552   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14553 
14554   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14555     // fold select_cc true, x, y -> x
14556     // fold select_cc false, x, y -> y
14557     return !SCCC->isNullValue() ? N2 : N3;
14558   }
14559 
14560   // Check to see if we can simplify the select into an fabs node
14561   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14562     // Allow either -0.0 or 0.0
14563     if (CFP->isZero()) {
14564       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14565       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14566           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14567           N2 == N3.getOperand(0))
14568         return DAG.getNode(ISD::FABS, DL, VT, N0);
14569 
14570       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14571       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14572           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14573           N2.getOperand(0) == N3)
14574         return DAG.getNode(ISD::FABS, DL, VT, N3);
14575     }
14576   }
14577 
14578   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14579   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14580   // in it.  This is a win when the constant is not otherwise available because
14581   // it replaces two constant pool loads with one.  We only do this if the FP
14582   // type is known to be legal, because if it isn't, then we are before legalize
14583   // types an we want the other legalization to happen first (e.g. to avoid
14584   // messing with soft float) and if the ConstantFP is not legal, because if
14585   // it is legal, we may not need to store the FP constant in a constant pool.
14586   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14587     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14588       if (TLI.isTypeLegal(N2.getValueType()) &&
14589           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14590                TargetLowering::Legal &&
14591            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14592            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14593           // If both constants have multiple uses, then we won't need to do an
14594           // extra load, they are likely around in registers for other users.
14595           (TV->hasOneUse() || FV->hasOneUse())) {
14596         Constant *Elts[] = {
14597           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14598           const_cast<ConstantFP*>(TV->getConstantFPValue())
14599         };
14600         Type *FPTy = Elts[0]->getType();
14601         const DataLayout &TD = DAG.getDataLayout();
14602 
14603         // Create a ConstantArray of the two constants.
14604         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14605         SDValue CPIdx =
14606             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14607                                 TD.getPrefTypeAlignment(FPTy));
14608         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14609 
14610         // Get the offsets to the 0 and 1 element of the array so that we can
14611         // select between them.
14612         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14613         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14614         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14615 
14616         SDValue Cond = DAG.getSetCC(DL,
14617                                     getSetCCResultType(N0.getValueType()),
14618                                     N0, N1, CC);
14619         AddToWorklist(Cond.getNode());
14620         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14621                                           Cond, One, Zero);
14622         AddToWorklist(CstOffset.getNode());
14623         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14624                             CstOffset);
14625         AddToWorklist(CPIdx.getNode());
14626         return DAG.getLoad(
14627             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14628             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14629             Alignment);
14630       }
14631     }
14632 
14633   // Check to see if we can perform the "gzip trick", transforming
14634   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14635   if (isNullConstant(N3) && CC == ISD::SETLT &&
14636       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14637        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14638     EVT XType = N0.getValueType();
14639     EVT AType = N2.getValueType();
14640     if (XType.bitsGE(AType)) {
14641       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14642       // single-bit constant.
14643       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14644         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14645         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14646         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14647                                        getShiftAmountTy(N0.getValueType()));
14648         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14649                                     XType, N0, ShCt);
14650         AddToWorklist(Shift.getNode());
14651 
14652         if (XType.bitsGT(AType)) {
14653           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14654           AddToWorklist(Shift.getNode());
14655         }
14656 
14657         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14658       }
14659 
14660       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14661                                   XType, N0,
14662                                   DAG.getConstant(XType.getSizeInBits() - 1,
14663                                                   SDLoc(N0),
14664                                          getShiftAmountTy(N0.getValueType())));
14665       AddToWorklist(Shift.getNode());
14666 
14667       if (XType.bitsGT(AType)) {
14668         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14669         AddToWorklist(Shift.getNode());
14670       }
14671 
14672       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14673     }
14674   }
14675 
14676   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14677   // where y is has a single bit set.
14678   // A plaintext description would be, we can turn the SELECT_CC into an AND
14679   // when the condition can be materialized as an all-ones register.  Any
14680   // single bit-test can be materialized as an all-ones register with
14681   // shift-left and shift-right-arith.
14682   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14683       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14684     SDValue AndLHS = N0->getOperand(0);
14685     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14686     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14687       // Shift the tested bit over the sign bit.
14688       const APInt &AndMask = ConstAndRHS->getAPIntValue();
14689       SDValue ShlAmt =
14690         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14691                         getShiftAmountTy(AndLHS.getValueType()));
14692       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14693 
14694       // Now arithmetic right shift it all the way over, so the result is either
14695       // all-ones, or zero.
14696       SDValue ShrAmt =
14697         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14698                         getShiftAmountTy(Shl.getValueType()));
14699       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14700 
14701       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14702     }
14703   }
14704 
14705   // fold select C, 16, 0 -> shl C, 4
14706   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14707       TLI.getBooleanContents(N0.getValueType()) ==
14708           TargetLowering::ZeroOrOneBooleanContent) {
14709 
14710     // If the caller doesn't want us to simplify this into a zext of a compare,
14711     // don't do it.
14712     if (NotExtCompare && N2C->isOne())
14713       return SDValue();
14714 
14715     // Get a SetCC of the condition
14716     // NOTE: Don't create a SETCC if it's not legal on this target.
14717     if (!LegalOperations ||
14718         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14719       SDValue Temp, SCC;
14720       // cast from setcc result type to select result type
14721       if (LegalTypes) {
14722         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14723                             N0, N1, CC);
14724         if (N2.getValueType().bitsLT(SCC.getValueType()))
14725           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14726                                         N2.getValueType());
14727         else
14728           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14729                              N2.getValueType(), SCC);
14730       } else {
14731         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14732         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14733                            N2.getValueType(), SCC);
14734       }
14735 
14736       AddToWorklist(SCC.getNode());
14737       AddToWorklist(Temp.getNode());
14738 
14739       if (N2C->isOne())
14740         return Temp;
14741 
14742       // shl setcc result by log2 n2c
14743       return DAG.getNode(
14744           ISD::SHL, DL, N2.getValueType(), Temp,
14745           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14746                           getShiftAmountTy(Temp.getValueType())));
14747     }
14748   }
14749 
14750   // Check to see if this is an integer abs.
14751   // select_cc setg[te] X,  0,  X, -X ->
14752   // select_cc setgt    X, -1,  X, -X ->
14753   // select_cc setl[te] X,  0, -X,  X ->
14754   // select_cc setlt    X,  1, -X,  X ->
14755   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14756   if (N1C) {
14757     ConstantSDNode *SubC = nullptr;
14758     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14759          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14760         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14761       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14762     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14763               (N1C->isOne() && CC == ISD::SETLT)) &&
14764              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14765       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14766 
14767     EVT XType = N0.getValueType();
14768     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14769       SDLoc DL(N0);
14770       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14771                                   N0,
14772                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14773                                          getShiftAmountTy(N0.getValueType())));
14774       SDValue Add = DAG.getNode(ISD::ADD, DL,
14775                                 XType, N0, Shift);
14776       AddToWorklist(Shift.getNode());
14777       AddToWorklist(Add.getNode());
14778       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14779     }
14780   }
14781 
14782   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14783   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14784   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14785   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14786   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14787   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14788   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14789   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14790   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14791     SDValue ValueOnZero = N2;
14792     SDValue Count = N3;
14793     // If the condition is NE instead of E, swap the operands.
14794     if (CC == ISD::SETNE)
14795       std::swap(ValueOnZero, Count);
14796     // Check if the value on zero is a constant equal to the bits in the type.
14797     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14798       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14799         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14800         // legal, combine to just cttz.
14801         if ((Count.getOpcode() == ISD::CTTZ ||
14802              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14803             N0 == Count.getOperand(0) &&
14804             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14805           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14806         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14807         // legal, combine to just ctlz.
14808         if ((Count.getOpcode() == ISD::CTLZ ||
14809              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14810             N0 == Count.getOperand(0) &&
14811             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14812           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14813       }
14814     }
14815   }
14816 
14817   return SDValue();
14818 }
14819 
14820 /// This is a stub for TargetLowering::SimplifySetCC.
14821 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
14822                                    ISD::CondCode Cond, const SDLoc &DL,
14823                                    bool foldBooleans) {
14824   TargetLowering::DAGCombinerInfo
14825     DagCombineInfo(DAG, Level, false, this);
14826   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14827 }
14828 
14829 /// Given an ISD::SDIV node expressing a divide by constant, return
14830 /// a DAG expression to select that will generate the same value by multiplying
14831 /// by a magic number.
14832 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14833 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14834   // when optimising for minimum size, we don't want to expand a div to a mul
14835   // and a shift.
14836   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14837     return SDValue();
14838 
14839   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14840   if (!C)
14841     return SDValue();
14842 
14843   // Avoid division by zero.
14844   if (C->isNullValue())
14845     return SDValue();
14846 
14847   std::vector<SDNode*> Built;
14848   SDValue S =
14849       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14850 
14851   for (SDNode *N : Built)
14852     AddToWorklist(N);
14853   return S;
14854 }
14855 
14856 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14857 /// DAG expression that will generate the same value by right shifting.
14858 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14859   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14860   if (!C)
14861     return SDValue();
14862 
14863   // Avoid division by zero.
14864   if (C->isNullValue())
14865     return SDValue();
14866 
14867   std::vector<SDNode *> Built;
14868   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14869 
14870   for (SDNode *N : Built)
14871     AddToWorklist(N);
14872   return S;
14873 }
14874 
14875 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14876 /// expression that will generate the same value by multiplying by a magic
14877 /// number.
14878 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14879 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14880   // when optimising for minimum size, we don't want to expand a div to a mul
14881   // and a shift.
14882   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14883     return SDValue();
14884 
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 =
14895       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14896 
14897   for (SDNode *N : Built)
14898     AddToWorklist(N);
14899   return S;
14900 }
14901 
14902 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14903   if (Level >= AfterLegalizeDAG)
14904     return SDValue();
14905 
14906   // Expose the DAG combiner to the target combiner implementations.
14907   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14908 
14909   unsigned Iterations = 0;
14910   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14911     if (Iterations) {
14912       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14913       // For the reciprocal, we need to find the zero of the function:
14914       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14915       //     =>
14916       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14917       //     does not require additional intermediate precision]
14918       EVT VT = Op.getValueType();
14919       SDLoc DL(Op);
14920       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14921 
14922       AddToWorklist(Est.getNode());
14923 
14924       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14925       for (unsigned i = 0; i < Iterations; ++i) {
14926         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14927         AddToWorklist(NewEst.getNode());
14928 
14929         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14930         AddToWorklist(NewEst.getNode());
14931 
14932         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14933         AddToWorklist(NewEst.getNode());
14934 
14935         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14936         AddToWorklist(Est.getNode());
14937       }
14938     }
14939     return Est;
14940   }
14941 
14942   return SDValue();
14943 }
14944 
14945 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14946 /// For the reciprocal sqrt, we need to find the zero of the function:
14947 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14948 ///     =>
14949 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14950 /// As a result, we precompute A/2 prior to the iteration loop.
14951 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
14952                                          unsigned Iterations,
14953                                          SDNodeFlags *Flags, bool Reciprocal) {
14954   EVT VT = Arg.getValueType();
14955   SDLoc DL(Arg);
14956   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14957 
14958   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14959   // this entire sequence requires only one FP constant.
14960   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14961   AddToWorklist(HalfArg.getNode());
14962 
14963   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14964   AddToWorklist(HalfArg.getNode());
14965 
14966   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14967   for (unsigned i = 0; i < Iterations; ++i) {
14968     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14969     AddToWorklist(NewEst.getNode());
14970 
14971     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14972     AddToWorklist(NewEst.getNode());
14973 
14974     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14975     AddToWorklist(NewEst.getNode());
14976 
14977     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14978     AddToWorklist(Est.getNode());
14979   }
14980 
14981   // If non-reciprocal square root is requested, multiply the result by Arg.
14982   if (!Reciprocal) {
14983     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14984     AddToWorklist(Est.getNode());
14985   }
14986 
14987   return Est;
14988 }
14989 
14990 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14991 /// For the reciprocal sqrt, we need to find the zero of the function:
14992 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14993 ///     =>
14994 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14995 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
14996                                          unsigned Iterations,
14997                                          SDNodeFlags *Flags, bool Reciprocal) {
14998   EVT VT = Arg.getValueType();
14999   SDLoc DL(Arg);
15000   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
15001   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
15002 
15003   // This routine must enter the loop below to work correctly
15004   // when (Reciprocal == false).
15005   assert(Iterations > 0);
15006 
15007   // Newton iterations for reciprocal square root:
15008   // E = (E * -0.5) * ((A * E) * E + -3.0)
15009   for (unsigned i = 0; i < Iterations; ++i) {
15010     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
15011     AddToWorklist(AE.getNode());
15012 
15013     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
15014     AddToWorklist(AEE.getNode());
15015 
15016     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
15017     AddToWorklist(RHS.getNode());
15018 
15019     // When calculating a square root at the last iteration build:
15020     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
15021     // (notice a common subexpression)
15022     SDValue LHS;
15023     if (Reciprocal || (i + 1) < Iterations) {
15024       // RSQRT: LHS = (E * -0.5)
15025       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
15026     } else {
15027       // SQRT: LHS = (A * E) * -0.5
15028       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
15029     }
15030     AddToWorklist(LHS.getNode());
15031 
15032     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
15033     AddToWorklist(Est.getNode());
15034   }
15035 
15036   return Est;
15037 }
15038 
15039 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
15040 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
15041 /// Op can be zero.
15042 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
15043                                            bool Reciprocal) {
15044   if (Level >= AfterLegalizeDAG)
15045     return SDValue();
15046 
15047   // Expose the DAG combiner to the target combiner implementations.
15048   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
15049   unsigned Iterations = 0;
15050   bool UseOneConstNR = false;
15051   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
15052     AddToWorklist(Est.getNode());
15053     if (Iterations) {
15054       Est = UseOneConstNR
15055                 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
15056                 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
15057     }
15058     return Est;
15059   }
15060 
15061   return SDValue();
15062 }
15063 
15064 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15065   return buildSqrtEstimateImpl(Op, Flags, true);
15066 }
15067 
15068 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
15069   SDValue Est = buildSqrtEstimateImpl(Op, Flags, false);
15070   if (!Est)
15071     return SDValue();
15072 
15073   // Unfortunately, Est is now NaN if the input was exactly 0.
15074   // Select out this case and force the answer to 0.
15075   EVT VT = Est.getValueType();
15076   SDLoc DL(Op);
15077   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
15078   EVT CCVT = getSetCCResultType(VT);
15079   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, Zero, ISD::SETEQ);
15080   AddToWorklist(ZeroCmp.getNode());
15081 
15082   Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, ZeroCmp,
15083                     Zero, Est);
15084   AddToWorklist(Est.getNode());
15085   return Est;
15086 }
15087 
15088 /// Return true if base is a frame index, which is known not to alias with
15089 /// anything but itself.  Provides base object and offset as results.
15090 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
15091                            const GlobalValue *&GV, const void *&CV) {
15092   // Assume it is a primitive operation.
15093   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
15094 
15095   // If it's an adding a simple constant then integrate the offset.
15096   if (Base.getOpcode() == ISD::ADD) {
15097     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
15098       Base = Base.getOperand(0);
15099       Offset += C->getZExtValue();
15100     }
15101   }
15102 
15103   // Return the underlying GlobalValue, and update the Offset.  Return false
15104   // for GlobalAddressSDNode since the same GlobalAddress may be represented
15105   // by multiple nodes with different offsets.
15106   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
15107     GV = G->getGlobal();
15108     Offset += G->getOffset();
15109     return false;
15110   }
15111 
15112   // Return the underlying Constant value, and update the Offset.  Return false
15113   // for ConstantSDNodes since the same constant pool entry may be represented
15114   // by multiple nodes with different offsets.
15115   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
15116     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
15117                                          : (const void *)C->getConstVal();
15118     Offset += C->getOffset();
15119     return false;
15120   }
15121   // If it's any of the following then it can't alias with anything but itself.
15122   return isa<FrameIndexSDNode>(Base);
15123 }
15124 
15125 /// Return true if there is any possibility that the two addresses overlap.
15126 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
15127   // If they are the same then they must be aliases.
15128   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
15129 
15130   // If they are both volatile then they cannot be reordered.
15131   if (Op0->isVolatile() && Op1->isVolatile()) return true;
15132 
15133   // If one operation reads from invariant memory, and the other may store, they
15134   // cannot alias. These should really be checking the equivalent of mayWrite,
15135   // but it only matters for memory nodes other than load /store.
15136   if (Op0->isInvariant() && Op1->writeMem())
15137     return false;
15138 
15139   if (Op1->isInvariant() && Op0->writeMem())
15140     return false;
15141 
15142   // Gather base node and offset information.
15143   SDValue Base1, Base2;
15144   int64_t Offset1, Offset2;
15145   const GlobalValue *GV1, *GV2;
15146   const void *CV1, *CV2;
15147   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
15148                                       Base1, Offset1, GV1, CV1);
15149   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
15150                                       Base2, Offset2, GV2, CV2);
15151 
15152   // If they have a same base address then check to see if they overlap.
15153   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
15154     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15155              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15156 
15157   // It is possible for different frame indices to alias each other, mostly
15158   // when tail call optimization reuses return address slots for arguments.
15159   // To catch this case, look up the actual index of frame indices to compute
15160   // the real alias relationship.
15161   if (isFrameIndex1 && isFrameIndex2) {
15162     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
15163     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
15164     Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
15165     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15166              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15167   }
15168 
15169   // Otherwise, if we know what the bases are, and they aren't identical, then
15170   // we know they cannot alias.
15171   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
15172     return false;
15173 
15174   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
15175   // compared to the size and offset of the access, we may be able to prove they
15176   // do not alias.  This check is conservative for now to catch cases created by
15177   // splitting vector types.
15178   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
15179       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
15180       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
15181        Op1->getMemoryVT().getSizeInBits() >> 3) &&
15182       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
15183     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
15184     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
15185 
15186     // There is no overlap between these relatively aligned accesses of similar
15187     // size, return no alias.
15188     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
15189         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
15190       return false;
15191   }
15192 
15193   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
15194                    ? CombinerGlobalAA
15195                    : DAG.getSubtarget().useAA();
15196 #ifndef NDEBUG
15197   if (CombinerAAOnlyFunc.getNumOccurrences() &&
15198       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
15199     UseAA = false;
15200 #endif
15201   if (UseAA &&
15202       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
15203     // Use alias analysis information.
15204     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
15205                                  Op1->getSrcValueOffset());
15206     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
15207         Op0->getSrcValueOffset() - MinOffset;
15208     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
15209         Op1->getSrcValueOffset() - MinOffset;
15210     AliasResult AAResult =
15211         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
15212                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
15213                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
15214                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
15215     if (AAResult == NoAlias)
15216       return false;
15217   }
15218 
15219   // Otherwise we have to assume they alias.
15220   return true;
15221 }
15222 
15223 /// Walk up chain skipping non-aliasing memory nodes,
15224 /// looking for aliasing nodes and adding them to the Aliases vector.
15225 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
15226                                    SmallVectorImpl<SDValue> &Aliases) {
15227   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
15228   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
15229 
15230   // Get alias information for node.
15231   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
15232 
15233   // Starting off.
15234   Chains.push_back(OriginalChain);
15235   unsigned Depth = 0;
15236 
15237   // Look at each chain and determine if it is an alias.  If so, add it to the
15238   // aliases list.  If not, then continue up the chain looking for the next
15239   // candidate.
15240   while (!Chains.empty()) {
15241     SDValue Chain = Chains.pop_back_val();
15242 
15243     // For TokenFactor nodes, look at each operand and only continue up the
15244     // chain until we reach the depth limit.
15245     //
15246     // FIXME: The depth check could be made to return the last non-aliasing
15247     // chain we found before we hit a tokenfactor rather than the original
15248     // chain.
15249     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
15250       Aliases.clear();
15251       Aliases.push_back(OriginalChain);
15252       return;
15253     }
15254 
15255     // Don't bother if we've been before.
15256     if (!Visited.insert(Chain.getNode()).second)
15257       continue;
15258 
15259     switch (Chain.getOpcode()) {
15260     case ISD::EntryToken:
15261       // Entry token is ideal chain operand, but handled in FindBetterChain.
15262       break;
15263 
15264     case ISD::LOAD:
15265     case ISD::STORE: {
15266       // Get alias information for Chain.
15267       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
15268           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
15269 
15270       // If chain is alias then stop here.
15271       if (!(IsLoad && IsOpLoad) &&
15272           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
15273         Aliases.push_back(Chain);
15274       } else {
15275         // Look further up the chain.
15276         Chains.push_back(Chain.getOperand(0));
15277         ++Depth;
15278       }
15279       break;
15280     }
15281 
15282     case ISD::TokenFactor:
15283       // We have to check each of the operands of the token factor for "small"
15284       // token factors, so we queue them up.  Adding the operands to the queue
15285       // (stack) in reverse order maintains the original order and increases the
15286       // likelihood that getNode will find a matching token factor (CSE.)
15287       if (Chain.getNumOperands() > 16) {
15288         Aliases.push_back(Chain);
15289         break;
15290       }
15291       for (unsigned n = Chain.getNumOperands(); n;)
15292         Chains.push_back(Chain.getOperand(--n));
15293       ++Depth;
15294       break;
15295 
15296     default:
15297       // For all other instructions we will just have to take what we can get.
15298       Aliases.push_back(Chain);
15299       break;
15300     }
15301   }
15302 }
15303 
15304 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
15305 /// (aliasing node.)
15306 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
15307   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
15308 
15309   // Accumulate all the aliases to this node.
15310   GatherAllAliases(N, OldChain, Aliases);
15311 
15312   // If no operands then chain to entry token.
15313   if (Aliases.size() == 0)
15314     return DAG.getEntryNode();
15315 
15316   // If a single operand then chain to it.  We don't need to revisit it.
15317   if (Aliases.size() == 1)
15318     return Aliases[0];
15319 
15320   // Construct a custom tailored token factor.
15321   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
15322 }
15323 
15324 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
15325   // This holds the base pointer, index, and the offset in bytes from the base
15326   // pointer.
15327   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
15328 
15329   // We must have a base and an offset.
15330   if (!BasePtr.Base.getNode())
15331     return false;
15332 
15333   // Do not handle stores to undef base pointers.
15334   if (BasePtr.Base.isUndef())
15335     return false;
15336 
15337   SmallVector<StoreSDNode *, 8> ChainedStores;
15338   ChainedStores.push_back(St);
15339 
15340   // Walk up the chain and look for nodes with offsets from the same
15341   // base pointer. Stop when reaching an instruction with a different kind
15342   // or instruction which has a different base pointer.
15343   StoreSDNode *Index = St;
15344   while (Index) {
15345     // If the chain has more than one use, then we can't reorder the mem ops.
15346     if (Index != St && !SDValue(Index, 0)->hasOneUse())
15347       break;
15348 
15349     if (Index->isVolatile() || Index->isIndexed())
15350       break;
15351 
15352     // Find the base pointer and offset for this memory node.
15353     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
15354 
15355     // Check that the base pointer is the same as the original one.
15356     if (!Ptr.equalBaseIndex(BasePtr))
15357       break;
15358 
15359     // Find the next memory operand in the chain. If the next operand in the
15360     // chain is a store then move up and continue the scan with the next
15361     // memory operand. If the next operand is a load save it and use alias
15362     // information to check if it interferes with anything.
15363     SDNode *NextInChain = Index->getChain().getNode();
15364     while (true) {
15365       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
15366         // We found a store node. Use it for the next iteration.
15367         if (STn->isVolatile() || STn->isIndexed()) {
15368           Index = nullptr;
15369           break;
15370         }
15371         ChainedStores.push_back(STn);
15372         Index = STn;
15373         break;
15374       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
15375         NextInChain = Ldn->getChain().getNode();
15376         continue;
15377       } else {
15378         Index = nullptr;
15379         break;
15380       }
15381     }
15382   }
15383 
15384   bool MadeChangeToSt = false;
15385   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
15386 
15387   for (StoreSDNode *ChainedStore : ChainedStores) {
15388     SDValue Chain = ChainedStore->getChain();
15389     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15390 
15391     if (Chain != BetterChain) {
15392       if (ChainedStore == St)
15393         MadeChangeToSt = true;
15394       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15395     }
15396   }
15397 
15398   // Do all replacements after finding the replacements to make to avoid making
15399   // the chains more complicated by introducing new TokenFactors.
15400   for (auto Replacement : BetterChains)
15401     replaceStoreChain(Replacement.first, Replacement.second);
15402 
15403   return MadeChangeToSt;
15404 }
15405 
15406 /// This is the entry point for the file.
15407 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15408                            CodeGenOpt::Level OptLevel) {
15409   /// This is the main entry point to this class.
15410   DAGCombiner(*this, AA, OptLevel).Run(Level);
15411 }
15412