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.getValueType().getScalarType().getSizeInBits();
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     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
338     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
339     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
340     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
341                              SDValue N2, SDValue N3, ISD::CondCode CC,
342                              bool NotExtCompare = false);
343     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
344                           const SDLoc &DL, bool foldBooleans = true);
345 
346     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
347                            SDValue &CC) const;
348     bool isOneUseSetCC(SDValue N) const;
349 
350     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
351                                          unsigned HiOp);
352     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
353     SDValue CombineExtLoad(SDNode *N);
354     SDValue combineRepeatedFPDivisors(SDNode *N);
355     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
356     SDValue BuildSDIV(SDNode *N);
357     SDValue BuildSDIVPow2(SDNode *N);
358     SDValue BuildUDIV(SDNode *N);
359     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
360     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
361     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
362     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
363     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
364                                 SDNodeFlags *Flags, bool Reciprocal);
365     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
366                                 SDNodeFlags *Flags, bool Reciprocal);
367     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
368                                bool DemandHighBits = true);
369     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
370     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
371                               SDValue InnerPos, SDValue InnerNeg,
372                               unsigned PosOpcode, unsigned NegOpcode,
373                               const SDLoc &DL);
374     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
375     SDValue ReduceLoadWidth(SDNode *N);
376     SDValue ReduceLoadOpStoreWidth(SDNode *N);
377     SDValue splitMergedValStore(StoreSDNode *ST);
378     SDValue TransformFPLoadStorePair(SDNode *N);
379     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
380     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
381     SDValue reduceBuildVecToShuffle(SDNode *N);
382 
383     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
384 
385     /// Walk up chain skipping non-aliasing memory nodes,
386     /// looking for aliasing nodes and adding them to the Aliases vector.
387     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
388                           SmallVectorImpl<SDValue> &Aliases);
389 
390     /// Return true if there is any possibility that the two addresses overlap.
391     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
392 
393     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
394     /// chain (aliasing node.)
395     SDValue FindBetterChain(SDNode *N, SDValue Chain);
396 
397     /// Try to replace a store and any possibly adjacent stores on
398     /// consecutive chains with better chains. Return true only if St is
399     /// replaced.
400     ///
401     /// Notice that other chains may still be replaced even if the function
402     /// returns false.
403     bool findBetterNeighborChains(StoreSDNode *St);
404 
405     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
406     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
407 
408     /// Holds a pointer to an LSBaseSDNode as well as information on where it
409     /// is located in a sequence of memory operations connected by a chain.
410     struct MemOpLink {
411       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
412       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
413       // Ptr to the mem node.
414       LSBaseSDNode *MemNode;
415       // Offset from the base ptr.
416       int64_t OffsetFromBase;
417       // What is the sequence number of this mem node.
418       // Lowest mem operand in the DAG starts at zero.
419       unsigned SequenceNum;
420     };
421 
422     /// This is a helper function for visitMUL to check the profitability
423     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
424     /// MulNode is the original multiply, AddNode is (add x, c1),
425     /// and ConstNode is c2.
426     bool isMulAddWithConstProfitable(SDNode *MulNode,
427                                      SDValue &AddNode,
428                                      SDValue &ConstNode);
429 
430     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
431     /// constant build_vector of the stored constant values in Stores.
432     SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL,
433                                          ArrayRef<MemOpLink> Stores,
434                                          SmallVectorImpl<SDValue> &Chains,
435                                          EVT Ty) const;
436 
437     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
438     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
439     /// the type of the loaded value to be extended.  LoadedVT returns the type
440     /// of the original loaded value.  NarrowLoad returns whether the load would
441     /// need to be narrowed in order to match.
442     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
443                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
444                           bool &NarrowLoad);
445 
446     /// This is a helper function for MergeConsecutiveStores. When the source
447     /// elements of the consecutive stores are all constants or all extracted
448     /// vector elements, try to merge them into one larger store.
449     /// \return True if a merged store was created.
450     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
451                                          EVT MemVT, unsigned NumStores,
452                                          bool IsConstantSrc, bool UseVector);
453 
454     /// This is a helper function for MergeConsecutiveStores.
455     /// Stores that may be merged are placed in StoreNodes.
456     /// Loads that may alias with those stores are placed in AliasLoadNodes.
457     void getStoreMergeAndAliasCandidates(
458         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
459         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
460 
461     /// Helper function for MergeConsecutiveStores. Checks if
462     /// Candidate stores have indirect dependency through their
463     /// operands. \return True if safe to merge
464     bool checkMergeStoreCandidatesForDependencies(
465         SmallVectorImpl<MemOpLink> &StoreNodes);
466 
467     /// Merge consecutive store operations into a wide store.
468     /// This optimization uses wide integers or vectors when possible.
469     /// \return True if some memory operations were changed.
470     bool MergeConsecutiveStores(StoreSDNode *N);
471 
472     /// \brief Try to transform a truncation where C is a constant:
473     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
474     ///
475     /// \p N needs to be a truncation and its first operand an AND. Other
476     /// requirements are checked by the function (e.g. that trunc is
477     /// single-use) and if missed an empty SDValue is returned.
478     SDValue distributeTruncateThroughAnd(SDNode *N);
479 
480   public:
481     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
482         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
483           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
484       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
485     }
486 
487     /// Runs the dag combiner on all nodes in the work list
488     void Run(CombineLevel AtLevel);
489 
490     SelectionDAG &getDAG() const { return DAG; }
491 
492     /// Returns a type large enough to hold any valid shift amount - before type
493     /// legalization these can be huge.
494     EVT getShiftAmountTy(EVT LHSTy) {
495       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
496       if (LHSTy.isVector())
497         return LHSTy;
498       auto &DL = DAG.getDataLayout();
499       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
500                         : TLI.getPointerTy(DL);
501     }
502 
503     /// This method returns true if we are running before type legalization or
504     /// if the specified VT is legal.
505     bool isTypeLegal(const EVT &VT) {
506       if (!LegalTypes) return true;
507       return TLI.isTypeLegal(VT);
508     }
509 
510     /// Convenience wrapper around TargetLowering::getSetCCResultType
511     EVT getSetCCResultType(EVT VT) const {
512       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
513     }
514   };
515 }
516 
517 
518 namespace {
519 /// This class is a DAGUpdateListener that removes any deleted
520 /// nodes from the worklist.
521 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
522   DAGCombiner &DC;
523 public:
524   explicit WorklistRemover(DAGCombiner &dc)
525     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
526 
527   void NodeDeleted(SDNode *N, SDNode *E) override {
528     DC.removeFromWorklist(N);
529   }
530 };
531 }
532 
533 //===----------------------------------------------------------------------===//
534 //  TargetLowering::DAGCombinerInfo implementation
535 //===----------------------------------------------------------------------===//
536 
537 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
538   ((DAGCombiner*)DC)->AddToWorklist(N);
539 }
540 
541 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
542   ((DAGCombiner*)DC)->removeFromWorklist(N);
543 }
544 
545 SDValue TargetLowering::DAGCombinerInfo::
546 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
547   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
548 }
549 
550 SDValue TargetLowering::DAGCombinerInfo::
551 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
552   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
553 }
554 
555 
556 SDValue TargetLowering::DAGCombinerInfo::
557 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
558   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
559 }
560 
561 void TargetLowering::DAGCombinerInfo::
562 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
563   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
564 }
565 
566 //===----------------------------------------------------------------------===//
567 // Helper Functions
568 //===----------------------------------------------------------------------===//
569 
570 void DAGCombiner::deleteAndRecombine(SDNode *N) {
571   removeFromWorklist(N);
572 
573   // If the operands of this node are only used by the node, they will now be
574   // dead. Make sure to re-visit them and recursively delete dead nodes.
575   for (const SDValue &Op : N->ops())
576     // For an operand generating multiple values, one of the values may
577     // become dead allowing further simplification (e.g. split index
578     // arithmetic from an indexed load).
579     if (Op->hasOneUse() || Op->getNumValues() > 1)
580       AddToWorklist(Op.getNode());
581 
582   DAG.DeleteNode(N);
583 }
584 
585 /// Return 1 if we can compute the negated form of the specified expression for
586 /// the same cost as the expression itself, or 2 if we can compute the negated
587 /// form more cheaply than the expression itself.
588 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
589                                const TargetLowering &TLI,
590                                const TargetOptions *Options,
591                                unsigned Depth = 0) {
592   // fneg is removable even if it has multiple uses.
593   if (Op.getOpcode() == ISD::FNEG) return 2;
594 
595   // Don't allow anything with multiple uses.
596   if (!Op.hasOneUse()) return 0;
597 
598   // Don't recurse exponentially.
599   if (Depth > 6) return 0;
600 
601   switch (Op.getOpcode()) {
602   default: return false;
603   case ISD::ConstantFP:
604     // Don't invert constant FP values after legalize.  The negated constant
605     // isn't necessarily legal.
606     return LegalOperations ? 0 : 1;
607   case ISD::FADD:
608     // FIXME: determine better conditions for this xform.
609     if (!Options->UnsafeFPMath) return 0;
610 
611     // After operation legalization, it might not be legal to create new FSUBs.
612     if (LegalOperations &&
613         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
614       return 0;
615 
616     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
617     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
618                                     Options, Depth + 1))
619       return V;
620     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
621     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
622                               Depth + 1);
623   case ISD::FSUB:
624     // We can't turn -(A-B) into B-A when we honor signed zeros.
625     if (!Options->UnsafeFPMath) return 0;
626 
627     // fold (fneg (fsub A, B)) -> (fsub B, A)
628     return 1;
629 
630   case ISD::FMUL:
631   case ISD::FDIV:
632     if (Options->HonorSignDependentRoundingFPMath()) return 0;
633 
634     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
635     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
636                                     Options, Depth + 1))
637       return V;
638 
639     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
640                               Depth + 1);
641 
642   case ISD::FP_EXTEND:
643   case ISD::FP_ROUND:
644   case ISD::FSIN:
645     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
646                               Depth + 1);
647   }
648 }
649 
650 /// If isNegatibleForFree returns true, return the newly negated expression.
651 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
652                                     bool LegalOperations, unsigned Depth = 0) {
653   const TargetOptions &Options = DAG.getTarget().Options;
654   // fneg is removable even if it has multiple uses.
655   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
656 
657   // Don't allow anything with multiple uses.
658   assert(Op.hasOneUse() && "Unknown reuse!");
659 
660   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
661 
662   const SDNodeFlags *Flags = Op.getNode()->getFlags();
663 
664   switch (Op.getOpcode()) {
665   default: llvm_unreachable("Unknown code");
666   case ISD::ConstantFP: {
667     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
668     V.changeSign();
669     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
670   }
671   case ISD::FADD:
672     // FIXME: determine better conditions for this xform.
673     assert(Options.UnsafeFPMath);
674 
675     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
676     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
677                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
678       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
679                          GetNegatedExpression(Op.getOperand(0), DAG,
680                                               LegalOperations, Depth+1),
681                          Op.getOperand(1), Flags);
682     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
683     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
684                        GetNegatedExpression(Op.getOperand(1), DAG,
685                                             LegalOperations, Depth+1),
686                        Op.getOperand(0), Flags);
687   case ISD::FSUB:
688     // We can't turn -(A-B) into B-A when we honor signed zeros.
689     assert(Options.UnsafeFPMath);
690 
691     // fold (fneg (fsub 0, B)) -> B
692     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
693       if (N0CFP->isZero())
694         return Op.getOperand(1);
695 
696     // fold (fneg (fsub A, B)) -> (fsub B, A)
697     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
698                        Op.getOperand(1), Op.getOperand(0), Flags);
699 
700   case ISD::FMUL:
701   case ISD::FDIV:
702     assert(!Options.HonorSignDependentRoundingFPMath());
703 
704     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
705     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
706                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
707       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
708                          GetNegatedExpression(Op.getOperand(0), DAG,
709                                               LegalOperations, Depth+1),
710                          Op.getOperand(1), Flags);
711 
712     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
713     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
714                        Op.getOperand(0),
715                        GetNegatedExpression(Op.getOperand(1), DAG,
716                                             LegalOperations, Depth+1), Flags);
717 
718   case ISD::FP_EXTEND:
719   case ISD::FSIN:
720     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
721                        GetNegatedExpression(Op.getOperand(0), DAG,
722                                             LegalOperations, Depth+1));
723   case ISD::FP_ROUND:
724       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
725                          GetNegatedExpression(Op.getOperand(0), DAG,
726                                               LegalOperations, Depth+1),
727                          Op.getOperand(1));
728   }
729 }
730 
731 // APInts must be the same size for most operations, this helper
732 // function zero extends the shorter of the pair so that they match.
733 // We provide an Offset so that we can create bitwidths that won't overflow.
734 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
735   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
736   LHS = LHS.zextOrSelf(Bits);
737   RHS = RHS.zextOrSelf(Bits);
738 }
739 
740 // Return true if this node is a setcc, or is a select_cc
741 // that selects between the target values used for true and false, making it
742 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
743 // the appropriate nodes based on the type of node we are checking. This
744 // simplifies life a bit for the callers.
745 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
746                                     SDValue &CC) const {
747   if (N.getOpcode() == ISD::SETCC) {
748     LHS = N.getOperand(0);
749     RHS = N.getOperand(1);
750     CC  = N.getOperand(2);
751     return true;
752   }
753 
754   if (N.getOpcode() != ISD::SELECT_CC ||
755       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
756       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
757     return false;
758 
759   if (TLI.getBooleanContents(N.getValueType()) ==
760       TargetLowering::UndefinedBooleanContent)
761     return false;
762 
763   LHS = N.getOperand(0);
764   RHS = N.getOperand(1);
765   CC  = N.getOperand(4);
766   return true;
767 }
768 
769 /// Return true if this is a SetCC-equivalent operation with only one use.
770 /// If this is true, it allows the users to invert the operation for free when
771 /// it is profitable to do so.
772 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
773   SDValue N0, N1, N2;
774   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
775     return true;
776   return false;
777 }
778 
779 // \brief Returns the SDNode if it is a constant float BuildVector
780 // or constant float.
781 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
782   if (isa<ConstantFPSDNode>(N))
783     return N.getNode();
784   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
785     return N.getNode();
786   return nullptr;
787 }
788 
789 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
790 // int.
791 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
792   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
793     return CN;
794 
795   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
796     BitVector UndefElements;
797     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
798 
799     // BuildVectors can truncate their operands. Ignore that case here.
800     // FIXME: We blindly ignore splats which include undef which is overly
801     // pessimistic.
802     if (CN && UndefElements.none() &&
803         CN->getValueType(0) == N.getValueType().getScalarType())
804       return CN;
805   }
806 
807   return nullptr;
808 }
809 
810 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
811 // float.
812 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
813   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
814     return CN;
815 
816   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
817     BitVector UndefElements;
818     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
819 
820     if (CN && UndefElements.none())
821       return CN;
822   }
823 
824   return nullptr;
825 }
826 
827 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
828                                     SDValue N1) {
829   EVT VT = N0.getValueType();
830   if (N0.getOpcode() == Opc) {
831     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
832       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
833         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
834         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
835           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
836         return SDValue();
837       }
838       if (N0.hasOneUse()) {
839         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
840         // use
841         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
842         if (!OpNode.getNode())
843           return SDValue();
844         AddToWorklist(OpNode.getNode());
845         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
846       }
847     }
848   }
849 
850   if (N1.getOpcode() == Opc) {
851     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
852       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
853         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
854         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
855           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
856         return SDValue();
857       }
858       if (N1.hasOneUse()) {
859         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
860         // use
861         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
862         if (!OpNode.getNode())
863           return SDValue();
864         AddToWorklist(OpNode.getNode());
865         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
866       }
867     }
868   }
869 
870   return SDValue();
871 }
872 
873 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
874                                bool AddTo) {
875   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
876   ++NodesCombined;
877   DEBUG(dbgs() << "\nReplacing.1 ";
878         N->dump(&DAG);
879         dbgs() << "\nWith: ";
880         To[0].getNode()->dump(&DAG);
881         dbgs() << " and " << NumTo-1 << " other values\n");
882   for (unsigned i = 0, e = NumTo; i != e; ++i)
883     assert((!To[i].getNode() ||
884             N->getValueType(i) == To[i].getValueType()) &&
885            "Cannot combine value to value of different type!");
886 
887   WorklistRemover DeadNodes(*this);
888   DAG.ReplaceAllUsesWith(N, To);
889   if (AddTo) {
890     // Push the new nodes and any users onto the worklist
891     for (unsigned i = 0, e = NumTo; i != e; ++i) {
892       if (To[i].getNode()) {
893         AddToWorklist(To[i].getNode());
894         AddUsersToWorklist(To[i].getNode());
895       }
896     }
897   }
898 
899   // Finally, if the node is now dead, remove it from the graph.  The node
900   // may not be dead if the replacement process recursively simplified to
901   // something else needing this node.
902   if (N->use_empty())
903     deleteAndRecombine(N);
904   return SDValue(N, 0);
905 }
906 
907 void DAGCombiner::
908 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
909   // Replace all uses.  If any nodes become isomorphic to other nodes and
910   // are deleted, make sure to remove them from our worklist.
911   WorklistRemover DeadNodes(*this);
912   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
913 
914   // Push the new node and any (possibly new) users onto the worklist.
915   AddToWorklist(TLO.New.getNode());
916   AddUsersToWorklist(TLO.New.getNode());
917 
918   // Finally, if the node is now dead, remove it from the graph.  The node
919   // may not be dead if the replacement process recursively simplified to
920   // something else needing this node.
921   if (TLO.Old.getNode()->use_empty())
922     deleteAndRecombine(TLO.Old.getNode());
923 }
924 
925 /// Check the specified integer node value to see if it can be simplified or if
926 /// things it uses can be simplified by bit propagation. If so, return true.
927 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
928   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
929   APInt KnownZero, KnownOne;
930   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
931     return false;
932 
933   // Revisit the node.
934   AddToWorklist(Op.getNode());
935 
936   // Replace the old value with the new one.
937   ++NodesCombined;
938   DEBUG(dbgs() << "\nReplacing.2 ";
939         TLO.Old.getNode()->dump(&DAG);
940         dbgs() << "\nWith: ";
941         TLO.New.getNode()->dump(&DAG);
942         dbgs() << '\n');
943 
944   CommitTargetLoweringOpt(TLO);
945   return true;
946 }
947 
948 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
949   SDLoc dl(Load);
950   EVT VT = Load->getValueType(0);
951   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
952 
953   DEBUG(dbgs() << "\nReplacing.9 ";
954         Load->dump(&DAG);
955         dbgs() << "\nWith: ";
956         Trunc.getNode()->dump(&DAG);
957         dbgs() << '\n');
958   WorklistRemover DeadNodes(*this);
959   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
960   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
961   deleteAndRecombine(Load);
962   AddToWorklist(Trunc.getNode());
963 }
964 
965 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
966   Replace = false;
967   SDLoc dl(Op);
968   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
969     LoadSDNode *LD = cast<LoadSDNode>(Op);
970     EVT MemVT = LD->getMemoryVT();
971     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
972       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
973                                                        : ISD::EXTLOAD)
974       : LD->getExtensionType();
975     Replace = true;
976     return DAG.getExtLoad(ExtType, dl, PVT,
977                           LD->getChain(), LD->getBasePtr(),
978                           MemVT, LD->getMemOperand());
979   }
980 
981   unsigned Opc = Op.getOpcode();
982   switch (Opc) {
983   default: break;
984   case ISD::AssertSext:
985     return DAG.getNode(ISD::AssertSext, dl, PVT,
986                        SExtPromoteOperand(Op.getOperand(0), PVT),
987                        Op.getOperand(1));
988   case ISD::AssertZext:
989     return DAG.getNode(ISD::AssertZext, dl, PVT,
990                        ZExtPromoteOperand(Op.getOperand(0), PVT),
991                        Op.getOperand(1));
992   case ISD::Constant: {
993     unsigned ExtOpc =
994       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
995     return DAG.getNode(ExtOpc, dl, PVT, Op);
996   }
997   }
998 
999   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1000     return SDValue();
1001   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
1002 }
1003 
1004 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1005   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1006     return SDValue();
1007   EVT OldVT = Op.getValueType();
1008   SDLoc dl(Op);
1009   bool Replace = false;
1010   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1011   if (!NewOp.getNode())
1012     return SDValue();
1013   AddToWorklist(NewOp.getNode());
1014 
1015   if (Replace)
1016     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1017   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1018                      DAG.getValueType(OldVT));
1019 }
1020 
1021 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1022   EVT OldVT = Op.getValueType();
1023   SDLoc dl(Op);
1024   bool Replace = false;
1025   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1026   if (!NewOp.getNode())
1027     return SDValue();
1028   AddToWorklist(NewOp.getNode());
1029 
1030   if (Replace)
1031     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1032   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1033 }
1034 
1035 /// Promote the specified integer binary operation if the target indicates it is
1036 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1037 /// i32 since i16 instructions are longer.
1038 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1039   if (!LegalOperations)
1040     return SDValue();
1041 
1042   EVT VT = Op.getValueType();
1043   if (VT.isVector() || !VT.isInteger())
1044     return SDValue();
1045 
1046   // If operation type is 'undesirable', e.g. i16 on x86, consider
1047   // promoting it.
1048   unsigned Opc = Op.getOpcode();
1049   if (TLI.isTypeDesirableForOp(Opc, VT))
1050     return SDValue();
1051 
1052   EVT PVT = VT;
1053   // Consult target whether it is a good idea to promote this operation and
1054   // what's the right type to promote it to.
1055   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056     assert(PVT != VT && "Don't know what type to promote to!");
1057 
1058     bool Replace0 = false;
1059     SDValue N0 = Op.getOperand(0);
1060     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1061     if (!NN0.getNode())
1062       return SDValue();
1063 
1064     bool Replace1 = false;
1065     SDValue N1 = Op.getOperand(1);
1066     SDValue NN1;
1067     if (N0 == N1)
1068       NN1 = NN0;
1069     else {
1070       NN1 = PromoteOperand(N1, PVT, Replace1);
1071       if (!NN1.getNode())
1072         return SDValue();
1073     }
1074 
1075     AddToWorklist(NN0.getNode());
1076     if (NN1.getNode())
1077       AddToWorklist(NN1.getNode());
1078 
1079     if (Replace0)
1080       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1081     if (Replace1)
1082       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1083 
1084     DEBUG(dbgs() << "\nPromoting ";
1085           Op.getNode()->dump(&DAG));
1086     SDLoc dl(Op);
1087     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1088                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1089   }
1090   return SDValue();
1091 }
1092 
1093 /// Promote the specified integer shift operation if the target indicates it is
1094 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1095 /// i32 since i16 instructions are longer.
1096 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1097   if (!LegalOperations)
1098     return SDValue();
1099 
1100   EVT VT = Op.getValueType();
1101   if (VT.isVector() || !VT.isInteger())
1102     return SDValue();
1103 
1104   // If operation type is 'undesirable', e.g. i16 on x86, consider
1105   // promoting it.
1106   unsigned Opc = Op.getOpcode();
1107   if (TLI.isTypeDesirableForOp(Opc, VT))
1108     return SDValue();
1109 
1110   EVT PVT = VT;
1111   // Consult target whether it is a good idea to promote this operation and
1112   // what's the right type to promote it to.
1113   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1114     assert(PVT != VT && "Don't know what type to promote to!");
1115 
1116     bool Replace = false;
1117     SDValue N0 = Op.getOperand(0);
1118     if (Opc == ISD::SRA)
1119       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1120     else if (Opc == ISD::SRL)
1121       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1122     else
1123       N0 = PromoteOperand(N0, PVT, Replace);
1124     if (!N0.getNode())
1125       return SDValue();
1126 
1127     AddToWorklist(N0.getNode());
1128     if (Replace)
1129       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1130 
1131     DEBUG(dbgs() << "\nPromoting ";
1132           Op.getNode()->dump(&DAG));
1133     SDLoc dl(Op);
1134     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1135                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1136   }
1137   return SDValue();
1138 }
1139 
1140 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1141   if (!LegalOperations)
1142     return SDValue();
1143 
1144   EVT VT = Op.getValueType();
1145   if (VT.isVector() || !VT.isInteger())
1146     return SDValue();
1147 
1148   // If operation type is 'undesirable', e.g. i16 on x86, consider
1149   // promoting it.
1150   unsigned Opc = Op.getOpcode();
1151   if (TLI.isTypeDesirableForOp(Opc, VT))
1152     return SDValue();
1153 
1154   EVT PVT = VT;
1155   // Consult target whether it is a good idea to promote this operation and
1156   // what's the right type to promote it to.
1157   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1158     assert(PVT != VT && "Don't know what type to promote to!");
1159     // fold (aext (aext x)) -> (aext x)
1160     // fold (aext (zext x)) -> (zext x)
1161     // fold (aext (sext x)) -> (sext x)
1162     DEBUG(dbgs() << "\nPromoting ";
1163           Op.getNode()->dump(&DAG));
1164     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1165   }
1166   return SDValue();
1167 }
1168 
1169 bool DAGCombiner::PromoteLoad(SDValue Op) {
1170   if (!LegalOperations)
1171     return false;
1172 
1173   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1174     return false;
1175 
1176   EVT VT = Op.getValueType();
1177   if (VT.isVector() || !VT.isInteger())
1178     return false;
1179 
1180   // If operation type is 'undesirable', e.g. i16 on x86, consider
1181   // promoting it.
1182   unsigned Opc = Op.getOpcode();
1183   if (TLI.isTypeDesirableForOp(Opc, VT))
1184     return false;
1185 
1186   EVT PVT = VT;
1187   // Consult target whether it is a good idea to promote this operation and
1188   // what's the right type to promote it to.
1189   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1190     assert(PVT != VT && "Don't know what type to promote to!");
1191 
1192     SDLoc dl(Op);
1193     SDNode *N = Op.getNode();
1194     LoadSDNode *LD = cast<LoadSDNode>(N);
1195     EVT MemVT = LD->getMemoryVT();
1196     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1197       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1198                                                        : ISD::EXTLOAD)
1199       : LD->getExtensionType();
1200     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1201                                    LD->getChain(), LD->getBasePtr(),
1202                                    MemVT, LD->getMemOperand());
1203     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1204 
1205     DEBUG(dbgs() << "\nPromoting ";
1206           N->dump(&DAG);
1207           dbgs() << "\nTo: ";
1208           Result.getNode()->dump(&DAG);
1209           dbgs() << '\n');
1210     WorklistRemover DeadNodes(*this);
1211     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1212     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1213     deleteAndRecombine(N);
1214     AddToWorklist(Result.getNode());
1215     return true;
1216   }
1217   return false;
1218 }
1219 
1220 /// \brief Recursively delete a node which has no uses and any operands for
1221 /// which it is the only use.
1222 ///
1223 /// Note that this both deletes the nodes and removes them from the worklist.
1224 /// It also adds any nodes who have had a user deleted to the worklist as they
1225 /// may now have only one use and subject to other combines.
1226 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1227   if (!N->use_empty())
1228     return false;
1229 
1230   SmallSetVector<SDNode *, 16> Nodes;
1231   Nodes.insert(N);
1232   do {
1233     N = Nodes.pop_back_val();
1234     if (!N)
1235       continue;
1236 
1237     if (N->use_empty()) {
1238       for (const SDValue &ChildN : N->op_values())
1239         Nodes.insert(ChildN.getNode());
1240 
1241       removeFromWorklist(N);
1242       DAG.DeleteNode(N);
1243     } else {
1244       AddToWorklist(N);
1245     }
1246   } while (!Nodes.empty());
1247   return true;
1248 }
1249 
1250 //===----------------------------------------------------------------------===//
1251 //  Main DAG Combiner implementation
1252 //===----------------------------------------------------------------------===//
1253 
1254 void DAGCombiner::Run(CombineLevel AtLevel) {
1255   // set the instance variables, so that the various visit routines may use it.
1256   Level = AtLevel;
1257   LegalOperations = Level >= AfterLegalizeVectorOps;
1258   LegalTypes = Level >= AfterLegalizeTypes;
1259 
1260   // Add all the dag nodes to the worklist.
1261   for (SDNode &Node : DAG.allnodes())
1262     AddToWorklist(&Node);
1263 
1264   // Create a dummy node (which is not added to allnodes), that adds a reference
1265   // to the root node, preventing it from being deleted, and tracking any
1266   // changes of the root.
1267   HandleSDNode Dummy(DAG.getRoot());
1268 
1269   // While the worklist isn't empty, find a node and try to combine it.
1270   while (!WorklistMap.empty()) {
1271     SDNode *N;
1272     // The Worklist holds the SDNodes in order, but it may contain null entries.
1273     do {
1274       N = Worklist.pop_back_val();
1275     } while (!N);
1276 
1277     bool GoodWorklistEntry = WorklistMap.erase(N);
1278     (void)GoodWorklistEntry;
1279     assert(GoodWorklistEntry &&
1280            "Found a worklist entry without a corresponding map entry!");
1281 
1282     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1283     // N is deleted from the DAG, since they too may now be dead or may have a
1284     // reduced number of uses, allowing other xforms.
1285     if (recursivelyDeleteUnusedNodes(N))
1286       continue;
1287 
1288     WorklistRemover DeadNodes(*this);
1289 
1290     // If this combine is running after legalizing the DAG, re-legalize any
1291     // nodes pulled off the worklist.
1292     if (Level == AfterLegalizeDAG) {
1293       SmallSetVector<SDNode *, 16> UpdatedNodes;
1294       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1295 
1296       for (SDNode *LN : UpdatedNodes) {
1297         AddToWorklist(LN);
1298         AddUsersToWorklist(LN);
1299       }
1300       if (!NIsValid)
1301         continue;
1302     }
1303 
1304     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1305 
1306     // Add any operands of the new node which have not yet been combined to the
1307     // worklist as well. Because the worklist uniques things already, this
1308     // won't repeatedly process the same operand.
1309     CombinedNodes.insert(N);
1310     for (const SDValue &ChildN : N->op_values())
1311       if (!CombinedNodes.count(ChildN.getNode()))
1312         AddToWorklist(ChildN.getNode());
1313 
1314     SDValue RV = combine(N);
1315 
1316     if (!RV.getNode())
1317       continue;
1318 
1319     ++NodesCombined;
1320 
1321     // If we get back the same node we passed in, rather than a new node or
1322     // zero, we know that the node must have defined multiple values and
1323     // CombineTo was used.  Since CombineTo takes care of the worklist
1324     // mechanics for us, we have no work to do in this case.
1325     if (RV.getNode() == N)
1326       continue;
1327 
1328     assert(N->getOpcode() != ISD::DELETED_NODE &&
1329            RV.getOpcode() != ISD::DELETED_NODE &&
1330            "Node was deleted but visit returned new node!");
1331 
1332     DEBUG(dbgs() << " ... into: ";
1333           RV.getNode()->dump(&DAG));
1334 
1335     if (N->getNumValues() == RV.getNode()->getNumValues())
1336       DAG.ReplaceAllUsesWith(N, RV.getNode());
1337     else {
1338       assert(N->getValueType(0) == RV.getValueType() &&
1339              N->getNumValues() == 1 && "Type mismatch");
1340       SDValue OpV = RV;
1341       DAG.ReplaceAllUsesWith(N, &OpV);
1342     }
1343 
1344     // Push the new node and any users onto the worklist
1345     AddToWorklist(RV.getNode());
1346     AddUsersToWorklist(RV.getNode());
1347 
1348     // Finally, if the node is now dead, remove it from the graph.  The node
1349     // may not be dead if the replacement process recursively simplified to
1350     // something else needing this node. This will also take care of adding any
1351     // operands which have lost a user to the worklist.
1352     recursivelyDeleteUnusedNodes(N);
1353   }
1354 
1355   // If the root changed (e.g. it was a dead load, update the root).
1356   DAG.setRoot(Dummy.getValue());
1357   DAG.RemoveDeadNodes();
1358 }
1359 
1360 SDValue DAGCombiner::visit(SDNode *N) {
1361   switch (N->getOpcode()) {
1362   default: break;
1363   case ISD::TokenFactor:        return visitTokenFactor(N);
1364   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1365   case ISD::ADD:                return visitADD(N);
1366   case ISD::SUB:                return visitSUB(N);
1367   case ISD::ADDC:               return visitADDC(N);
1368   case ISD::SUBC:               return visitSUBC(N);
1369   case ISD::ADDE:               return visitADDE(N);
1370   case ISD::SUBE:               return visitSUBE(N);
1371   case ISD::MUL:                return visitMUL(N);
1372   case ISD::SDIV:               return visitSDIV(N);
1373   case ISD::UDIV:               return visitUDIV(N);
1374   case ISD::SREM:
1375   case ISD::UREM:               return visitREM(N);
1376   case ISD::MULHU:              return visitMULHU(N);
1377   case ISD::MULHS:              return visitMULHS(N);
1378   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1379   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1380   case ISD::SMULO:              return visitSMULO(N);
1381   case ISD::UMULO:              return visitUMULO(N);
1382   case ISD::SMIN:
1383   case ISD::SMAX:
1384   case ISD::UMIN:
1385   case ISD::UMAX:               return visitIMINMAX(N);
1386   case ISD::AND:                return visitAND(N);
1387   case ISD::OR:                 return visitOR(N);
1388   case ISD::XOR:                return visitXOR(N);
1389   case ISD::SHL:                return visitSHL(N);
1390   case ISD::SRA:                return visitSRA(N);
1391   case ISD::SRL:                return visitSRL(N);
1392   case ISD::ROTR:
1393   case ISD::ROTL:               return visitRotate(N);
1394   case ISD::BSWAP:              return visitBSWAP(N);
1395   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1396   case ISD::CTLZ:               return visitCTLZ(N);
1397   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1398   case ISD::CTTZ:               return visitCTTZ(N);
1399   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1400   case ISD::CTPOP:              return visitCTPOP(N);
1401   case ISD::SELECT:             return visitSELECT(N);
1402   case ISD::VSELECT:            return visitVSELECT(N);
1403   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1404   case ISD::SETCC:              return visitSETCC(N);
1405   case ISD::SETCCE:             return visitSETCCE(N);
1406   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1407   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1408   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1409   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1410   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1411   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1412   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1413   case ISD::BITCAST:            return visitBITCAST(N);
1414   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1415   case ISD::FADD:               return visitFADD(N);
1416   case ISD::FSUB:               return visitFSUB(N);
1417   case ISD::FMUL:               return visitFMUL(N);
1418   case ISD::FMA:                return visitFMA(N);
1419   case ISD::FDIV:               return visitFDIV(N);
1420   case ISD::FREM:               return visitFREM(N);
1421   case ISD::FSQRT:              return visitFSQRT(N);
1422   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1423   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1424   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1425   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1426   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1427   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1428   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1429   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1430   case ISD::FNEG:               return visitFNEG(N);
1431   case ISD::FABS:               return visitFABS(N);
1432   case ISD::FFLOOR:             return visitFFLOOR(N);
1433   case ISD::FMINNUM:            return visitFMINNUM(N);
1434   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1435   case ISD::FCEIL:              return visitFCEIL(N);
1436   case ISD::FTRUNC:             return visitFTRUNC(N);
1437   case ISD::BRCOND:             return visitBRCOND(N);
1438   case ISD::BR_CC:              return visitBR_CC(N);
1439   case ISD::LOAD:               return visitLOAD(N);
1440   case ISD::STORE:              return visitSTORE(N);
1441   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1442   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1443   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1444   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1445   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1446   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1447   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1448   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1449   case ISD::MGATHER:            return visitMGATHER(N);
1450   case ISD::MLOAD:              return visitMLOAD(N);
1451   case ISD::MSCATTER:           return visitMSCATTER(N);
1452   case ISD::MSTORE:             return visitMSTORE(N);
1453   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1454   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1455   }
1456   return SDValue();
1457 }
1458 
1459 SDValue DAGCombiner::combine(SDNode *N) {
1460   SDValue RV = visit(N);
1461 
1462   // If nothing happened, try a target-specific DAG combine.
1463   if (!RV.getNode()) {
1464     assert(N->getOpcode() != ISD::DELETED_NODE &&
1465            "Node was deleted but visit returned NULL!");
1466 
1467     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1468         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1469 
1470       // Expose the DAG combiner to the target combiner impls.
1471       TargetLowering::DAGCombinerInfo
1472         DagCombineInfo(DAG, Level, false, this);
1473 
1474       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1475     }
1476   }
1477 
1478   // If nothing happened still, try promoting the operation.
1479   if (!RV.getNode()) {
1480     switch (N->getOpcode()) {
1481     default: break;
1482     case ISD::ADD:
1483     case ISD::SUB:
1484     case ISD::MUL:
1485     case ISD::AND:
1486     case ISD::OR:
1487     case ISD::XOR:
1488       RV = PromoteIntBinOp(SDValue(N, 0));
1489       break;
1490     case ISD::SHL:
1491     case ISD::SRA:
1492     case ISD::SRL:
1493       RV = PromoteIntShiftOp(SDValue(N, 0));
1494       break;
1495     case ISD::SIGN_EXTEND:
1496     case ISD::ZERO_EXTEND:
1497     case ISD::ANY_EXTEND:
1498       RV = PromoteExtend(SDValue(N, 0));
1499       break;
1500     case ISD::LOAD:
1501       if (PromoteLoad(SDValue(N, 0)))
1502         RV = SDValue(N, 0);
1503       break;
1504     }
1505   }
1506 
1507   // If N is a commutative binary node, try commuting it to enable more
1508   // sdisel CSE.
1509   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1510       N->getNumValues() == 1) {
1511     SDValue N0 = N->getOperand(0);
1512     SDValue N1 = N->getOperand(1);
1513 
1514     // Constant operands are canonicalized to RHS.
1515     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1516       SDValue Ops[] = {N1, N0};
1517       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1518                                             N->getFlags());
1519       if (CSENode)
1520         return SDValue(CSENode, 0);
1521     }
1522   }
1523 
1524   return RV;
1525 }
1526 
1527 /// Given a node, return its input chain if it has one, otherwise return a null
1528 /// sd operand.
1529 static SDValue getInputChainForNode(SDNode *N) {
1530   if (unsigned NumOps = N->getNumOperands()) {
1531     if (N->getOperand(0).getValueType() == MVT::Other)
1532       return N->getOperand(0);
1533     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1534       return N->getOperand(NumOps-1);
1535     for (unsigned i = 1; i < NumOps-1; ++i)
1536       if (N->getOperand(i).getValueType() == MVT::Other)
1537         return N->getOperand(i);
1538   }
1539   return SDValue();
1540 }
1541 
1542 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1543   // If N has two operands, where one has an input chain equal to the other,
1544   // the 'other' chain is redundant.
1545   if (N->getNumOperands() == 2) {
1546     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1547       return N->getOperand(0);
1548     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1549       return N->getOperand(1);
1550   }
1551 
1552   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1553   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1554   SmallPtrSet<SDNode*, 16> SeenOps;
1555   bool Changed = false;             // If we should replace this token factor.
1556 
1557   // Start out with this token factor.
1558   TFs.push_back(N);
1559 
1560   // Iterate through token factors.  The TFs grows when new token factors are
1561   // encountered.
1562   for (unsigned i = 0; i < TFs.size(); ++i) {
1563     SDNode *TF = TFs[i];
1564 
1565     // Check each of the operands.
1566     for (const SDValue &Op : TF->op_values()) {
1567 
1568       switch (Op.getOpcode()) {
1569       case ISD::EntryToken:
1570         // Entry tokens don't need to be added to the list. They are
1571         // redundant.
1572         Changed = true;
1573         break;
1574 
1575       case ISD::TokenFactor:
1576         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1577           // Queue up for processing.
1578           TFs.push_back(Op.getNode());
1579           // Clean up in case the token factor is removed.
1580           AddToWorklist(Op.getNode());
1581           Changed = true;
1582           break;
1583         }
1584         LLVM_FALLTHROUGH;
1585 
1586       default:
1587         // Only add if it isn't already in the list.
1588         if (SeenOps.insert(Op.getNode()).second)
1589           Ops.push_back(Op);
1590         else
1591           Changed = true;
1592         break;
1593       }
1594     }
1595   }
1596 
1597   SDValue Result;
1598 
1599   // If we've changed things around then replace token factor.
1600   if (Changed) {
1601     if (Ops.empty()) {
1602       // The entry token is the only possible outcome.
1603       Result = DAG.getEntryNode();
1604     } else {
1605       // New and improved token factor.
1606       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1607     }
1608 
1609     // Add users to worklist if AA is enabled, since it may introduce
1610     // a lot of new chained token factors while removing memory deps.
1611     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1612       : DAG.getSubtarget().useAA();
1613     return CombineTo(N, Result, UseAA /*add to worklist*/);
1614   }
1615 
1616   return Result;
1617 }
1618 
1619 /// MERGE_VALUES can always be eliminated.
1620 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1621   WorklistRemover DeadNodes(*this);
1622   // Replacing results may cause a different MERGE_VALUES to suddenly
1623   // be CSE'd with N, and carry its uses with it. Iterate until no
1624   // uses remain, to ensure that the node can be safely deleted.
1625   // First add the users of this node to the work list so that they
1626   // can be tried again once they have new operands.
1627   AddUsersToWorklist(N);
1628   do {
1629     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1630       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1631   } while (!N->use_empty());
1632   deleteAndRecombine(N);
1633   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1634 }
1635 
1636 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1637 /// ConstantSDNode pointer else nullptr.
1638 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1639   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1640   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1641 }
1642 
1643 SDValue DAGCombiner::visitADD(SDNode *N) {
1644   SDValue N0 = N->getOperand(0);
1645   SDValue N1 = N->getOperand(1);
1646   EVT VT = N0.getValueType();
1647 
1648   // fold vector ops
1649   if (VT.isVector()) {
1650     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1651       return FoldedVOp;
1652 
1653     // fold (add x, 0) -> x, vector edition
1654     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1655       return N0;
1656     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1657       return N1;
1658   }
1659 
1660   // fold (add x, undef) -> undef
1661   if (N0.isUndef())
1662     return N0;
1663   if (N1.isUndef())
1664     return N1;
1665   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1666     // canonicalize constant to RHS
1667     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1668       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1669     // fold (add c1, c2) -> c1+c2
1670     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT,
1671                                       N0.getNode(), N1.getNode());
1672   }
1673   // fold (add x, 0) -> x
1674   if (isNullConstant(N1))
1675     return N0;
1676   // fold ((c1-A)+c2) -> (c1+c2)-A
1677   if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) {
1678     if (N0.getOpcode() == ISD::SUB)
1679       if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1680         SDLoc DL(N);
1681         return DAG.getNode(ISD::SUB, DL, VT,
1682                            DAG.getConstant(N1C->getAPIntValue()+
1683                                            N0C->getAPIntValue(), DL, VT),
1684                            N0.getOperand(1));
1685       }
1686   }
1687   // reassociate add
1688   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1689     return RADD;
1690   // fold ((0-A) + B) -> B-A
1691   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1692     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1693   // fold (A + (0-B)) -> A-B
1694   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1695     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1696   // fold (A+(B-A)) -> B
1697   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1698     return N1.getOperand(0);
1699   // fold ((B-A)+A) -> B
1700   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1701     return N0.getOperand(0);
1702   // fold (A+(B-(A+C))) to (B-C)
1703   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1704       N0 == N1.getOperand(1).getOperand(0))
1705     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1706                        N1.getOperand(1).getOperand(1));
1707   // fold (A+(B-(C+A))) to (B-C)
1708   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1709       N0 == N1.getOperand(1).getOperand(1))
1710     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1711                        N1.getOperand(1).getOperand(0));
1712   // fold (A+((B-A)+or-C)) to (B+or-C)
1713   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1714       N1.getOperand(0).getOpcode() == ISD::SUB &&
1715       N0 == N1.getOperand(0).getOperand(1))
1716     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1717                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1718 
1719   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1720   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1721     SDValue N00 = N0.getOperand(0);
1722     SDValue N01 = N0.getOperand(1);
1723     SDValue N10 = N1.getOperand(0);
1724     SDValue N11 = N1.getOperand(1);
1725 
1726     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1727       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1728                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1729                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1730   }
1731 
1732   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1733     return SDValue(N, 0);
1734 
1735   // fold (a+b) -> (a|b) iff a and b share no bits.
1736   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1737       VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1))
1738     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1739 
1740   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1741   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1742       isNullConstant(N1.getOperand(0).getOperand(0)))
1743     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1744                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1745                                    N1.getOperand(0).getOperand(1),
1746                                    N1.getOperand(1)));
1747   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1748       isNullConstant(N0.getOperand(0).getOperand(0)))
1749     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1750                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1751                                    N0.getOperand(0).getOperand(1),
1752                                    N0.getOperand(1)));
1753 
1754   if (N1.getOpcode() == ISD::AND) {
1755     SDValue AndOp0 = N1.getOperand(0);
1756     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1757     unsigned DestBits = VT.getScalarType().getSizeInBits();
1758 
1759     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1760     // and similar xforms where the inner op is either ~0 or 0.
1761     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1762       SDLoc DL(N);
1763       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1764     }
1765   }
1766 
1767   // add (sext i1), X -> sub X, (zext i1)
1768   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1769       N0.getOperand(0).getValueType() == MVT::i1 &&
1770       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1771     SDLoc DL(N);
1772     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1773     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1774   }
1775 
1776   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1777   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1778     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1779     if (TN->getVT() == MVT::i1) {
1780       SDLoc DL(N);
1781       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1782                                  DAG.getConstant(1, DL, VT));
1783       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1784     }
1785   }
1786 
1787   return SDValue();
1788 }
1789 
1790 SDValue DAGCombiner::visitADDC(SDNode *N) {
1791   SDValue N0 = N->getOperand(0);
1792   SDValue N1 = N->getOperand(1);
1793   EVT VT = N0.getValueType();
1794 
1795   // If the flag result is dead, turn this into an ADD.
1796   if (!N->hasAnyUseOfValue(1))
1797     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1798                      DAG.getNode(ISD::CARRY_FALSE,
1799                                  SDLoc(N), MVT::Glue));
1800 
1801   // canonicalize constant to RHS.
1802   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1803   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1804   if (N0C && !N1C)
1805     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1806 
1807   // fold (addc x, 0) -> x + no carry out
1808   if (isNullConstant(N1))
1809     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1810                                         SDLoc(N), MVT::Glue));
1811 
1812   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1813   APInt LHSZero, LHSOne;
1814   APInt RHSZero, RHSOne;
1815   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1816 
1817   if (LHSZero.getBoolValue()) {
1818     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1819 
1820     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1821     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1822     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1823       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1824                        DAG.getNode(ISD::CARRY_FALSE,
1825                                    SDLoc(N), MVT::Glue));
1826   }
1827 
1828   return SDValue();
1829 }
1830 
1831 SDValue DAGCombiner::visitADDE(SDNode *N) {
1832   SDValue N0 = N->getOperand(0);
1833   SDValue N1 = N->getOperand(1);
1834   SDValue CarryIn = N->getOperand(2);
1835 
1836   // canonicalize constant to RHS
1837   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1838   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1839   if (N0C && !N1C)
1840     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1841                        N1, N0, CarryIn);
1842 
1843   // fold (adde x, y, false) -> (addc x, y)
1844   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1845     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1846 
1847   return SDValue();
1848 }
1849 
1850 // Since it may not be valid to emit a fold to zero for vector initializers
1851 // check if we can before folding.
1852 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
1853                              SelectionDAG &DAG, bool LegalOperations,
1854                              bool LegalTypes) {
1855   if (!VT.isVector())
1856     return DAG.getConstant(0, DL, VT);
1857   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1858     return DAG.getConstant(0, DL, VT);
1859   return SDValue();
1860 }
1861 
1862 SDValue DAGCombiner::visitSUB(SDNode *N) {
1863   SDValue N0 = N->getOperand(0);
1864   SDValue N1 = N->getOperand(1);
1865   EVT VT = N0.getValueType();
1866 
1867   // fold vector ops
1868   if (VT.isVector()) {
1869     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1870       return FoldedVOp;
1871 
1872     // fold (sub x, 0) -> x, vector edition
1873     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1874       return N0;
1875   }
1876 
1877   // fold (sub x, x) -> 0
1878   // FIXME: Refactor this and xor and other similar operations together.
1879   if (N0 == N1)
1880     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1881   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1882       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1883     // fold (sub c1, c2) -> c1-c2
1884     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT,
1885                                       N0.getNode(), N1.getNode());
1886   }
1887   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1888   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1889   // fold (sub x, c) -> (add x, -c)
1890   if (N1C) {
1891     SDLoc DL(N);
1892     return DAG.getNode(ISD::ADD, DL, VT, N0,
1893                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1894   }
1895   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1896   if (isAllOnesConstant(N0))
1897     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1898   // fold A-(A-B) -> B
1899   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1900     return N1.getOperand(1);
1901   // fold (A+B)-A -> B
1902   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1903     return N0.getOperand(1);
1904   // fold (A+B)-B -> A
1905   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1906     return N0.getOperand(0);
1907   // fold C2-(A+C1) -> (C2-C1)-A
1908   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1909     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1910   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1911     SDLoc DL(N);
1912     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1913                                    DL, VT);
1914     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1915                        N1.getOperand(0));
1916   }
1917   // fold ((A+(B+or-C))-B) -> A+or-C
1918   if (N0.getOpcode() == ISD::ADD &&
1919       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1920        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1921       N0.getOperand(1).getOperand(0) == N1)
1922     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1923                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1924   // fold ((A+(C+B))-B) -> A+C
1925   if (N0.getOpcode() == ISD::ADD &&
1926       N0.getOperand(1).getOpcode() == ISD::ADD &&
1927       N0.getOperand(1).getOperand(1) == N1)
1928     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1929                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1930   // fold ((A-(B-C))-C) -> A-B
1931   if (N0.getOpcode() == ISD::SUB &&
1932       N0.getOperand(1).getOpcode() == ISD::SUB &&
1933       N0.getOperand(1).getOperand(1) == N1)
1934     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1935                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1936 
1937   // If either operand of a sub is undef, the result is undef
1938   if (N0.isUndef())
1939     return N0;
1940   if (N1.isUndef())
1941     return N1;
1942 
1943   // If the relocation model supports it, consider symbol offsets.
1944   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1945     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1946       // fold (sub Sym, c) -> Sym-c
1947       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1948         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1949                                     GA->getOffset() -
1950                                       (uint64_t)N1C->getSExtValue());
1951       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1952       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1953         if (GA->getGlobal() == GB->getGlobal())
1954           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1955                                  SDLoc(N), VT);
1956     }
1957 
1958   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1959   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1960     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1961     if (TN->getVT() == MVT::i1) {
1962       SDLoc DL(N);
1963       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1964                                  DAG.getConstant(1, DL, VT));
1965       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1966     }
1967   }
1968 
1969   return SDValue();
1970 }
1971 
1972 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1973   SDValue N0 = N->getOperand(0);
1974   SDValue N1 = N->getOperand(1);
1975   EVT VT = N0.getValueType();
1976   SDLoc DL(N);
1977 
1978   // If the flag result is dead, turn this into an SUB.
1979   if (!N->hasAnyUseOfValue(1))
1980     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1981                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1982 
1983   // fold (subc x, x) -> 0 + no borrow
1984   if (N0 == N1)
1985     return CombineTo(N, DAG.getConstant(0, DL, VT),
1986                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1987 
1988   // fold (subc x, 0) -> x + no borrow
1989   if (isNullConstant(N1))
1990     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1991 
1992   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1993   if (isAllOnesConstant(N0))
1994     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
1995                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1996 
1997   return SDValue();
1998 }
1999 
2000 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2001   SDValue N0 = N->getOperand(0);
2002   SDValue N1 = N->getOperand(1);
2003   SDValue CarryIn = N->getOperand(2);
2004 
2005   // fold (sube x, y, false) -> (subc x, y)
2006   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2007     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2008 
2009   return SDValue();
2010 }
2011 
2012 SDValue DAGCombiner::visitMUL(SDNode *N) {
2013   SDValue N0 = N->getOperand(0);
2014   SDValue N1 = N->getOperand(1);
2015   EVT VT = N0.getValueType();
2016 
2017   // fold (mul x, undef) -> 0
2018   if (N0.isUndef() || N1.isUndef())
2019     return DAG.getConstant(0, SDLoc(N), VT);
2020 
2021   bool N0IsConst = false;
2022   bool N1IsConst = false;
2023   bool N1IsOpaqueConst = false;
2024   bool N0IsOpaqueConst = false;
2025   APInt ConstValue0, ConstValue1;
2026   // fold vector ops
2027   if (VT.isVector()) {
2028     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2029       return FoldedVOp;
2030 
2031     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2032     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2033   } else {
2034     N0IsConst = isa<ConstantSDNode>(N0);
2035     if (N0IsConst) {
2036       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2037       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2038     }
2039     N1IsConst = isa<ConstantSDNode>(N1);
2040     if (N1IsConst) {
2041       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2042       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2043     }
2044   }
2045 
2046   // fold (mul c1, c2) -> c1*c2
2047   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2048     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2049                                       N0.getNode(), N1.getNode());
2050 
2051   // canonicalize constant to RHS (vector doesn't have to splat)
2052   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2053      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2054     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2055   // fold (mul x, 0) -> 0
2056   if (N1IsConst && ConstValue1 == 0)
2057     return N1;
2058   // We require a splat of the entire scalar bit width for non-contiguous
2059   // bit patterns.
2060   bool IsFullSplat =
2061     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2062   // fold (mul x, 1) -> x
2063   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2064     return N0;
2065   // fold (mul x, -1) -> 0-x
2066   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2067     SDLoc DL(N);
2068     return DAG.getNode(ISD::SUB, DL, VT,
2069                        DAG.getConstant(0, DL, VT), N0);
2070   }
2071   // fold (mul x, (1 << c)) -> x << c
2072   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2073       IsFullSplat) {
2074     SDLoc DL(N);
2075     return DAG.getNode(ISD::SHL, DL, VT, N0,
2076                        DAG.getConstant(ConstValue1.logBase2(), DL,
2077                                        getShiftAmountTy(N0.getValueType())));
2078   }
2079   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2080   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2081       IsFullSplat) {
2082     unsigned Log2Val = (-ConstValue1).logBase2();
2083     SDLoc DL(N);
2084     // FIXME: If the input is something that is easily negated (e.g. a
2085     // single-use add), we should put the negate there.
2086     return DAG.getNode(ISD::SUB, DL, VT,
2087                        DAG.getConstant(0, DL, VT),
2088                        DAG.getNode(ISD::SHL, DL, VT, N0,
2089                             DAG.getConstant(Log2Val, DL,
2090                                       getShiftAmountTy(N0.getValueType()))));
2091   }
2092 
2093   APInt Val;
2094   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2095   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2096       (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2097        isa<ConstantSDNode>(N0.getOperand(1)))) {
2098     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2099     AddToWorklist(C3.getNode());
2100     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2101   }
2102 
2103   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2104   // use.
2105   {
2106     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2107     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2108     if (N0.getOpcode() == ISD::SHL &&
2109         (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2110          isa<ConstantSDNode>(N0.getOperand(1))) &&
2111         N0.getNode()->hasOneUse()) {
2112       Sh = N0; Y = N1;
2113     } else if (N1.getOpcode() == ISD::SHL &&
2114                isa<ConstantSDNode>(N1.getOperand(1)) &&
2115                N1.getNode()->hasOneUse()) {
2116       Sh = N1; Y = N0;
2117     }
2118 
2119     if (Sh.getNode()) {
2120       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2121       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2122     }
2123   }
2124 
2125   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2126   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2127       N0.getOpcode() == ISD::ADD &&
2128       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2129       isMulAddWithConstProfitable(N, N0, N1))
2130       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2131                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2132                                      N0.getOperand(0), N1),
2133                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2134                                      N0.getOperand(1), N1));
2135 
2136   // reassociate mul
2137   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2138     return RMUL;
2139 
2140   return SDValue();
2141 }
2142 
2143 /// Return true if divmod libcall is available.
2144 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2145                                      const TargetLowering &TLI) {
2146   RTLIB::Libcall LC;
2147   EVT NodeType = Node->getValueType(0);
2148   if (!NodeType.isSimple())
2149     return false;
2150   switch (NodeType.getSimpleVT().SimpleTy) {
2151   default: return false; // No libcall for vector types.
2152   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2153   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2154   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2155   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2156   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2157   }
2158 
2159   return TLI.getLibcallName(LC) != nullptr;
2160 }
2161 
2162 /// Issue divrem if both quotient and remainder are needed.
2163 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2164   if (Node->use_empty())
2165     return SDValue(); // This is a dead node, leave it alone.
2166 
2167   unsigned Opcode = Node->getOpcode();
2168   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2169   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2170 
2171   // DivMod lib calls can still work on non-legal types if using lib-calls.
2172   EVT VT = Node->getValueType(0);
2173   if (VT.isVector() || !VT.isInteger())
2174     return SDValue();
2175 
2176   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2177     return SDValue();
2178 
2179   // If DIVREM is going to get expanded into a libcall,
2180   // but there is no libcall available, then don't combine.
2181   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2182       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2183     return SDValue();
2184 
2185   // If div is legal, it's better to do the normal expansion
2186   unsigned OtherOpcode = 0;
2187   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2188     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2189     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2190       return SDValue();
2191   } else {
2192     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2193     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2194       return SDValue();
2195   }
2196 
2197   SDValue Op0 = Node->getOperand(0);
2198   SDValue Op1 = Node->getOperand(1);
2199   SDValue combined;
2200   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2201          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2202     SDNode *User = *UI;
2203     if (User == Node || User->use_empty())
2204       continue;
2205     // Convert the other matching node(s), too;
2206     // otherwise, the DIVREM may get target-legalized into something
2207     // target-specific that we won't be able to recognize.
2208     unsigned UserOpc = User->getOpcode();
2209     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2210         User->getOperand(0) == Op0 &&
2211         User->getOperand(1) == Op1) {
2212       if (!combined) {
2213         if (UserOpc == OtherOpcode) {
2214           SDVTList VTs = DAG.getVTList(VT, VT);
2215           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2216         } else if (UserOpc == DivRemOpc) {
2217           combined = SDValue(User, 0);
2218         } else {
2219           assert(UserOpc == Opcode);
2220           continue;
2221         }
2222       }
2223       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2224         CombineTo(User, combined);
2225       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2226         CombineTo(User, combined.getValue(1));
2227     }
2228   }
2229   return combined;
2230 }
2231 
2232 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2233   SDValue N0 = N->getOperand(0);
2234   SDValue N1 = N->getOperand(1);
2235   EVT VT = N->getValueType(0);
2236 
2237   // fold vector ops
2238   if (VT.isVector())
2239     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2240       return FoldedVOp;
2241 
2242   SDLoc DL(N);
2243 
2244   // fold (sdiv c1, c2) -> c1/c2
2245   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2246   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2247   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2248     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2249   // fold (sdiv X, 1) -> X
2250   if (N1C && N1C->isOne())
2251     return N0;
2252   // fold (sdiv X, -1) -> 0-X
2253   if (N1C && N1C->isAllOnesValue())
2254     return DAG.getNode(ISD::SUB, DL, VT,
2255                        DAG.getConstant(0, DL, VT), N0);
2256 
2257   // If we know the sign bits of both operands are zero, strength reduce to a
2258   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2259   if (!VT.isVector()) {
2260     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2261       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2262   }
2263 
2264   // fold (sdiv X, pow2) -> simple ops after legalize
2265   // FIXME: We check for the exact bit here because the generic lowering gives
2266   // better results in that case. The target-specific lowering should learn how
2267   // to handle exact sdivs efficiently.
2268   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2269       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2270       (N1C->getAPIntValue().isPowerOf2() ||
2271        (-N1C->getAPIntValue()).isPowerOf2())) {
2272     // Target-specific implementation of sdiv x, pow2.
2273     if (SDValue Res = BuildSDIVPow2(N))
2274       return Res;
2275 
2276     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2277 
2278     // Splat the sign bit into the register
2279     SDValue SGN =
2280         DAG.getNode(ISD::SRA, DL, VT, N0,
2281                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2282                                     getShiftAmountTy(N0.getValueType())));
2283     AddToWorklist(SGN.getNode());
2284 
2285     // Add (N0 < 0) ? abs2 - 1 : 0;
2286     SDValue SRL =
2287         DAG.getNode(ISD::SRL, DL, VT, SGN,
2288                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2289                                     getShiftAmountTy(SGN.getValueType())));
2290     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2291     AddToWorklist(SRL.getNode());
2292     AddToWorklist(ADD.getNode());    // Divide by pow2
2293     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2294                   DAG.getConstant(lg2, DL,
2295                                   getShiftAmountTy(ADD.getValueType())));
2296 
2297     // If we're dividing by a positive value, we're done.  Otherwise, we must
2298     // negate the result.
2299     if (N1C->getAPIntValue().isNonNegative())
2300       return SRA;
2301 
2302     AddToWorklist(SRA.getNode());
2303     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2304   }
2305 
2306   // If integer divide is expensive and we satisfy the requirements, emit an
2307   // alternate sequence.  Targets may check function attributes for size/speed
2308   // trade-offs.
2309   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2310   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2311     if (SDValue Op = BuildSDIV(N))
2312       return Op;
2313 
2314   // sdiv, srem -> sdivrem
2315   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2316   // Otherwise, we break the simplification logic in visitREM().
2317   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2318     if (SDValue DivRem = useDivRem(N))
2319         return DivRem;
2320 
2321   // undef / X -> 0
2322   if (N0.isUndef())
2323     return DAG.getConstant(0, DL, VT);
2324   // X / undef -> undef
2325   if (N1.isUndef())
2326     return N1;
2327 
2328   return SDValue();
2329 }
2330 
2331 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2332   SDValue N0 = N->getOperand(0);
2333   SDValue N1 = N->getOperand(1);
2334   EVT VT = N->getValueType(0);
2335 
2336   // fold vector ops
2337   if (VT.isVector())
2338     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2339       return FoldedVOp;
2340 
2341   SDLoc DL(N);
2342 
2343   // fold (udiv c1, c2) -> c1/c2
2344   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2345   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2346   if (N0C && N1C)
2347     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2348                                                     N0C, N1C))
2349       return Folded;
2350   // fold (udiv x, (1 << c)) -> x >>u c
2351   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2352     return DAG.getNode(ISD::SRL, DL, VT, N0,
2353                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2354                                        getShiftAmountTy(N0.getValueType())));
2355 
2356   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2357   if (N1.getOpcode() == ISD::SHL) {
2358     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2359       if (SHC->getAPIntValue().isPowerOf2()) {
2360         EVT ADDVT = N1.getOperand(1).getValueType();
2361         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2362                                   N1.getOperand(1),
2363                                   DAG.getConstant(SHC->getAPIntValue()
2364                                                                   .logBase2(),
2365                                                   DL, ADDVT));
2366         AddToWorklist(Add.getNode());
2367         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2368       }
2369     }
2370   }
2371 
2372   // fold (udiv x, c) -> alternate
2373   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2374   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2375     if (SDValue Op = BuildUDIV(N))
2376       return Op;
2377 
2378   // sdiv, srem -> sdivrem
2379   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2380   // Otherwise, we break the simplification logic in visitREM().
2381   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2382     if (SDValue DivRem = useDivRem(N))
2383         return DivRem;
2384 
2385   // undef / X -> 0
2386   if (N0.isUndef())
2387     return DAG.getConstant(0, DL, VT);
2388   // X / undef -> undef
2389   if (N1.isUndef())
2390     return N1;
2391 
2392   return SDValue();
2393 }
2394 
2395 // handles ISD::SREM and ISD::UREM
2396 SDValue DAGCombiner::visitREM(SDNode *N) {
2397   unsigned Opcode = N->getOpcode();
2398   SDValue N0 = N->getOperand(0);
2399   SDValue N1 = N->getOperand(1);
2400   EVT VT = N->getValueType(0);
2401   bool isSigned = (Opcode == ISD::SREM);
2402   SDLoc DL(N);
2403 
2404   // fold (rem c1, c2) -> c1%c2
2405   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2406   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2407   if (N0C && N1C)
2408     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2409       return Folded;
2410 
2411   if (isSigned) {
2412     // If we know the sign bits of both operands are zero, strength reduce to a
2413     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2414     if (!VT.isVector()) {
2415       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2416         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2417     }
2418   } else {
2419     // fold (urem x, pow2) -> (and x, pow2-1)
2420     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2421         N1C->getAPIntValue().isPowerOf2()) {
2422       return DAG.getNode(ISD::AND, DL, VT, N0,
2423                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2424     }
2425     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2426     if (N1.getOpcode() == ISD::SHL) {
2427       ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0));
2428       if (SHC && SHC->getAPIntValue().isPowerOf2()) {
2429         APInt NegOne = APInt::getAllOnesValue(VT.getSizeInBits());
2430         SDValue Add =
2431             DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2432         AddToWorklist(Add.getNode());
2433         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2434       }
2435     }
2436   }
2437 
2438   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2439 
2440   // If X/C can be simplified by the division-by-constant logic, lower
2441   // X%C to the equivalent of X-X/C*C.
2442   // To avoid mangling nodes, this simplification requires that the combine()
2443   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2444   // against this by skipping the simplification if isIntDivCheap().  When
2445   // div is not cheap, combine will not return a DIVREM.  Regardless,
2446   // checking cheapness here makes sense since the simplification results in
2447   // fatter code.
2448   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2449     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2450     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2451     AddToWorklist(Div.getNode());
2452     SDValue OptimizedDiv = combine(Div.getNode());
2453     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2454       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2455              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2456       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2457       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2458       AddToWorklist(Mul.getNode());
2459       return Sub;
2460     }
2461   }
2462 
2463   // sdiv, srem -> sdivrem
2464   if (SDValue DivRem = useDivRem(N))
2465     return DivRem.getValue(1);
2466 
2467   // undef % X -> 0
2468   if (N0.isUndef())
2469     return DAG.getConstant(0, DL, VT);
2470   // X % undef -> undef
2471   if (N1.isUndef())
2472     return N1;
2473 
2474   return SDValue();
2475 }
2476 
2477 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2478   SDValue N0 = N->getOperand(0);
2479   SDValue N1 = N->getOperand(1);
2480   EVT VT = N->getValueType(0);
2481   SDLoc DL(N);
2482 
2483   // fold (mulhs x, 0) -> 0
2484   if (isNullConstant(N1))
2485     return N1;
2486   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2487   if (isOneConstant(N1)) {
2488     SDLoc DL(N);
2489     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2490                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2491                                        DL,
2492                                        getShiftAmountTy(N0.getValueType())));
2493   }
2494   // fold (mulhs x, undef) -> 0
2495   if (N0.isUndef() || N1.isUndef())
2496     return DAG.getConstant(0, SDLoc(N), VT);
2497 
2498   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2499   // plus a shift.
2500   if (VT.isSimple() && !VT.isVector()) {
2501     MVT Simple = VT.getSimpleVT();
2502     unsigned SimpleSize = Simple.getSizeInBits();
2503     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2504     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2505       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2506       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2507       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2508       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2509             DAG.getConstant(SimpleSize, DL,
2510                             getShiftAmountTy(N1.getValueType())));
2511       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2512     }
2513   }
2514 
2515   return SDValue();
2516 }
2517 
2518 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2519   SDValue N0 = N->getOperand(0);
2520   SDValue N1 = N->getOperand(1);
2521   EVT VT = N->getValueType(0);
2522   SDLoc DL(N);
2523 
2524   // fold (mulhu x, 0) -> 0
2525   if (isNullConstant(N1))
2526     return N1;
2527   // fold (mulhu x, 1) -> 0
2528   if (isOneConstant(N1))
2529     return DAG.getConstant(0, DL, N0.getValueType());
2530   // fold (mulhu x, undef) -> 0
2531   if (N0.isUndef() || N1.isUndef())
2532     return DAG.getConstant(0, DL, VT);
2533 
2534   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2535   // plus a shift.
2536   if (VT.isSimple() && !VT.isVector()) {
2537     MVT Simple = VT.getSimpleVT();
2538     unsigned SimpleSize = Simple.getSizeInBits();
2539     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2540     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2541       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2542       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2543       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2544       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2545             DAG.getConstant(SimpleSize, DL,
2546                             getShiftAmountTy(N1.getValueType())));
2547       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2548     }
2549   }
2550 
2551   return SDValue();
2552 }
2553 
2554 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2555 /// give the opcodes for the two computations that are being performed. Return
2556 /// true if a simplification was made.
2557 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2558                                                 unsigned HiOp) {
2559   // If the high half is not needed, just compute the low half.
2560   bool HiExists = N->hasAnyUseOfValue(1);
2561   if (!HiExists &&
2562       (!LegalOperations ||
2563        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2564     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2565     return CombineTo(N, Res, Res);
2566   }
2567 
2568   // If the low half is not needed, just compute the high half.
2569   bool LoExists = N->hasAnyUseOfValue(0);
2570   if (!LoExists &&
2571       (!LegalOperations ||
2572        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2573     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2574     return CombineTo(N, Res, Res);
2575   }
2576 
2577   // If both halves are used, return as it is.
2578   if (LoExists && HiExists)
2579     return SDValue();
2580 
2581   // If the two computed results can be simplified separately, separate them.
2582   if (LoExists) {
2583     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2584     AddToWorklist(Lo.getNode());
2585     SDValue LoOpt = combine(Lo.getNode());
2586     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2587         (!LegalOperations ||
2588          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2589       return CombineTo(N, LoOpt, LoOpt);
2590   }
2591 
2592   if (HiExists) {
2593     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2594     AddToWorklist(Hi.getNode());
2595     SDValue HiOpt = combine(Hi.getNode());
2596     if (HiOpt.getNode() && HiOpt != Hi &&
2597         (!LegalOperations ||
2598          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2599       return CombineTo(N, HiOpt, HiOpt);
2600   }
2601 
2602   return SDValue();
2603 }
2604 
2605 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2606   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2607     return Res;
2608 
2609   EVT VT = N->getValueType(0);
2610   SDLoc DL(N);
2611 
2612   // If the type is twice as wide is legal, transform the mulhu to a wider
2613   // multiply plus a shift.
2614   if (VT.isSimple() && !VT.isVector()) {
2615     MVT Simple = VT.getSimpleVT();
2616     unsigned SimpleSize = Simple.getSizeInBits();
2617     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2618     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2619       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2620       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2621       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2622       // Compute the high part as N1.
2623       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2624             DAG.getConstant(SimpleSize, DL,
2625                             getShiftAmountTy(Lo.getValueType())));
2626       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2627       // Compute the low part as N0.
2628       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2629       return CombineTo(N, Lo, Hi);
2630     }
2631   }
2632 
2633   return SDValue();
2634 }
2635 
2636 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2637   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2638     return Res;
2639 
2640   EVT VT = N->getValueType(0);
2641   SDLoc DL(N);
2642 
2643   // If the type is twice as wide is legal, transform the mulhu to a wider
2644   // multiply plus a shift.
2645   if (VT.isSimple() && !VT.isVector()) {
2646     MVT Simple = VT.getSimpleVT();
2647     unsigned SimpleSize = Simple.getSizeInBits();
2648     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2649     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2650       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2651       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2652       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2653       // Compute the high part as N1.
2654       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2655             DAG.getConstant(SimpleSize, DL,
2656                             getShiftAmountTy(Lo.getValueType())));
2657       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2658       // Compute the low part as N0.
2659       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2660       return CombineTo(N, Lo, Hi);
2661     }
2662   }
2663 
2664   return SDValue();
2665 }
2666 
2667 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2668   // (smulo x, 2) -> (saddo x, x)
2669   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2670     if (C2->getAPIntValue() == 2)
2671       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2672                          N->getOperand(0), N->getOperand(0));
2673 
2674   return SDValue();
2675 }
2676 
2677 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2678   // (umulo x, 2) -> (uaddo x, x)
2679   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2680     if (C2->getAPIntValue() == 2)
2681       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2682                          N->getOperand(0), N->getOperand(0));
2683 
2684   return SDValue();
2685 }
2686 
2687 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2688   SDValue N0 = N->getOperand(0);
2689   SDValue N1 = N->getOperand(1);
2690   EVT VT = N0.getValueType();
2691 
2692   // fold vector ops
2693   if (VT.isVector())
2694     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2695       return FoldedVOp;
2696 
2697   // fold (add c1, c2) -> c1+c2
2698   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2699   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2700   if (N0C && N1C)
2701     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2702 
2703   // canonicalize constant to RHS
2704   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2705      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2706     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2707 
2708   return SDValue();
2709 }
2710 
2711 /// If this is a binary operator with two operands of the same opcode, try to
2712 /// simplify it.
2713 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2714   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2715   EVT VT = N0.getValueType();
2716   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2717 
2718   // Bail early if none of these transforms apply.
2719   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2720 
2721   // For each of OP in AND/OR/XOR:
2722   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2723   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2724   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2725   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2726   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2727   //
2728   // do not sink logical op inside of a vector extend, since it may combine
2729   // into a vsetcc.
2730   EVT Op0VT = N0.getOperand(0).getValueType();
2731   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2732        N0.getOpcode() == ISD::SIGN_EXTEND ||
2733        N0.getOpcode() == ISD::BSWAP ||
2734        // Avoid infinite looping with PromoteIntBinOp.
2735        (N0.getOpcode() == ISD::ANY_EXTEND &&
2736         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2737        (N0.getOpcode() == ISD::TRUNCATE &&
2738         (!TLI.isZExtFree(VT, Op0VT) ||
2739          !TLI.isTruncateFree(Op0VT, VT)) &&
2740         TLI.isTypeLegal(Op0VT))) &&
2741       !VT.isVector() &&
2742       Op0VT == N1.getOperand(0).getValueType() &&
2743       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2744     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2745                                  N0.getOperand(0).getValueType(),
2746                                  N0.getOperand(0), N1.getOperand(0));
2747     AddToWorklist(ORNode.getNode());
2748     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2749   }
2750 
2751   // For each of OP in SHL/SRL/SRA/AND...
2752   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2753   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2754   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2755   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2756        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2757       N0.getOperand(1) == N1.getOperand(1)) {
2758     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2759                                  N0.getOperand(0).getValueType(),
2760                                  N0.getOperand(0), N1.getOperand(0));
2761     AddToWorklist(ORNode.getNode());
2762     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2763                        ORNode, N0.getOperand(1));
2764   }
2765 
2766   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2767   // Only perform this optimization up until type legalization, before
2768   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2769   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2770   // we don't want to undo this promotion.
2771   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2772   // on scalars.
2773   if ((N0.getOpcode() == ISD::BITCAST ||
2774        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2775        Level <= AfterLegalizeTypes) {
2776     SDValue In0 = N0.getOperand(0);
2777     SDValue In1 = N1.getOperand(0);
2778     EVT In0Ty = In0.getValueType();
2779     EVT In1Ty = In1.getValueType();
2780     SDLoc DL(N);
2781     // If both incoming values are integers, and the original types are the
2782     // same.
2783     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2784       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2785       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2786       AddToWorklist(Op.getNode());
2787       return BC;
2788     }
2789   }
2790 
2791   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2792   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2793   // If both shuffles use the same mask, and both shuffle within a single
2794   // vector, then it is worthwhile to move the swizzle after the operation.
2795   // The type-legalizer generates this pattern when loading illegal
2796   // vector types from memory. In many cases this allows additional shuffle
2797   // optimizations.
2798   // There are other cases where moving the shuffle after the xor/and/or
2799   // is profitable even if shuffles don't perform a swizzle.
2800   // If both shuffles use the same mask, and both shuffles have the same first
2801   // or second operand, then it might still be profitable to move the shuffle
2802   // after the xor/and/or operation.
2803   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2804     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2805     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2806 
2807     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2808            "Inputs to shuffles are not the same type");
2809 
2810     // Check that both shuffles use the same mask. The masks are known to be of
2811     // the same length because the result vector type is the same.
2812     // Check also that shuffles have only one use to avoid introducing extra
2813     // instructions.
2814     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2815         SVN0->getMask().equals(SVN1->getMask())) {
2816       SDValue ShOp = N0->getOperand(1);
2817 
2818       // Don't try to fold this node if it requires introducing a
2819       // build vector of all zeros that might be illegal at this stage.
2820       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2821         if (!LegalTypes)
2822           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2823         else
2824           ShOp = SDValue();
2825       }
2826 
2827       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2828       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2829       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2830       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2831         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2832                                       N0->getOperand(0), N1->getOperand(0));
2833         AddToWorklist(NewNode.getNode());
2834         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2835                                     SVN0->getMask());
2836       }
2837 
2838       // Don't try to fold this node if it requires introducing a
2839       // build vector of all zeros that might be illegal at this stage.
2840       ShOp = N0->getOperand(0);
2841       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2842         if (!LegalTypes)
2843           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2844         else
2845           ShOp = SDValue();
2846       }
2847 
2848       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2849       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2850       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2851       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2852         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2853                                       N0->getOperand(1), N1->getOperand(1));
2854         AddToWorklist(NewNode.getNode());
2855         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2856                                     SVN0->getMask());
2857       }
2858     }
2859   }
2860 
2861   return SDValue();
2862 }
2863 
2864 /// This contains all DAGCombine rules which reduce two values combined by
2865 /// an And operation to a single value. This makes them reusable in the context
2866 /// of visitSELECT(). Rules involving constants are not included as
2867 /// visitSELECT() already handles those cases.
2868 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2869                                   SDNode *LocReference) {
2870   EVT VT = N1.getValueType();
2871 
2872   // fold (and x, undef) -> 0
2873   if (N0.isUndef() || N1.isUndef())
2874     return DAG.getConstant(0, SDLoc(LocReference), VT);
2875   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2876   SDValue LL, LR, RL, RR, CC0, CC1;
2877   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2878     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2879     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2880 
2881     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2882         LL.getValueType().isInteger()) {
2883       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2884       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2885         EVT CCVT = getSetCCResultType(LR.getValueType());
2886         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2887           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2888                                        LR.getValueType(), LL, RL);
2889           AddToWorklist(ORNode.getNode());
2890           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2891         }
2892       }
2893       if (isAllOnesConstant(LR)) {
2894         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2895         if (Op1 == ISD::SETEQ) {
2896           EVT CCVT = getSetCCResultType(LR.getValueType());
2897           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2898             SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2899                                           LR.getValueType(), LL, RL);
2900             AddToWorklist(ANDNode.getNode());
2901             return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2902           }
2903         }
2904         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2905         if (Op1 == ISD::SETGT) {
2906           EVT CCVT = getSetCCResultType(LR.getValueType());
2907           if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2908             SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2909                                          LR.getValueType(), LL, RL);
2910             AddToWorklist(ORNode.getNode());
2911             return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2912           }
2913         }
2914       }
2915     }
2916     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2917     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2918         Op0 == Op1 && LL.getValueType().isInteger() &&
2919       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2920                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2921       EVT CCVT = getSetCCResultType(LL.getValueType());
2922       if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
2923         SDLoc DL(N0);
2924         SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2925                                       LL, DAG.getConstant(1, DL,
2926                                                           LL.getValueType()));
2927         AddToWorklist(ADDNode.getNode());
2928         return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2929                             DAG.getConstant(2, DL, LL.getValueType()),
2930                             ISD::SETUGE);
2931       }
2932     }
2933     // canonicalize equivalent to ll == rl
2934     if (LL == RR && LR == RL) {
2935       Op1 = ISD::getSetCCSwappedOperands(Op1);
2936       std::swap(RL, RR);
2937     }
2938     if (LL == RL && LR == RR) {
2939       bool isInteger = LL.getValueType().isInteger();
2940       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2941       if (Result != ISD::SETCC_INVALID &&
2942           (!LegalOperations ||
2943            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2944             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2945         EVT CCVT = getSetCCResultType(LL.getValueType());
2946         if (N0.getValueType() == CCVT ||
2947             (!LegalOperations && N0.getValueType() == MVT::i1))
2948           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2949                               LL, LR, Result);
2950       }
2951     }
2952   }
2953 
2954   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2955       VT.getSizeInBits() <= 64) {
2956     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2957       APInt ADDC = ADDI->getAPIntValue();
2958       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2959         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2960         // immediate for an add, but it is legal if its top c2 bits are set,
2961         // transform the ADD so the immediate doesn't need to be materialized
2962         // in a register.
2963         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2964           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2965                                              SRLI->getZExtValue());
2966           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2967             ADDC |= Mask;
2968             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2969               SDLoc DL(N0);
2970               SDValue NewAdd =
2971                 DAG.getNode(ISD::ADD, DL, VT,
2972                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2973               CombineTo(N0.getNode(), NewAdd);
2974               // Return N so it doesn't get rechecked!
2975               return SDValue(LocReference, 0);
2976             }
2977           }
2978         }
2979       }
2980     }
2981   }
2982 
2983   // Reduce bit extract of low half of an integer to the narrower type.
2984   // (and (srl i64:x, K), KMask) ->
2985   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
2986   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
2987     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
2988       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2989         unsigned Size = VT.getSizeInBits();
2990         const APInt &AndMask = CAnd->getAPIntValue();
2991         unsigned ShiftBits = CShift->getZExtValue();
2992         unsigned MaskBits = AndMask.countTrailingOnes();
2993         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
2994 
2995         if (APIntOps::isMask(AndMask) &&
2996             // Required bits must not span the two halves of the integer and
2997             // must fit in the half size type.
2998             (ShiftBits + MaskBits <= Size / 2) &&
2999             TLI.isNarrowingProfitable(VT, HalfVT) &&
3000             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3001             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3002             TLI.isTruncateFree(VT, HalfVT) &&
3003             TLI.isZExtFree(HalfVT, VT)) {
3004           // The isNarrowingProfitable is to avoid regressions on PPC and
3005           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3006           // on downstream users of this. Those patterns could probably be
3007           // extended to handle extensions mixed in.
3008 
3009           SDValue SL(N0);
3010           assert(ShiftBits != 0 && MaskBits <= Size);
3011 
3012           // Extracting the highest bit of the low half.
3013           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3014           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3015                                       N0.getOperand(0));
3016 
3017           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3018           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3019           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3020           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3021           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3022         }
3023       }
3024     }
3025   }
3026 
3027   return SDValue();
3028 }
3029 
3030 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3031                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3032                                    bool &NarrowLoad) {
3033   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3034 
3035   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3036     return false;
3037 
3038   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3039   LoadedVT = LoadN->getMemoryVT();
3040 
3041   if (ExtVT == LoadedVT &&
3042       (!LegalOperations ||
3043        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3044     // ZEXTLOAD will match without needing to change the size of the value being
3045     // loaded.
3046     NarrowLoad = false;
3047     return true;
3048   }
3049 
3050   // Do not change the width of a volatile load.
3051   if (LoadN->isVolatile())
3052     return false;
3053 
3054   // Do not generate loads of non-round integer types since these can
3055   // be expensive (and would be wrong if the type is not byte sized).
3056   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3057     return false;
3058 
3059   if (LegalOperations &&
3060       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3061     return false;
3062 
3063   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3064     return false;
3065 
3066   NarrowLoad = true;
3067   return true;
3068 }
3069 
3070 SDValue DAGCombiner::visitAND(SDNode *N) {
3071   SDValue N0 = N->getOperand(0);
3072   SDValue N1 = N->getOperand(1);
3073   EVT VT = N1.getValueType();
3074 
3075   // fold vector ops
3076   if (VT.isVector()) {
3077     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3078       return FoldedVOp;
3079 
3080     // fold (and x, 0) -> 0, vector edition
3081     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3082       // do not return N0, because undef node may exist in N0
3083       return DAG.getConstant(
3084           APInt::getNullValue(
3085               N0.getValueType().getScalarType().getSizeInBits()),
3086           SDLoc(N), N0.getValueType());
3087     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3088       // do not return N1, because undef node may exist in N1
3089       return DAG.getConstant(
3090           APInt::getNullValue(
3091               N1.getValueType().getScalarType().getSizeInBits()),
3092           SDLoc(N), N1.getValueType());
3093 
3094     // fold (and x, -1) -> x, vector edition
3095     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3096       return N1;
3097     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3098       return N0;
3099   }
3100 
3101   // fold (and c1, c2) -> c1&c2
3102   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3103   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3104   if (N0C && N1C && !N1C->isOpaque())
3105     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3106   // canonicalize constant to RHS
3107   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3108      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3109     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3110   // fold (and x, -1) -> x
3111   if (isAllOnesConstant(N1))
3112     return N0;
3113   // if (and x, c) is known to be zero, return 0
3114   unsigned BitWidth = VT.getScalarType().getSizeInBits();
3115   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3116                                    APInt::getAllOnesValue(BitWidth)))
3117     return DAG.getConstant(0, SDLoc(N), VT);
3118   // reassociate and
3119   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3120     return RAND;
3121   // fold (and (or x, C), D) -> D if (C & D) == D
3122   if (N1C && N0.getOpcode() == ISD::OR)
3123     if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3124       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3125         return N1;
3126   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3127   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3128     SDValue N0Op0 = N0.getOperand(0);
3129     APInt Mask = ~N1C->getAPIntValue();
3130     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3131     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3132       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3133                                  N0.getValueType(), N0Op0);
3134 
3135       // Replace uses of the AND with uses of the Zero extend node.
3136       CombineTo(N, Zext);
3137 
3138       // We actually want to replace all uses of the any_extend with the
3139       // zero_extend, to avoid duplicating things.  This will later cause this
3140       // AND to be folded.
3141       CombineTo(N0.getNode(), Zext);
3142       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3143     }
3144   }
3145   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3146   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3147   // already be zero by virtue of the width of the base type of the load.
3148   //
3149   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3150   // more cases.
3151   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3152        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3153        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3154        N0.getOperand(0).getResNo() == 0) ||
3155       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3156     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3157                                          N0 : N0.getOperand(0) );
3158 
3159     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3160     // This can be a pure constant or a vector splat, in which case we treat the
3161     // vector as a scalar and use the splat value.
3162     APInt Constant = APInt::getNullValue(1);
3163     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3164       Constant = C->getAPIntValue();
3165     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3166       APInt SplatValue, SplatUndef;
3167       unsigned SplatBitSize;
3168       bool HasAnyUndefs;
3169       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3170                                              SplatBitSize, HasAnyUndefs);
3171       if (IsSplat) {
3172         // Undef bits can contribute to a possible optimisation if set, so
3173         // set them.
3174         SplatValue |= SplatUndef;
3175 
3176         // The splat value may be something like "0x00FFFFFF", which means 0 for
3177         // the first vector value and FF for the rest, repeating. We need a mask
3178         // that will apply equally to all members of the vector, so AND all the
3179         // lanes of the constant together.
3180         EVT VT = Vector->getValueType(0);
3181         unsigned BitWidth = VT.getScalarType().getSizeInBits();
3182 
3183         // If the splat value has been compressed to a bitlength lower
3184         // than the size of the vector lane, we need to re-expand it to
3185         // the lane size.
3186         if (BitWidth > SplatBitSize)
3187           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3188                SplatBitSize < BitWidth;
3189                SplatBitSize = SplatBitSize * 2)
3190             SplatValue |= SplatValue.shl(SplatBitSize);
3191 
3192         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3193         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3194         if (SplatBitSize % BitWidth == 0) {
3195           Constant = APInt::getAllOnesValue(BitWidth);
3196           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3197             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3198         }
3199       }
3200     }
3201 
3202     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3203     // actually legal and isn't going to get expanded, else this is a false
3204     // optimisation.
3205     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3206                                                     Load->getValueType(0),
3207                                                     Load->getMemoryVT());
3208 
3209     // Resize the constant to the same size as the original memory access before
3210     // extension. If it is still the AllOnesValue then this AND is completely
3211     // unneeded.
3212     Constant =
3213       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3214 
3215     bool B;
3216     switch (Load->getExtensionType()) {
3217     default: B = false; break;
3218     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3219     case ISD::ZEXTLOAD:
3220     case ISD::NON_EXTLOAD: B = true; break;
3221     }
3222 
3223     if (B && Constant.isAllOnesValue()) {
3224       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3225       // preserve semantics once we get rid of the AND.
3226       SDValue NewLoad(Load, 0);
3227       if (Load->getExtensionType() == ISD::EXTLOAD) {
3228         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3229                               Load->getValueType(0), SDLoc(Load),
3230                               Load->getChain(), Load->getBasePtr(),
3231                               Load->getOffset(), Load->getMemoryVT(),
3232                               Load->getMemOperand());
3233         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3234         if (Load->getNumValues() == 3) {
3235           // PRE/POST_INC loads have 3 values.
3236           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3237                            NewLoad.getValue(2) };
3238           CombineTo(Load, To, 3, true);
3239         } else {
3240           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3241         }
3242       }
3243 
3244       // Fold the AND away, taking care not to fold to the old load node if we
3245       // replaced it.
3246       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3247 
3248       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3249     }
3250   }
3251 
3252   // fold (and (load x), 255) -> (zextload x, i8)
3253   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3254   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3255   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3256                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
3257                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3258     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3259     LoadSDNode *LN0 = HasAnyExt
3260       ? cast<LoadSDNode>(N0.getOperand(0))
3261       : cast<LoadSDNode>(N0);
3262     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3263         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3264       auto NarrowLoad = false;
3265       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3266       EVT ExtVT, LoadedVT;
3267       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3268                            NarrowLoad)) {
3269         if (!NarrowLoad) {
3270           SDValue NewLoad =
3271             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3272                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3273                            LN0->getMemOperand());
3274           AddToWorklist(N);
3275           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3276           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3277         } else {
3278           EVT PtrType = LN0->getOperand(1).getValueType();
3279 
3280           unsigned Alignment = LN0->getAlignment();
3281           SDValue NewPtr = LN0->getBasePtr();
3282 
3283           // For big endian targets, we need to add an offset to the pointer
3284           // to load the correct bytes.  For little endian systems, we merely
3285           // need to read fewer bytes from the same pointer.
3286           if (DAG.getDataLayout().isBigEndian()) {
3287             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3288             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3289             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3290             SDLoc DL(LN0);
3291             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3292                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3293             Alignment = MinAlign(Alignment, PtrOff);
3294           }
3295 
3296           AddToWorklist(NewPtr.getNode());
3297 
3298           SDValue Load = DAG.getExtLoad(
3299               ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3300               LN0->getPointerInfo(), ExtVT, Alignment,
3301               LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3302           AddToWorklist(N);
3303           CombineTo(LN0, Load, Load.getValue(1));
3304           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3305         }
3306       }
3307     }
3308   }
3309 
3310   if (SDValue Combined = visitANDLike(N0, N1, N))
3311     return Combined;
3312 
3313   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3314   if (N0.getOpcode() == N1.getOpcode())
3315     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3316       return Tmp;
3317 
3318   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3319   // fold (and (sra)) -> (and (srl)) when possible.
3320   if (!VT.isVector() &&
3321       SimplifyDemandedBits(SDValue(N, 0)))
3322     return SDValue(N, 0);
3323 
3324   // fold (zext_inreg (extload x)) -> (zextload x)
3325   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3326     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3327     EVT MemVT = LN0->getMemoryVT();
3328     // If we zero all the possible extended bits, then we can turn this into
3329     // a zextload if we are running before legalize or the operation is legal.
3330     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3331     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3332                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3333         ((!LegalOperations && !LN0->isVolatile()) ||
3334          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3335       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3336                                        LN0->getChain(), LN0->getBasePtr(),
3337                                        MemVT, LN0->getMemOperand());
3338       AddToWorklist(N);
3339       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3340       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3341     }
3342   }
3343   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3344   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3345       N0.hasOneUse()) {
3346     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3347     EVT MemVT = LN0->getMemoryVT();
3348     // If we zero all the possible extended bits, then we can turn this into
3349     // a zextload if we are running before legalize or the operation is legal.
3350     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3351     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3352                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3353         ((!LegalOperations && !LN0->isVolatile()) ||
3354          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3355       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3356                                        LN0->getChain(), LN0->getBasePtr(),
3357                                        MemVT, LN0->getMemOperand());
3358       AddToWorklist(N);
3359       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3360       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3361     }
3362   }
3363   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3364   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3365     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3366                                            N0.getOperand(1), false))
3367       return BSwap;
3368   }
3369 
3370   return SDValue();
3371 }
3372 
3373 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3374 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3375                                         bool DemandHighBits) {
3376   if (!LegalOperations)
3377     return SDValue();
3378 
3379   EVT VT = N->getValueType(0);
3380   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3381     return SDValue();
3382   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3383     return SDValue();
3384 
3385   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3386   bool LookPassAnd0 = false;
3387   bool LookPassAnd1 = false;
3388   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3389       std::swap(N0, N1);
3390   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3391       std::swap(N0, N1);
3392   if (N0.getOpcode() == ISD::AND) {
3393     if (!N0.getNode()->hasOneUse())
3394       return SDValue();
3395     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3396     if (!N01C || N01C->getZExtValue() != 0xFF00)
3397       return SDValue();
3398     N0 = N0.getOperand(0);
3399     LookPassAnd0 = true;
3400   }
3401 
3402   if (N1.getOpcode() == ISD::AND) {
3403     if (!N1.getNode()->hasOneUse())
3404       return SDValue();
3405     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3406     if (!N11C || N11C->getZExtValue() != 0xFF)
3407       return SDValue();
3408     N1 = N1.getOperand(0);
3409     LookPassAnd1 = true;
3410   }
3411 
3412   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3413     std::swap(N0, N1);
3414   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3415     return SDValue();
3416   if (!N0.getNode()->hasOneUse() ||
3417       !N1.getNode()->hasOneUse())
3418     return SDValue();
3419 
3420   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3421   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3422   if (!N01C || !N11C)
3423     return SDValue();
3424   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3425     return SDValue();
3426 
3427   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3428   SDValue N00 = N0->getOperand(0);
3429   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3430     if (!N00.getNode()->hasOneUse())
3431       return SDValue();
3432     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3433     if (!N001C || N001C->getZExtValue() != 0xFF)
3434       return SDValue();
3435     N00 = N00.getOperand(0);
3436     LookPassAnd0 = true;
3437   }
3438 
3439   SDValue N10 = N1->getOperand(0);
3440   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3441     if (!N10.getNode()->hasOneUse())
3442       return SDValue();
3443     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3444     if (!N101C || N101C->getZExtValue() != 0xFF00)
3445       return SDValue();
3446     N10 = N10.getOperand(0);
3447     LookPassAnd1 = true;
3448   }
3449 
3450   if (N00 != N10)
3451     return SDValue();
3452 
3453   // Make sure everything beyond the low halfword gets set to zero since the SRL
3454   // 16 will clear the top bits.
3455   unsigned OpSizeInBits = VT.getSizeInBits();
3456   if (DemandHighBits && OpSizeInBits > 16) {
3457     // If the left-shift isn't masked out then the only way this is a bswap is
3458     // if all bits beyond the low 8 are 0. In that case the entire pattern
3459     // reduces to a left shift anyway: leave it for other parts of the combiner.
3460     if (!LookPassAnd0)
3461       return SDValue();
3462 
3463     // However, if the right shift isn't masked out then it might be because
3464     // it's not needed. See if we can spot that too.
3465     if (!LookPassAnd1 &&
3466         !DAG.MaskedValueIsZero(
3467             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3468       return SDValue();
3469   }
3470 
3471   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3472   if (OpSizeInBits > 16) {
3473     SDLoc DL(N);
3474     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3475                       DAG.getConstant(OpSizeInBits - 16, DL,
3476                                       getShiftAmountTy(VT)));
3477   }
3478   return Res;
3479 }
3480 
3481 /// Return true if the specified node is an element that makes up a 32-bit
3482 /// packed halfword byteswap.
3483 /// ((x & 0x000000ff) << 8) |
3484 /// ((x & 0x0000ff00) >> 8) |
3485 /// ((x & 0x00ff0000) << 8) |
3486 /// ((x & 0xff000000) >> 8)
3487 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3488   if (!N.getNode()->hasOneUse())
3489     return false;
3490 
3491   unsigned Opc = N.getOpcode();
3492   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3493     return false;
3494 
3495   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3496   if (!N1C)
3497     return false;
3498 
3499   unsigned Num;
3500   switch (N1C->getZExtValue()) {
3501   default:
3502     return false;
3503   case 0xFF:       Num = 0; break;
3504   case 0xFF00:     Num = 1; break;
3505   case 0xFF0000:   Num = 2; break;
3506   case 0xFF000000: Num = 3; break;
3507   }
3508 
3509   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3510   SDValue N0 = N.getOperand(0);
3511   if (Opc == ISD::AND) {
3512     if (Num == 0 || Num == 2) {
3513       // (x >> 8) & 0xff
3514       // (x >> 8) & 0xff0000
3515       if (N0.getOpcode() != ISD::SRL)
3516         return false;
3517       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3518       if (!C || C->getZExtValue() != 8)
3519         return false;
3520     } else {
3521       // (x << 8) & 0xff00
3522       // (x << 8) & 0xff000000
3523       if (N0.getOpcode() != ISD::SHL)
3524         return false;
3525       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3526       if (!C || C->getZExtValue() != 8)
3527         return false;
3528     }
3529   } else if (Opc == ISD::SHL) {
3530     // (x & 0xff) << 8
3531     // (x & 0xff0000) << 8
3532     if (Num != 0 && Num != 2)
3533       return false;
3534     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3535     if (!C || C->getZExtValue() != 8)
3536       return false;
3537   } else { // Opc == ISD::SRL
3538     // (x & 0xff00) >> 8
3539     // (x & 0xff000000) >> 8
3540     if (Num != 1 && Num != 3)
3541       return false;
3542     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3543     if (!C || C->getZExtValue() != 8)
3544       return false;
3545   }
3546 
3547   if (Parts[Num])
3548     return false;
3549 
3550   Parts[Num] = N0.getOperand(0).getNode();
3551   return true;
3552 }
3553 
3554 /// Match a 32-bit packed halfword bswap. That is
3555 /// ((x & 0x000000ff) << 8) |
3556 /// ((x & 0x0000ff00) >> 8) |
3557 /// ((x & 0x00ff0000) << 8) |
3558 /// ((x & 0xff000000) >> 8)
3559 /// => (rotl (bswap x), 16)
3560 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3561   if (!LegalOperations)
3562     return SDValue();
3563 
3564   EVT VT = N->getValueType(0);
3565   if (VT != MVT::i32)
3566     return SDValue();
3567   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3568     return SDValue();
3569 
3570   // Look for either
3571   // (or (or (and), (and)), (or (and), (and)))
3572   // (or (or (or (and), (and)), (and)), (and))
3573   if (N0.getOpcode() != ISD::OR)
3574     return SDValue();
3575   SDValue N00 = N0.getOperand(0);
3576   SDValue N01 = N0.getOperand(1);
3577   SDNode *Parts[4] = {};
3578 
3579   if (N1.getOpcode() == ISD::OR &&
3580       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3581     // (or (or (and), (and)), (or (and), (and)))
3582     SDValue N000 = N00.getOperand(0);
3583     if (!isBSwapHWordElement(N000, Parts))
3584       return SDValue();
3585 
3586     SDValue N001 = N00.getOperand(1);
3587     if (!isBSwapHWordElement(N001, Parts))
3588       return SDValue();
3589     SDValue N010 = N01.getOperand(0);
3590     if (!isBSwapHWordElement(N010, Parts))
3591       return SDValue();
3592     SDValue N011 = N01.getOperand(1);
3593     if (!isBSwapHWordElement(N011, Parts))
3594       return SDValue();
3595   } else {
3596     // (or (or (or (and), (and)), (and)), (and))
3597     if (!isBSwapHWordElement(N1, Parts))
3598       return SDValue();
3599     if (!isBSwapHWordElement(N01, Parts))
3600       return SDValue();
3601     if (N00.getOpcode() != ISD::OR)
3602       return SDValue();
3603     SDValue N000 = N00.getOperand(0);
3604     if (!isBSwapHWordElement(N000, Parts))
3605       return SDValue();
3606     SDValue N001 = N00.getOperand(1);
3607     if (!isBSwapHWordElement(N001, Parts))
3608       return SDValue();
3609   }
3610 
3611   // Make sure the parts are all coming from the same node.
3612   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3613     return SDValue();
3614 
3615   SDLoc DL(N);
3616   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3617                               SDValue(Parts[0], 0));
3618 
3619   // Result of the bswap should be rotated by 16. If it's not legal, then
3620   // do  (x << 16) | (x >> 16).
3621   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3622   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3623     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3624   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3625     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3626   return DAG.getNode(ISD::OR, DL, VT,
3627                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3628                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3629 }
3630 
3631 /// This contains all DAGCombine rules which reduce two values combined by
3632 /// an Or operation to a single value \see visitANDLike().
3633 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3634   EVT VT = N1.getValueType();
3635   // fold (or x, undef) -> -1
3636   if (!LegalOperations &&
3637       (N0.isUndef() || N1.isUndef())) {
3638     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3639     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3640                            SDLoc(LocReference), VT);
3641   }
3642   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3643   SDValue LL, LR, RL, RR, CC0, CC1;
3644   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3645     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3646     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3647 
3648     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3649       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3650       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3651       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3652         EVT CCVT = getSetCCResultType(LR.getValueType());
3653         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3654           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3655                                        LR.getValueType(), LL, RL);
3656           AddToWorklist(ORNode.getNode());
3657           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3658         }
3659       }
3660       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3661       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3662       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3663         EVT CCVT = getSetCCResultType(LR.getValueType());
3664         if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) {
3665           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3666                                         LR.getValueType(), LL, RL);
3667           AddToWorklist(ANDNode.getNode());
3668           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3669         }
3670       }
3671     }
3672     // canonicalize equivalent to ll == rl
3673     if (LL == RR && LR == RL) {
3674       Op1 = ISD::getSetCCSwappedOperands(Op1);
3675       std::swap(RL, RR);
3676     }
3677     if (LL == RL && LR == RR) {
3678       bool isInteger = LL.getValueType().isInteger();
3679       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3680       if (Result != ISD::SETCC_INVALID &&
3681           (!LegalOperations ||
3682            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3683             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3684         EVT CCVT = getSetCCResultType(LL.getValueType());
3685         if (N0.getValueType() == CCVT ||
3686             (!LegalOperations && N0.getValueType() == MVT::i1))
3687           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3688                               LL, LR, Result);
3689       }
3690     }
3691   }
3692 
3693   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3694   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3695       // Don't increase # computations.
3696       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3697     // We can only do this xform if we know that bits from X that are set in C2
3698     // but not in C1 are already zero.  Likewise for Y.
3699     if (const ConstantSDNode *N0O1C =
3700         getAsNonOpaqueConstant(N0.getOperand(1))) {
3701       if (const ConstantSDNode *N1O1C =
3702           getAsNonOpaqueConstant(N1.getOperand(1))) {
3703         // We can only do this xform if we know that bits from X that are set in
3704         // C2 but not in C1 are already zero.  Likewise for Y.
3705         const APInt &LHSMask = N0O1C->getAPIntValue();
3706         const APInt &RHSMask = N1O1C->getAPIntValue();
3707 
3708         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3709             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3710           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3711                                   N0.getOperand(0), N1.getOperand(0));
3712           SDLoc DL(LocReference);
3713           return DAG.getNode(ISD::AND, DL, VT, X,
3714                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3715         }
3716       }
3717     }
3718   }
3719 
3720   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3721   if (N0.getOpcode() == ISD::AND &&
3722       N1.getOpcode() == ISD::AND &&
3723       N0.getOperand(0) == N1.getOperand(0) &&
3724       // Don't increase # computations.
3725       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3726     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3727                             N0.getOperand(1), N1.getOperand(1));
3728     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3729   }
3730 
3731   return SDValue();
3732 }
3733 
3734 SDValue DAGCombiner::visitOR(SDNode *N) {
3735   SDValue N0 = N->getOperand(0);
3736   SDValue N1 = N->getOperand(1);
3737   EVT VT = N1.getValueType();
3738 
3739   // fold vector ops
3740   if (VT.isVector()) {
3741     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3742       return FoldedVOp;
3743 
3744     // fold (or x, 0) -> x, vector edition
3745     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3746       return N1;
3747     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3748       return N0;
3749 
3750     // fold (or x, -1) -> -1, vector edition
3751     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3752       // do not return N0, because undef node may exist in N0
3753       return DAG.getConstant(
3754           APInt::getAllOnesValue(
3755               N0.getValueType().getScalarType().getSizeInBits()),
3756           SDLoc(N), N0.getValueType());
3757     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3758       // do not return N1, because undef node may exist in N1
3759       return DAG.getConstant(
3760           APInt::getAllOnesValue(
3761               N1.getValueType().getScalarType().getSizeInBits()),
3762           SDLoc(N), N1.getValueType());
3763 
3764     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
3765     // Do this only if the resulting shuffle is legal.
3766     if (isa<ShuffleVectorSDNode>(N0) &&
3767         isa<ShuffleVectorSDNode>(N1) &&
3768         // Avoid folding a node with illegal type.
3769         TLI.isTypeLegal(VT)) {
3770       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
3771       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
3772       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
3773       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
3774       // Ensure both shuffles have a zero input.
3775       if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) {
3776         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
3777         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
3778         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3779         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3780         bool CanFold = true;
3781         int NumElts = VT.getVectorNumElements();
3782         SmallVector<int, 4> Mask(NumElts);
3783 
3784         for (int i = 0; i != NumElts; ++i) {
3785           int M0 = SV0->getMaskElt(i);
3786           int M1 = SV1->getMaskElt(i);
3787 
3788           // Determine if either index is pointing to a zero vector.
3789           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
3790           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
3791 
3792           // If one element is zero and the otherside is undef, keep undef.
3793           // This also handles the case that both are undef.
3794           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
3795             Mask[i] = -1;
3796             continue;
3797           }
3798 
3799           // Make sure only one of the elements is zero.
3800           if (M0Zero == M1Zero) {
3801             CanFold = false;
3802             break;
3803           }
3804 
3805           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
3806 
3807           // We have a zero and non-zero element. If the non-zero came from
3808           // SV0 make the index a LHS index. If it came from SV1, make it
3809           // a RHS index. We need to mod by NumElts because we don't care
3810           // which operand it came from in the original shuffles.
3811           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
3812         }
3813 
3814         if (CanFold) {
3815           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
3816           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
3817 
3818           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3819           if (!LegalMask) {
3820             std::swap(NewLHS, NewRHS);
3821             ShuffleVectorSDNode::commuteMask(Mask);
3822             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
3823           }
3824 
3825           if (LegalMask)
3826             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
3827         }
3828       }
3829     }
3830   }
3831 
3832   // fold (or c1, c2) -> c1|c2
3833   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3834   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3835   if (N0C && N1C && !N1C->isOpaque())
3836     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3837   // canonicalize constant to RHS
3838   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3839      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3840     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3841   // fold (or x, 0) -> x
3842   if (isNullConstant(N1))
3843     return N0;
3844   // fold (or x, -1) -> -1
3845   if (isAllOnesConstant(N1))
3846     return N1;
3847   // fold (or x, c) -> c iff (x & ~c) == 0
3848   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3849     return N1;
3850 
3851   if (SDValue Combined = visitORLike(N0, N1, N))
3852     return Combined;
3853 
3854   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3855   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3856     return BSwap;
3857   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3858     return BSwap;
3859 
3860   // reassociate or
3861   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3862     return ROR;
3863   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3864   // iff (c1 & c2) == 0.
3865   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3866              isa<ConstantSDNode>(N0.getOperand(1))) {
3867     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3868     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3869       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3870                                                    N1C, C1))
3871         return DAG.getNode(
3872             ISD::AND, SDLoc(N), VT,
3873             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3874       return SDValue();
3875     }
3876   }
3877   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3878   if (N0.getOpcode() == N1.getOpcode())
3879     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3880       return Tmp;
3881 
3882   // See if this is some rotate idiom.
3883   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3884     return SDValue(Rot, 0);
3885 
3886   // Simplify the operands using demanded-bits information.
3887   if (!VT.isVector() &&
3888       SimplifyDemandedBits(SDValue(N, 0)))
3889     return SDValue(N, 0);
3890 
3891   return SDValue();
3892 }
3893 
3894 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3895 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3896   if (Op.getOpcode() == ISD::AND) {
3897     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3898       Mask = Op.getOperand(1);
3899       Op = Op.getOperand(0);
3900     } else {
3901       return false;
3902     }
3903   }
3904 
3905   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3906     Shift = Op;
3907     return true;
3908   }
3909 
3910   return false;
3911 }
3912 
3913 // Return true if we can prove that, whenever Neg and Pos are both in the
3914 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3915 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3916 //
3917 //     (or (shift1 X, Neg), (shift2 X, Pos))
3918 //
3919 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3920 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3921 // to consider shift amounts with defined behavior.
3922 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3923   // If EltSize is a power of 2 then:
3924   //
3925   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3926   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3927   //
3928   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3929   // for the stronger condition:
3930   //
3931   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3932   //
3933   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3934   // we can just replace Neg with Neg' for the rest of the function.
3935   //
3936   // In other cases we check for the even stronger condition:
3937   //
3938   //     Neg == EltSize - Pos                                    [B]
3939   //
3940   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3941   // behavior if Pos == 0 (and consequently Neg == EltSize).
3942   //
3943   // We could actually use [A] whenever EltSize is a power of 2, but the
3944   // only extra cases that it would match are those uninteresting ones
3945   // where Neg and Pos are never in range at the same time.  E.g. for
3946   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3947   // as well as (sub 32, Pos), but:
3948   //
3949   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3950   //
3951   // always invokes undefined behavior for 32-bit X.
3952   //
3953   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3954   unsigned MaskLoBits = 0;
3955   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3956     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3957       if (NegC->getAPIntValue() == EltSize - 1) {
3958         Neg = Neg.getOperand(0);
3959         MaskLoBits = Log2_64(EltSize);
3960       }
3961     }
3962   }
3963 
3964   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3965   if (Neg.getOpcode() != ISD::SUB)
3966     return false;
3967   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3968   if (!NegC)
3969     return false;
3970   SDValue NegOp1 = Neg.getOperand(1);
3971 
3972   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3973   // Pos'.  The truncation is redundant for the purpose of the equality.
3974   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3975     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3976       if (PosC->getAPIntValue() == EltSize - 1)
3977         Pos = Pos.getOperand(0);
3978 
3979   // The condition we need is now:
3980   //
3981   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3982   //
3983   // If NegOp1 == Pos then we need:
3984   //
3985   //              EltSize & Mask == NegC & Mask
3986   //
3987   // (because "x & Mask" is a truncation and distributes through subtraction).
3988   APInt Width;
3989   if (Pos == NegOp1)
3990     Width = NegC->getAPIntValue();
3991 
3992   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3993   // Then the condition we want to prove becomes:
3994   //
3995   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3996   //
3997   // which, again because "x & Mask" is a truncation, becomes:
3998   //
3999   //                NegC & Mask == (EltSize - PosC) & Mask
4000   //             EltSize & Mask == (NegC + PosC) & Mask
4001   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4002     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4003       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4004     else
4005       return false;
4006   } else
4007     return false;
4008 
4009   // Now we just need to check that EltSize & Mask == Width & Mask.
4010   if (MaskLoBits)
4011     // EltSize & Mask is 0 since Mask is EltSize - 1.
4012     return Width.getLoBits(MaskLoBits) == 0;
4013   return Width == EltSize;
4014 }
4015 
4016 // A subroutine of MatchRotate used once we have found an OR of two opposite
4017 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4018 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4019 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4020 // Neg with outer conversions stripped away.
4021 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4022                                        SDValue Neg, SDValue InnerPos,
4023                                        SDValue InnerNeg, unsigned PosOpcode,
4024                                        unsigned NegOpcode, const SDLoc &DL) {
4025   // fold (or (shl x, (*ext y)),
4026   //          (srl x, (*ext (sub 32, y)))) ->
4027   //   (rotl x, y) or (rotr x, (sub 32, y))
4028   //
4029   // fold (or (shl x, (*ext (sub 32, y))),
4030   //          (srl x, (*ext y))) ->
4031   //   (rotr x, y) or (rotl x, (sub 32, y))
4032   EVT VT = Shifted.getValueType();
4033   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4034     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4035     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4036                        HasPos ? Pos : Neg).getNode();
4037   }
4038 
4039   return nullptr;
4040 }
4041 
4042 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4043 // idioms for rotate, and if the target supports rotation instructions, generate
4044 // a rot[lr].
4045 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4046   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4047   EVT VT = LHS.getValueType();
4048   if (!TLI.isTypeLegal(VT)) return nullptr;
4049 
4050   // The target must have at least one rotate flavor.
4051   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4052   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4053   if (!HasROTL && !HasROTR) return nullptr;
4054 
4055   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4056   SDValue LHSShift;   // The shift.
4057   SDValue LHSMask;    // AND value if any.
4058   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4059     return nullptr; // Not part of a rotate.
4060 
4061   SDValue RHSShift;   // The shift.
4062   SDValue RHSMask;    // AND value if any.
4063   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4064     return nullptr; // Not part of a rotate.
4065 
4066   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4067     return nullptr;   // Not shifting the same value.
4068 
4069   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4070     return nullptr;   // Shifts must disagree.
4071 
4072   // Canonicalize shl to left side in a shl/srl pair.
4073   if (RHSShift.getOpcode() == ISD::SHL) {
4074     std::swap(LHS, RHS);
4075     std::swap(LHSShift, RHSShift);
4076     std::swap(LHSMask, RHSMask);
4077   }
4078 
4079   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4080   SDValue LHSShiftArg = LHSShift.getOperand(0);
4081   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4082   SDValue RHSShiftArg = RHSShift.getOperand(0);
4083   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4084 
4085   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4086   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4087   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4088     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4089     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4090     if ((LShVal + RShVal) != EltSizeInBits)
4091       return nullptr;
4092 
4093     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4094                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4095 
4096     // If there is an AND of either shifted operand, apply it to the result.
4097     if (LHSMask.getNode() || RHSMask.getNode()) {
4098       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4099       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4100 
4101       if (LHSMask.getNode()) {
4102         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4103         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4104                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4105                                        DAG.getConstant(RHSBits, DL, VT)));
4106       }
4107       if (RHSMask.getNode()) {
4108         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4109         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4110                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4111                                        DAG.getConstant(LHSBits, DL, VT)));
4112       }
4113 
4114       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4115     }
4116 
4117     return Rot.getNode();
4118   }
4119 
4120   // If there is a mask here, and we have a variable shift, we can't be sure
4121   // that we're masking out the right stuff.
4122   if (LHSMask.getNode() || RHSMask.getNode())
4123     return nullptr;
4124 
4125   // If the shift amount is sign/zext/any-extended just peel it off.
4126   SDValue LExtOp0 = LHSShiftAmt;
4127   SDValue RExtOp0 = RHSShiftAmt;
4128   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4129        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4130        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4131        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4132       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4133        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4134        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4135        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4136     LExtOp0 = LHSShiftAmt.getOperand(0);
4137     RExtOp0 = RHSShiftAmt.getOperand(0);
4138   }
4139 
4140   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4141                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4142   if (TryL)
4143     return TryL;
4144 
4145   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4146                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4147   if (TryR)
4148     return TryR;
4149 
4150   return nullptr;
4151 }
4152 
4153 SDValue DAGCombiner::visitXOR(SDNode *N) {
4154   SDValue N0 = N->getOperand(0);
4155   SDValue N1 = N->getOperand(1);
4156   EVT VT = N0.getValueType();
4157 
4158   // fold vector ops
4159   if (VT.isVector()) {
4160     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4161       return FoldedVOp;
4162 
4163     // fold (xor x, 0) -> x, vector edition
4164     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4165       return N1;
4166     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4167       return N0;
4168   }
4169 
4170   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4171   if (N0.isUndef() && N1.isUndef())
4172     return DAG.getConstant(0, SDLoc(N), VT);
4173   // fold (xor x, undef) -> undef
4174   if (N0.isUndef())
4175     return N0;
4176   if (N1.isUndef())
4177     return N1;
4178   // fold (xor c1, c2) -> c1^c2
4179   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4180   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4181   if (N0C && N1C)
4182     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4183   // canonicalize constant to RHS
4184   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4185      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4186     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4187   // fold (xor x, 0) -> x
4188   if (isNullConstant(N1))
4189     return N0;
4190   // reassociate xor
4191   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4192     return RXOR;
4193 
4194   // fold !(x cc y) -> (x !cc y)
4195   SDValue LHS, RHS, CC;
4196   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4197     bool isInt = LHS.getValueType().isInteger();
4198     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4199                                                isInt);
4200 
4201     if (!LegalOperations ||
4202         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4203       switch (N0.getOpcode()) {
4204       default:
4205         llvm_unreachable("Unhandled SetCC Equivalent!");
4206       case ISD::SETCC:
4207         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4208       case ISD::SELECT_CC:
4209         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4210                                N0.getOperand(3), NotCC);
4211       }
4212     }
4213   }
4214 
4215   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4216   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4217       N0.getNode()->hasOneUse() &&
4218       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4219     SDValue V = N0.getOperand(0);
4220     SDLoc DL(N0);
4221     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4222                     DAG.getConstant(1, DL, V.getValueType()));
4223     AddToWorklist(V.getNode());
4224     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4225   }
4226 
4227   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4228   if (isOneConstant(N1) && VT == MVT::i1 &&
4229       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4230     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4231     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4232       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4233       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4234       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4235       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4236       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4237     }
4238   }
4239   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4240   if (isAllOnesConstant(N1) &&
4241       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4242     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4243     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4244       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4245       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4246       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4247       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4248       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4249     }
4250   }
4251   // fold (xor (and x, y), y) -> (and (not x), y)
4252   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4253       N0->getOperand(1) == N1) {
4254     SDValue X = N0->getOperand(0);
4255     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4256     AddToWorklist(NotX.getNode());
4257     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4258   }
4259   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4260   if (N1C && N0.getOpcode() == ISD::XOR) {
4261     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4262       SDLoc DL(N);
4263       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4264                          DAG.getConstant(N1C->getAPIntValue() ^
4265                                          N00C->getAPIntValue(), DL, VT));
4266     }
4267     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4268       SDLoc DL(N);
4269       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4270                          DAG.getConstant(N1C->getAPIntValue() ^
4271                                          N01C->getAPIntValue(), DL, VT));
4272     }
4273   }
4274   // fold (xor x, x) -> 0
4275   if (N0 == N1)
4276     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4277 
4278   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4279   // Here is a concrete example of this equivalence:
4280   // i16   x ==  14
4281   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4282   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4283   //
4284   // =>
4285   //
4286   // i16     ~1      == 0b1111111111111110
4287   // i16 rol(~1, 14) == 0b1011111111111111
4288   //
4289   // Some additional tips to help conceptualize this transform:
4290   // - Try to see the operation as placing a single zero in a value of all ones.
4291   // - There exists no value for x which would allow the result to contain zero.
4292   // - Values of x larger than the bitwidth are undefined and do not require a
4293   //   consistent result.
4294   // - Pushing the zero left requires shifting one bits in from the right.
4295   // A rotate left of ~1 is a nice way of achieving the desired result.
4296   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4297       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4298     SDLoc DL(N);
4299     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4300                        N0.getOperand(1));
4301   }
4302 
4303   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4304   if (N0.getOpcode() == N1.getOpcode())
4305     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4306       return Tmp;
4307 
4308   // Simplify the expression using non-local knowledge.
4309   if (!VT.isVector() &&
4310       SimplifyDemandedBits(SDValue(N, 0)))
4311     return SDValue(N, 0);
4312 
4313   return SDValue();
4314 }
4315 
4316 /// Handle transforms common to the three shifts, when the shift amount is a
4317 /// constant.
4318 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4319   SDNode *LHS = N->getOperand(0).getNode();
4320   if (!LHS->hasOneUse()) return SDValue();
4321 
4322   // We want to pull some binops through shifts, so that we have (and (shift))
4323   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4324   // thing happens with address calculations, so it's important to canonicalize
4325   // it.
4326   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4327 
4328   switch (LHS->getOpcode()) {
4329   default: return SDValue();
4330   case ISD::OR:
4331   case ISD::XOR:
4332     HighBitSet = false; // We can only transform sra if the high bit is clear.
4333     break;
4334   case ISD::AND:
4335     HighBitSet = true;  // We can only transform sra if the high bit is set.
4336     break;
4337   case ISD::ADD:
4338     if (N->getOpcode() != ISD::SHL)
4339       return SDValue(); // only shl(add) not sr[al](add).
4340     HighBitSet = false; // We can only transform sra if the high bit is clear.
4341     break;
4342   }
4343 
4344   // We require the RHS of the binop to be a constant and not opaque as well.
4345   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4346   if (!BinOpCst) return SDValue();
4347 
4348   // FIXME: disable this unless the input to the binop is a shift by a constant.
4349   // If it is not a shift, it pessimizes some common cases like:
4350   //
4351   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4352   //    int bar(int *X, int i) { return X[i & 255]; }
4353   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4354   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4355        BinOpLHSVal->getOpcode() != ISD::SRA &&
4356        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4357       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4358     return SDValue();
4359 
4360   EVT VT = N->getValueType(0);
4361 
4362   // If this is a signed shift right, and the high bit is modified by the
4363   // logical operation, do not perform the transformation. The highBitSet
4364   // boolean indicates the value of the high bit of the constant which would
4365   // cause it to be modified for this operation.
4366   if (N->getOpcode() == ISD::SRA) {
4367     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4368     if (BinOpRHSSignSet != HighBitSet)
4369       return SDValue();
4370   }
4371 
4372   if (!TLI.isDesirableToCommuteWithShift(LHS))
4373     return SDValue();
4374 
4375   // Fold the constants, shifting the binop RHS by the shift amount.
4376   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4377                                N->getValueType(0),
4378                                LHS->getOperand(1), N->getOperand(1));
4379   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4380 
4381   // Create the new shift.
4382   SDValue NewShift = DAG.getNode(N->getOpcode(),
4383                                  SDLoc(LHS->getOperand(0)),
4384                                  VT, LHS->getOperand(0), N->getOperand(1));
4385 
4386   // Create the new binop.
4387   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4388 }
4389 
4390 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4391   assert(N->getOpcode() == ISD::TRUNCATE);
4392   assert(N->getOperand(0).getOpcode() == ISD::AND);
4393 
4394   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4395   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4396     SDValue N01 = N->getOperand(0).getOperand(1);
4397 
4398     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4399       if (!N01C->isOpaque()) {
4400         EVT TruncVT = N->getValueType(0);
4401         SDValue N00 = N->getOperand(0).getOperand(0);
4402         APInt TruncC = N01C->getAPIntValue();
4403         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4404         SDLoc DL(N);
4405 
4406         return DAG.getNode(ISD::AND, DL, TruncVT,
4407                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4408                            DAG.getConstant(TruncC, DL, TruncVT));
4409       }
4410     }
4411   }
4412 
4413   return SDValue();
4414 }
4415 
4416 SDValue DAGCombiner::visitRotate(SDNode *N) {
4417   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4418   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4419       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4420     if (SDValue NewOp1 =
4421             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4422       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4423                          N->getOperand(0), NewOp1);
4424   }
4425   return SDValue();
4426 }
4427 
4428 SDValue DAGCombiner::visitSHL(SDNode *N) {
4429   SDValue N0 = N->getOperand(0);
4430   SDValue N1 = N->getOperand(1);
4431   EVT VT = N0.getValueType();
4432   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4433 
4434   // fold vector ops
4435   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4436   if (VT.isVector()) {
4437     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4438       return FoldedVOp;
4439 
4440     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4441     // If setcc produces all-one true value then:
4442     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4443     if (N1CV && N1CV->isConstant()) {
4444       if (N0.getOpcode() == ISD::AND) {
4445         SDValue N00 = N0->getOperand(0);
4446         SDValue N01 = N0->getOperand(1);
4447         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4448 
4449         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4450             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4451                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4452           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4453                                                      N01CV, N1CV))
4454             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4455         }
4456       } else {
4457         N1C = isConstOrConstSplat(N1);
4458       }
4459     }
4460   }
4461 
4462   // fold (shl c1, c2) -> c1<<c2
4463   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4464   if (N0C && N1C && !N1C->isOpaque())
4465     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4466   // fold (shl 0, x) -> 0
4467   if (isNullConstant(N0))
4468     return N0;
4469   // fold (shl x, c >= size(x)) -> undef
4470   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4471     return DAG.getUNDEF(VT);
4472   // fold (shl x, 0) -> x
4473   if (N1C && N1C->isNullValue())
4474     return N0;
4475   // fold (shl undef, x) -> 0
4476   if (N0.isUndef())
4477     return DAG.getConstant(0, SDLoc(N), VT);
4478   // if (shl x, c) is known to be zero, return 0
4479   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4480                             APInt::getAllOnesValue(OpSizeInBits)))
4481     return DAG.getConstant(0, SDLoc(N), VT);
4482   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4483   if (N1.getOpcode() == ISD::TRUNCATE &&
4484       N1.getOperand(0).getOpcode() == ISD::AND) {
4485     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4486       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4487   }
4488 
4489   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4490     return SDValue(N, 0);
4491 
4492   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4493   if (N1C && N0.getOpcode() == ISD::SHL) {
4494     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4495       SDLoc DL(N);
4496       APInt c1 = N0C1->getAPIntValue();
4497       APInt c2 = N1C->getAPIntValue();
4498       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4499 
4500       APInt Sum = c1 + c2;
4501       if (Sum.uge(OpSizeInBits))
4502         return DAG.getConstant(0, DL, VT);
4503 
4504       return DAG.getNode(
4505           ISD::SHL, DL, VT, N0.getOperand(0),
4506           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4507     }
4508   }
4509 
4510   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4511   // For this to be valid, the second form must not preserve any of the bits
4512   // that are shifted out by the inner shift in the first form.  This means
4513   // the outer shift size must be >= the number of bits added by the ext.
4514   // As a corollary, we don't care what kind of ext it is.
4515   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4516               N0.getOpcode() == ISD::ANY_EXTEND ||
4517               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4518       N0.getOperand(0).getOpcode() == ISD::SHL) {
4519     SDValue N0Op0 = N0.getOperand(0);
4520     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4521       APInt c1 = N0Op0C1->getAPIntValue();
4522       APInt c2 = N1C->getAPIntValue();
4523       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4524 
4525       EVT InnerShiftVT = N0Op0.getValueType();
4526       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4527       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
4528         SDLoc DL(N0);
4529         APInt Sum = c1 + c2;
4530         if (Sum.uge(OpSizeInBits))
4531           return DAG.getConstant(0, DL, VT);
4532 
4533         return DAG.getNode(
4534             ISD::SHL, DL, VT,
4535             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
4536             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4537       }
4538     }
4539   }
4540 
4541   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4542   // Only fold this if the inner zext has no other uses to avoid increasing
4543   // the total number of instructions.
4544   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4545       N0.getOperand(0).getOpcode() == ISD::SRL) {
4546     SDValue N0Op0 = N0.getOperand(0);
4547     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4548       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
4549         uint64_t c1 = N0Op0C1->getZExtValue();
4550         uint64_t c2 = N1C->getZExtValue();
4551         if (c1 == c2) {
4552           SDValue NewOp0 = N0.getOperand(0);
4553           EVT CountVT = NewOp0.getOperand(1).getValueType();
4554           SDLoc DL(N);
4555           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4556                                        NewOp0,
4557                                        DAG.getConstant(c2, DL, CountVT));
4558           AddToWorklist(NewSHL.getNode());
4559           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4560         }
4561       }
4562     }
4563   }
4564 
4565   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4566   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4567   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4568       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4569     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4570       uint64_t C1 = N0C1->getZExtValue();
4571       uint64_t C2 = N1C->getZExtValue();
4572       SDLoc DL(N);
4573       if (C1 <= C2)
4574         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4575                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4576       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4577                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4578     }
4579   }
4580 
4581   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4582   //                               (and (srl x, (sub c1, c2), MASK)
4583   // Only fold this if the inner shift has no other uses -- if it does, folding
4584   // this will increase the total number of instructions.
4585   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4586     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4587       uint64_t c1 = N0C1->getZExtValue();
4588       if (c1 < OpSizeInBits) {
4589         uint64_t c2 = N1C->getZExtValue();
4590         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4591         SDValue Shift;
4592         if (c2 > c1) {
4593           Mask = Mask.shl(c2 - c1);
4594           SDLoc DL(N);
4595           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4596                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4597         } else {
4598           Mask = Mask.lshr(c1 - c2);
4599           SDLoc DL(N);
4600           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4601                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4602         }
4603         SDLoc DL(N0);
4604         return DAG.getNode(ISD::AND, DL, VT, Shift,
4605                            DAG.getConstant(Mask, DL, VT));
4606       }
4607     }
4608   }
4609   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4610   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4611     unsigned BitSize = VT.getScalarSizeInBits();
4612     SDLoc DL(N);
4613     SDValue HiBitsMask =
4614       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4615                                             BitSize - N1C->getZExtValue()),
4616                       DL, VT);
4617     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4618                        HiBitsMask);
4619   }
4620 
4621   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4622   // Variant of version done on multiply, except mul by a power of 2 is turned
4623   // into a shift.
4624   APInt Val;
4625   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4626       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4627        ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4628     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4629     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4630     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4631   }
4632 
4633   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4634   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4635     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4636       if (SDValue Folded =
4637               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4638         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4639     }
4640   }
4641 
4642   if (N1C && !N1C->isOpaque())
4643     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4644       return NewSHL;
4645 
4646   return SDValue();
4647 }
4648 
4649 SDValue DAGCombiner::visitSRA(SDNode *N) {
4650   SDValue N0 = N->getOperand(0);
4651   SDValue N1 = N->getOperand(1);
4652   EVT VT = N0.getValueType();
4653   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4654 
4655   // fold vector ops
4656   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4657   if (VT.isVector()) {
4658     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4659       return FoldedVOp;
4660 
4661     N1C = isConstOrConstSplat(N1);
4662   }
4663 
4664   // fold (sra c1, c2) -> (sra c1, c2)
4665   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4666   if (N0C && N1C && !N1C->isOpaque())
4667     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4668   // fold (sra 0, x) -> 0
4669   if (isNullConstant(N0))
4670     return N0;
4671   // fold (sra -1, x) -> -1
4672   if (isAllOnesConstant(N0))
4673     return N0;
4674   // fold (sra x, c >= size(x)) -> undef
4675   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4676     return DAG.getUNDEF(VT);
4677   // fold (sra x, 0) -> x
4678   if (N1C && N1C->isNullValue())
4679     return N0;
4680   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4681   // sext_inreg.
4682   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4683     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4684     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4685     if (VT.isVector())
4686       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4687                                ExtVT, VT.getVectorNumElements());
4688     if ((!LegalOperations ||
4689          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4690       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4691                          N0.getOperand(0), DAG.getValueType(ExtVT));
4692   }
4693 
4694   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4695   if (N1C && N0.getOpcode() == ISD::SRA) {
4696     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4697       SDLoc DL(N);
4698       APInt c1 = N0C1->getAPIntValue();
4699       APInt c2 = N1C->getAPIntValue();
4700       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4701 
4702       APInt Sum = c1 + c2;
4703       if (Sum.uge(OpSizeInBits))
4704         Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
4705 
4706       return DAG.getNode(
4707           ISD::SRA, DL, VT, N0.getOperand(0),
4708           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4709     }
4710   }
4711 
4712   // fold (sra (shl X, m), (sub result_size, n))
4713   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4714   // result_size - n != m.
4715   // If truncate is free for the target sext(shl) is likely to result in better
4716   // code.
4717   if (N0.getOpcode() == ISD::SHL && N1C) {
4718     // Get the two constanst of the shifts, CN0 = m, CN = n.
4719     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4720     if (N01C) {
4721       LLVMContext &Ctx = *DAG.getContext();
4722       // Determine what the truncate's result bitsize and type would be.
4723       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4724 
4725       if (VT.isVector())
4726         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4727 
4728       // Determine the residual right-shift amount.
4729       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4730 
4731       // If the shift is not a no-op (in which case this should be just a sign
4732       // extend already), the truncated to type is legal, sign_extend is legal
4733       // on that type, and the truncate to that type is both legal and free,
4734       // perform the transform.
4735       if ((ShiftAmt > 0) &&
4736           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4737           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4738           TLI.isTruncateFree(VT, TruncVT)) {
4739 
4740         SDLoc DL(N);
4741         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4742             getShiftAmountTy(N0.getOperand(0).getValueType()));
4743         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4744                                     N0.getOperand(0), Amt);
4745         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4746                                     Shift);
4747         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4748                            N->getValueType(0), Trunc);
4749       }
4750     }
4751   }
4752 
4753   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4754   if (N1.getOpcode() == ISD::TRUNCATE &&
4755       N1.getOperand(0).getOpcode() == ISD::AND) {
4756     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4757       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4758   }
4759 
4760   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4761   //      if c1 is equal to the number of bits the trunc removes
4762   if (N0.getOpcode() == ISD::TRUNCATE &&
4763       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4764        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4765       N0.getOperand(0).hasOneUse() &&
4766       N0.getOperand(0).getOperand(1).hasOneUse() &&
4767       N1C) {
4768     SDValue N0Op0 = N0.getOperand(0);
4769     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4770       unsigned LargeShiftVal = LargeShift->getZExtValue();
4771       EVT LargeVT = N0Op0.getValueType();
4772 
4773       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4774         SDLoc DL(N);
4775         SDValue Amt =
4776           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4777                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4778         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4779                                   N0Op0.getOperand(0), Amt);
4780         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4781       }
4782     }
4783   }
4784 
4785   // Simplify, based on bits shifted out of the LHS.
4786   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4787     return SDValue(N, 0);
4788 
4789 
4790   // If the sign bit is known to be zero, switch this to a SRL.
4791   if (DAG.SignBitIsZero(N0))
4792     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4793 
4794   if (N1C && !N1C->isOpaque())
4795     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4796       return NewSRA;
4797 
4798   return SDValue();
4799 }
4800 
4801 SDValue DAGCombiner::visitSRL(SDNode *N) {
4802   SDValue N0 = N->getOperand(0);
4803   SDValue N1 = N->getOperand(1);
4804   EVT VT = N0.getValueType();
4805   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4806 
4807   // fold vector ops
4808   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4809   if (VT.isVector()) {
4810     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4811       return FoldedVOp;
4812 
4813     N1C = isConstOrConstSplat(N1);
4814   }
4815 
4816   // fold (srl c1, c2) -> c1 >>u c2
4817   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4818   if (N0C && N1C && !N1C->isOpaque())
4819     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4820   // fold (srl 0, x) -> 0
4821   if (isNullConstant(N0))
4822     return N0;
4823   // fold (srl x, c >= size(x)) -> undef
4824   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4825     return DAG.getUNDEF(VT);
4826   // fold (srl x, 0) -> x
4827   if (N1C && N1C->isNullValue())
4828     return N0;
4829   // if (srl x, c) is known to be zero, return 0
4830   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4831                                    APInt::getAllOnesValue(OpSizeInBits)))
4832     return DAG.getConstant(0, SDLoc(N), VT);
4833 
4834   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4835   if (N1C && N0.getOpcode() == ISD::SRL) {
4836     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4837       SDLoc DL(N);
4838       APInt c1 = N0C1->getAPIntValue();
4839       APInt c2 = N1C->getAPIntValue();
4840       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
4841 
4842       APInt Sum = c1 + c2;
4843       if (Sum.uge(OpSizeInBits))
4844         return DAG.getConstant(0, DL, VT);
4845 
4846       return DAG.getNode(
4847           ISD::SRL, DL, VT, N0.getOperand(0),
4848           DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
4849     }
4850   }
4851 
4852   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4853   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4854       N0.getOperand(0).getOpcode() == ISD::SRL &&
4855       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4856     uint64_t c1 =
4857       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4858     uint64_t c2 = N1C->getZExtValue();
4859     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4860     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4861     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4862     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4863     if (c1 + OpSizeInBits == InnerShiftSize) {
4864       SDLoc DL(N0);
4865       if (c1 + c2 >= InnerShiftSize)
4866         return DAG.getConstant(0, DL, VT);
4867       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4868                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4869                                      N0.getOperand(0)->getOperand(0),
4870                                      DAG.getConstant(c1 + c2, DL,
4871                                                      ShiftCountVT)));
4872     }
4873   }
4874 
4875   // fold (srl (shl x, c), c) -> (and x, cst2)
4876   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4877     unsigned BitSize = N0.getScalarValueSizeInBits();
4878     if (BitSize <= 64) {
4879       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4880       SDLoc DL(N);
4881       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4882                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4883     }
4884   }
4885 
4886   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4887   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4888     // Shifting in all undef bits?
4889     EVT SmallVT = N0.getOperand(0).getValueType();
4890     unsigned BitSize = SmallVT.getScalarSizeInBits();
4891     if (N1C->getZExtValue() >= BitSize)
4892       return DAG.getUNDEF(VT);
4893 
4894     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4895       uint64_t ShiftAmt = N1C->getZExtValue();
4896       SDLoc DL0(N0);
4897       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4898                                        N0.getOperand(0),
4899                           DAG.getConstant(ShiftAmt, DL0,
4900                                           getShiftAmountTy(SmallVT)));
4901       AddToWorklist(SmallShift.getNode());
4902       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4903       SDLoc DL(N);
4904       return DAG.getNode(ISD::AND, DL, VT,
4905                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4906                          DAG.getConstant(Mask, DL, VT));
4907     }
4908   }
4909 
4910   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4911   // bit, which is unmodified by sra.
4912   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4913     if (N0.getOpcode() == ISD::SRA)
4914       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4915   }
4916 
4917   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4918   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4919       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4920     APInt KnownZero, KnownOne;
4921     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4922 
4923     // If any of the input bits are KnownOne, then the input couldn't be all
4924     // zeros, thus the result of the srl will always be zero.
4925     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4926 
4927     // If all of the bits input the to ctlz node are known to be zero, then
4928     // the result of the ctlz is "32" and the result of the shift is one.
4929     APInt UnknownBits = ~KnownZero;
4930     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4931 
4932     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4933     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4934       // Okay, we know that only that the single bit specified by UnknownBits
4935       // could be set on input to the CTLZ node. If this bit is set, the SRL
4936       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4937       // to an SRL/XOR pair, which is likely to simplify more.
4938       unsigned ShAmt = UnknownBits.countTrailingZeros();
4939       SDValue Op = N0.getOperand(0);
4940 
4941       if (ShAmt) {
4942         SDLoc DL(N0);
4943         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4944                   DAG.getConstant(ShAmt, DL,
4945                                   getShiftAmountTy(Op.getValueType())));
4946         AddToWorklist(Op.getNode());
4947       }
4948 
4949       SDLoc DL(N);
4950       return DAG.getNode(ISD::XOR, DL, VT,
4951                          Op, DAG.getConstant(1, DL, VT));
4952     }
4953   }
4954 
4955   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4956   if (N1.getOpcode() == ISD::TRUNCATE &&
4957       N1.getOperand(0).getOpcode() == ISD::AND) {
4958     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4959       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4960   }
4961 
4962   // fold operands of srl based on knowledge that the low bits are not
4963   // demanded.
4964   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4965     return SDValue(N, 0);
4966 
4967   if (N1C && !N1C->isOpaque())
4968     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4969       return NewSRL;
4970 
4971   // Attempt to convert a srl of a load into a narrower zero-extending load.
4972   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4973     return NarrowLoad;
4974 
4975   // Here is a common situation. We want to optimize:
4976   //
4977   //   %a = ...
4978   //   %b = and i32 %a, 2
4979   //   %c = srl i32 %b, 1
4980   //   brcond i32 %c ...
4981   //
4982   // into
4983   //
4984   //   %a = ...
4985   //   %b = and %a, 2
4986   //   %c = setcc eq %b, 0
4987   //   brcond %c ...
4988   //
4989   // However when after the source operand of SRL is optimized into AND, the SRL
4990   // itself may not be optimized further. Look for it and add the BRCOND into
4991   // the worklist.
4992   if (N->hasOneUse()) {
4993     SDNode *Use = *N->use_begin();
4994     if (Use->getOpcode() == ISD::BRCOND)
4995       AddToWorklist(Use);
4996     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4997       // Also look pass the truncate.
4998       Use = *Use->use_begin();
4999       if (Use->getOpcode() == ISD::BRCOND)
5000         AddToWorklist(Use);
5001     }
5002   }
5003 
5004   return SDValue();
5005 }
5006 
5007 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5008   SDValue N0 = N->getOperand(0);
5009   EVT VT = N->getValueType(0);
5010 
5011   // fold (bswap c1) -> c2
5012   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5013     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5014   // fold (bswap (bswap x)) -> x
5015   if (N0.getOpcode() == ISD::BSWAP)
5016     return N0->getOperand(0);
5017   return SDValue();
5018 }
5019 
5020 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5021   SDValue N0 = N->getOperand(0);
5022 
5023   // fold (bitreverse (bitreverse x)) -> x
5024   if (N0.getOpcode() == ISD::BITREVERSE)
5025     return N0.getOperand(0);
5026   return SDValue();
5027 }
5028 
5029 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5030   SDValue N0 = N->getOperand(0);
5031   EVT VT = N->getValueType(0);
5032 
5033   // fold (ctlz c1) -> c2
5034   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5035     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5036   return SDValue();
5037 }
5038 
5039 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5040   SDValue N0 = N->getOperand(0);
5041   EVT VT = N->getValueType(0);
5042 
5043   // fold (ctlz_zero_undef c1) -> c2
5044   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5045     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5046   return SDValue();
5047 }
5048 
5049 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5050   SDValue N0 = N->getOperand(0);
5051   EVT VT = N->getValueType(0);
5052 
5053   // fold (cttz c1) -> c2
5054   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5055     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5056   return SDValue();
5057 }
5058 
5059 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5060   SDValue N0 = N->getOperand(0);
5061   EVT VT = N->getValueType(0);
5062 
5063   // fold (cttz_zero_undef c1) -> c2
5064   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5065     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5066   return SDValue();
5067 }
5068 
5069 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5070   SDValue N0 = N->getOperand(0);
5071   EVT VT = N->getValueType(0);
5072 
5073   // fold (ctpop c1) -> c2
5074   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5075     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5076   return SDValue();
5077 }
5078 
5079 
5080 /// \brief Generate Min/Max node
5081 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5082                                    SDValue RHS, SDValue True, SDValue False,
5083                                    ISD::CondCode CC, const TargetLowering &TLI,
5084                                    SelectionDAG &DAG) {
5085   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5086     return SDValue();
5087 
5088   switch (CC) {
5089   case ISD::SETOLT:
5090   case ISD::SETOLE:
5091   case ISD::SETLT:
5092   case ISD::SETLE:
5093   case ISD::SETULT:
5094   case ISD::SETULE: {
5095     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5096     if (TLI.isOperationLegal(Opcode, VT))
5097       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5098     return SDValue();
5099   }
5100   case ISD::SETOGT:
5101   case ISD::SETOGE:
5102   case ISD::SETGT:
5103   case ISD::SETGE:
5104   case ISD::SETUGT:
5105   case ISD::SETUGE: {
5106     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5107     if (TLI.isOperationLegal(Opcode, VT))
5108       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5109     return SDValue();
5110   }
5111   default:
5112     return SDValue();
5113   }
5114 }
5115 
5116 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5117   SDValue N0 = N->getOperand(0);
5118   SDValue N1 = N->getOperand(1);
5119   SDValue N2 = N->getOperand(2);
5120   EVT VT = N->getValueType(0);
5121   EVT VT0 = N0.getValueType();
5122 
5123   // fold (select C, X, X) -> X
5124   if (N1 == N2)
5125     return N1;
5126   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5127     // fold (select true, X, Y) -> X
5128     // fold (select false, X, Y) -> Y
5129     return !N0C->isNullValue() ? N1 : N2;
5130   }
5131   // fold (select C, 1, X) -> (or C, X)
5132   if (VT == MVT::i1 && isOneConstant(N1))
5133     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5134   // fold (select C, 0, 1) -> (xor C, 1)
5135   // We can't do this reliably if integer based booleans have different contents
5136   // to floating point based booleans. This is because we can't tell whether we
5137   // have an integer-based boolean or a floating-point-based boolean unless we
5138   // can find the SETCC that produced it and inspect its operands. This is
5139   // fairly easy if C is the SETCC node, but it can potentially be
5140   // undiscoverable (or not reasonably discoverable). For example, it could be
5141   // in another basic block or it could require searching a complicated
5142   // expression.
5143   if (VT.isInteger() &&
5144       (VT0 == MVT::i1 || (VT0.isInteger() &&
5145                           TLI.getBooleanContents(false, false) ==
5146                               TLI.getBooleanContents(false, true) &&
5147                           TLI.getBooleanContents(false, false) ==
5148                               TargetLowering::ZeroOrOneBooleanContent)) &&
5149       isNullConstant(N1) && isOneConstant(N2)) {
5150     SDValue XORNode;
5151     if (VT == VT0) {
5152       SDLoc DL(N);
5153       return DAG.getNode(ISD::XOR, DL, VT0,
5154                          N0, DAG.getConstant(1, DL, VT0));
5155     }
5156     SDLoc DL0(N0);
5157     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5158                           N0, DAG.getConstant(1, DL0, VT0));
5159     AddToWorklist(XORNode.getNode());
5160     if (VT.bitsGT(VT0))
5161       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5162     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5163   }
5164   // fold (select C, 0, X) -> (and (not C), X)
5165   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5166     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5167     AddToWorklist(NOTNode.getNode());
5168     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5169   }
5170   // fold (select C, X, 1) -> (or (not C), X)
5171   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5172     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5173     AddToWorklist(NOTNode.getNode());
5174     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5175   }
5176   // fold (select C, X, 0) -> (and C, X)
5177   if (VT == MVT::i1 && isNullConstant(N2))
5178     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5179   // fold (select X, X, Y) -> (or X, Y)
5180   // fold (select X, 1, Y) -> (or X, Y)
5181   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5182     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5183   // fold (select X, Y, X) -> (and X, Y)
5184   // fold (select X, Y, 0) -> (and X, Y)
5185   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5186     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5187 
5188   // If we can fold this based on the true/false value, do so.
5189   if (SimplifySelectOps(N, N1, N2))
5190     return SDValue(N, 0);  // Don't revisit N.
5191 
5192   if (VT0 == MVT::i1) {
5193     // The code in this block deals with the following 2 equivalences:
5194     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5195     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5196     // The target can specify its prefered form with the
5197     // shouldNormalizeToSelectSequence() callback. However we always transform
5198     // to the right anyway if we find the inner select exists in the DAG anyway
5199     // and we always transform to the left side if we know that we can further
5200     // optimize the combination of the conditions.
5201     bool normalizeToSequence
5202       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5203     // select (and Cond0, Cond1), X, Y
5204     //   -> select Cond0, (select Cond1, X, Y), Y
5205     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5206       SDValue Cond0 = N0->getOperand(0);
5207       SDValue Cond1 = N0->getOperand(1);
5208       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5209                                         N1.getValueType(), Cond1, N1, N2);
5210       if (normalizeToSequence || !InnerSelect.use_empty())
5211         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5212                            InnerSelect, N2);
5213     }
5214     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5215     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5216       SDValue Cond0 = N0->getOperand(0);
5217       SDValue Cond1 = N0->getOperand(1);
5218       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5219                                         N1.getValueType(), Cond1, N1, N2);
5220       if (normalizeToSequence || !InnerSelect.use_empty())
5221         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5222                            InnerSelect);
5223     }
5224 
5225     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5226     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5227       SDValue N1_0 = N1->getOperand(0);
5228       SDValue N1_1 = N1->getOperand(1);
5229       SDValue N1_2 = N1->getOperand(2);
5230       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5231         // Create the actual and node if we can generate good code for it.
5232         if (!normalizeToSequence) {
5233           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5234                                     N0, N1_0);
5235           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5236                              N1_1, N2);
5237         }
5238         // Otherwise see if we can optimize the "and" to a better pattern.
5239         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5240           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5241                              N1_1, N2);
5242       }
5243     }
5244     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5245     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5246       SDValue N2_0 = N2->getOperand(0);
5247       SDValue N2_1 = N2->getOperand(1);
5248       SDValue N2_2 = N2->getOperand(2);
5249       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5250         // Create the actual or node if we can generate good code for it.
5251         if (!normalizeToSequence) {
5252           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5253                                    N0, N2_0);
5254           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5255                              N1, N2_2);
5256         }
5257         // Otherwise see if we can optimize to a better pattern.
5258         if (SDValue Combined = visitORLike(N0, N2_0, N))
5259           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5260                              N1, N2_2);
5261       }
5262     }
5263   }
5264 
5265   // select (xor Cond, 1), X, Y -> select Cond, Y, X
5266   // select (xor Cond, 0), X, Y -> selext Cond, X, Y
5267   if (VT0 == MVT::i1) {
5268     if (N0->getOpcode() == ISD::XOR) {
5269       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
5270         SDValue Cond0 = N0->getOperand(0);
5271         if (C->isOne())
5272           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5273                              Cond0, N2, N1);
5274         else
5275           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
5276                              Cond0, N1, N2);
5277       }
5278     }
5279   }
5280 
5281   // fold selects based on a setcc into other things, such as min/max/abs
5282   if (N0.getOpcode() == ISD::SETCC) {
5283     // select x, y (fcmp lt x, y) -> fminnum x, y
5284     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5285     //
5286     // This is OK if we don't care about what happens if either operand is a
5287     // NaN.
5288     //
5289 
5290     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5291     // no signed zeros as well as no nans.
5292     const TargetOptions &Options = DAG.getTarget().Options;
5293     if (Options.UnsafeFPMath &&
5294         VT.isFloatingPoint() && N0.hasOneUse() &&
5295         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5296       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5297 
5298       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5299                                                 N0.getOperand(1), N1, N2, CC,
5300                                                 TLI, DAG))
5301         return FMinMax;
5302     }
5303 
5304     if ((!LegalOperations &&
5305          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5306         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5307       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5308                          N0.getOperand(0), N0.getOperand(1),
5309                          N1, N2, N0.getOperand(2));
5310     return SimplifySelect(SDLoc(N), N0, N1, N2);
5311   }
5312 
5313   return SDValue();
5314 }
5315 
5316 static
5317 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5318   SDLoc DL(N);
5319   EVT LoVT, HiVT;
5320   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5321 
5322   // Split the inputs.
5323   SDValue Lo, Hi, LL, LH, RL, RH;
5324   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5325   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5326 
5327   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5328   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5329 
5330   return std::make_pair(Lo, Hi);
5331 }
5332 
5333 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5334 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5335 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5336   SDLoc dl(N);
5337   SDValue Cond = N->getOperand(0);
5338   SDValue LHS = N->getOperand(1);
5339   SDValue RHS = N->getOperand(2);
5340   EVT VT = N->getValueType(0);
5341   int NumElems = VT.getVectorNumElements();
5342   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5343          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5344          Cond.getOpcode() == ISD::BUILD_VECTOR);
5345 
5346   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5347   // binary ones here.
5348   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5349     return SDValue();
5350 
5351   // We're sure we have an even number of elements due to the
5352   // concat_vectors we have as arguments to vselect.
5353   // Skip BV elements until we find one that's not an UNDEF
5354   // After we find an UNDEF element, keep looping until we get to half the
5355   // length of the BV and see if all the non-undef nodes are the same.
5356   ConstantSDNode *BottomHalf = nullptr;
5357   for (int i = 0; i < NumElems / 2; ++i) {
5358     if (Cond->getOperand(i)->isUndef())
5359       continue;
5360 
5361     if (BottomHalf == nullptr)
5362       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5363     else if (Cond->getOperand(i).getNode() != BottomHalf)
5364       return SDValue();
5365   }
5366 
5367   // Do the same for the second half of the BuildVector
5368   ConstantSDNode *TopHalf = nullptr;
5369   for (int i = NumElems / 2; i < NumElems; ++i) {
5370     if (Cond->getOperand(i)->isUndef())
5371       continue;
5372 
5373     if (TopHalf == nullptr)
5374       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5375     else if (Cond->getOperand(i).getNode() != TopHalf)
5376       return SDValue();
5377   }
5378 
5379   assert(TopHalf && BottomHalf &&
5380          "One half of the selector was all UNDEFs and the other was all the "
5381          "same value. This should have been addressed before this function.");
5382   return DAG.getNode(
5383       ISD::CONCAT_VECTORS, dl, VT,
5384       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5385       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5386 }
5387 
5388 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5389 
5390   if (Level >= AfterLegalizeTypes)
5391     return SDValue();
5392 
5393   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5394   SDValue Mask = MSC->getMask();
5395   SDValue Data  = MSC->getValue();
5396   SDLoc DL(N);
5397 
5398   // If the MSCATTER data type requires splitting and the mask is provided by a
5399   // SETCC, then split both nodes and its operands before legalization. This
5400   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5401   // and enables future optimizations (e.g. min/max pattern matching on X86).
5402   if (Mask.getOpcode() != ISD::SETCC)
5403     return SDValue();
5404 
5405   // Check if any splitting is required.
5406   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5407       TargetLowering::TypeSplitVector)
5408     return SDValue();
5409   SDValue MaskLo, MaskHi, Lo, Hi;
5410   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5411 
5412   EVT LoVT, HiVT;
5413   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5414 
5415   SDValue Chain = MSC->getChain();
5416 
5417   EVT MemoryVT = MSC->getMemoryVT();
5418   unsigned Alignment = MSC->getOriginalAlignment();
5419 
5420   EVT LoMemVT, HiMemVT;
5421   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5422 
5423   SDValue DataLo, DataHi;
5424   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5425 
5426   SDValue BasePtr = MSC->getBasePtr();
5427   SDValue IndexLo, IndexHi;
5428   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5429 
5430   MachineMemOperand *MMO = DAG.getMachineFunction().
5431     getMachineMemOperand(MSC->getPointerInfo(),
5432                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5433                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5434 
5435   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5436   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5437                             DL, OpsLo, MMO);
5438 
5439   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5440   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5441                             DL, OpsHi, MMO);
5442 
5443   AddToWorklist(Lo.getNode());
5444   AddToWorklist(Hi.getNode());
5445 
5446   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5447 }
5448 
5449 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5450 
5451   if (Level >= AfterLegalizeTypes)
5452     return SDValue();
5453 
5454   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5455   SDValue Mask = MST->getMask();
5456   SDValue Data  = MST->getValue();
5457   SDLoc DL(N);
5458 
5459   // If the MSTORE data type requires splitting and the mask is provided by a
5460   // SETCC, then split both nodes and its operands before legalization. This
5461   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5462   // and enables future optimizations (e.g. min/max pattern matching on X86).
5463   if (Mask.getOpcode() == ISD::SETCC) {
5464 
5465     // Check if any splitting is required.
5466     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5467         TargetLowering::TypeSplitVector)
5468       return SDValue();
5469 
5470     SDValue MaskLo, MaskHi, Lo, Hi;
5471     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5472 
5473     EVT LoVT, HiVT;
5474     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5475 
5476     SDValue Chain = MST->getChain();
5477     SDValue Ptr   = MST->getBasePtr();
5478 
5479     EVT MemoryVT = MST->getMemoryVT();
5480     unsigned Alignment = MST->getOriginalAlignment();
5481 
5482     // if Alignment is equal to the vector size,
5483     // take the half of it for the second part
5484     unsigned SecondHalfAlignment =
5485       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5486          Alignment/2 : Alignment;
5487 
5488     EVT LoMemVT, HiMemVT;
5489     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5490 
5491     SDValue DataLo, DataHi;
5492     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5493 
5494     MachineMemOperand *MMO = DAG.getMachineFunction().
5495       getMachineMemOperand(MST->getPointerInfo(),
5496                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5497                            Alignment, MST->getAAInfo(), MST->getRanges());
5498 
5499     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5500                             MST->isTruncatingStore());
5501 
5502     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5503     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5504                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5505 
5506     MMO = DAG.getMachineFunction().
5507       getMachineMemOperand(MST->getPointerInfo(),
5508                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5509                            SecondHalfAlignment, MST->getAAInfo(),
5510                            MST->getRanges());
5511 
5512     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5513                             MST->isTruncatingStore());
5514 
5515     AddToWorklist(Lo.getNode());
5516     AddToWorklist(Hi.getNode());
5517 
5518     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5519   }
5520   return SDValue();
5521 }
5522 
5523 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5524 
5525   if (Level >= AfterLegalizeTypes)
5526     return SDValue();
5527 
5528   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5529   SDValue Mask = MGT->getMask();
5530   SDLoc DL(N);
5531 
5532   // If the MGATHER result requires splitting and the mask is provided by a
5533   // SETCC, then split both nodes and its operands before legalization. This
5534   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5535   // and enables future optimizations (e.g. min/max pattern matching on X86).
5536 
5537   if (Mask.getOpcode() != ISD::SETCC)
5538     return SDValue();
5539 
5540   EVT VT = N->getValueType(0);
5541 
5542   // Check if any splitting is required.
5543   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5544       TargetLowering::TypeSplitVector)
5545     return SDValue();
5546 
5547   SDValue MaskLo, MaskHi, Lo, Hi;
5548   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5549 
5550   SDValue Src0 = MGT->getValue();
5551   SDValue Src0Lo, Src0Hi;
5552   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5553 
5554   EVT LoVT, HiVT;
5555   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5556 
5557   SDValue Chain = MGT->getChain();
5558   EVT MemoryVT = MGT->getMemoryVT();
5559   unsigned Alignment = MGT->getOriginalAlignment();
5560 
5561   EVT LoMemVT, HiMemVT;
5562   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5563 
5564   SDValue BasePtr = MGT->getBasePtr();
5565   SDValue Index = MGT->getIndex();
5566   SDValue IndexLo, IndexHi;
5567   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5568 
5569   MachineMemOperand *MMO = DAG.getMachineFunction().
5570     getMachineMemOperand(MGT->getPointerInfo(),
5571                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5572                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5573 
5574   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5575   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5576                             MMO);
5577 
5578   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5579   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5580                             MMO);
5581 
5582   AddToWorklist(Lo.getNode());
5583   AddToWorklist(Hi.getNode());
5584 
5585   // Build a factor node to remember that this load is independent of the
5586   // other one.
5587   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5588                       Hi.getValue(1));
5589 
5590   // Legalized the chain result - switch anything that used the old chain to
5591   // use the new one.
5592   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5593 
5594   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5595 
5596   SDValue RetOps[] = { GatherRes, Chain };
5597   return DAG.getMergeValues(RetOps, DL);
5598 }
5599 
5600 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5601 
5602   if (Level >= AfterLegalizeTypes)
5603     return SDValue();
5604 
5605   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5606   SDValue Mask = MLD->getMask();
5607   SDLoc DL(N);
5608 
5609   // If the MLOAD result requires splitting and the mask is provided by a
5610   // SETCC, then split both nodes and its operands before legalization. This
5611   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5612   // and enables future optimizations (e.g. min/max pattern matching on X86).
5613 
5614   if (Mask.getOpcode() == ISD::SETCC) {
5615     EVT VT = N->getValueType(0);
5616 
5617     // Check if any splitting is required.
5618     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5619         TargetLowering::TypeSplitVector)
5620       return SDValue();
5621 
5622     SDValue MaskLo, MaskHi, Lo, Hi;
5623     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5624 
5625     SDValue Src0 = MLD->getSrc0();
5626     SDValue Src0Lo, Src0Hi;
5627     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5628 
5629     EVT LoVT, HiVT;
5630     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5631 
5632     SDValue Chain = MLD->getChain();
5633     SDValue Ptr   = MLD->getBasePtr();
5634     EVT MemoryVT = MLD->getMemoryVT();
5635     unsigned Alignment = MLD->getOriginalAlignment();
5636 
5637     // if Alignment is equal to the vector size,
5638     // take the half of it for the second part
5639     unsigned SecondHalfAlignment =
5640       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5641          Alignment/2 : Alignment;
5642 
5643     EVT LoMemVT, HiMemVT;
5644     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5645 
5646     MachineMemOperand *MMO = DAG.getMachineFunction().
5647     getMachineMemOperand(MLD->getPointerInfo(),
5648                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5649                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5650 
5651     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5652                            ISD::NON_EXTLOAD);
5653 
5654     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5655     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5656                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5657 
5658     MMO = DAG.getMachineFunction().
5659     getMachineMemOperand(MLD->getPointerInfo(),
5660                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5661                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5662 
5663     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5664                            ISD::NON_EXTLOAD);
5665 
5666     AddToWorklist(Lo.getNode());
5667     AddToWorklist(Hi.getNode());
5668 
5669     // Build a factor node to remember that this load is independent of the
5670     // other one.
5671     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5672                         Hi.getValue(1));
5673 
5674     // Legalized the chain result - switch anything that used the old chain to
5675     // use the new one.
5676     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5677 
5678     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5679 
5680     SDValue RetOps[] = { LoadRes, Chain };
5681     return DAG.getMergeValues(RetOps, DL);
5682   }
5683   return SDValue();
5684 }
5685 
5686 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5687   SDValue N0 = N->getOperand(0);
5688   SDValue N1 = N->getOperand(1);
5689   SDValue N2 = N->getOperand(2);
5690   SDLoc DL(N);
5691 
5692   // Canonicalize integer abs.
5693   // vselect (setg[te] X,  0),  X, -X ->
5694   // vselect (setgt    X, -1),  X, -X ->
5695   // vselect (setl[te] X,  0), -X,  X ->
5696   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5697   if (N0.getOpcode() == ISD::SETCC) {
5698     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5699     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5700     bool isAbs = false;
5701     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5702 
5703     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5704          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5705         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5706       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5707     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5708              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5709       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5710 
5711     if (isAbs) {
5712       EVT VT = LHS.getValueType();
5713       SDValue Shift = DAG.getNode(
5714           ISD::SRA, DL, VT, LHS,
5715           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5716       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5717       AddToWorklist(Shift.getNode());
5718       AddToWorklist(Add.getNode());
5719       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5720     }
5721   }
5722 
5723   if (SimplifySelectOps(N, N1, N2))
5724     return SDValue(N, 0);  // Don't revisit N.
5725 
5726   // If the VSELECT result requires splitting and the mask is provided by a
5727   // SETCC, then split both nodes and its operands before legalization. This
5728   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5729   // and enables future optimizations (e.g. min/max pattern matching on X86).
5730   if (N0.getOpcode() == ISD::SETCC) {
5731     EVT VT = N->getValueType(0);
5732 
5733     // Check if any splitting is required.
5734     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5735         TargetLowering::TypeSplitVector)
5736       return SDValue();
5737 
5738     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5739     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5740     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5741     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5742 
5743     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5744     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5745 
5746     // Add the new VSELECT nodes to the work list in case they need to be split
5747     // again.
5748     AddToWorklist(Lo.getNode());
5749     AddToWorklist(Hi.getNode());
5750 
5751     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5752   }
5753 
5754   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5755   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5756     return N1;
5757   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5758   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5759     return N2;
5760 
5761   // The ConvertSelectToConcatVector function is assuming both the above
5762   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5763   // and addressed.
5764   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5765       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5766       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5767     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5768       return CV;
5769   }
5770 
5771   return SDValue();
5772 }
5773 
5774 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5775   SDValue N0 = N->getOperand(0);
5776   SDValue N1 = N->getOperand(1);
5777   SDValue N2 = N->getOperand(2);
5778   SDValue N3 = N->getOperand(3);
5779   SDValue N4 = N->getOperand(4);
5780   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5781 
5782   // fold select_cc lhs, rhs, x, x, cc -> x
5783   if (N2 == N3)
5784     return N2;
5785 
5786   // Determine if the condition we're dealing with is constant
5787   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5788                                   CC, SDLoc(N), false)) {
5789     AddToWorklist(SCC.getNode());
5790 
5791     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5792       if (!SCCC->isNullValue())
5793         return N2;    // cond always true -> true val
5794       else
5795         return N3;    // cond always false -> false val
5796     } else if (SCC->isUndef()) {
5797       // When the condition is UNDEF, just return the first operand. This is
5798       // coherent the DAG creation, no setcc node is created in this case
5799       return N2;
5800     } else if (SCC.getOpcode() == ISD::SETCC) {
5801       // Fold to a simpler select_cc
5802       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5803                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5804                          SCC.getOperand(2));
5805     }
5806   }
5807 
5808   // If we can fold this based on the true/false value, do so.
5809   if (SimplifySelectOps(N, N2, N3))
5810     return SDValue(N, 0);  // Don't revisit N.
5811 
5812   // fold select_cc into other things, such as min/max/abs
5813   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5814 }
5815 
5816 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5817   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5818                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5819                        SDLoc(N));
5820 }
5821 
5822 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5823   SDValue LHS = N->getOperand(0);
5824   SDValue RHS = N->getOperand(1);
5825   SDValue Carry = N->getOperand(2);
5826   SDValue Cond = N->getOperand(3);
5827 
5828   // If Carry is false, fold to a regular SETCC.
5829   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5830     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5831 
5832   return SDValue();
5833 }
5834 
5835 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5836 /// a build_vector of constants.
5837 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5838 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5839 /// Vector extends are not folded if operations are legal; this is to
5840 /// avoid introducing illegal build_vector dag nodes.
5841 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5842                                          SelectionDAG &DAG, bool LegalTypes,
5843                                          bool LegalOperations) {
5844   unsigned Opcode = N->getOpcode();
5845   SDValue N0 = N->getOperand(0);
5846   EVT VT = N->getValueType(0);
5847 
5848   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5849          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5850          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5851          && "Expected EXTEND dag node in input!");
5852 
5853   // fold (sext c1) -> c1
5854   // fold (zext c1) -> c1
5855   // fold (aext c1) -> c1
5856   if (isa<ConstantSDNode>(N0))
5857     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5858 
5859   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5860   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5861   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5862   EVT SVT = VT.getScalarType();
5863   if (!(VT.isVector() &&
5864       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5865       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5866     return nullptr;
5867 
5868   // We can fold this node into a build_vector.
5869   unsigned VTBits = SVT.getSizeInBits();
5870   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5871   SmallVector<SDValue, 8> Elts;
5872   unsigned NumElts = VT.getVectorNumElements();
5873   SDLoc DL(N);
5874 
5875   for (unsigned i=0; i != NumElts; ++i) {
5876     SDValue Op = N0->getOperand(i);
5877     if (Op->isUndef()) {
5878       Elts.push_back(DAG.getUNDEF(SVT));
5879       continue;
5880     }
5881 
5882     SDLoc DL(Op);
5883     // Get the constant value and if needed trunc it to the size of the type.
5884     // Nodes like build_vector might have constants wider than the scalar type.
5885     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5886     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5887       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5888     else
5889       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5890   }
5891 
5892   return DAG.getBuildVector(VT, DL, Elts).getNode();
5893 }
5894 
5895 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5896 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5897 // transformation. Returns true if extension are possible and the above
5898 // mentioned transformation is profitable.
5899 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5900                                     unsigned ExtOpc,
5901                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5902                                     const TargetLowering &TLI) {
5903   bool HasCopyToRegUses = false;
5904   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5905   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5906                             UE = N0.getNode()->use_end();
5907        UI != UE; ++UI) {
5908     SDNode *User = *UI;
5909     if (User == N)
5910       continue;
5911     if (UI.getUse().getResNo() != N0.getResNo())
5912       continue;
5913     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5914     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5915       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5916       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5917         // Sign bits will be lost after a zext.
5918         return false;
5919       bool Add = false;
5920       for (unsigned i = 0; i != 2; ++i) {
5921         SDValue UseOp = User->getOperand(i);
5922         if (UseOp == N0)
5923           continue;
5924         if (!isa<ConstantSDNode>(UseOp))
5925           return false;
5926         Add = true;
5927       }
5928       if (Add)
5929         ExtendNodes.push_back(User);
5930       continue;
5931     }
5932     // If truncates aren't free and there are users we can't
5933     // extend, it isn't worthwhile.
5934     if (!isTruncFree)
5935       return false;
5936     // Remember if this value is live-out.
5937     if (User->getOpcode() == ISD::CopyToReg)
5938       HasCopyToRegUses = true;
5939   }
5940 
5941   if (HasCopyToRegUses) {
5942     bool BothLiveOut = false;
5943     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5944          UI != UE; ++UI) {
5945       SDUse &Use = UI.getUse();
5946       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5947         BothLiveOut = true;
5948         break;
5949       }
5950     }
5951     if (BothLiveOut)
5952       // Both unextended and extended values are live out. There had better be
5953       // a good reason for the transformation.
5954       return ExtendNodes.size();
5955   }
5956   return true;
5957 }
5958 
5959 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5960                                   SDValue Trunc, SDValue ExtLoad,
5961                                   const SDLoc &DL, ISD::NodeType ExtType) {
5962   // Extend SetCC uses if necessary.
5963   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5964     SDNode *SetCC = SetCCs[i];
5965     SmallVector<SDValue, 4> Ops;
5966 
5967     for (unsigned j = 0; j != 2; ++j) {
5968       SDValue SOp = SetCC->getOperand(j);
5969       if (SOp == Trunc)
5970         Ops.push_back(ExtLoad);
5971       else
5972         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5973     }
5974 
5975     Ops.push_back(SetCC->getOperand(2));
5976     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5977   }
5978 }
5979 
5980 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5981 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5982   SDValue N0 = N->getOperand(0);
5983   EVT DstVT = N->getValueType(0);
5984   EVT SrcVT = N0.getValueType();
5985 
5986   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5987           N->getOpcode() == ISD::ZERO_EXTEND) &&
5988          "Unexpected node type (not an extend)!");
5989 
5990   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5991   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5992   //   (v8i32 (sext (v8i16 (load x))))
5993   // into:
5994   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5995   //                          (v4i32 (sextload (x + 16)))))
5996   // Where uses of the original load, i.e.:
5997   //   (v8i16 (load x))
5998   // are replaced with:
5999   //   (v8i16 (truncate
6000   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
6001   //                            (v4i32 (sextload (x + 16)))))))
6002   //
6003   // This combine is only applicable to illegal, but splittable, vectors.
6004   // All legal types, and illegal non-vector types, are handled elsewhere.
6005   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6006   //
6007   if (N0->getOpcode() != ISD::LOAD)
6008     return SDValue();
6009 
6010   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6011 
6012   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6013       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6014       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6015     return SDValue();
6016 
6017   SmallVector<SDNode *, 4> SetCCs;
6018   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6019     return SDValue();
6020 
6021   ISD::LoadExtType ExtType =
6022       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6023 
6024   // Try to split the vector types to get down to legal types.
6025   EVT SplitSrcVT = SrcVT;
6026   EVT SplitDstVT = DstVT;
6027   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6028          SplitSrcVT.getVectorNumElements() > 1) {
6029     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6030     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6031   }
6032 
6033   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6034     return SDValue();
6035 
6036   SDLoc DL(N);
6037   const unsigned NumSplits =
6038       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6039   const unsigned Stride = SplitSrcVT.getStoreSize();
6040   SmallVector<SDValue, 4> Loads;
6041   SmallVector<SDValue, 4> Chains;
6042 
6043   SDValue BasePtr = LN0->getBasePtr();
6044   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6045     const unsigned Offset = Idx * Stride;
6046     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6047 
6048     SDValue SplitLoad = DAG.getExtLoad(
6049         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6050         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6051         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6052 
6053     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6054                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6055 
6056     Loads.push_back(SplitLoad.getValue(0));
6057     Chains.push_back(SplitLoad.getValue(1));
6058   }
6059 
6060   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6061   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6062 
6063   CombineTo(N, NewValue);
6064 
6065   // Replace uses of the original load (before extension)
6066   // with a truncate of the concatenated sextloaded vectors.
6067   SDValue Trunc =
6068       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6069   CombineTo(N0.getNode(), Trunc, NewChain);
6070   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6071                   (ISD::NodeType)N->getOpcode());
6072   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6073 }
6074 
6075 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6076   SDValue N0 = N->getOperand(0);
6077   EVT VT = N->getValueType(0);
6078 
6079   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6080                                               LegalOperations))
6081     return SDValue(Res, 0);
6082 
6083   // fold (sext (sext x)) -> (sext x)
6084   // fold (sext (aext x)) -> (sext x)
6085   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6086     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6087                        N0.getOperand(0));
6088 
6089   if (N0.getOpcode() == ISD::TRUNCATE) {
6090     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6091     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6092     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6093       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6094       if (NarrowLoad.getNode() != N0.getNode()) {
6095         CombineTo(N0.getNode(), NarrowLoad);
6096         // CombineTo deleted the truncate, if needed, but not what's under it.
6097         AddToWorklist(oye);
6098       }
6099       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6100     }
6101 
6102     // See if the value being truncated is already sign extended.  If so, just
6103     // eliminate the trunc/sext pair.
6104     SDValue Op = N0.getOperand(0);
6105     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
6106     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
6107     unsigned DestBits = VT.getScalarType().getSizeInBits();
6108     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6109 
6110     if (OpBits == DestBits) {
6111       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6112       // bits, it is already ready.
6113       if (NumSignBits > DestBits-MidBits)
6114         return Op;
6115     } else if (OpBits < DestBits) {
6116       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6117       // bits, just sext from i32.
6118       if (NumSignBits > OpBits-MidBits)
6119         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6120     } else {
6121       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6122       // bits, just truncate to i32.
6123       if (NumSignBits > OpBits-MidBits)
6124         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6125     }
6126 
6127     // fold (sext (truncate x)) -> (sextinreg x).
6128     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6129                                                  N0.getValueType())) {
6130       if (OpBits < DestBits)
6131         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6132       else if (OpBits > DestBits)
6133         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6134       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6135                          DAG.getValueType(N0.getValueType()));
6136     }
6137   }
6138 
6139   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6140   // Only generate vector extloads when 1) they're legal, and 2) they are
6141   // deemed desirable by the target.
6142   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6143       ((!LegalOperations && !VT.isVector() &&
6144         !cast<LoadSDNode>(N0)->isVolatile()) ||
6145        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6146     bool DoXform = true;
6147     SmallVector<SDNode*, 4> SetCCs;
6148     if (!N0.hasOneUse())
6149       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6150     if (VT.isVector())
6151       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6152     if (DoXform) {
6153       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6154       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6155                                        LN0->getChain(),
6156                                        LN0->getBasePtr(), N0.getValueType(),
6157                                        LN0->getMemOperand());
6158       CombineTo(N, ExtLoad);
6159       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6160                                   N0.getValueType(), ExtLoad);
6161       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6162       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6163                       ISD::SIGN_EXTEND);
6164       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6165     }
6166   }
6167 
6168   // fold (sext (load x)) to multiple smaller sextloads.
6169   // Only on illegal but splittable vectors.
6170   if (SDValue ExtLoad = CombineExtLoad(N))
6171     return ExtLoad;
6172 
6173   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6174   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6175   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6176       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6177     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6178     EVT MemVT = LN0->getMemoryVT();
6179     if ((!LegalOperations && !LN0->isVolatile()) ||
6180         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6181       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6182                                        LN0->getChain(),
6183                                        LN0->getBasePtr(), MemVT,
6184                                        LN0->getMemOperand());
6185       CombineTo(N, ExtLoad);
6186       CombineTo(N0.getNode(),
6187                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6188                             N0.getValueType(), ExtLoad),
6189                 ExtLoad.getValue(1));
6190       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6191     }
6192   }
6193 
6194   // fold (sext (and/or/xor (load x), cst)) ->
6195   //      (and/or/xor (sextload x), (sext cst))
6196   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6197        N0.getOpcode() == ISD::XOR) &&
6198       isa<LoadSDNode>(N0.getOperand(0)) &&
6199       N0.getOperand(1).getOpcode() == ISD::Constant &&
6200       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6201       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6202     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6203     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6204       bool DoXform = true;
6205       SmallVector<SDNode*, 4> SetCCs;
6206       if (!N0.hasOneUse())
6207         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6208                                           SetCCs, TLI);
6209       if (DoXform) {
6210         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6211                                          LN0->getChain(), LN0->getBasePtr(),
6212                                          LN0->getMemoryVT(),
6213                                          LN0->getMemOperand());
6214         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6215         Mask = Mask.sext(VT.getSizeInBits());
6216         SDLoc DL(N);
6217         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6218                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6219         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6220                                     SDLoc(N0.getOperand(0)),
6221                                     N0.getOperand(0).getValueType(), ExtLoad);
6222         CombineTo(N, And);
6223         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6224         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6225                         ISD::SIGN_EXTEND);
6226         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6227       }
6228     }
6229   }
6230 
6231   if (N0.getOpcode() == ISD::SETCC) {
6232     EVT N0VT = N0.getOperand(0).getValueType();
6233     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6234     // Only do this before legalize for now.
6235     if (VT.isVector() && !LegalOperations &&
6236         TLI.getBooleanContents(N0VT) ==
6237             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6238       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6239       // of the same size as the compared operands. Only optimize sext(setcc())
6240       // if this is the case.
6241       EVT SVT = getSetCCResultType(N0VT);
6242 
6243       // We know that the # elements of the results is the same as the
6244       // # elements of the compare (and the # elements of the compare result
6245       // for that matter).  Check to see that they are the same size.  If so,
6246       // we know that the element size of the sext'd result matches the
6247       // element size of the compare operands.
6248       if (VT.getSizeInBits() == SVT.getSizeInBits())
6249         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6250                              N0.getOperand(1),
6251                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6252 
6253       // If the desired elements are smaller or larger than the source
6254       // elements we can use a matching integer vector type and then
6255       // truncate/sign extend
6256       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6257       if (SVT == MatchingVectorType) {
6258         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6259                                N0.getOperand(0), N0.getOperand(1),
6260                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6261         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6262       }
6263     }
6264 
6265     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
6266     // Here, T can be 1 or -1, depending on the type of the setcc and
6267     // getBooleanContents().
6268     unsigned SetCCWidth = N0.getValueType().getScalarSizeInBits();
6269 
6270     SDLoc DL(N);
6271     // To determine the "true" side of the select, we need to know the high bit
6272     // of the value returned by the setcc if it evaluates to true.
6273     // If the type of the setcc is i1, then the true case of the select is just
6274     // sext(i1 1), that is, -1.
6275     // If the type of the setcc is larger (say, i8) then the value of the high
6276     // bit depends on getBooleanContents(). So, ask TLI for a real "true" value
6277     // of the appropriate width.
6278     SDValue ExtTrueVal =
6279         (SetCCWidth == 1)
6280             ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()),
6281                               DL, VT)
6282             : TLI.getConstTrueVal(DAG, VT, DL);
6283 
6284     if (SDValue SCC = SimplifySelectCC(
6285             DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal,
6286             DAG.getConstant(0, DL, VT),
6287             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6288       return SCC;
6289 
6290     if (!VT.isVector()) {
6291       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6292       if (!LegalOperations ||
6293           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6294         SDLoc DL(N);
6295         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6296         SDValue SetCC =
6297             DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC);
6298         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal,
6299                              DAG.getConstant(0, DL, VT));
6300       }
6301     }
6302   }
6303 
6304   // fold (sext x) -> (zext x) if the sign bit is known zero.
6305   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6306       DAG.SignBitIsZero(N0))
6307     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6308 
6309   return SDValue();
6310 }
6311 
6312 // isTruncateOf - If N is a truncate of some other value, return true, record
6313 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6314 // This function computes KnownZero to avoid a duplicated call to
6315 // computeKnownBits in the caller.
6316 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6317                          APInt &KnownZero) {
6318   APInt KnownOne;
6319   if (N->getOpcode() == ISD::TRUNCATE) {
6320     Op = N->getOperand(0);
6321     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6322     return true;
6323   }
6324 
6325   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6326       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6327     return false;
6328 
6329   SDValue Op0 = N->getOperand(0);
6330   SDValue Op1 = N->getOperand(1);
6331   assert(Op0.getValueType() == Op1.getValueType());
6332 
6333   if (isNullConstant(Op0))
6334     Op = Op1;
6335   else if (isNullConstant(Op1))
6336     Op = Op0;
6337   else
6338     return false;
6339 
6340   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6341 
6342   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6343     return false;
6344 
6345   return true;
6346 }
6347 
6348 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6349   SDValue N0 = N->getOperand(0);
6350   EVT VT = N->getValueType(0);
6351 
6352   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6353                                               LegalOperations))
6354     return SDValue(Res, 0);
6355 
6356   // fold (zext (zext x)) -> (zext x)
6357   // fold (zext (aext x)) -> (zext x)
6358   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6359     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6360                        N0.getOperand(0));
6361 
6362   // fold (zext (truncate x)) -> (zext x) or
6363   //      (zext (truncate x)) -> (truncate x)
6364   // This is valid when the truncated bits of x are already zero.
6365   // FIXME: We should extend this to work for vectors too.
6366   SDValue Op;
6367   APInt KnownZero;
6368   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6369     APInt TruncatedBits =
6370       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6371       APInt(Op.getValueSizeInBits(), 0) :
6372       APInt::getBitsSet(Op.getValueSizeInBits(),
6373                         N0.getValueSizeInBits(),
6374                         std::min(Op.getValueSizeInBits(),
6375                                  VT.getSizeInBits()));
6376     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6377       if (VT.bitsGT(Op.getValueType()))
6378         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6379       if (VT.bitsLT(Op.getValueType()))
6380         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6381 
6382       return Op;
6383     }
6384   }
6385 
6386   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6387   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6388   if (N0.getOpcode() == ISD::TRUNCATE) {
6389     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6390       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6391       if (NarrowLoad.getNode() != N0.getNode()) {
6392         CombineTo(N0.getNode(), NarrowLoad);
6393         // CombineTo deleted the truncate, if needed, but not what's under it.
6394         AddToWorklist(oye);
6395       }
6396       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6397     }
6398   }
6399 
6400   // fold (zext (truncate x)) -> (and x, mask)
6401   if (N0.getOpcode() == ISD::TRUNCATE) {
6402     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6403     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6404     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6405       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6406       if (NarrowLoad.getNode() != N0.getNode()) {
6407         CombineTo(N0.getNode(), NarrowLoad);
6408         // CombineTo deleted the truncate, if needed, but not what's under it.
6409         AddToWorklist(oye);
6410       }
6411       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6412     }
6413 
6414     EVT SrcVT = N0.getOperand(0).getValueType();
6415     EVT MinVT = N0.getValueType();
6416 
6417     // Try to mask before the extension to avoid having to generate a larger mask,
6418     // possibly over several sub-vectors.
6419     if (SrcVT.bitsLT(VT)) {
6420       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6421                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6422         SDValue Op = N0.getOperand(0);
6423         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6424         AddToWorklist(Op.getNode());
6425         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6426       }
6427     }
6428 
6429     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6430       SDValue Op = N0.getOperand(0);
6431       if (SrcVT.bitsLT(VT)) {
6432         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6433         AddToWorklist(Op.getNode());
6434       } else if (SrcVT.bitsGT(VT)) {
6435         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6436         AddToWorklist(Op.getNode());
6437       }
6438       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6439     }
6440   }
6441 
6442   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6443   // if either of the casts is not free.
6444   if (N0.getOpcode() == ISD::AND &&
6445       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6446       N0.getOperand(1).getOpcode() == ISD::Constant &&
6447       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6448                            N0.getValueType()) ||
6449        !TLI.isZExtFree(N0.getValueType(), VT))) {
6450     SDValue X = N0.getOperand(0).getOperand(0);
6451     if (X.getValueType().bitsLT(VT)) {
6452       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6453     } else if (X.getValueType().bitsGT(VT)) {
6454       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6455     }
6456     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6457     Mask = Mask.zext(VT.getSizeInBits());
6458     SDLoc DL(N);
6459     return DAG.getNode(ISD::AND, DL, VT,
6460                        X, DAG.getConstant(Mask, DL, VT));
6461   }
6462 
6463   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6464   // Only generate vector extloads when 1) they're legal, and 2) they are
6465   // deemed desirable by the target.
6466   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6467       ((!LegalOperations && !VT.isVector() &&
6468         !cast<LoadSDNode>(N0)->isVolatile()) ||
6469        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6470     bool DoXform = true;
6471     SmallVector<SDNode*, 4> SetCCs;
6472     if (!N0.hasOneUse())
6473       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6474     if (VT.isVector())
6475       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6476     if (DoXform) {
6477       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6478       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6479                                        LN0->getChain(),
6480                                        LN0->getBasePtr(), N0.getValueType(),
6481                                        LN0->getMemOperand());
6482       CombineTo(N, ExtLoad);
6483       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6484                                   N0.getValueType(), ExtLoad);
6485       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6486 
6487       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6488                       ISD::ZERO_EXTEND);
6489       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6490     }
6491   }
6492 
6493   // fold (zext (load x)) to multiple smaller zextloads.
6494   // Only on illegal but splittable vectors.
6495   if (SDValue ExtLoad = CombineExtLoad(N))
6496     return ExtLoad;
6497 
6498   // fold (zext (and/or/xor (load x), cst)) ->
6499   //      (and/or/xor (zextload x), (zext cst))
6500   // Unless (and (load x) cst) will match as a zextload already and has
6501   // additional users.
6502   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6503        N0.getOpcode() == ISD::XOR) &&
6504       isa<LoadSDNode>(N0.getOperand(0)) &&
6505       N0.getOperand(1).getOpcode() == ISD::Constant &&
6506       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6507       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6508     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6509     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6510       bool DoXform = true;
6511       SmallVector<SDNode*, 4> SetCCs;
6512       if (!N0.hasOneUse()) {
6513         if (N0.getOpcode() == ISD::AND) {
6514           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6515           auto NarrowLoad = false;
6516           EVT LoadResultTy = AndC->getValueType(0);
6517           EVT ExtVT, LoadedVT;
6518           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6519                                NarrowLoad))
6520             DoXform = false;
6521         }
6522         if (DoXform)
6523           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6524                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6525       }
6526       if (DoXform) {
6527         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6528                                          LN0->getChain(), LN0->getBasePtr(),
6529                                          LN0->getMemoryVT(),
6530                                          LN0->getMemOperand());
6531         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6532         Mask = Mask.zext(VT.getSizeInBits());
6533         SDLoc DL(N);
6534         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6535                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6536         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6537                                     SDLoc(N0.getOperand(0)),
6538                                     N0.getOperand(0).getValueType(), ExtLoad);
6539         CombineTo(N, And);
6540         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6541         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6542                         ISD::ZERO_EXTEND);
6543         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6544       }
6545     }
6546   }
6547 
6548   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6549   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6550   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6551       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6552     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6553     EVT MemVT = LN0->getMemoryVT();
6554     if ((!LegalOperations && !LN0->isVolatile()) ||
6555         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6556       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6557                                        LN0->getChain(),
6558                                        LN0->getBasePtr(), MemVT,
6559                                        LN0->getMemOperand());
6560       CombineTo(N, ExtLoad);
6561       CombineTo(N0.getNode(),
6562                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6563                             ExtLoad),
6564                 ExtLoad.getValue(1));
6565       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6566     }
6567   }
6568 
6569   if (N0.getOpcode() == ISD::SETCC) {
6570     // Only do this before legalize for now.
6571     if (!LegalOperations && VT.isVector() &&
6572         N0.getValueType().getVectorElementType() == MVT::i1) {
6573       EVT N00VT = N0.getOperand(0).getValueType();
6574       if (getSetCCResultType(N00VT) == N0.getValueType())
6575         return SDValue();
6576 
6577       // We know that the # elements of the results is the same as the #
6578       // elements of the compare (and the # elements of the compare result for
6579       // that matter). Check to see that they are the same size. If so, we know
6580       // that the element size of the sext'd result matches the element size of
6581       // the compare operands.
6582       SDLoc DL(N);
6583       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6584       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
6585         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6586         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
6587                                      N0.getOperand(1), N0.getOperand(2));
6588         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
6589       }
6590 
6591       // If the desired elements are smaller or larger than the source
6592       // elements we can use a matching integer vector type and then
6593       // truncate/sign extend.
6594       EVT MatchingElementType = EVT::getIntegerVT(
6595           *DAG.getContext(), N00VT.getScalarType().getSizeInBits());
6596       EVT MatchingVectorType = EVT::getVectorVT(
6597           *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
6598       SDValue VsetCC =
6599           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
6600                       N0.getOperand(1), N0.getOperand(2));
6601       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
6602                          VecOnes);
6603     }
6604 
6605     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6606     SDLoc DL(N);
6607     if (SDValue SCC = SimplifySelectCC(
6608             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6609             DAG.getConstant(0, DL, VT),
6610             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6611       return SCC;
6612   }
6613 
6614   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6615   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6616       isa<ConstantSDNode>(N0.getOperand(1)) &&
6617       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6618       N0.hasOneUse()) {
6619     SDValue ShAmt = N0.getOperand(1);
6620     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6621     if (N0.getOpcode() == ISD::SHL) {
6622       SDValue InnerZExt = N0.getOperand(0);
6623       // If the original shl may be shifting out bits, do not perform this
6624       // transformation.
6625       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6626         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6627       if (ShAmtVal > KnownZeroBits)
6628         return SDValue();
6629     }
6630 
6631     SDLoc DL(N);
6632 
6633     // Ensure that the shift amount is wide enough for the shifted value.
6634     if (VT.getSizeInBits() >= 256)
6635       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6636 
6637     return DAG.getNode(N0.getOpcode(), DL, VT,
6638                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6639                        ShAmt);
6640   }
6641 
6642   return SDValue();
6643 }
6644 
6645 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6646   SDValue N0 = N->getOperand(0);
6647   EVT VT = N->getValueType(0);
6648 
6649   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6650                                               LegalOperations))
6651     return SDValue(Res, 0);
6652 
6653   // fold (aext (aext x)) -> (aext x)
6654   // fold (aext (zext x)) -> (zext x)
6655   // fold (aext (sext x)) -> (sext x)
6656   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6657       N0.getOpcode() == ISD::ZERO_EXTEND ||
6658       N0.getOpcode() == ISD::SIGN_EXTEND)
6659     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6660 
6661   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6662   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6663   if (N0.getOpcode() == ISD::TRUNCATE) {
6664     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6665       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6666       if (NarrowLoad.getNode() != N0.getNode()) {
6667         CombineTo(N0.getNode(), NarrowLoad);
6668         // CombineTo deleted the truncate, if needed, but not what's under it.
6669         AddToWorklist(oye);
6670       }
6671       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6672     }
6673   }
6674 
6675   // fold (aext (truncate x))
6676   if (N0.getOpcode() == ISD::TRUNCATE) {
6677     SDValue TruncOp = N0.getOperand(0);
6678     if (TruncOp.getValueType() == VT)
6679       return TruncOp; // x iff x size == zext size.
6680     if (TruncOp.getValueType().bitsGT(VT))
6681       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6682     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6683   }
6684 
6685   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6686   // if the trunc is not free.
6687   if (N0.getOpcode() == ISD::AND &&
6688       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6689       N0.getOperand(1).getOpcode() == ISD::Constant &&
6690       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6691                           N0.getValueType())) {
6692     SDValue X = N0.getOperand(0).getOperand(0);
6693     if (X.getValueType().bitsLT(VT)) {
6694       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6695     } else if (X.getValueType().bitsGT(VT)) {
6696       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6697     }
6698     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6699     Mask = Mask.zext(VT.getSizeInBits());
6700     SDLoc DL(N);
6701     return DAG.getNode(ISD::AND, DL, VT,
6702                        X, DAG.getConstant(Mask, DL, VT));
6703   }
6704 
6705   // fold (aext (load x)) -> (aext (truncate (extload x)))
6706   // None of the supported targets knows how to perform load and any_ext
6707   // on vectors in one instruction.  We only perform this transformation on
6708   // scalars.
6709   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6710       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6711       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6712     bool DoXform = true;
6713     SmallVector<SDNode*, 4> SetCCs;
6714     if (!N0.hasOneUse())
6715       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6716     if (DoXform) {
6717       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6718       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6719                                        LN0->getChain(),
6720                                        LN0->getBasePtr(), N0.getValueType(),
6721                                        LN0->getMemOperand());
6722       CombineTo(N, ExtLoad);
6723       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6724                                   N0.getValueType(), ExtLoad);
6725       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6726       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6727                       ISD::ANY_EXTEND);
6728       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6729     }
6730   }
6731 
6732   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6733   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6734   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6735   if (N0.getOpcode() == ISD::LOAD &&
6736       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6737       N0.hasOneUse()) {
6738     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6739     ISD::LoadExtType ExtType = LN0->getExtensionType();
6740     EVT MemVT = LN0->getMemoryVT();
6741     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6742       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6743                                        VT, LN0->getChain(), LN0->getBasePtr(),
6744                                        MemVT, LN0->getMemOperand());
6745       CombineTo(N, ExtLoad);
6746       CombineTo(N0.getNode(),
6747                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6748                             N0.getValueType(), ExtLoad),
6749                 ExtLoad.getValue(1));
6750       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6751     }
6752   }
6753 
6754   if (N0.getOpcode() == ISD::SETCC) {
6755     // For vectors:
6756     // aext(setcc) -> vsetcc
6757     // aext(setcc) -> truncate(vsetcc)
6758     // aext(setcc) -> aext(vsetcc)
6759     // Only do this before legalize for now.
6760     if (VT.isVector() && !LegalOperations) {
6761       EVT N0VT = N0.getOperand(0).getValueType();
6762         // We know that the # elements of the results is the same as the
6763         // # elements of the compare (and the # elements of the compare result
6764         // for that matter).  Check to see that they are the same size.  If so,
6765         // we know that the element size of the sext'd result matches the
6766         // element size of the compare operands.
6767       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6768         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6769                              N0.getOperand(1),
6770                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6771       // If the desired elements are smaller or larger than the source
6772       // elements we can use a matching integer vector type and then
6773       // truncate/any extend
6774       else {
6775         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6776         SDValue VsetCC =
6777           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6778                         N0.getOperand(1),
6779                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6780         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6781       }
6782     }
6783 
6784     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6785     SDLoc DL(N);
6786     if (SDValue SCC = SimplifySelectCC(
6787             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6788             DAG.getConstant(0, DL, VT),
6789             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6790       return SCC;
6791   }
6792 
6793   return SDValue();
6794 }
6795 
6796 /// See if the specified operand can be simplified with the knowledge that only
6797 /// the bits specified by Mask are used.  If so, return the simpler operand,
6798 /// otherwise return a null SDValue.
6799 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6800   switch (V.getOpcode()) {
6801   default: break;
6802   case ISD::Constant: {
6803     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6804     assert(CV && "Const value should be ConstSDNode.");
6805     const APInt &CVal = CV->getAPIntValue();
6806     APInt NewVal = CVal & Mask;
6807     if (NewVal != CVal)
6808       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6809     break;
6810   }
6811   case ISD::OR:
6812   case ISD::XOR:
6813     // If the LHS or RHS don't contribute bits to the or, drop them.
6814     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6815       return V.getOperand(1);
6816     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6817       return V.getOperand(0);
6818     break;
6819   case ISD::SRL:
6820     // Only look at single-use SRLs.
6821     if (!V.getNode()->hasOneUse())
6822       break;
6823     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6824       // See if we can recursively simplify the LHS.
6825       unsigned Amt = RHSC->getZExtValue();
6826 
6827       // Watch out for shift count overflow though.
6828       if (Amt >= Mask.getBitWidth()) break;
6829       APInt NewMask = Mask << Amt;
6830       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6831         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6832                            SimplifyLHS, V.getOperand(1));
6833     }
6834   }
6835   return SDValue();
6836 }
6837 
6838 /// If the result of a wider load is shifted to right of N  bits and then
6839 /// truncated to a narrower type and where N is a multiple of number of bits of
6840 /// the narrower type, transform it to a narrower load from address + N / num of
6841 /// bits of new type. If the result is to be extended, also fold the extension
6842 /// to form a extending load.
6843 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6844   unsigned Opc = N->getOpcode();
6845 
6846   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6847   SDValue N0 = N->getOperand(0);
6848   EVT VT = N->getValueType(0);
6849   EVT ExtVT = VT;
6850 
6851   // This transformation isn't valid for vector loads.
6852   if (VT.isVector())
6853     return SDValue();
6854 
6855   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6856   // extended to VT.
6857   if (Opc == ISD::SIGN_EXTEND_INREG) {
6858     ExtType = ISD::SEXTLOAD;
6859     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6860   } else if (Opc == ISD::SRL) {
6861     // Another special-case: SRL is basically zero-extending a narrower value.
6862     ExtType = ISD::ZEXTLOAD;
6863     N0 = SDValue(N, 0);
6864     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6865     if (!N01) return SDValue();
6866     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6867                               VT.getSizeInBits() - N01->getZExtValue());
6868   }
6869   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6870     return SDValue();
6871 
6872   unsigned EVTBits = ExtVT.getSizeInBits();
6873 
6874   // Do not generate loads of non-round integer types since these can
6875   // be expensive (and would be wrong if the type is not byte sized).
6876   if (!ExtVT.isRound())
6877     return SDValue();
6878 
6879   unsigned ShAmt = 0;
6880   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6881     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6882       ShAmt = N01->getZExtValue();
6883       // Is the shift amount a multiple of size of VT?
6884       if ((ShAmt & (EVTBits-1)) == 0) {
6885         N0 = N0.getOperand(0);
6886         // Is the load width a multiple of size of VT?
6887         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6888           return SDValue();
6889       }
6890 
6891       // At this point, we must have a load or else we can't do the transform.
6892       if (!isa<LoadSDNode>(N0)) return SDValue();
6893 
6894       // Because a SRL must be assumed to *need* to zero-extend the high bits
6895       // (as opposed to anyext the high bits), we can't combine the zextload
6896       // lowering of SRL and an sextload.
6897       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6898         return SDValue();
6899 
6900       // If the shift amount is larger than the input type then we're not
6901       // accessing any of the loaded bytes.  If the load was a zextload/extload
6902       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6903       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6904         return SDValue();
6905     }
6906   }
6907 
6908   // If the load is shifted left (and the result isn't shifted back right),
6909   // we can fold the truncate through the shift.
6910   unsigned ShLeftAmt = 0;
6911   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6912       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6913     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6914       ShLeftAmt = N01->getZExtValue();
6915       N0 = N0.getOperand(0);
6916     }
6917   }
6918 
6919   // If we haven't found a load, we can't narrow it.  Don't transform one with
6920   // multiple uses, this would require adding a new load.
6921   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6922     return SDValue();
6923 
6924   // Don't change the width of a volatile load.
6925   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6926   if (LN0->isVolatile())
6927     return SDValue();
6928 
6929   // Verify that we are actually reducing a load width here.
6930   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6931     return SDValue();
6932 
6933   // For the transform to be legal, the load must produce only two values
6934   // (the value loaded and the chain).  Don't transform a pre-increment
6935   // load, for example, which produces an extra value.  Otherwise the
6936   // transformation is not equivalent, and the downstream logic to replace
6937   // uses gets things wrong.
6938   if (LN0->getNumValues() > 2)
6939     return SDValue();
6940 
6941   // If the load that we're shrinking is an extload and we're not just
6942   // discarding the extension we can't simply shrink the load. Bail.
6943   // TODO: It would be possible to merge the extensions in some cases.
6944   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6945       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6946     return SDValue();
6947 
6948   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6949     return SDValue();
6950 
6951   EVT PtrType = N0.getOperand(1).getValueType();
6952 
6953   if (PtrType == MVT::Untyped || PtrType.isExtended())
6954     // It's not possible to generate a constant of extended or untyped type.
6955     return SDValue();
6956 
6957   // For big endian targets, we need to adjust the offset to the pointer to
6958   // load the correct bytes.
6959   if (DAG.getDataLayout().isBigEndian()) {
6960     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6961     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6962     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6963   }
6964 
6965   uint64_t PtrOff = ShAmt / 8;
6966   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6967   SDLoc DL(LN0);
6968   // The original load itself didn't wrap, so an offset within it doesn't.
6969   SDNodeFlags Flags;
6970   Flags.setNoUnsignedWrap(true);
6971   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6972                                PtrType, LN0->getBasePtr(),
6973                                DAG.getConstant(PtrOff, DL, PtrType),
6974                                &Flags);
6975   AddToWorklist(NewPtr.getNode());
6976 
6977   SDValue Load;
6978   if (ExtType == ISD::NON_EXTLOAD)
6979     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6980                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
6981                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6982   else
6983     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
6984                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
6985                           NewAlign, LN0->getMemOperand()->getFlags(),
6986                           LN0->getAAInfo());
6987 
6988   // Replace the old load's chain with the new load's chain.
6989   WorklistRemover DeadNodes(*this);
6990   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6991 
6992   // Shift the result left, if we've swallowed a left shift.
6993   SDValue Result = Load;
6994   if (ShLeftAmt != 0) {
6995     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6996     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6997       ShImmTy = VT;
6998     // If the shift amount is as large as the result size (but, presumably,
6999     // no larger than the source) then the useful bits of the result are
7000     // zero; we can't simply return the shortened shift, because the result
7001     // of that operation is undefined.
7002     SDLoc DL(N0);
7003     if (ShLeftAmt >= VT.getSizeInBits())
7004       Result = DAG.getConstant(0, DL, VT);
7005     else
7006       Result = DAG.getNode(ISD::SHL, DL, VT,
7007                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7008   }
7009 
7010   // Return the new loaded value.
7011   return Result;
7012 }
7013 
7014 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7015   SDValue N0 = N->getOperand(0);
7016   SDValue N1 = N->getOperand(1);
7017   EVT VT = N->getValueType(0);
7018   EVT EVT = cast<VTSDNode>(N1)->getVT();
7019   unsigned VTBits = VT.getScalarType().getSizeInBits();
7020   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
7021 
7022   if (N0.isUndef())
7023     return DAG.getUNDEF(VT);
7024 
7025   // fold (sext_in_reg c1) -> c1
7026   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7027     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7028 
7029   // If the input is already sign extended, just drop the extension.
7030   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7031     return N0;
7032 
7033   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7034   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7035       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7036     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7037                        N0.getOperand(0), N1);
7038 
7039   // fold (sext_in_reg (sext x)) -> (sext x)
7040   // fold (sext_in_reg (aext x)) -> (sext x)
7041   // if x is small enough.
7042   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7043     SDValue N00 = N0.getOperand(0);
7044     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
7045         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7046       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7047   }
7048 
7049   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7050   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
7051     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7052 
7053   // fold operands of sext_in_reg based on knowledge that the top bits are not
7054   // demanded.
7055   if (SimplifyDemandedBits(SDValue(N, 0)))
7056     return SDValue(N, 0);
7057 
7058   // fold (sext_in_reg (load x)) -> (smaller sextload x)
7059   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7060   if (SDValue NarrowLoad = ReduceLoadWidth(N))
7061     return NarrowLoad;
7062 
7063   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7064   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7065   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7066   if (N0.getOpcode() == ISD::SRL) {
7067     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7068       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7069         // We can turn this into an SRA iff the input to the SRL is already sign
7070         // extended enough.
7071         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7072         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7073           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7074                              N0.getOperand(0), N0.getOperand(1));
7075       }
7076   }
7077 
7078   // fold (sext_inreg (extload x)) -> (sextload x)
7079   if (ISD::isEXTLoad(N0.getNode()) &&
7080       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7081       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7082       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7083        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7084     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7085     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7086                                      LN0->getChain(),
7087                                      LN0->getBasePtr(), EVT,
7088                                      LN0->getMemOperand());
7089     CombineTo(N, ExtLoad);
7090     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7091     AddToWorklist(ExtLoad.getNode());
7092     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7093   }
7094   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7095   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7096       N0.hasOneUse() &&
7097       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7098       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7099        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7100     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7101     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7102                                      LN0->getChain(),
7103                                      LN0->getBasePtr(), EVT,
7104                                      LN0->getMemOperand());
7105     CombineTo(N, ExtLoad);
7106     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7107     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7108   }
7109 
7110   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7111   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7112     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7113                                            N0.getOperand(1), false))
7114       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7115                          BSwap, N1);
7116   }
7117 
7118   return SDValue();
7119 }
7120 
7121 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7122   SDValue N0 = N->getOperand(0);
7123   EVT VT = N->getValueType(0);
7124 
7125   if (N0.isUndef())
7126     return DAG.getUNDEF(VT);
7127 
7128   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7129                                               LegalOperations))
7130     return SDValue(Res, 0);
7131 
7132   return SDValue();
7133 }
7134 
7135 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7136   SDValue N0 = N->getOperand(0);
7137   EVT VT = N->getValueType(0);
7138 
7139   if (N0.isUndef())
7140     return DAG.getUNDEF(VT);
7141 
7142   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7143                                               LegalOperations))
7144     return SDValue(Res, 0);
7145 
7146   return SDValue();
7147 }
7148 
7149 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7150   SDValue N0 = N->getOperand(0);
7151   EVT VT = N->getValueType(0);
7152   bool isLE = DAG.getDataLayout().isLittleEndian();
7153 
7154   // noop truncate
7155   if (N0.getValueType() == N->getValueType(0))
7156     return N0;
7157   // fold (truncate c1) -> c1
7158   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7159     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7160   // fold (truncate (truncate x)) -> (truncate x)
7161   if (N0.getOpcode() == ISD::TRUNCATE)
7162     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7163   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7164   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7165       N0.getOpcode() == ISD::SIGN_EXTEND ||
7166       N0.getOpcode() == ISD::ANY_EXTEND) {
7167     // if the source is smaller than the dest, we still need an extend.
7168     if (N0.getOperand(0).getValueType().bitsLT(VT))
7169       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7170     // if the source is larger than the dest, than we just need the truncate.
7171     if (N0.getOperand(0).getValueType().bitsGT(VT))
7172       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7173     // if the source and dest are the same type, we can drop both the extend
7174     // and the truncate.
7175     return N0.getOperand(0);
7176   }
7177 
7178   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
7179   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
7180     return SDValue();
7181 
7182   // Fold extract-and-trunc into a narrow extract. For example:
7183   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7184   //   i32 y = TRUNCATE(i64 x)
7185   //        -- becomes --
7186   //   v16i8 b = BITCAST (v2i64 val)
7187   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7188   //
7189   // Note: We only run this optimization after type legalization (which often
7190   // creates this pattern) and before operation legalization after which
7191   // we need to be more careful about the vector instructions that we generate.
7192   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7193       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7194 
7195     EVT VecTy = N0.getOperand(0).getValueType();
7196     EVT ExTy = N0.getValueType();
7197     EVT TrTy = N->getValueType(0);
7198 
7199     unsigned NumElem = VecTy.getVectorNumElements();
7200     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7201 
7202     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7203     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7204 
7205     SDValue EltNo = N0->getOperand(1);
7206     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7207       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7208       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7209       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7210 
7211       SDLoc DL(N);
7212       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7213                          DAG.getBitcast(NVT, N0.getOperand(0)),
7214                          DAG.getConstant(Index, DL, IndexTy));
7215     }
7216   }
7217 
7218   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7219   if (N0.getOpcode() == ISD::SELECT) {
7220     EVT SrcVT = N0.getValueType();
7221     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7222         TLI.isTruncateFree(SrcVT, VT)) {
7223       SDLoc SL(N0);
7224       SDValue Cond = N0.getOperand(0);
7225       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7226       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7227       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7228     }
7229   }
7230 
7231   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
7232   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7233       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7234       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7235     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7236       uint64_t Amt = CAmt->getZExtValue();
7237       unsigned Size = VT.getScalarSizeInBits();
7238 
7239       if (Amt < Size) {
7240         SDLoc SL(N);
7241         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7242 
7243         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7244         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7245                            DAG.getConstant(Amt, SL, AmtVT));
7246       }
7247     }
7248   }
7249 
7250   // Fold a series of buildvector, bitcast, and truncate if possible.
7251   // For example fold
7252   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7253   //   (2xi32 (buildvector x, y)).
7254   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7255       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7256       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7257       N0.getOperand(0).hasOneUse()) {
7258 
7259     SDValue BuildVect = N0.getOperand(0);
7260     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7261     EVT TruncVecEltTy = VT.getVectorElementType();
7262 
7263     // Check that the element types match.
7264     if (BuildVectEltTy == TruncVecEltTy) {
7265       // Now we only need to compute the offset of the truncated elements.
7266       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7267       unsigned TruncVecNumElts = VT.getVectorNumElements();
7268       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7269 
7270       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7271              "Invalid number of elements");
7272 
7273       SmallVector<SDValue, 8> Opnds;
7274       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7275         Opnds.push_back(BuildVect.getOperand(i));
7276 
7277       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7278     }
7279   }
7280 
7281   // See if we can simplify the input to this truncate through knowledge that
7282   // only the low bits are being used.
7283   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7284   // Currently we only perform this optimization on scalars because vectors
7285   // may have different active low bits.
7286   if (!VT.isVector()) {
7287     if (SDValue Shorter =
7288             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7289                                                      VT.getSizeInBits())))
7290       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7291   }
7292   // fold (truncate (load x)) -> (smaller load x)
7293   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7294   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7295     if (SDValue Reduced = ReduceLoadWidth(N))
7296       return Reduced;
7297 
7298     // Handle the case where the load remains an extending load even
7299     // after truncation.
7300     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7301       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7302       if (!LN0->isVolatile() &&
7303           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7304         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7305                                          VT, LN0->getChain(), LN0->getBasePtr(),
7306                                          LN0->getMemoryVT(),
7307                                          LN0->getMemOperand());
7308         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7309         return NewLoad;
7310       }
7311     }
7312   }
7313   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7314   // where ... are all 'undef'.
7315   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7316     SmallVector<EVT, 8> VTs;
7317     SDValue V;
7318     unsigned Idx = 0;
7319     unsigned NumDefs = 0;
7320 
7321     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7322       SDValue X = N0.getOperand(i);
7323       if (!X.isUndef()) {
7324         V = X;
7325         Idx = i;
7326         NumDefs++;
7327       }
7328       // Stop if more than one members are non-undef.
7329       if (NumDefs > 1)
7330         break;
7331       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7332                                      VT.getVectorElementType(),
7333                                      X.getValueType().getVectorNumElements()));
7334     }
7335 
7336     if (NumDefs == 0)
7337       return DAG.getUNDEF(VT);
7338 
7339     if (NumDefs == 1) {
7340       assert(V.getNode() && "The single defined operand is empty!");
7341       SmallVector<SDValue, 8> Opnds;
7342       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7343         if (i != Idx) {
7344           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7345           continue;
7346         }
7347         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7348         AddToWorklist(NV.getNode());
7349         Opnds.push_back(NV);
7350       }
7351       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7352     }
7353   }
7354 
7355   // Fold truncate of a bitcast of a vector to an extract of the low vector
7356   // element.
7357   //
7358   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7359   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7360     SDValue VecSrc = N0.getOperand(0);
7361     EVT SrcVT = VecSrc.getValueType();
7362     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7363         (!LegalOperations ||
7364          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7365       SDLoc SL(N);
7366 
7367       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7368       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7369                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7370     }
7371   }
7372 
7373   // Simplify the operands using demanded-bits information.
7374   if (!VT.isVector() &&
7375       SimplifyDemandedBits(SDValue(N, 0)))
7376     return SDValue(N, 0);
7377 
7378   return SDValue();
7379 }
7380 
7381 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7382   SDValue Elt = N->getOperand(i);
7383   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7384     return Elt.getNode();
7385   return Elt.getOperand(Elt.getResNo()).getNode();
7386 }
7387 
7388 /// build_pair (load, load) -> load
7389 /// if load locations are consecutive.
7390 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7391   assert(N->getOpcode() == ISD::BUILD_PAIR);
7392 
7393   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7394   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7395   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7396       LD1->getAddressSpace() != LD2->getAddressSpace())
7397     return SDValue();
7398   EVT LD1VT = LD1->getValueType(0);
7399   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7400   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7401       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7402     unsigned Align = LD1->getAlignment();
7403     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7404         VT.getTypeForEVT(*DAG.getContext()));
7405 
7406     if (NewAlign <= Align &&
7407         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7408       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
7409                          LD1->getPointerInfo(), Align);
7410   }
7411 
7412   return SDValue();
7413 }
7414 
7415 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7416   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7417   // and Lo parts; on big-endian machines it doesn't.
7418   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7419 }
7420 
7421 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7422                                     const TargetLowering &TLI) {
7423   // If this is not a bitcast to an FP type or if the target doesn't have
7424   // IEEE754-compliant FP logic, we're done.
7425   EVT VT = N->getValueType(0);
7426   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7427     return SDValue();
7428 
7429   // TODO: Use splat values for the constant-checking below and remove this
7430   // restriction.
7431   SDValue N0 = N->getOperand(0);
7432   EVT SourceVT = N0.getValueType();
7433   if (SourceVT.isVector())
7434     return SDValue();
7435 
7436   unsigned FPOpcode;
7437   APInt SignMask;
7438   switch (N0.getOpcode()) {
7439   case ISD::AND:
7440     FPOpcode = ISD::FABS;
7441     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7442     break;
7443   case ISD::XOR:
7444     FPOpcode = ISD::FNEG;
7445     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7446     break;
7447   // TODO: ISD::OR --> ISD::FNABS?
7448   default:
7449     return SDValue();
7450   }
7451 
7452   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7453   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7454   SDValue LogicOp0 = N0.getOperand(0);
7455   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7456   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7457       LogicOp0.getOpcode() == ISD::BITCAST &&
7458       LogicOp0->getOperand(0).getValueType() == VT)
7459     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7460 
7461   return SDValue();
7462 }
7463 
7464 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7465   SDValue N0 = N->getOperand(0);
7466   EVT VT = N->getValueType(0);
7467 
7468   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7469   // Only do this before legalize, since afterward the target may be depending
7470   // on the bitconvert.
7471   // First check to see if this is all constant.
7472   if (!LegalTypes &&
7473       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7474       VT.isVector()) {
7475     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7476 
7477     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7478     assert(!DestEltVT.isVector() &&
7479            "Element type of vector ValueType must not be vector!");
7480     if (isSimple)
7481       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7482   }
7483 
7484   // If the input is a constant, let getNode fold it.
7485   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7486     // If we can't allow illegal operations, we need to check that this is just
7487     // a fp -> int or int -> conversion and that the resulting operation will
7488     // be legal.
7489     if (!LegalOperations ||
7490         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7491          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7492         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7493          TLI.isOperationLegal(ISD::Constant, VT)))
7494       return DAG.getBitcast(VT, N0);
7495   }
7496 
7497   // (conv (conv x, t1), t2) -> (conv x, t2)
7498   if (N0.getOpcode() == ISD::BITCAST)
7499     return DAG.getBitcast(VT, N0.getOperand(0));
7500 
7501   // fold (conv (load x)) -> (load (conv*)x)
7502   // If the resultant load doesn't need a higher alignment than the original!
7503   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7504       // Do not change the width of a volatile load.
7505       !cast<LoadSDNode>(N0)->isVolatile() &&
7506       // Do not remove the cast if the types differ in endian layout.
7507       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7508           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7509       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7510       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7511     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7512     unsigned OrigAlign = LN0->getAlignment();
7513 
7514     bool Fast = false;
7515     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7516                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7517         Fast) {
7518       SDValue Load =
7519           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7520                       LN0->getPointerInfo(), OrigAlign,
7521                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7522       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7523       return Load;
7524     }
7525   }
7526 
7527   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7528     return V;
7529 
7530   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7531   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7532   //
7533   // For ppc_fp128:
7534   // fold (bitcast (fneg x)) ->
7535   //     flipbit = signbit
7536   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7537   //
7538   // fold (bitcast (fabs x)) ->
7539   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7540   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7541   // This often reduces constant pool loads.
7542   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7543        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7544       N0.getNode()->hasOneUse() && VT.isInteger() &&
7545       !VT.isVector() && !N0.getValueType().isVector()) {
7546     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7547     AddToWorklist(NewConv.getNode());
7548 
7549     SDLoc DL(N);
7550     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7551       assert(VT.getSizeInBits() == 128);
7552       SDValue SignBit = DAG.getConstant(
7553           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7554       SDValue FlipBit;
7555       if (N0.getOpcode() == ISD::FNEG) {
7556         FlipBit = SignBit;
7557         AddToWorklist(FlipBit.getNode());
7558       } else {
7559         assert(N0.getOpcode() == ISD::FABS);
7560         SDValue Hi =
7561             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7562                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7563                                               SDLoc(NewConv)));
7564         AddToWorklist(Hi.getNode());
7565         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7566         AddToWorklist(FlipBit.getNode());
7567       }
7568       SDValue FlipBits =
7569           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7570       AddToWorklist(FlipBits.getNode());
7571       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7572     }
7573     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7574     if (N0.getOpcode() == ISD::FNEG)
7575       return DAG.getNode(ISD::XOR, DL, VT,
7576                          NewConv, DAG.getConstant(SignBit, DL, VT));
7577     assert(N0.getOpcode() == ISD::FABS);
7578     return DAG.getNode(ISD::AND, DL, VT,
7579                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7580   }
7581 
7582   // fold (bitconvert (fcopysign cst, x)) ->
7583   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7584   // Note that we don't handle (copysign x, cst) because this can always be
7585   // folded to an fneg or fabs.
7586   //
7587   // For ppc_fp128:
7588   // fold (bitcast (fcopysign cst, x)) ->
7589   //     flipbit = (and (extract_element
7590   //                     (xor (bitcast cst), (bitcast x)), 0),
7591   //                    signbit)
7592   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7593   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7594       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7595       VT.isInteger() && !VT.isVector()) {
7596     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7597     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7598     if (isTypeLegal(IntXVT)) {
7599       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7600       AddToWorklist(X.getNode());
7601 
7602       // If X has a different width than the result/lhs, sext it or truncate it.
7603       unsigned VTWidth = VT.getSizeInBits();
7604       if (OrigXWidth < VTWidth) {
7605         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7606         AddToWorklist(X.getNode());
7607       } else if (OrigXWidth > VTWidth) {
7608         // To get the sign bit in the right place, we have to shift it right
7609         // before truncating.
7610         SDLoc DL(X);
7611         X = DAG.getNode(ISD::SRL, DL,
7612                         X.getValueType(), X,
7613                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7614                                         X.getValueType()));
7615         AddToWorklist(X.getNode());
7616         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7617         AddToWorklist(X.getNode());
7618       }
7619 
7620       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7621         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7622         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7623         AddToWorklist(Cst.getNode());
7624         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7625         AddToWorklist(X.getNode());
7626         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7627         AddToWorklist(XorResult.getNode());
7628         SDValue XorResult64 = DAG.getNode(
7629             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7630             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7631                                   SDLoc(XorResult)));
7632         AddToWorklist(XorResult64.getNode());
7633         SDValue FlipBit =
7634             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7635                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7636         AddToWorklist(FlipBit.getNode());
7637         SDValue FlipBits =
7638             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7639         AddToWorklist(FlipBits.getNode());
7640         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7641       }
7642       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7643       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7644                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7645       AddToWorklist(X.getNode());
7646 
7647       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7648       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7649                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7650       AddToWorklist(Cst.getNode());
7651 
7652       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7653     }
7654   }
7655 
7656   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7657   if (N0.getOpcode() == ISD::BUILD_PAIR)
7658     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7659       return CombineLD;
7660 
7661   // Remove double bitcasts from shuffles - this is often a legacy of
7662   // XformToShuffleWithZero being used to combine bitmaskings (of
7663   // float vectors bitcast to integer vectors) into shuffles.
7664   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7665   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7666       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7667       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7668       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7669     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7670 
7671     // If operands are a bitcast, peek through if it casts the original VT.
7672     // If operands are a constant, just bitcast back to original VT.
7673     auto PeekThroughBitcast = [&](SDValue Op) {
7674       if (Op.getOpcode() == ISD::BITCAST &&
7675           Op.getOperand(0).getValueType() == VT)
7676         return SDValue(Op.getOperand(0));
7677       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7678           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7679         return DAG.getBitcast(VT, Op);
7680       return SDValue();
7681     };
7682 
7683     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7684     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7685     if (!(SV0 && SV1))
7686       return SDValue();
7687 
7688     int MaskScale =
7689         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7690     SmallVector<int, 8> NewMask;
7691     for (int M : SVN->getMask())
7692       for (int i = 0; i != MaskScale; ++i)
7693         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7694 
7695     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7696     if (!LegalMask) {
7697       std::swap(SV0, SV1);
7698       ShuffleVectorSDNode::commuteMask(NewMask);
7699       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7700     }
7701 
7702     if (LegalMask)
7703       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7704   }
7705 
7706   return SDValue();
7707 }
7708 
7709 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7710   EVT VT = N->getValueType(0);
7711   return CombineConsecutiveLoads(N, VT);
7712 }
7713 
7714 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7715 /// operands. DstEltVT indicates the destination element value type.
7716 SDValue DAGCombiner::
7717 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7718   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7719 
7720   // If this is already the right type, we're done.
7721   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7722 
7723   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7724   unsigned DstBitSize = DstEltVT.getSizeInBits();
7725 
7726   // If this is a conversion of N elements of one type to N elements of another
7727   // type, convert each element.  This handles FP<->INT cases.
7728   if (SrcBitSize == DstBitSize) {
7729     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7730                               BV->getValueType(0).getVectorNumElements());
7731 
7732     // Due to the FP element handling below calling this routine recursively,
7733     // we can end up with a scalar-to-vector node here.
7734     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7735       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7736                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7737 
7738     SmallVector<SDValue, 8> Ops;
7739     for (SDValue Op : BV->op_values()) {
7740       // If the vector element type is not legal, the BUILD_VECTOR operands
7741       // are promoted and implicitly truncated.  Make that explicit here.
7742       if (Op.getValueType() != SrcEltVT)
7743         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7744       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7745       AddToWorklist(Ops.back().getNode());
7746     }
7747     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7748   }
7749 
7750   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7751   // handle annoying details of growing/shrinking FP values, we convert them to
7752   // int first.
7753   if (SrcEltVT.isFloatingPoint()) {
7754     // Convert the input float vector to a int vector where the elements are the
7755     // same sizes.
7756     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7757     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7758     SrcEltVT = IntVT;
7759   }
7760 
7761   // Now we know the input is an integer vector.  If the output is a FP type,
7762   // convert to integer first, then to FP of the right size.
7763   if (DstEltVT.isFloatingPoint()) {
7764     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7765     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7766 
7767     // Next, convert to FP elements of the same size.
7768     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7769   }
7770 
7771   SDLoc DL(BV);
7772 
7773   // Okay, we know the src/dst types are both integers of differing types.
7774   // Handling growing first.
7775   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7776   if (SrcBitSize < DstBitSize) {
7777     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7778 
7779     SmallVector<SDValue, 8> Ops;
7780     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7781          i += NumInputsPerOutput) {
7782       bool isLE = DAG.getDataLayout().isLittleEndian();
7783       APInt NewBits = APInt(DstBitSize, 0);
7784       bool EltIsUndef = true;
7785       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7786         // Shift the previously computed bits over.
7787         NewBits <<= SrcBitSize;
7788         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7789         if (Op.isUndef()) continue;
7790         EltIsUndef = false;
7791 
7792         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7793                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7794       }
7795 
7796       if (EltIsUndef)
7797         Ops.push_back(DAG.getUNDEF(DstEltVT));
7798       else
7799         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7800     }
7801 
7802     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7803     return DAG.getBuildVector(VT, DL, Ops);
7804   }
7805 
7806   // Finally, this must be the case where we are shrinking elements: each input
7807   // turns into multiple outputs.
7808   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7809   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7810                             NumOutputsPerInput*BV->getNumOperands());
7811   SmallVector<SDValue, 8> Ops;
7812 
7813   for (const SDValue &Op : BV->op_values()) {
7814     if (Op.isUndef()) {
7815       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7816       continue;
7817     }
7818 
7819     APInt OpVal = cast<ConstantSDNode>(Op)->
7820                   getAPIntValue().zextOrTrunc(SrcBitSize);
7821 
7822     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7823       APInt ThisVal = OpVal.trunc(DstBitSize);
7824       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7825       OpVal = OpVal.lshr(DstBitSize);
7826     }
7827 
7828     // For big endian targets, swap the order of the pieces of each element.
7829     if (DAG.getDataLayout().isBigEndian())
7830       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7831   }
7832 
7833   return DAG.getBuildVector(VT, DL, Ops);
7834 }
7835 
7836 /// Try to perform FMA combining on a given FADD node.
7837 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7838   SDValue N0 = N->getOperand(0);
7839   SDValue N1 = N->getOperand(1);
7840   EVT VT = N->getValueType(0);
7841   SDLoc SL(N);
7842 
7843   const TargetOptions &Options = DAG.getTarget().Options;
7844   bool AllowFusion =
7845       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7846 
7847   // Floating-point multiply-add with intermediate rounding.
7848   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7849 
7850   // Floating-point multiply-add without intermediate rounding.
7851   bool HasFMA =
7852       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7853       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7854 
7855   // No valid opcode, do not combine.
7856   if (!HasFMAD && !HasFMA)
7857     return SDValue();
7858 
7859   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7860   ;
7861   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7862     return SDValue();
7863 
7864   // Always prefer FMAD to FMA for precision.
7865   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7866   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7867   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7868 
7869   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7870   // prefer to fold the multiply with fewer uses.
7871   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7872       N1.getOpcode() == ISD::FMUL) {
7873     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7874       std::swap(N0, N1);
7875   }
7876 
7877   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7878   if (N0.getOpcode() == ISD::FMUL &&
7879       (Aggressive || N0->hasOneUse())) {
7880     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7881                        N0.getOperand(0), N0.getOperand(1), N1);
7882   }
7883 
7884   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7885   // Note: Commutes FADD operands.
7886   if (N1.getOpcode() == ISD::FMUL &&
7887       (Aggressive || N1->hasOneUse())) {
7888     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7889                        N1.getOperand(0), N1.getOperand(1), N0);
7890   }
7891 
7892   // Look through FP_EXTEND nodes to do more combining.
7893   if (AllowFusion && LookThroughFPExt) {
7894     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7895     if (N0.getOpcode() == ISD::FP_EXTEND) {
7896       SDValue N00 = N0.getOperand(0);
7897       if (N00.getOpcode() == ISD::FMUL)
7898         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7899                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7900                                        N00.getOperand(0)),
7901                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7902                                        N00.getOperand(1)), N1);
7903     }
7904 
7905     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7906     // Note: Commutes FADD operands.
7907     if (N1.getOpcode() == ISD::FP_EXTEND) {
7908       SDValue N10 = N1.getOperand(0);
7909       if (N10.getOpcode() == ISD::FMUL)
7910         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7911                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7912                                        N10.getOperand(0)),
7913                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7914                                        N10.getOperand(1)), N0);
7915     }
7916   }
7917 
7918   // More folding opportunities when target permits.
7919   if ((AllowFusion || HasFMAD)  && Aggressive) {
7920     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7921     if (N0.getOpcode() == PreferredFusedOpcode &&
7922         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7923       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7924                          N0.getOperand(0), N0.getOperand(1),
7925                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7926                                      N0.getOperand(2).getOperand(0),
7927                                      N0.getOperand(2).getOperand(1),
7928                                      N1));
7929     }
7930 
7931     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7932     if (N1->getOpcode() == PreferredFusedOpcode &&
7933         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7934       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7935                          N1.getOperand(0), N1.getOperand(1),
7936                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7937                                      N1.getOperand(2).getOperand(0),
7938                                      N1.getOperand(2).getOperand(1),
7939                                      N0));
7940     }
7941 
7942     if (AllowFusion && LookThroughFPExt) {
7943       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7944       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7945       auto FoldFAddFMAFPExtFMul = [&] (
7946           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7947         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7948                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7949                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7950                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7951                                        Z));
7952       };
7953       if (N0.getOpcode() == PreferredFusedOpcode) {
7954         SDValue N02 = N0.getOperand(2);
7955         if (N02.getOpcode() == ISD::FP_EXTEND) {
7956           SDValue N020 = N02.getOperand(0);
7957           if (N020.getOpcode() == ISD::FMUL)
7958             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7959                                         N020.getOperand(0), N020.getOperand(1),
7960                                         N1);
7961         }
7962       }
7963 
7964       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7965       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7966       // FIXME: This turns two single-precision and one double-precision
7967       // operation into two double-precision operations, which might not be
7968       // interesting for all targets, especially GPUs.
7969       auto FoldFAddFPExtFMAFMul = [&] (
7970           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7971         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7972                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7973                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7974                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7975                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7976                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7977                                        Z));
7978       };
7979       if (N0.getOpcode() == ISD::FP_EXTEND) {
7980         SDValue N00 = N0.getOperand(0);
7981         if (N00.getOpcode() == PreferredFusedOpcode) {
7982           SDValue N002 = N00.getOperand(2);
7983           if (N002.getOpcode() == ISD::FMUL)
7984             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7985                                         N002.getOperand(0), N002.getOperand(1),
7986                                         N1);
7987         }
7988       }
7989 
7990       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7991       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7992       if (N1.getOpcode() == PreferredFusedOpcode) {
7993         SDValue N12 = N1.getOperand(2);
7994         if (N12.getOpcode() == ISD::FP_EXTEND) {
7995           SDValue N120 = N12.getOperand(0);
7996           if (N120.getOpcode() == ISD::FMUL)
7997             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7998                                         N120.getOperand(0), N120.getOperand(1),
7999                                         N0);
8000         }
8001       }
8002 
8003       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8004       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8005       // FIXME: This turns two single-precision and one double-precision
8006       // operation into two double-precision operations, which might not be
8007       // interesting for all targets, especially GPUs.
8008       if (N1.getOpcode() == ISD::FP_EXTEND) {
8009         SDValue N10 = N1.getOperand(0);
8010         if (N10.getOpcode() == PreferredFusedOpcode) {
8011           SDValue N102 = N10.getOperand(2);
8012           if (N102.getOpcode() == ISD::FMUL)
8013             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8014                                         N102.getOperand(0), N102.getOperand(1),
8015                                         N0);
8016         }
8017       }
8018     }
8019   }
8020 
8021   return SDValue();
8022 }
8023 
8024 /// Try to perform FMA combining on a given FSUB node.
8025 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8026   SDValue N0 = N->getOperand(0);
8027   SDValue N1 = N->getOperand(1);
8028   EVT VT = N->getValueType(0);
8029   SDLoc SL(N);
8030 
8031   const TargetOptions &Options = DAG.getTarget().Options;
8032   bool AllowFusion =
8033       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8034 
8035   // Floating-point multiply-add with intermediate rounding.
8036   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8037 
8038   // Floating-point multiply-add without intermediate rounding.
8039   bool HasFMA =
8040       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8041       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8042 
8043   // No valid opcode, do not combine.
8044   if (!HasFMAD && !HasFMA)
8045     return SDValue();
8046 
8047   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8048   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
8049     return SDValue();
8050 
8051   // Always prefer FMAD to FMA for precision.
8052   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8053   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8054   bool LookThroughFPExt = TLI.isFPExtFree(VT);
8055 
8056   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8057   if (N0.getOpcode() == ISD::FMUL &&
8058       (Aggressive || N0->hasOneUse())) {
8059     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8060                        N0.getOperand(0), N0.getOperand(1),
8061                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8062   }
8063 
8064   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8065   // Note: Commutes FSUB operands.
8066   if (N1.getOpcode() == ISD::FMUL &&
8067       (Aggressive || N1->hasOneUse()))
8068     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8069                        DAG.getNode(ISD::FNEG, SL, VT,
8070                                    N1.getOperand(0)),
8071                        N1.getOperand(1), N0);
8072 
8073   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8074   if (N0.getOpcode() == ISD::FNEG &&
8075       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8076       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8077     SDValue N00 = N0.getOperand(0).getOperand(0);
8078     SDValue N01 = N0.getOperand(0).getOperand(1);
8079     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8080                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8081                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8082   }
8083 
8084   // Look through FP_EXTEND nodes to do more combining.
8085   if (AllowFusion && LookThroughFPExt) {
8086     // fold (fsub (fpext (fmul x, y)), z)
8087     //   -> (fma (fpext x), (fpext y), (fneg z))
8088     if (N0.getOpcode() == ISD::FP_EXTEND) {
8089       SDValue N00 = N0.getOperand(0);
8090       if (N00.getOpcode() == ISD::FMUL)
8091         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8092                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8093                                        N00.getOperand(0)),
8094                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8095                                        N00.getOperand(1)),
8096                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8097     }
8098 
8099     // fold (fsub x, (fpext (fmul y, z)))
8100     //   -> (fma (fneg (fpext y)), (fpext z), x)
8101     // Note: Commutes FSUB operands.
8102     if (N1.getOpcode() == ISD::FP_EXTEND) {
8103       SDValue N10 = N1.getOperand(0);
8104       if (N10.getOpcode() == ISD::FMUL)
8105         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8106                            DAG.getNode(ISD::FNEG, SL, VT,
8107                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8108                                                    N10.getOperand(0))),
8109                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8110                                        N10.getOperand(1)),
8111                            N0);
8112     }
8113 
8114     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8115     //   -> (fneg (fma (fpext x), (fpext y), z))
8116     // Note: This could be removed with appropriate canonicalization of the
8117     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8118     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8119     // from implementing the canonicalization in visitFSUB.
8120     if (N0.getOpcode() == ISD::FP_EXTEND) {
8121       SDValue N00 = N0.getOperand(0);
8122       if (N00.getOpcode() == ISD::FNEG) {
8123         SDValue N000 = N00.getOperand(0);
8124         if (N000.getOpcode() == ISD::FMUL) {
8125           return DAG.getNode(ISD::FNEG, SL, VT,
8126                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8127                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8128                                                      N000.getOperand(0)),
8129                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8130                                                      N000.getOperand(1)),
8131                                          N1));
8132         }
8133       }
8134     }
8135 
8136     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8137     //   -> (fneg (fma (fpext x)), (fpext y), z)
8138     // Note: This could be removed with appropriate canonicalization of the
8139     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8140     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8141     // from implementing the canonicalization in visitFSUB.
8142     if (N0.getOpcode() == ISD::FNEG) {
8143       SDValue N00 = N0.getOperand(0);
8144       if (N00.getOpcode() == ISD::FP_EXTEND) {
8145         SDValue N000 = N00.getOperand(0);
8146         if (N000.getOpcode() == ISD::FMUL) {
8147           return DAG.getNode(ISD::FNEG, SL, VT,
8148                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8149                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8150                                                      N000.getOperand(0)),
8151                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8152                                                      N000.getOperand(1)),
8153                                          N1));
8154         }
8155       }
8156     }
8157 
8158   }
8159 
8160   // More folding opportunities when target permits.
8161   if ((AllowFusion || HasFMAD) && Aggressive) {
8162     // fold (fsub (fma x, y, (fmul u, v)), z)
8163     //   -> (fma x, y (fma u, v, (fneg z)))
8164     if (N0.getOpcode() == PreferredFusedOpcode &&
8165         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8166       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8167                          N0.getOperand(0), N0.getOperand(1),
8168                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8169                                      N0.getOperand(2).getOperand(0),
8170                                      N0.getOperand(2).getOperand(1),
8171                                      DAG.getNode(ISD::FNEG, SL, VT,
8172                                                  N1)));
8173     }
8174 
8175     // fold (fsub x, (fma y, z, (fmul u, v)))
8176     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8177     if (N1.getOpcode() == PreferredFusedOpcode &&
8178         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8179       SDValue N20 = N1.getOperand(2).getOperand(0);
8180       SDValue N21 = N1.getOperand(2).getOperand(1);
8181       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8182                          DAG.getNode(ISD::FNEG, SL, VT,
8183                                      N1.getOperand(0)),
8184                          N1.getOperand(1),
8185                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8186                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8187 
8188                                      N21, N0));
8189     }
8190 
8191     if (AllowFusion && LookThroughFPExt) {
8192       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8193       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8194       if (N0.getOpcode() == PreferredFusedOpcode) {
8195         SDValue N02 = N0.getOperand(2);
8196         if (N02.getOpcode() == ISD::FP_EXTEND) {
8197           SDValue N020 = N02.getOperand(0);
8198           if (N020.getOpcode() == ISD::FMUL)
8199             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8200                                N0.getOperand(0), N0.getOperand(1),
8201                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8202                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8203                                                        N020.getOperand(0)),
8204                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8205                                                        N020.getOperand(1)),
8206                                            DAG.getNode(ISD::FNEG, SL, VT,
8207                                                        N1)));
8208         }
8209       }
8210 
8211       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8212       //   -> (fma (fpext x), (fpext y),
8213       //           (fma (fpext u), (fpext v), (fneg z)))
8214       // FIXME: This turns two single-precision and one double-precision
8215       // operation into two double-precision operations, which might not be
8216       // interesting for all targets, especially GPUs.
8217       if (N0.getOpcode() == ISD::FP_EXTEND) {
8218         SDValue N00 = N0.getOperand(0);
8219         if (N00.getOpcode() == PreferredFusedOpcode) {
8220           SDValue N002 = N00.getOperand(2);
8221           if (N002.getOpcode() == ISD::FMUL)
8222             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8223                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8224                                            N00.getOperand(0)),
8225                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8226                                            N00.getOperand(1)),
8227                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8228                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8229                                                        N002.getOperand(0)),
8230                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8231                                                        N002.getOperand(1)),
8232                                            DAG.getNode(ISD::FNEG, SL, VT,
8233                                                        N1)));
8234         }
8235       }
8236 
8237       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8238       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8239       if (N1.getOpcode() == PreferredFusedOpcode &&
8240         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8241         SDValue N120 = N1.getOperand(2).getOperand(0);
8242         if (N120.getOpcode() == ISD::FMUL) {
8243           SDValue N1200 = N120.getOperand(0);
8244           SDValue N1201 = N120.getOperand(1);
8245           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8246                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8247                              N1.getOperand(1),
8248                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8249                                          DAG.getNode(ISD::FNEG, SL, VT,
8250                                              DAG.getNode(ISD::FP_EXTEND, SL,
8251                                                          VT, N1200)),
8252                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8253                                                      N1201),
8254                                          N0));
8255         }
8256       }
8257 
8258       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8259       //   -> (fma (fneg (fpext y)), (fpext z),
8260       //           (fma (fneg (fpext u)), (fpext v), x))
8261       // FIXME: This turns two single-precision and one double-precision
8262       // operation into two double-precision operations, which might not be
8263       // interesting for all targets, especially GPUs.
8264       if (N1.getOpcode() == ISD::FP_EXTEND &&
8265         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8266         SDValue N100 = N1.getOperand(0).getOperand(0);
8267         SDValue N101 = N1.getOperand(0).getOperand(1);
8268         SDValue N102 = N1.getOperand(0).getOperand(2);
8269         if (N102.getOpcode() == ISD::FMUL) {
8270           SDValue N1020 = N102.getOperand(0);
8271           SDValue N1021 = N102.getOperand(1);
8272           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8273                              DAG.getNode(ISD::FNEG, SL, VT,
8274                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8275                                                      N100)),
8276                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8277                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8278                                          DAG.getNode(ISD::FNEG, SL, VT,
8279                                              DAG.getNode(ISD::FP_EXTEND, SL,
8280                                                          VT, N1020)),
8281                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8282                                                      N1021),
8283                                          N0));
8284         }
8285       }
8286     }
8287   }
8288 
8289   return SDValue();
8290 }
8291 
8292 /// Try to perform FMA combining on a given FMUL node.
8293 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8294   SDValue N0 = N->getOperand(0);
8295   SDValue N1 = N->getOperand(1);
8296   EVT VT = N->getValueType(0);
8297   SDLoc SL(N);
8298 
8299   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8300 
8301   const TargetOptions &Options = DAG.getTarget().Options;
8302   bool AllowFusion =
8303       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8304 
8305   // Floating-point multiply-add with intermediate rounding.
8306   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8307 
8308   // Floating-point multiply-add without intermediate rounding.
8309   bool HasFMA =
8310       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8311       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8312 
8313   // No valid opcode, do not combine.
8314   if (!HasFMAD && !HasFMA)
8315     return SDValue();
8316 
8317   // Always prefer FMAD to FMA for precision.
8318   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8319   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8320 
8321   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8322   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8323   auto FuseFADD = [&](SDValue X, SDValue Y) {
8324     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8325       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8326       if (XC1 && XC1->isExactlyValue(+1.0))
8327         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8328       if (XC1 && XC1->isExactlyValue(-1.0))
8329         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8330                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8331     }
8332     return SDValue();
8333   };
8334 
8335   if (SDValue FMA = FuseFADD(N0, N1))
8336     return FMA;
8337   if (SDValue FMA = FuseFADD(N1, N0))
8338     return FMA;
8339 
8340   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8341   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8342   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8343   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8344   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8345     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8346       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8347       if (XC0 && XC0->isExactlyValue(+1.0))
8348         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8349                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8350                            Y);
8351       if (XC0 && XC0->isExactlyValue(-1.0))
8352         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8353                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8354                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8355 
8356       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8357       if (XC1 && XC1->isExactlyValue(+1.0))
8358         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8359                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8360       if (XC1 && XC1->isExactlyValue(-1.0))
8361         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8362     }
8363     return SDValue();
8364   };
8365 
8366   if (SDValue FMA = FuseFSUB(N0, N1))
8367     return FMA;
8368   if (SDValue FMA = FuseFSUB(N1, N0))
8369     return FMA;
8370 
8371   return SDValue();
8372 }
8373 
8374 SDValue DAGCombiner::visitFADD(SDNode *N) {
8375   SDValue N0 = N->getOperand(0);
8376   SDValue N1 = N->getOperand(1);
8377   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8378   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8379   EVT VT = N->getValueType(0);
8380   SDLoc DL(N);
8381   const TargetOptions &Options = DAG.getTarget().Options;
8382   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8383 
8384   // fold vector ops
8385   if (VT.isVector())
8386     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8387       return FoldedVOp;
8388 
8389   // fold (fadd c1, c2) -> c1 + c2
8390   if (N0CFP && N1CFP)
8391     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8392 
8393   // canonicalize constant to RHS
8394   if (N0CFP && !N1CFP)
8395     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8396 
8397   // fold (fadd A, (fneg B)) -> (fsub A, B)
8398   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8399       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8400     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8401                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8402 
8403   // fold (fadd (fneg A), B) -> (fsub B, A)
8404   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8405       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8406     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8407                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8408 
8409   // If 'unsafe math' is enabled, fold lots of things.
8410   if (Options.UnsafeFPMath) {
8411     // No FP constant should be created after legalization as Instruction
8412     // Selection pass has a hard time dealing with FP constants.
8413     bool AllowNewConst = (Level < AfterLegalizeDAG);
8414 
8415     // fold (fadd A, 0) -> A
8416     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8417       if (N1C->isZero())
8418         return N0;
8419 
8420     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8421     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8422         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8423       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8424                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8425                                      Flags),
8426                          Flags);
8427 
8428     // If allowed, fold (fadd (fneg x), x) -> 0.0
8429     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8430       return DAG.getConstantFP(0.0, DL, VT);
8431 
8432     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8433     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8434       return DAG.getConstantFP(0.0, DL, VT);
8435 
8436     // We can fold chains of FADD's of the same value into multiplications.
8437     // This transform is not safe in general because we are reducing the number
8438     // of rounding steps.
8439     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8440       if (N0.getOpcode() == ISD::FMUL) {
8441         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8442         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8443 
8444         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8445         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8446           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8447                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8448           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8449         }
8450 
8451         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8452         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8453             N1.getOperand(0) == N1.getOperand(1) &&
8454             N0.getOperand(0) == N1.getOperand(0)) {
8455           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8456                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8457           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8458         }
8459       }
8460 
8461       if (N1.getOpcode() == ISD::FMUL) {
8462         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8463         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8464 
8465         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8466         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8467           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8468                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8469           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8470         }
8471 
8472         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8473         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8474             N0.getOperand(0) == N0.getOperand(1) &&
8475             N1.getOperand(0) == N0.getOperand(0)) {
8476           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8477                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8478           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8479         }
8480       }
8481 
8482       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8483         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8484         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8485         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8486             (N0.getOperand(0) == N1)) {
8487           return DAG.getNode(ISD::FMUL, DL, VT,
8488                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8489         }
8490       }
8491 
8492       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8493         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8494         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8495         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8496             N1.getOperand(0) == N0) {
8497           return DAG.getNode(ISD::FMUL, DL, VT,
8498                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8499         }
8500       }
8501 
8502       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8503       if (AllowNewConst &&
8504           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8505           N0.getOperand(0) == N0.getOperand(1) &&
8506           N1.getOperand(0) == N1.getOperand(1) &&
8507           N0.getOperand(0) == N1.getOperand(0)) {
8508         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8509                            DAG.getConstantFP(4.0, DL, VT), Flags);
8510       }
8511     }
8512   } // enable-unsafe-fp-math
8513 
8514   // FADD -> FMA combines:
8515   if (SDValue Fused = visitFADDForFMACombine(N)) {
8516     AddToWorklist(Fused.getNode());
8517     return Fused;
8518   }
8519   return SDValue();
8520 }
8521 
8522 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8523   SDValue N0 = N->getOperand(0);
8524   SDValue N1 = N->getOperand(1);
8525   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8526   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8527   EVT VT = N->getValueType(0);
8528   SDLoc dl(N);
8529   const TargetOptions &Options = DAG.getTarget().Options;
8530   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8531 
8532   // fold vector ops
8533   if (VT.isVector())
8534     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8535       return FoldedVOp;
8536 
8537   // fold (fsub c1, c2) -> c1-c2
8538   if (N0CFP && N1CFP)
8539     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8540 
8541   // fold (fsub A, (fneg B)) -> (fadd A, B)
8542   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8543     return DAG.getNode(ISD::FADD, dl, VT, N0,
8544                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8545 
8546   // If 'unsafe math' is enabled, fold lots of things.
8547   if (Options.UnsafeFPMath) {
8548     // (fsub A, 0) -> A
8549     if (N1CFP && N1CFP->isZero())
8550       return N0;
8551 
8552     // (fsub 0, B) -> -B
8553     if (N0CFP && N0CFP->isZero()) {
8554       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8555         return GetNegatedExpression(N1, DAG, LegalOperations);
8556       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8557         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8558     }
8559 
8560     // (fsub x, x) -> 0.0
8561     if (N0 == N1)
8562       return DAG.getConstantFP(0.0f, dl, VT);
8563 
8564     // (fsub x, (fadd x, y)) -> (fneg y)
8565     // (fsub x, (fadd y, x)) -> (fneg y)
8566     if (N1.getOpcode() == ISD::FADD) {
8567       SDValue N10 = N1->getOperand(0);
8568       SDValue N11 = N1->getOperand(1);
8569 
8570       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8571         return GetNegatedExpression(N11, DAG, LegalOperations);
8572 
8573       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8574         return GetNegatedExpression(N10, DAG, LegalOperations);
8575     }
8576   }
8577 
8578   // FSUB -> FMA combines:
8579   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8580     AddToWorklist(Fused.getNode());
8581     return Fused;
8582   }
8583 
8584   return SDValue();
8585 }
8586 
8587 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8588   SDValue N0 = N->getOperand(0);
8589   SDValue N1 = N->getOperand(1);
8590   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8591   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8592   EVT VT = N->getValueType(0);
8593   SDLoc DL(N);
8594   const TargetOptions &Options = DAG.getTarget().Options;
8595   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8596 
8597   // fold vector ops
8598   if (VT.isVector()) {
8599     // This just handles C1 * C2 for vectors. Other vector folds are below.
8600     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8601       return FoldedVOp;
8602   }
8603 
8604   // fold (fmul c1, c2) -> c1*c2
8605   if (N0CFP && N1CFP)
8606     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8607 
8608   // canonicalize constant to RHS
8609   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8610      !isConstantFPBuildVectorOrConstantFP(N1))
8611     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8612 
8613   // fold (fmul A, 1.0) -> A
8614   if (N1CFP && N1CFP->isExactlyValue(1.0))
8615     return N0;
8616 
8617   if (Options.UnsafeFPMath) {
8618     // fold (fmul A, 0) -> 0
8619     if (N1CFP && N1CFP->isZero())
8620       return N1;
8621 
8622     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8623     if (N0.getOpcode() == ISD::FMUL) {
8624       // Fold scalars or any vector constants (not just splats).
8625       // This fold is done in general by InstCombine, but extra fmul insts
8626       // may have been generated during lowering.
8627       SDValue N00 = N0.getOperand(0);
8628       SDValue N01 = N0.getOperand(1);
8629       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8630       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8631       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8632 
8633       // Check 1: Make sure that the first operand of the inner multiply is NOT
8634       // a constant. Otherwise, we may induce infinite looping.
8635       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8636         // Check 2: Make sure that the second operand of the inner multiply and
8637         // the second operand of the outer multiply are constants.
8638         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8639             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8640           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8641           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8642         }
8643       }
8644     }
8645 
8646     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8647     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8648     // during an early run of DAGCombiner can prevent folding with fmuls
8649     // inserted during lowering.
8650     if (N0.getOpcode() == ISD::FADD &&
8651         (N0.getOperand(0) == N0.getOperand(1)) &&
8652         N0.hasOneUse()) {
8653       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8654       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8655       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8656     }
8657   }
8658 
8659   // fold (fmul X, 2.0) -> (fadd X, X)
8660   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8661     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8662 
8663   // fold (fmul X, -1.0) -> (fneg X)
8664   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8665     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8666       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8667 
8668   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8669   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8670     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8671       // Both can be negated for free, check to see if at least one is cheaper
8672       // negated.
8673       if (LHSNeg == 2 || RHSNeg == 2)
8674         return DAG.getNode(ISD::FMUL, DL, VT,
8675                            GetNegatedExpression(N0, DAG, LegalOperations),
8676                            GetNegatedExpression(N1, DAG, LegalOperations),
8677                            Flags);
8678     }
8679   }
8680 
8681   // FMUL -> FMA combines:
8682   if (SDValue Fused = visitFMULForFMACombine(N)) {
8683     AddToWorklist(Fused.getNode());
8684     return Fused;
8685   }
8686 
8687   return SDValue();
8688 }
8689 
8690 SDValue DAGCombiner::visitFMA(SDNode *N) {
8691   SDValue N0 = N->getOperand(0);
8692   SDValue N1 = N->getOperand(1);
8693   SDValue N2 = N->getOperand(2);
8694   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8695   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8696   EVT VT = N->getValueType(0);
8697   SDLoc dl(N);
8698   const TargetOptions &Options = DAG.getTarget().Options;
8699 
8700   // Constant fold FMA.
8701   if (isa<ConstantFPSDNode>(N0) &&
8702       isa<ConstantFPSDNode>(N1) &&
8703       isa<ConstantFPSDNode>(N2)) {
8704     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8705   }
8706 
8707   if (Options.UnsafeFPMath) {
8708     if (N0CFP && N0CFP->isZero())
8709       return N2;
8710     if (N1CFP && N1CFP->isZero())
8711       return N2;
8712   }
8713   // TODO: The FMA node should have flags that propagate to these nodes.
8714   if (N0CFP && N0CFP->isExactlyValue(1.0))
8715     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8716   if (N1CFP && N1CFP->isExactlyValue(1.0))
8717     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8718 
8719   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8720   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8721      !isConstantFPBuildVectorOrConstantFP(N1))
8722     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8723 
8724   // TODO: FMA nodes should have flags that propagate to the created nodes.
8725   // For now, create a Flags object for use with all unsafe math transforms.
8726   SDNodeFlags Flags;
8727   Flags.setUnsafeAlgebra(true);
8728 
8729   if (Options.UnsafeFPMath) {
8730     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8731     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8732         isConstantFPBuildVectorOrConstantFP(N1) &&
8733         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8734       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8735                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8736                                      &Flags), &Flags);
8737     }
8738 
8739     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8740     if (N0.getOpcode() == ISD::FMUL &&
8741         isConstantFPBuildVectorOrConstantFP(N1) &&
8742         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8743       return DAG.getNode(ISD::FMA, dl, VT,
8744                          N0.getOperand(0),
8745                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8746                                      &Flags),
8747                          N2);
8748     }
8749   }
8750 
8751   // (fma x, 1, y) -> (fadd x, y)
8752   // (fma x, -1, y) -> (fadd (fneg x), y)
8753   if (N1CFP) {
8754     if (N1CFP->isExactlyValue(1.0))
8755       // TODO: The FMA node should have flags that propagate to this node.
8756       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8757 
8758     if (N1CFP->isExactlyValue(-1.0) &&
8759         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8760       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8761       AddToWorklist(RHSNeg.getNode());
8762       // TODO: The FMA node should have flags that propagate to this node.
8763       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8764     }
8765   }
8766 
8767   if (Options.UnsafeFPMath) {
8768     // (fma x, c, x) -> (fmul x, (c+1))
8769     if (N1CFP && N0 == N2) {
8770     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8771                          DAG.getNode(ISD::FADD, dl, VT,
8772                                      N1, DAG.getConstantFP(1.0, dl, VT),
8773                                      &Flags), &Flags);
8774     }
8775 
8776     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8777     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8778       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8779                          DAG.getNode(ISD::FADD, dl, VT,
8780                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8781                                      &Flags), &Flags);
8782     }
8783   }
8784 
8785   return SDValue();
8786 }
8787 
8788 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8789 // reciprocal.
8790 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8791 // Notice that this is not always beneficial. One reason is different target
8792 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8793 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8794 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8795 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8796   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8797   const SDNodeFlags *Flags = N->getFlags();
8798   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8799     return SDValue();
8800 
8801   // Skip if current node is a reciprocal.
8802   SDValue N0 = N->getOperand(0);
8803   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8804   if (N0CFP && N0CFP->isExactlyValue(1.0))
8805     return SDValue();
8806 
8807   // Exit early if the target does not want this transform or if there can't
8808   // possibly be enough uses of the divisor to make the transform worthwhile.
8809   SDValue N1 = N->getOperand(1);
8810   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8811   if (!MinUses || N1->use_size() < MinUses)
8812     return SDValue();
8813 
8814   // Find all FDIV users of the same divisor.
8815   // Use a set because duplicates may be present in the user list.
8816   SetVector<SDNode *> Users;
8817   for (auto *U : N1->uses()) {
8818     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8819       // This division is eligible for optimization only if global unsafe math
8820       // is enabled or if this division allows reciprocal formation.
8821       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8822         Users.insert(U);
8823     }
8824   }
8825 
8826   // Now that we have the actual number of divisor uses, make sure it meets
8827   // the minimum threshold specified by the target.
8828   if (Users.size() < MinUses)
8829     return SDValue();
8830 
8831   EVT VT = N->getValueType(0);
8832   SDLoc DL(N);
8833   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8834   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8835 
8836   // Dividend / Divisor -> Dividend * Reciprocal
8837   for (auto *U : Users) {
8838     SDValue Dividend = U->getOperand(0);
8839     if (Dividend != FPOne) {
8840       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8841                                     Reciprocal, Flags);
8842       CombineTo(U, NewNode);
8843     } else if (U != Reciprocal.getNode()) {
8844       // In the absence of fast-math-flags, this user node is always the
8845       // same node as Reciprocal, but with FMF they may be different nodes.
8846       CombineTo(U, Reciprocal);
8847     }
8848   }
8849   return SDValue(N, 0);  // N was replaced.
8850 }
8851 
8852 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8853   SDValue N0 = N->getOperand(0);
8854   SDValue N1 = N->getOperand(1);
8855   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8856   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8857   EVT VT = N->getValueType(0);
8858   SDLoc DL(N);
8859   const TargetOptions &Options = DAG.getTarget().Options;
8860   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8861 
8862   // fold vector ops
8863   if (VT.isVector())
8864     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8865       return FoldedVOp;
8866 
8867   // fold (fdiv c1, c2) -> c1/c2
8868   if (N0CFP && N1CFP)
8869     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8870 
8871   if (Options.UnsafeFPMath) {
8872     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8873     if (N1CFP) {
8874       // Compute the reciprocal 1.0 / c2.
8875       const APFloat &N1APF = N1CFP->getValueAPF();
8876       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8877       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8878       // Only do the transform if the reciprocal is a legal fp immediate that
8879       // isn't too nasty (eg NaN, denormal, ...).
8880       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8881           (!LegalOperations ||
8882            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8883            // backend)... we should handle this gracefully after Legalize.
8884            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8885            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8886            TLI.isFPImmLegal(Recip, VT)))
8887         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8888                            DAG.getConstantFP(Recip, DL, VT), Flags);
8889     }
8890 
8891     // If this FDIV is part of a reciprocal square root, it may be folded
8892     // into a target-specific square root estimate instruction.
8893     if (N1.getOpcode() == ISD::FSQRT) {
8894       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
8895         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8896       }
8897     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8898                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8899       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8900                                           Flags)) {
8901         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8902         AddToWorklist(RV.getNode());
8903         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8904       }
8905     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8906                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8907       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8908                                           Flags)) {
8909         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8910         AddToWorklist(RV.getNode());
8911         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8912       }
8913     } else if (N1.getOpcode() == ISD::FMUL) {
8914       // Look through an FMUL. Even though this won't remove the FDIV directly,
8915       // it's still worthwhile to get rid of the FSQRT if possible.
8916       SDValue SqrtOp;
8917       SDValue OtherOp;
8918       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8919         SqrtOp = N1.getOperand(0);
8920         OtherOp = N1.getOperand(1);
8921       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8922         SqrtOp = N1.getOperand(1);
8923         OtherOp = N1.getOperand(0);
8924       }
8925       if (SqrtOp.getNode()) {
8926         // We found a FSQRT, so try to make this fold:
8927         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8928         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8929           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8930           AddToWorklist(RV.getNode());
8931           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8932         }
8933       }
8934     }
8935 
8936     // Fold into a reciprocal estimate and multiply instead of a real divide.
8937     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8938       AddToWorklist(RV.getNode());
8939       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8940     }
8941   }
8942 
8943   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8944   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8945     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8946       // Both can be negated for free, check to see if at least one is cheaper
8947       // negated.
8948       if (LHSNeg == 2 || RHSNeg == 2)
8949         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8950                            GetNegatedExpression(N0, DAG, LegalOperations),
8951                            GetNegatedExpression(N1, DAG, LegalOperations),
8952                            Flags);
8953     }
8954   }
8955 
8956   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8957     return CombineRepeatedDivisors;
8958 
8959   return SDValue();
8960 }
8961 
8962 SDValue DAGCombiner::visitFREM(SDNode *N) {
8963   SDValue N0 = N->getOperand(0);
8964   SDValue N1 = N->getOperand(1);
8965   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8966   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8967   EVT VT = N->getValueType(0);
8968 
8969   // fold (frem c1, c2) -> fmod(c1,c2)
8970   if (N0CFP && N1CFP)
8971     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8972                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8973 
8974   return SDValue();
8975 }
8976 
8977 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8978   if (!DAG.getTarget().Options.UnsafeFPMath)
8979     return SDValue();
8980 
8981   SDValue N0 = N->getOperand(0);
8982   if (TLI.isFsqrtCheap(N0, DAG))
8983     return SDValue();
8984 
8985   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8986   // For now, create a Flags object for use with all unsafe math transforms.
8987   SDNodeFlags Flags;
8988   Flags.setUnsafeAlgebra(true);
8989   return buildSqrtEstimate(N0, &Flags);
8990 }
8991 
8992 /// copysign(x, fp_extend(y)) -> copysign(x, y)
8993 /// copysign(x, fp_round(y)) -> copysign(x, y)
8994 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
8995   SDValue N1 = N->getOperand(1);
8996   if ((N1.getOpcode() == ISD::FP_EXTEND ||
8997        N1.getOpcode() == ISD::FP_ROUND)) {
8998     // Do not optimize out type conversion of f128 type yet.
8999     // For some targets like x86_64, configuration is changed to keep one f128
9000     // value in one SSE register, but instruction selection cannot handle
9001     // FCOPYSIGN on SSE registers yet.
9002     EVT N1VT = N1->getValueType(0);
9003     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9004     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9005   }
9006   return false;
9007 }
9008 
9009 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9010   SDValue N0 = N->getOperand(0);
9011   SDValue N1 = N->getOperand(1);
9012   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9013   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9014   EVT VT = N->getValueType(0);
9015 
9016   if (N0CFP && N1CFP)  // Constant fold
9017     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9018 
9019   if (N1CFP) {
9020     const APFloat& V = N1CFP->getValueAPF();
9021     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
9022     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9023     if (!V.isNegative()) {
9024       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9025         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9026     } else {
9027       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9028         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9029                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9030     }
9031   }
9032 
9033   // copysign(fabs(x), y) -> copysign(x, y)
9034   // copysign(fneg(x), y) -> copysign(x, y)
9035   // copysign(copysign(x,z), y) -> copysign(x, y)
9036   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9037       N0.getOpcode() == ISD::FCOPYSIGN)
9038     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9039                        N0.getOperand(0), N1);
9040 
9041   // copysign(x, abs(y)) -> abs(x)
9042   if (N1.getOpcode() == ISD::FABS)
9043     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9044 
9045   // copysign(x, copysign(y,z)) -> copysign(x, z)
9046   if (N1.getOpcode() == ISD::FCOPYSIGN)
9047     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9048                        N0, N1.getOperand(1));
9049 
9050   // copysign(x, fp_extend(y)) -> copysign(x, y)
9051   // copysign(x, fp_round(y)) -> copysign(x, y)
9052   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9053     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9054                        N0, N1.getOperand(0));
9055 
9056   return SDValue();
9057 }
9058 
9059 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9060   SDValue N0 = N->getOperand(0);
9061   EVT VT = N->getValueType(0);
9062   EVT OpVT = N0.getValueType();
9063 
9064   // fold (sint_to_fp c1) -> c1fp
9065   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9066       // ...but only if the target supports immediate floating-point values
9067       (!LegalOperations ||
9068        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9069     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9070 
9071   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9072   // but UINT_TO_FP is legal on this target, try to convert.
9073   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9074       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9075     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9076     if (DAG.SignBitIsZero(N0))
9077       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9078   }
9079 
9080   // The next optimizations are desirable only if SELECT_CC can be lowered.
9081   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9082     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9083     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9084         !VT.isVector() &&
9085         (!LegalOperations ||
9086          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9087       SDLoc DL(N);
9088       SDValue Ops[] =
9089         { N0.getOperand(0), N0.getOperand(1),
9090           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9091           N0.getOperand(2) };
9092       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9093     }
9094 
9095     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9096     //      (select_cc x, y, 1.0, 0.0,, cc)
9097     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9098         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9099         (!LegalOperations ||
9100          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9101       SDLoc DL(N);
9102       SDValue Ops[] =
9103         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9104           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9105           N0.getOperand(0).getOperand(2) };
9106       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9107     }
9108   }
9109 
9110   return SDValue();
9111 }
9112 
9113 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9114   SDValue N0 = N->getOperand(0);
9115   EVT VT = N->getValueType(0);
9116   EVT OpVT = N0.getValueType();
9117 
9118   // fold (uint_to_fp c1) -> c1fp
9119   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9120       // ...but only if the target supports immediate floating-point values
9121       (!LegalOperations ||
9122        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9123     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9124 
9125   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9126   // but SINT_TO_FP is legal on this target, try to convert.
9127   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9128       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9129     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9130     if (DAG.SignBitIsZero(N0))
9131       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9132   }
9133 
9134   // The next optimizations are desirable only if SELECT_CC can be lowered.
9135   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9136     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9137 
9138     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9139         (!LegalOperations ||
9140          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9141       SDLoc DL(N);
9142       SDValue Ops[] =
9143         { N0.getOperand(0), N0.getOperand(1),
9144           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9145           N0.getOperand(2) };
9146       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9147     }
9148   }
9149 
9150   return SDValue();
9151 }
9152 
9153 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9154 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9155   SDValue N0 = N->getOperand(0);
9156   EVT VT = N->getValueType(0);
9157 
9158   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9159     return SDValue();
9160 
9161   SDValue Src = N0.getOperand(0);
9162   EVT SrcVT = Src.getValueType();
9163   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9164   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9165 
9166   // We can safely assume the conversion won't overflow the output range,
9167   // because (for example) (uint8_t)18293.f is undefined behavior.
9168 
9169   // Since we can assume the conversion won't overflow, our decision as to
9170   // whether the input will fit in the float should depend on the minimum
9171   // of the input range and output range.
9172 
9173   // This means this is also safe for a signed input and unsigned output, since
9174   // a negative input would lead to undefined behavior.
9175   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9176   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9177   unsigned ActualSize = std::min(InputSize, OutputSize);
9178   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9179 
9180   // We can only fold away the float conversion if the input range can be
9181   // represented exactly in the float range.
9182   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9183     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9184       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9185                                                        : ISD::ZERO_EXTEND;
9186       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9187     }
9188     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9189       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9190     return DAG.getBitcast(VT, Src);
9191   }
9192   return SDValue();
9193 }
9194 
9195 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9196   SDValue N0 = N->getOperand(0);
9197   EVT VT = N->getValueType(0);
9198 
9199   // fold (fp_to_sint c1fp) -> c1
9200   if (isConstantFPBuildVectorOrConstantFP(N0))
9201     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9202 
9203   return FoldIntToFPToInt(N, DAG);
9204 }
9205 
9206 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9207   SDValue N0 = N->getOperand(0);
9208   EVT VT = N->getValueType(0);
9209 
9210   // fold (fp_to_uint c1fp) -> c1
9211   if (isConstantFPBuildVectorOrConstantFP(N0))
9212     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9213 
9214   return FoldIntToFPToInt(N, DAG);
9215 }
9216 
9217 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9218   SDValue N0 = N->getOperand(0);
9219   SDValue N1 = N->getOperand(1);
9220   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9221   EVT VT = N->getValueType(0);
9222 
9223   // fold (fp_round c1fp) -> c1fp
9224   if (N0CFP)
9225     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9226 
9227   // fold (fp_round (fp_extend x)) -> x
9228   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9229     return N0.getOperand(0);
9230 
9231   // fold (fp_round (fp_round x)) -> (fp_round x)
9232   if (N0.getOpcode() == ISD::FP_ROUND) {
9233     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9234     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9235 
9236     // Skip this folding if it results in an fp_round from f80 to f16.
9237     //
9238     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9239     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9240     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9241     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9242     // x86.
9243     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9244       return SDValue();
9245 
9246     // If the first fp_round isn't a value preserving truncation, it might
9247     // introduce a tie in the second fp_round, that wouldn't occur in the
9248     // single-step fp_round we want to fold to.
9249     // In other words, double rounding isn't the same as rounding.
9250     // Also, this is a value preserving truncation iff both fp_round's are.
9251     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9252       SDLoc DL(N);
9253       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9254                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9255     }
9256   }
9257 
9258   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9259   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9260     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9261                               N0.getOperand(0), N1);
9262     AddToWorklist(Tmp.getNode());
9263     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9264                        Tmp, N0.getOperand(1));
9265   }
9266 
9267   return SDValue();
9268 }
9269 
9270 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9271   SDValue N0 = N->getOperand(0);
9272   EVT VT = N->getValueType(0);
9273   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9274   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9275 
9276   // fold (fp_round_inreg c1fp) -> c1fp
9277   if (N0CFP && isTypeLegal(EVT)) {
9278     SDLoc DL(N);
9279     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9280     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9281   }
9282 
9283   return SDValue();
9284 }
9285 
9286 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9287   SDValue N0 = N->getOperand(0);
9288   EVT VT = N->getValueType(0);
9289 
9290   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9291   if (N->hasOneUse() &&
9292       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9293     return SDValue();
9294 
9295   // fold (fp_extend c1fp) -> c1fp
9296   if (isConstantFPBuildVectorOrConstantFP(N0))
9297     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9298 
9299   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9300   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9301       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9302     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9303 
9304   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9305   // value of X.
9306   if (N0.getOpcode() == ISD::FP_ROUND
9307       && N0.getNode()->getConstantOperandVal(1) == 1) {
9308     SDValue In = N0.getOperand(0);
9309     if (In.getValueType() == VT) return In;
9310     if (VT.bitsLT(In.getValueType()))
9311       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9312                          In, N0.getOperand(1));
9313     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9314   }
9315 
9316   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9317   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9318        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9319     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9320     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9321                                      LN0->getChain(),
9322                                      LN0->getBasePtr(), N0.getValueType(),
9323                                      LN0->getMemOperand());
9324     CombineTo(N, ExtLoad);
9325     CombineTo(N0.getNode(),
9326               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9327                           N0.getValueType(), ExtLoad,
9328                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9329               ExtLoad.getValue(1));
9330     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9331   }
9332 
9333   return SDValue();
9334 }
9335 
9336 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9337   SDValue N0 = N->getOperand(0);
9338   EVT VT = N->getValueType(0);
9339 
9340   // fold (fceil c1) -> fceil(c1)
9341   if (isConstantFPBuildVectorOrConstantFP(N0))
9342     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9343 
9344   return SDValue();
9345 }
9346 
9347 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9348   SDValue N0 = N->getOperand(0);
9349   EVT VT = N->getValueType(0);
9350 
9351   // fold (ftrunc c1) -> ftrunc(c1)
9352   if (isConstantFPBuildVectorOrConstantFP(N0))
9353     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9354 
9355   return SDValue();
9356 }
9357 
9358 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9359   SDValue N0 = N->getOperand(0);
9360   EVT VT = N->getValueType(0);
9361 
9362   // fold (ffloor c1) -> ffloor(c1)
9363   if (isConstantFPBuildVectorOrConstantFP(N0))
9364     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9365 
9366   return SDValue();
9367 }
9368 
9369 // FIXME: FNEG and FABS have a lot in common; refactor.
9370 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9371   SDValue N0 = N->getOperand(0);
9372   EVT VT = N->getValueType(0);
9373 
9374   // Constant fold FNEG.
9375   if (isConstantFPBuildVectorOrConstantFP(N0))
9376     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9377 
9378   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9379                          &DAG.getTarget().Options))
9380     return GetNegatedExpression(N0, DAG, LegalOperations);
9381 
9382   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9383   // constant pool values.
9384   if (!TLI.isFNegFree(VT) &&
9385       N0.getOpcode() == ISD::BITCAST &&
9386       N0.getNode()->hasOneUse()) {
9387     SDValue Int = N0.getOperand(0);
9388     EVT IntVT = Int.getValueType();
9389     if (IntVT.isInteger() && !IntVT.isVector()) {
9390       APInt SignMask;
9391       if (N0.getValueType().isVector()) {
9392         // For a vector, get a mask such as 0x80... per scalar element
9393         // and splat it.
9394         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9395         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9396       } else {
9397         // For a scalar, just generate 0x80...
9398         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9399       }
9400       SDLoc DL0(N0);
9401       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9402                         DAG.getConstant(SignMask, DL0, IntVT));
9403       AddToWorklist(Int.getNode());
9404       return DAG.getBitcast(VT, Int);
9405     }
9406   }
9407 
9408   // (fneg (fmul c, x)) -> (fmul -c, x)
9409   if (N0.getOpcode() == ISD::FMUL &&
9410       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9411     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9412     if (CFP1) {
9413       APFloat CVal = CFP1->getValueAPF();
9414       CVal.changeSign();
9415       if (Level >= AfterLegalizeDAG &&
9416           (TLI.isFPImmLegal(CVal, VT) ||
9417            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9418         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9419                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9420                                        N0.getOperand(1)),
9421                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9422     }
9423   }
9424 
9425   return SDValue();
9426 }
9427 
9428 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9429   SDValue N0 = N->getOperand(0);
9430   SDValue N1 = N->getOperand(1);
9431   EVT VT = N->getValueType(0);
9432   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9433   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9434 
9435   if (N0CFP && N1CFP) {
9436     const APFloat &C0 = N0CFP->getValueAPF();
9437     const APFloat &C1 = N1CFP->getValueAPF();
9438     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9439   }
9440 
9441   // Canonicalize to constant on RHS.
9442   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9443      !isConstantFPBuildVectorOrConstantFP(N1))
9444     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9445 
9446   return SDValue();
9447 }
9448 
9449 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9450   SDValue N0 = N->getOperand(0);
9451   SDValue N1 = N->getOperand(1);
9452   EVT VT = N->getValueType(0);
9453   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9454   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9455 
9456   if (N0CFP && N1CFP) {
9457     const APFloat &C0 = N0CFP->getValueAPF();
9458     const APFloat &C1 = N1CFP->getValueAPF();
9459     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9460   }
9461 
9462   // Canonicalize to constant on RHS.
9463   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9464      !isConstantFPBuildVectorOrConstantFP(N1))
9465     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9466 
9467   return SDValue();
9468 }
9469 
9470 SDValue DAGCombiner::visitFABS(SDNode *N) {
9471   SDValue N0 = N->getOperand(0);
9472   EVT VT = N->getValueType(0);
9473 
9474   // fold (fabs c1) -> fabs(c1)
9475   if (isConstantFPBuildVectorOrConstantFP(N0))
9476     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9477 
9478   // fold (fabs (fabs x)) -> (fabs x)
9479   if (N0.getOpcode() == ISD::FABS)
9480     return N->getOperand(0);
9481 
9482   // fold (fabs (fneg x)) -> (fabs x)
9483   // fold (fabs (fcopysign x, y)) -> (fabs x)
9484   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9485     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9486 
9487   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9488   // constant pool values.
9489   if (!TLI.isFAbsFree(VT) &&
9490       N0.getOpcode() == ISD::BITCAST &&
9491       N0.getNode()->hasOneUse()) {
9492     SDValue Int = N0.getOperand(0);
9493     EVT IntVT = Int.getValueType();
9494     if (IntVT.isInteger() && !IntVT.isVector()) {
9495       APInt SignMask;
9496       if (N0.getValueType().isVector()) {
9497         // For a vector, get a mask such as 0x7f... per scalar element
9498         // and splat it.
9499         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9500         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9501       } else {
9502         // For a scalar, just generate 0x7f...
9503         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9504       }
9505       SDLoc DL(N0);
9506       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9507                         DAG.getConstant(SignMask, DL, IntVT));
9508       AddToWorklist(Int.getNode());
9509       return DAG.getBitcast(N->getValueType(0), Int);
9510     }
9511   }
9512 
9513   return SDValue();
9514 }
9515 
9516 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9517   SDValue Chain = N->getOperand(0);
9518   SDValue N1 = N->getOperand(1);
9519   SDValue N2 = N->getOperand(2);
9520 
9521   // If N is a constant we could fold this into a fallthrough or unconditional
9522   // branch. However that doesn't happen very often in normal code, because
9523   // Instcombine/SimplifyCFG should have handled the available opportunities.
9524   // If we did this folding here, it would be necessary to update the
9525   // MachineBasicBlock CFG, which is awkward.
9526 
9527   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9528   // on the target.
9529   if (N1.getOpcode() == ISD::SETCC &&
9530       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9531                                    N1.getOperand(0).getValueType())) {
9532     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9533                        Chain, N1.getOperand(2),
9534                        N1.getOperand(0), N1.getOperand(1), N2);
9535   }
9536 
9537   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9538       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9539        (N1.getOperand(0).hasOneUse() &&
9540         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9541     SDNode *Trunc = nullptr;
9542     if (N1.getOpcode() == ISD::TRUNCATE) {
9543       // Look pass the truncate.
9544       Trunc = N1.getNode();
9545       N1 = N1.getOperand(0);
9546     }
9547 
9548     // Match this pattern so that we can generate simpler code:
9549     //
9550     //   %a = ...
9551     //   %b = and i32 %a, 2
9552     //   %c = srl i32 %b, 1
9553     //   brcond i32 %c ...
9554     //
9555     // into
9556     //
9557     //   %a = ...
9558     //   %b = and i32 %a, 2
9559     //   %c = setcc eq %b, 0
9560     //   brcond %c ...
9561     //
9562     // This applies only when the AND constant value has one bit set and the
9563     // SRL constant is equal to the log2 of the AND constant. The back-end is
9564     // smart enough to convert the result into a TEST/JMP sequence.
9565     SDValue Op0 = N1.getOperand(0);
9566     SDValue Op1 = N1.getOperand(1);
9567 
9568     if (Op0.getOpcode() == ISD::AND &&
9569         Op1.getOpcode() == ISD::Constant) {
9570       SDValue AndOp1 = Op0.getOperand(1);
9571 
9572       if (AndOp1.getOpcode() == ISD::Constant) {
9573         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9574 
9575         if (AndConst.isPowerOf2() &&
9576             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9577           SDLoc DL(N);
9578           SDValue SetCC =
9579             DAG.getSetCC(DL,
9580                          getSetCCResultType(Op0.getValueType()),
9581                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9582                          ISD::SETNE);
9583 
9584           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9585                                           MVT::Other, Chain, SetCC, N2);
9586           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9587           // will convert it back to (X & C1) >> C2.
9588           CombineTo(N, NewBRCond, false);
9589           // Truncate is dead.
9590           if (Trunc)
9591             deleteAndRecombine(Trunc);
9592           // Replace the uses of SRL with SETCC
9593           WorklistRemover DeadNodes(*this);
9594           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9595           deleteAndRecombine(N1.getNode());
9596           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9597         }
9598       }
9599     }
9600 
9601     if (Trunc)
9602       // Restore N1 if the above transformation doesn't match.
9603       N1 = N->getOperand(1);
9604   }
9605 
9606   // Transform br(xor(x, y)) -> br(x != y)
9607   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9608   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9609     SDNode *TheXor = N1.getNode();
9610     SDValue Op0 = TheXor->getOperand(0);
9611     SDValue Op1 = TheXor->getOperand(1);
9612     if (Op0.getOpcode() == Op1.getOpcode()) {
9613       // Avoid missing important xor optimizations.
9614       if (SDValue Tmp = visitXOR(TheXor)) {
9615         if (Tmp.getNode() != TheXor) {
9616           DEBUG(dbgs() << "\nReplacing.8 ";
9617                 TheXor->dump(&DAG);
9618                 dbgs() << "\nWith: ";
9619                 Tmp.getNode()->dump(&DAG);
9620                 dbgs() << '\n');
9621           WorklistRemover DeadNodes(*this);
9622           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9623           deleteAndRecombine(TheXor);
9624           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9625                              MVT::Other, Chain, Tmp, N2);
9626         }
9627 
9628         // visitXOR has changed XOR's operands or replaced the XOR completely,
9629         // bail out.
9630         return SDValue(N, 0);
9631       }
9632     }
9633 
9634     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9635       bool Equal = false;
9636       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9637           Op0.getOpcode() == ISD::XOR) {
9638         TheXor = Op0.getNode();
9639         Equal = true;
9640       }
9641 
9642       EVT SetCCVT = N1.getValueType();
9643       if (LegalTypes)
9644         SetCCVT = getSetCCResultType(SetCCVT);
9645       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9646                                    SetCCVT,
9647                                    Op0, Op1,
9648                                    Equal ? ISD::SETEQ : ISD::SETNE);
9649       // Replace the uses of XOR with SETCC
9650       WorklistRemover DeadNodes(*this);
9651       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9652       deleteAndRecombine(N1.getNode());
9653       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9654                          MVT::Other, Chain, SetCC, N2);
9655     }
9656   }
9657 
9658   return SDValue();
9659 }
9660 
9661 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9662 //
9663 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9664   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9665   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9666 
9667   // If N is a constant we could fold this into a fallthrough or unconditional
9668   // branch. However that doesn't happen very often in normal code, because
9669   // Instcombine/SimplifyCFG should have handled the available opportunities.
9670   // If we did this folding here, it would be necessary to update the
9671   // MachineBasicBlock CFG, which is awkward.
9672 
9673   // Use SimplifySetCC to simplify SETCC's.
9674   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9675                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9676                                false);
9677   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9678 
9679   // fold to a simpler setcc
9680   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9681     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9682                        N->getOperand(0), Simp.getOperand(2),
9683                        Simp.getOperand(0), Simp.getOperand(1),
9684                        N->getOperand(4));
9685 
9686   return SDValue();
9687 }
9688 
9689 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9690 /// and that N may be folded in the load / store addressing mode.
9691 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9692                                     SelectionDAG &DAG,
9693                                     const TargetLowering &TLI) {
9694   EVT VT;
9695   unsigned AS;
9696 
9697   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9698     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9699       return false;
9700     VT = LD->getMemoryVT();
9701     AS = LD->getAddressSpace();
9702   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9703     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9704       return false;
9705     VT = ST->getMemoryVT();
9706     AS = ST->getAddressSpace();
9707   } else
9708     return false;
9709 
9710   TargetLowering::AddrMode AM;
9711   if (N->getOpcode() == ISD::ADD) {
9712     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9713     if (Offset)
9714       // [reg +/- imm]
9715       AM.BaseOffs = Offset->getSExtValue();
9716     else
9717       // [reg +/- reg]
9718       AM.Scale = 1;
9719   } else if (N->getOpcode() == ISD::SUB) {
9720     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9721     if (Offset)
9722       // [reg +/- imm]
9723       AM.BaseOffs = -Offset->getSExtValue();
9724     else
9725       // [reg +/- reg]
9726       AM.Scale = 1;
9727   } else
9728     return false;
9729 
9730   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9731                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9732 }
9733 
9734 /// Try turning a load/store into a pre-indexed load/store when the base
9735 /// pointer is an add or subtract and it has other uses besides the load/store.
9736 /// After the transformation, the new indexed load/store has effectively folded
9737 /// the add/subtract in and all of its other uses are redirected to the
9738 /// new load/store.
9739 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9740   if (Level < AfterLegalizeDAG)
9741     return false;
9742 
9743   bool isLoad = true;
9744   SDValue Ptr;
9745   EVT VT;
9746   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9747     if (LD->isIndexed())
9748       return false;
9749     VT = LD->getMemoryVT();
9750     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9751         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9752       return false;
9753     Ptr = LD->getBasePtr();
9754   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9755     if (ST->isIndexed())
9756       return false;
9757     VT = ST->getMemoryVT();
9758     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9759         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9760       return false;
9761     Ptr = ST->getBasePtr();
9762     isLoad = false;
9763   } else {
9764     return false;
9765   }
9766 
9767   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9768   // out.  There is no reason to make this a preinc/predec.
9769   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9770       Ptr.getNode()->hasOneUse())
9771     return false;
9772 
9773   // Ask the target to do addressing mode selection.
9774   SDValue BasePtr;
9775   SDValue Offset;
9776   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9777   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9778     return false;
9779 
9780   // Backends without true r+i pre-indexed forms may need to pass a
9781   // constant base with a variable offset so that constant coercion
9782   // will work with the patterns in canonical form.
9783   bool Swapped = false;
9784   if (isa<ConstantSDNode>(BasePtr)) {
9785     std::swap(BasePtr, Offset);
9786     Swapped = true;
9787   }
9788 
9789   // Don't create a indexed load / store with zero offset.
9790   if (isNullConstant(Offset))
9791     return false;
9792 
9793   // Try turning it into a pre-indexed load / store except when:
9794   // 1) The new base ptr is a frame index.
9795   // 2) If N is a store and the new base ptr is either the same as or is a
9796   //    predecessor of the value being stored.
9797   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9798   //    that would create a cycle.
9799   // 4) All uses are load / store ops that use it as old base ptr.
9800 
9801   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9802   // (plus the implicit offset) to a register to preinc anyway.
9803   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9804     return false;
9805 
9806   // Check #2.
9807   if (!isLoad) {
9808     SDValue Val = cast<StoreSDNode>(N)->getValue();
9809     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9810       return false;
9811   }
9812 
9813   // Caches for hasPredecessorHelper.
9814   SmallPtrSet<const SDNode *, 32> Visited;
9815   SmallVector<const SDNode *, 16> Worklist;
9816   Worklist.push_back(N);
9817 
9818   // If the offset is a constant, there may be other adds of constants that
9819   // can be folded with this one. We should do this to avoid having to keep
9820   // a copy of the original base pointer.
9821   SmallVector<SDNode *, 16> OtherUses;
9822   if (isa<ConstantSDNode>(Offset))
9823     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9824                               UE = BasePtr.getNode()->use_end();
9825          UI != UE; ++UI) {
9826       SDUse &Use = UI.getUse();
9827       // Skip the use that is Ptr and uses of other results from BasePtr's
9828       // node (important for nodes that return multiple results).
9829       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9830         continue;
9831 
9832       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9833         continue;
9834 
9835       if (Use.getUser()->getOpcode() != ISD::ADD &&
9836           Use.getUser()->getOpcode() != ISD::SUB) {
9837         OtherUses.clear();
9838         break;
9839       }
9840 
9841       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9842       if (!isa<ConstantSDNode>(Op1)) {
9843         OtherUses.clear();
9844         break;
9845       }
9846 
9847       // FIXME: In some cases, we can be smarter about this.
9848       if (Op1.getValueType() != Offset.getValueType()) {
9849         OtherUses.clear();
9850         break;
9851       }
9852 
9853       OtherUses.push_back(Use.getUser());
9854     }
9855 
9856   if (Swapped)
9857     std::swap(BasePtr, Offset);
9858 
9859   // Now check for #3 and #4.
9860   bool RealUse = false;
9861 
9862   for (SDNode *Use : Ptr.getNode()->uses()) {
9863     if (Use == N)
9864       continue;
9865     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9866       return false;
9867 
9868     // If Ptr may be folded in addressing mode of other use, then it's
9869     // not profitable to do this transformation.
9870     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9871       RealUse = true;
9872   }
9873 
9874   if (!RealUse)
9875     return false;
9876 
9877   SDValue Result;
9878   if (isLoad)
9879     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9880                                 BasePtr, Offset, AM);
9881   else
9882     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9883                                  BasePtr, Offset, AM);
9884   ++PreIndexedNodes;
9885   ++NodesCombined;
9886   DEBUG(dbgs() << "\nReplacing.4 ";
9887         N->dump(&DAG);
9888         dbgs() << "\nWith: ";
9889         Result.getNode()->dump(&DAG);
9890         dbgs() << '\n');
9891   WorklistRemover DeadNodes(*this);
9892   if (isLoad) {
9893     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9894     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9895   } else {
9896     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9897   }
9898 
9899   // Finally, since the node is now dead, remove it from the graph.
9900   deleteAndRecombine(N);
9901 
9902   if (Swapped)
9903     std::swap(BasePtr, Offset);
9904 
9905   // Replace other uses of BasePtr that can be updated to use Ptr
9906   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9907     unsigned OffsetIdx = 1;
9908     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9909       OffsetIdx = 0;
9910     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9911            BasePtr.getNode() && "Expected BasePtr operand");
9912 
9913     // We need to replace ptr0 in the following expression:
9914     //   x0 * offset0 + y0 * ptr0 = t0
9915     // knowing that
9916     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9917     //
9918     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9919     // indexed load/store and the expresion that needs to be re-written.
9920     //
9921     // Therefore, we have:
9922     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9923 
9924     ConstantSDNode *CN =
9925       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9926     int X0, X1, Y0, Y1;
9927     const APInt &Offset0 = CN->getAPIntValue();
9928     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9929 
9930     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9931     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9932     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9933     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9934 
9935     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9936 
9937     APInt CNV = Offset0;
9938     if (X0 < 0) CNV = -CNV;
9939     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9940     else CNV = CNV - Offset1;
9941 
9942     SDLoc DL(OtherUses[i]);
9943 
9944     // We can now generate the new expression.
9945     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9946     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9947 
9948     SDValue NewUse = DAG.getNode(Opcode,
9949                                  DL,
9950                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9951     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9952     deleteAndRecombine(OtherUses[i]);
9953   }
9954 
9955   // Replace the uses of Ptr with uses of the updated base value.
9956   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9957   deleteAndRecombine(Ptr.getNode());
9958 
9959   return true;
9960 }
9961 
9962 /// Try to combine a load/store with a add/sub of the base pointer node into a
9963 /// post-indexed load/store. The transformation folded the add/subtract into the
9964 /// new indexed load/store effectively and all of its uses are redirected to the
9965 /// new load/store.
9966 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9967   if (Level < AfterLegalizeDAG)
9968     return false;
9969 
9970   bool isLoad = true;
9971   SDValue Ptr;
9972   EVT VT;
9973   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9974     if (LD->isIndexed())
9975       return false;
9976     VT = LD->getMemoryVT();
9977     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9978         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9979       return false;
9980     Ptr = LD->getBasePtr();
9981   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9982     if (ST->isIndexed())
9983       return false;
9984     VT = ST->getMemoryVT();
9985     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9986         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9987       return false;
9988     Ptr = ST->getBasePtr();
9989     isLoad = false;
9990   } else {
9991     return false;
9992   }
9993 
9994   if (Ptr.getNode()->hasOneUse())
9995     return false;
9996 
9997   for (SDNode *Op : Ptr.getNode()->uses()) {
9998     if (Op == N ||
9999         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10000       continue;
10001 
10002     SDValue BasePtr;
10003     SDValue Offset;
10004     ISD::MemIndexedMode AM = ISD::UNINDEXED;
10005     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10006       // Don't create a indexed load / store with zero offset.
10007       if (isNullConstant(Offset))
10008         continue;
10009 
10010       // Try turning it into a post-indexed load / store except when
10011       // 1) All uses are load / store ops that use it as base ptr (and
10012       //    it may be folded as addressing mmode).
10013       // 2) Op must be independent of N, i.e. Op is neither a predecessor
10014       //    nor a successor of N. Otherwise, if Op is folded that would
10015       //    create a cycle.
10016 
10017       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10018         continue;
10019 
10020       // Check for #1.
10021       bool TryNext = false;
10022       for (SDNode *Use : BasePtr.getNode()->uses()) {
10023         if (Use == Ptr.getNode())
10024           continue;
10025 
10026         // If all the uses are load / store addresses, then don't do the
10027         // transformation.
10028         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10029           bool RealUse = false;
10030           for (SDNode *UseUse : Use->uses()) {
10031             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10032               RealUse = true;
10033           }
10034 
10035           if (!RealUse) {
10036             TryNext = true;
10037             break;
10038           }
10039         }
10040       }
10041 
10042       if (TryNext)
10043         continue;
10044 
10045       // Check for #2
10046       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10047         SDValue Result = isLoad
10048           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10049                                BasePtr, Offset, AM)
10050           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10051                                 BasePtr, Offset, AM);
10052         ++PostIndexedNodes;
10053         ++NodesCombined;
10054         DEBUG(dbgs() << "\nReplacing.5 ";
10055               N->dump(&DAG);
10056               dbgs() << "\nWith: ";
10057               Result.getNode()->dump(&DAG);
10058               dbgs() << '\n');
10059         WorklistRemover DeadNodes(*this);
10060         if (isLoad) {
10061           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10062           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10063         } else {
10064           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10065         }
10066 
10067         // Finally, since the node is now dead, remove it from the graph.
10068         deleteAndRecombine(N);
10069 
10070         // Replace the uses of Use with uses of the updated base value.
10071         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10072                                       Result.getValue(isLoad ? 1 : 0));
10073         deleteAndRecombine(Op);
10074         return true;
10075       }
10076     }
10077   }
10078 
10079   return false;
10080 }
10081 
10082 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10083 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10084   ISD::MemIndexedMode AM = LD->getAddressingMode();
10085   assert(AM != ISD::UNINDEXED);
10086   SDValue BP = LD->getOperand(1);
10087   SDValue Inc = LD->getOperand(2);
10088 
10089   // Some backends use TargetConstants for load offsets, but don't expect
10090   // TargetConstants in general ADD nodes. We can convert these constants into
10091   // regular Constants (if the constant is not opaque).
10092   assert((Inc.getOpcode() != ISD::TargetConstant ||
10093           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10094          "Cannot split out indexing using opaque target constants");
10095   if (Inc.getOpcode() == ISD::TargetConstant) {
10096     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10097     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10098                           ConstInc->getValueType(0));
10099   }
10100 
10101   unsigned Opc =
10102       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10103   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10104 }
10105 
10106 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10107   LoadSDNode *LD  = cast<LoadSDNode>(N);
10108   SDValue Chain = LD->getChain();
10109   SDValue Ptr   = LD->getBasePtr();
10110 
10111   // If load is not volatile and there are no uses of the loaded value (and
10112   // the updated indexed value in case of indexed loads), change uses of the
10113   // chain value into uses of the chain input (i.e. delete the dead load).
10114   if (!LD->isVolatile()) {
10115     if (N->getValueType(1) == MVT::Other) {
10116       // Unindexed loads.
10117       if (!N->hasAnyUseOfValue(0)) {
10118         // It's not safe to use the two value CombineTo variant here. e.g.
10119         // v1, chain2 = load chain1, loc
10120         // v2, chain3 = load chain2, loc
10121         // v3         = add v2, c
10122         // Now we replace use of chain2 with chain1.  This makes the second load
10123         // isomorphic to the one we are deleting, and thus makes this load live.
10124         DEBUG(dbgs() << "\nReplacing.6 ";
10125               N->dump(&DAG);
10126               dbgs() << "\nWith chain: ";
10127               Chain.getNode()->dump(&DAG);
10128               dbgs() << "\n");
10129         WorklistRemover DeadNodes(*this);
10130         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10131 
10132         if (N->use_empty())
10133           deleteAndRecombine(N);
10134 
10135         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10136       }
10137     } else {
10138       // Indexed loads.
10139       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10140 
10141       // If this load has an opaque TargetConstant offset, then we cannot split
10142       // the indexing into an add/sub directly (that TargetConstant may not be
10143       // valid for a different type of node, and we cannot convert an opaque
10144       // target constant into a regular constant).
10145       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10146                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10147 
10148       if (!N->hasAnyUseOfValue(0) &&
10149           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10150         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10151         SDValue Index;
10152         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10153           Index = SplitIndexingFromLoad(LD);
10154           // Try to fold the base pointer arithmetic into subsequent loads and
10155           // stores.
10156           AddUsersToWorklist(N);
10157         } else
10158           Index = DAG.getUNDEF(N->getValueType(1));
10159         DEBUG(dbgs() << "\nReplacing.7 ";
10160               N->dump(&DAG);
10161               dbgs() << "\nWith: ";
10162               Undef.getNode()->dump(&DAG);
10163               dbgs() << " and 2 other values\n");
10164         WorklistRemover DeadNodes(*this);
10165         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10166         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10167         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10168         deleteAndRecombine(N);
10169         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10170       }
10171     }
10172   }
10173 
10174   // If this load is directly stored, replace the load value with the stored
10175   // value.
10176   // TODO: Handle store large -> read small portion.
10177   // TODO: Handle TRUNCSTORE/LOADEXT
10178   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
10179     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10180       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10181       if (PrevST->getBasePtr() == Ptr &&
10182           PrevST->getValue().getValueType() == N->getValueType(0))
10183       return CombineTo(N, Chain.getOperand(1), Chain);
10184     }
10185   }
10186 
10187   // Try to infer better alignment information than the load already has.
10188   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10189     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10190       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10191         SDValue NewLoad = DAG.getExtLoad(
10192             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
10193             LD->getPointerInfo(), LD->getMemoryVT(), Align,
10194             LD->getMemOperand()->getFlags(), LD->getAAInfo());
10195         if (NewLoad.getNode() != N)
10196           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10197       }
10198     }
10199   }
10200 
10201   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10202                                                   : DAG.getSubtarget().useAA();
10203 #ifndef NDEBUG
10204   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10205       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10206     UseAA = false;
10207 #endif
10208   if (UseAA && LD->isUnindexed()) {
10209     // Walk up chain skipping non-aliasing memory nodes.
10210     SDValue BetterChain = FindBetterChain(N, Chain);
10211 
10212     // If there is a better chain.
10213     if (Chain != BetterChain) {
10214       SDValue ReplLoad;
10215 
10216       // Replace the chain to void dependency.
10217       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10218         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10219                                BetterChain, Ptr, LD->getMemOperand());
10220       } else {
10221         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10222                                   LD->getValueType(0),
10223                                   BetterChain, Ptr, LD->getMemoryVT(),
10224                                   LD->getMemOperand());
10225       }
10226 
10227       // Create token factor to keep old chain connected.
10228       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10229                                   MVT::Other, Chain, ReplLoad.getValue(1));
10230 
10231       // Make sure the new and old chains are cleaned up.
10232       AddToWorklist(Token.getNode());
10233 
10234       // Replace uses with load result and token factor. Don't add users
10235       // to work list.
10236       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10237     }
10238   }
10239 
10240   // Try transforming N to an indexed load.
10241   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10242     return SDValue(N, 0);
10243 
10244   // Try to slice up N to more direct loads if the slices are mapped to
10245   // different register banks or pairing can take place.
10246   if (SliceUpLoad(N))
10247     return SDValue(N, 0);
10248 
10249   return SDValue();
10250 }
10251 
10252 namespace {
10253 /// \brief Helper structure used to slice a load in smaller loads.
10254 /// Basically a slice is obtained from the following sequence:
10255 /// Origin = load Ty1, Base
10256 /// Shift = srl Ty1 Origin, CstTy Amount
10257 /// Inst = trunc Shift to Ty2
10258 ///
10259 /// Then, it will be rewriten into:
10260 /// Slice = load SliceTy, Base + SliceOffset
10261 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10262 ///
10263 /// SliceTy is deduced from the number of bits that are actually used to
10264 /// build Inst.
10265 struct LoadedSlice {
10266   /// \brief Helper structure used to compute the cost of a slice.
10267   struct Cost {
10268     /// Are we optimizing for code size.
10269     bool ForCodeSize;
10270     /// Various cost.
10271     unsigned Loads;
10272     unsigned Truncates;
10273     unsigned CrossRegisterBanksCopies;
10274     unsigned ZExts;
10275     unsigned Shift;
10276 
10277     Cost(bool ForCodeSize = false)
10278         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10279           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10280 
10281     /// \brief Get the cost of one isolated slice.
10282     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10283         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10284           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10285       EVT TruncType = LS.Inst->getValueType(0);
10286       EVT LoadedType = LS.getLoadedType();
10287       if (TruncType != LoadedType &&
10288           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10289         ZExts = 1;
10290     }
10291 
10292     /// \brief Account for slicing gain in the current cost.
10293     /// Slicing provide a few gains like removing a shift or a
10294     /// truncate. This method allows to grow the cost of the original
10295     /// load with the gain from this slice.
10296     void addSliceGain(const LoadedSlice &LS) {
10297       // Each slice saves a truncate.
10298       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10299       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10300                               LS.Inst->getValueType(0)))
10301         ++Truncates;
10302       // If there is a shift amount, this slice gets rid of it.
10303       if (LS.Shift)
10304         ++Shift;
10305       // If this slice can merge a cross register bank copy, account for it.
10306       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10307         ++CrossRegisterBanksCopies;
10308     }
10309 
10310     Cost &operator+=(const Cost &RHS) {
10311       Loads += RHS.Loads;
10312       Truncates += RHS.Truncates;
10313       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10314       ZExts += RHS.ZExts;
10315       Shift += RHS.Shift;
10316       return *this;
10317     }
10318 
10319     bool operator==(const Cost &RHS) const {
10320       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10321              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10322              ZExts == RHS.ZExts && Shift == RHS.Shift;
10323     }
10324 
10325     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10326 
10327     bool operator<(const Cost &RHS) const {
10328       // Assume cross register banks copies are as expensive as loads.
10329       // FIXME: Do we want some more target hooks?
10330       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10331       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10332       // Unless we are optimizing for code size, consider the
10333       // expensive operation first.
10334       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10335         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10336       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10337              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10338     }
10339 
10340     bool operator>(const Cost &RHS) const { return RHS < *this; }
10341 
10342     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10343 
10344     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10345   };
10346   // The last instruction that represent the slice. This should be a
10347   // truncate instruction.
10348   SDNode *Inst;
10349   // The original load instruction.
10350   LoadSDNode *Origin;
10351   // The right shift amount in bits from the original load.
10352   unsigned Shift;
10353   // The DAG from which Origin came from.
10354   // This is used to get some contextual information about legal types, etc.
10355   SelectionDAG *DAG;
10356 
10357   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10358               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10359       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10360 
10361   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10362   /// \return Result is \p BitWidth and has used bits set to 1 and
10363   ///         not used bits set to 0.
10364   APInt getUsedBits() const {
10365     // Reproduce the trunc(lshr) sequence:
10366     // - Start from the truncated value.
10367     // - Zero extend to the desired bit width.
10368     // - Shift left.
10369     assert(Origin && "No original load to compare against.");
10370     unsigned BitWidth = Origin->getValueSizeInBits(0);
10371     assert(Inst && "This slice is not bound to an instruction");
10372     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10373            "Extracted slice is bigger than the whole type!");
10374     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10375     UsedBits.setAllBits();
10376     UsedBits = UsedBits.zext(BitWidth);
10377     UsedBits <<= Shift;
10378     return UsedBits;
10379   }
10380 
10381   /// \brief Get the size of the slice to be loaded in bytes.
10382   unsigned getLoadedSize() const {
10383     unsigned SliceSize = getUsedBits().countPopulation();
10384     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10385     return SliceSize / 8;
10386   }
10387 
10388   /// \brief Get the type that will be loaded for this slice.
10389   /// Note: This may not be the final type for the slice.
10390   EVT getLoadedType() const {
10391     assert(DAG && "Missing context");
10392     LLVMContext &Ctxt = *DAG->getContext();
10393     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10394   }
10395 
10396   /// \brief Get the alignment of the load used for this slice.
10397   unsigned getAlignment() const {
10398     unsigned Alignment = Origin->getAlignment();
10399     unsigned Offset = getOffsetFromBase();
10400     if (Offset != 0)
10401       Alignment = MinAlign(Alignment, Alignment + Offset);
10402     return Alignment;
10403   }
10404 
10405   /// \brief Check if this slice can be rewritten with legal operations.
10406   bool isLegal() const {
10407     // An invalid slice is not legal.
10408     if (!Origin || !Inst || !DAG)
10409       return false;
10410 
10411     // Offsets are for indexed load only, we do not handle that.
10412     if (!Origin->getOffset().isUndef())
10413       return false;
10414 
10415     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10416 
10417     // Check that the type is legal.
10418     EVT SliceType = getLoadedType();
10419     if (!TLI.isTypeLegal(SliceType))
10420       return false;
10421 
10422     // Check that the load is legal for this type.
10423     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10424       return false;
10425 
10426     // Check that the offset can be computed.
10427     // 1. Check its type.
10428     EVT PtrType = Origin->getBasePtr().getValueType();
10429     if (PtrType == MVT::Untyped || PtrType.isExtended())
10430       return false;
10431 
10432     // 2. Check that it fits in the immediate.
10433     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10434       return false;
10435 
10436     // 3. Check that the computation is legal.
10437     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10438       return false;
10439 
10440     // Check that the zext is legal if it needs one.
10441     EVT TruncateType = Inst->getValueType(0);
10442     if (TruncateType != SliceType &&
10443         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10444       return false;
10445 
10446     return true;
10447   }
10448 
10449   /// \brief Get the offset in bytes of this slice in the original chunk of
10450   /// bits.
10451   /// \pre DAG != nullptr.
10452   uint64_t getOffsetFromBase() const {
10453     assert(DAG && "Missing context.");
10454     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10455     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10456     uint64_t Offset = Shift / 8;
10457     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10458     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10459            "The size of the original loaded type is not a multiple of a"
10460            " byte.");
10461     // If Offset is bigger than TySizeInBytes, it means we are loading all
10462     // zeros. This should have been optimized before in the process.
10463     assert(TySizeInBytes > Offset &&
10464            "Invalid shift amount for given loaded size");
10465     if (IsBigEndian)
10466       Offset = TySizeInBytes - Offset - getLoadedSize();
10467     return Offset;
10468   }
10469 
10470   /// \brief Generate the sequence of instructions to load the slice
10471   /// represented by this object and redirect the uses of this slice to
10472   /// this new sequence of instructions.
10473   /// \pre this->Inst && this->Origin are valid Instructions and this
10474   /// object passed the legal check: LoadedSlice::isLegal returned true.
10475   /// \return The last instruction of the sequence used to load the slice.
10476   SDValue loadSlice() const {
10477     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10478     const SDValue &OldBaseAddr = Origin->getBasePtr();
10479     SDValue BaseAddr = OldBaseAddr;
10480     // Get the offset in that chunk of bytes w.r.t. the endianess.
10481     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10482     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10483     if (Offset) {
10484       // BaseAddr = BaseAddr + Offset.
10485       EVT ArithType = BaseAddr.getValueType();
10486       SDLoc DL(Origin);
10487       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10488                               DAG->getConstant(Offset, DL, ArithType));
10489     }
10490 
10491     // Create the type of the loaded slice according to its size.
10492     EVT SliceType = getLoadedType();
10493 
10494     // Create the load for the slice.
10495     SDValue LastInst =
10496         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10497                      Origin->getPointerInfo().getWithOffset(Offset),
10498                      getAlignment(), Origin->getMemOperand()->getFlags());
10499     // If the final type is not the same as the loaded type, this means that
10500     // we have to pad with zero. Create a zero extend for that.
10501     EVT FinalType = Inst->getValueType(0);
10502     if (SliceType != FinalType)
10503       LastInst =
10504           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10505     return LastInst;
10506   }
10507 
10508   /// \brief Check if this slice can be merged with an expensive cross register
10509   /// bank copy. E.g.,
10510   /// i = load i32
10511   /// f = bitcast i32 i to float
10512   bool canMergeExpensiveCrossRegisterBankCopy() const {
10513     if (!Inst || !Inst->hasOneUse())
10514       return false;
10515     SDNode *Use = *Inst->use_begin();
10516     if (Use->getOpcode() != ISD::BITCAST)
10517       return false;
10518     assert(DAG && "Missing context");
10519     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10520     EVT ResVT = Use->getValueType(0);
10521     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10522     const TargetRegisterClass *ArgRC =
10523         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10524     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10525       return false;
10526 
10527     // At this point, we know that we perform a cross-register-bank copy.
10528     // Check if it is expensive.
10529     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10530     // Assume bitcasts are cheap, unless both register classes do not
10531     // explicitly share a common sub class.
10532     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10533       return false;
10534 
10535     // Check if it will be merged with the load.
10536     // 1. Check the alignment constraint.
10537     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10538         ResVT.getTypeForEVT(*DAG->getContext()));
10539 
10540     if (RequiredAlignment > getAlignment())
10541       return false;
10542 
10543     // 2. Check that the load is a legal operation for that type.
10544     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10545       return false;
10546 
10547     // 3. Check that we do not have a zext in the way.
10548     if (Inst->getValueType(0) != getLoadedType())
10549       return false;
10550 
10551     return true;
10552   }
10553 };
10554 }
10555 
10556 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10557 /// \p UsedBits looks like 0..0 1..1 0..0.
10558 static bool areUsedBitsDense(const APInt &UsedBits) {
10559   // If all the bits are one, this is dense!
10560   if (UsedBits.isAllOnesValue())
10561     return true;
10562 
10563   // Get rid of the unused bits on the right.
10564   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10565   // Get rid of the unused bits on the left.
10566   if (NarrowedUsedBits.countLeadingZeros())
10567     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10568   // Check that the chunk of bits is completely used.
10569   return NarrowedUsedBits.isAllOnesValue();
10570 }
10571 
10572 /// \brief Check whether or not \p First and \p Second are next to each other
10573 /// in memory. This means that there is no hole between the bits loaded
10574 /// by \p First and the bits loaded by \p Second.
10575 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10576                                      const LoadedSlice &Second) {
10577   assert(First.Origin == Second.Origin && First.Origin &&
10578          "Unable to match different memory origins.");
10579   APInt UsedBits = First.getUsedBits();
10580   assert((UsedBits & Second.getUsedBits()) == 0 &&
10581          "Slices are not supposed to overlap.");
10582   UsedBits |= Second.getUsedBits();
10583   return areUsedBitsDense(UsedBits);
10584 }
10585 
10586 /// \brief Adjust the \p GlobalLSCost according to the target
10587 /// paring capabilities and the layout of the slices.
10588 /// \pre \p GlobalLSCost should account for at least as many loads as
10589 /// there is in the slices in \p LoadedSlices.
10590 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10591                                  LoadedSlice::Cost &GlobalLSCost) {
10592   unsigned NumberOfSlices = LoadedSlices.size();
10593   // If there is less than 2 elements, no pairing is possible.
10594   if (NumberOfSlices < 2)
10595     return;
10596 
10597   // Sort the slices so that elements that are likely to be next to each
10598   // other in memory are next to each other in the list.
10599   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10600             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10601     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10602     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10603   });
10604   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10605   // First (resp. Second) is the first (resp. Second) potentially candidate
10606   // to be placed in a paired load.
10607   const LoadedSlice *First = nullptr;
10608   const LoadedSlice *Second = nullptr;
10609   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10610                 // Set the beginning of the pair.
10611                                                            First = Second) {
10612 
10613     Second = &LoadedSlices[CurrSlice];
10614 
10615     // If First is NULL, it means we start a new pair.
10616     // Get to the next slice.
10617     if (!First)
10618       continue;
10619 
10620     EVT LoadedType = First->getLoadedType();
10621 
10622     // If the types of the slices are different, we cannot pair them.
10623     if (LoadedType != Second->getLoadedType())
10624       continue;
10625 
10626     // Check if the target supplies paired loads for this type.
10627     unsigned RequiredAlignment = 0;
10628     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10629       // move to the next pair, this type is hopeless.
10630       Second = nullptr;
10631       continue;
10632     }
10633     // Check if we meet the alignment requirement.
10634     if (RequiredAlignment > First->getAlignment())
10635       continue;
10636 
10637     // Check that both loads are next to each other in memory.
10638     if (!areSlicesNextToEachOther(*First, *Second))
10639       continue;
10640 
10641     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10642     --GlobalLSCost.Loads;
10643     // Move to the next pair.
10644     Second = nullptr;
10645   }
10646 }
10647 
10648 /// \brief Check the profitability of all involved LoadedSlice.
10649 /// Currently, it is considered profitable if there is exactly two
10650 /// involved slices (1) which are (2) next to each other in memory, and
10651 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10652 ///
10653 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10654 /// the elements themselves.
10655 ///
10656 /// FIXME: When the cost model will be mature enough, we can relax
10657 /// constraints (1) and (2).
10658 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10659                                 const APInt &UsedBits, bool ForCodeSize) {
10660   unsigned NumberOfSlices = LoadedSlices.size();
10661   if (StressLoadSlicing)
10662     return NumberOfSlices > 1;
10663 
10664   // Check (1).
10665   if (NumberOfSlices != 2)
10666     return false;
10667 
10668   // Check (2).
10669   if (!areUsedBitsDense(UsedBits))
10670     return false;
10671 
10672   // Check (3).
10673   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10674   // The original code has one big load.
10675   OrigCost.Loads = 1;
10676   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10677     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10678     // Accumulate the cost of all the slices.
10679     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10680     GlobalSlicingCost += SliceCost;
10681 
10682     // Account as cost in the original configuration the gain obtained
10683     // with the current slices.
10684     OrigCost.addSliceGain(LS);
10685   }
10686 
10687   // If the target supports paired load, adjust the cost accordingly.
10688   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10689   return OrigCost > GlobalSlicingCost;
10690 }
10691 
10692 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10693 /// operations, split it in the various pieces being extracted.
10694 ///
10695 /// This sort of thing is introduced by SROA.
10696 /// This slicing takes care not to insert overlapping loads.
10697 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10698 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10699   if (Level < AfterLegalizeDAG)
10700     return false;
10701 
10702   LoadSDNode *LD = cast<LoadSDNode>(N);
10703   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10704       !LD->getValueType(0).isInteger())
10705     return false;
10706 
10707   // Keep track of already used bits to detect overlapping values.
10708   // In that case, we will just abort the transformation.
10709   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10710 
10711   SmallVector<LoadedSlice, 4> LoadedSlices;
10712 
10713   // Check if this load is used as several smaller chunks of bits.
10714   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10715   // of computation for each trunc.
10716   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10717        UI != UIEnd; ++UI) {
10718     // Skip the uses of the chain.
10719     if (UI.getUse().getResNo() != 0)
10720       continue;
10721 
10722     SDNode *User = *UI;
10723     unsigned Shift = 0;
10724 
10725     // Check if this is a trunc(lshr).
10726     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10727         isa<ConstantSDNode>(User->getOperand(1))) {
10728       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10729       User = *User->use_begin();
10730     }
10731 
10732     // At this point, User is a Truncate, iff we encountered, trunc or
10733     // trunc(lshr).
10734     if (User->getOpcode() != ISD::TRUNCATE)
10735       return false;
10736 
10737     // The width of the type must be a power of 2 and greater than 8-bits.
10738     // Otherwise the load cannot be represented in LLVM IR.
10739     // Moreover, if we shifted with a non-8-bits multiple, the slice
10740     // will be across several bytes. We do not support that.
10741     unsigned Width = User->getValueSizeInBits(0);
10742     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10743       return 0;
10744 
10745     // Build the slice for this chain of computations.
10746     LoadedSlice LS(User, LD, Shift, &DAG);
10747     APInt CurrentUsedBits = LS.getUsedBits();
10748 
10749     // Check if this slice overlaps with another.
10750     if ((CurrentUsedBits & UsedBits) != 0)
10751       return false;
10752     // Update the bits used globally.
10753     UsedBits |= CurrentUsedBits;
10754 
10755     // Check if the new slice would be legal.
10756     if (!LS.isLegal())
10757       return false;
10758 
10759     // Record the slice.
10760     LoadedSlices.push_back(LS);
10761   }
10762 
10763   // Abort slicing if it does not seem to be profitable.
10764   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10765     return false;
10766 
10767   ++SlicedLoads;
10768 
10769   // Rewrite each chain to use an independent load.
10770   // By construction, each chain can be represented by a unique load.
10771 
10772   // Prepare the argument for the new token factor for all the slices.
10773   SmallVector<SDValue, 8> ArgChains;
10774   for (SmallVectorImpl<LoadedSlice>::const_iterator
10775            LSIt = LoadedSlices.begin(),
10776            LSItEnd = LoadedSlices.end();
10777        LSIt != LSItEnd; ++LSIt) {
10778     SDValue SliceInst = LSIt->loadSlice();
10779     CombineTo(LSIt->Inst, SliceInst, true);
10780     if (SliceInst.getOpcode() != ISD::LOAD)
10781       SliceInst = SliceInst.getOperand(0);
10782     assert(SliceInst->getOpcode() == ISD::LOAD &&
10783            "It takes more than a zext to get to the loaded slice!!");
10784     ArgChains.push_back(SliceInst.getValue(1));
10785   }
10786 
10787   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10788                               ArgChains);
10789   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10790   return true;
10791 }
10792 
10793 /// Check to see if V is (and load (ptr), imm), where the load is having
10794 /// specific bytes cleared out.  If so, return the byte size being masked out
10795 /// and the shift amount.
10796 static std::pair<unsigned, unsigned>
10797 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10798   std::pair<unsigned, unsigned> Result(0, 0);
10799 
10800   // Check for the structure we're looking for.
10801   if (V->getOpcode() != ISD::AND ||
10802       !isa<ConstantSDNode>(V->getOperand(1)) ||
10803       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10804     return Result;
10805 
10806   // Check the chain and pointer.
10807   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10808   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10809 
10810   // The store should be chained directly to the load or be an operand of a
10811   // tokenfactor.
10812   if (LD == Chain.getNode())
10813     ; // ok.
10814   else if (Chain->getOpcode() != ISD::TokenFactor)
10815     return Result; // Fail.
10816   else {
10817     bool isOk = false;
10818     for (const SDValue &ChainOp : Chain->op_values())
10819       if (ChainOp.getNode() == LD) {
10820         isOk = true;
10821         break;
10822       }
10823     if (!isOk) return Result;
10824   }
10825 
10826   // This only handles simple types.
10827   if (V.getValueType() != MVT::i16 &&
10828       V.getValueType() != MVT::i32 &&
10829       V.getValueType() != MVT::i64)
10830     return Result;
10831 
10832   // Check the constant mask.  Invert it so that the bits being masked out are
10833   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10834   // follow the sign bit for uniformity.
10835   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10836   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10837   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10838   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10839   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10840   if (NotMaskLZ == 64) return Result;  // All zero mask.
10841 
10842   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10843   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10844     return Result;
10845 
10846   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10847   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10848     NotMaskLZ -= 64-V.getValueSizeInBits();
10849 
10850   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10851   switch (MaskedBytes) {
10852   case 1:
10853   case 2:
10854   case 4: break;
10855   default: return Result; // All one mask, or 5-byte mask.
10856   }
10857 
10858   // Verify that the first bit starts at a multiple of mask so that the access
10859   // is aligned the same as the access width.
10860   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10861 
10862   Result.first = MaskedBytes;
10863   Result.second = NotMaskTZ/8;
10864   return Result;
10865 }
10866 
10867 
10868 /// Check to see if IVal is something that provides a value as specified by
10869 /// MaskInfo. If so, replace the specified store with a narrower store of
10870 /// truncated IVal.
10871 static SDNode *
10872 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10873                                 SDValue IVal, StoreSDNode *St,
10874                                 DAGCombiner *DC) {
10875   unsigned NumBytes = MaskInfo.first;
10876   unsigned ByteShift = MaskInfo.second;
10877   SelectionDAG &DAG = DC->getDAG();
10878 
10879   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10880   // that uses this.  If not, this is not a replacement.
10881   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10882                                   ByteShift*8, (ByteShift+NumBytes)*8);
10883   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10884 
10885   // Check that it is legal on the target to do this.  It is legal if the new
10886   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10887   // legalization.
10888   MVT VT = MVT::getIntegerVT(NumBytes*8);
10889   if (!DC->isTypeLegal(VT))
10890     return nullptr;
10891 
10892   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10893   // shifted by ByteShift and truncated down to NumBytes.
10894   if (ByteShift) {
10895     SDLoc DL(IVal);
10896     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10897                        DAG.getConstant(ByteShift*8, DL,
10898                                     DC->getShiftAmountTy(IVal.getValueType())));
10899   }
10900 
10901   // Figure out the offset for the store and the alignment of the access.
10902   unsigned StOffset;
10903   unsigned NewAlign = St->getAlignment();
10904 
10905   if (DAG.getDataLayout().isLittleEndian())
10906     StOffset = ByteShift;
10907   else
10908     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10909 
10910   SDValue Ptr = St->getBasePtr();
10911   if (StOffset) {
10912     SDLoc DL(IVal);
10913     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10914                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10915     NewAlign = MinAlign(NewAlign, StOffset);
10916   }
10917 
10918   // Truncate down to the new size.
10919   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10920 
10921   ++OpsNarrowed;
10922   return DAG
10923       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10924                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
10925       .getNode();
10926 }
10927 
10928 
10929 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10930 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10931 /// narrowing the load and store if it would end up being a win for performance
10932 /// or code size.
10933 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10934   StoreSDNode *ST  = cast<StoreSDNode>(N);
10935   if (ST->isVolatile())
10936     return SDValue();
10937 
10938   SDValue Chain = ST->getChain();
10939   SDValue Value = ST->getValue();
10940   SDValue Ptr   = ST->getBasePtr();
10941   EVT VT = Value.getValueType();
10942 
10943   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10944     return SDValue();
10945 
10946   unsigned Opc = Value.getOpcode();
10947 
10948   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10949   // is a byte mask indicating a consecutive number of bytes, check to see if
10950   // Y is known to provide just those bytes.  If so, we try to replace the
10951   // load + replace + store sequence with a single (narrower) store, which makes
10952   // the load dead.
10953   if (Opc == ISD::OR) {
10954     std::pair<unsigned, unsigned> MaskedLoad;
10955     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10956     if (MaskedLoad.first)
10957       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10958                                                   Value.getOperand(1), ST,this))
10959         return SDValue(NewST, 0);
10960 
10961     // Or is commutative, so try swapping X and Y.
10962     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10963     if (MaskedLoad.first)
10964       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10965                                                   Value.getOperand(0), ST,this))
10966         return SDValue(NewST, 0);
10967   }
10968 
10969   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10970       Value.getOperand(1).getOpcode() != ISD::Constant)
10971     return SDValue();
10972 
10973   SDValue N0 = Value.getOperand(0);
10974   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10975       Chain == SDValue(N0.getNode(), 1)) {
10976     LoadSDNode *LD = cast<LoadSDNode>(N0);
10977     if (LD->getBasePtr() != Ptr ||
10978         LD->getPointerInfo().getAddrSpace() !=
10979         ST->getPointerInfo().getAddrSpace())
10980       return SDValue();
10981 
10982     // Find the type to narrow it the load / op / store to.
10983     SDValue N1 = Value.getOperand(1);
10984     unsigned BitWidth = N1.getValueSizeInBits();
10985     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10986     if (Opc == ISD::AND)
10987       Imm ^= APInt::getAllOnesValue(BitWidth);
10988     if (Imm == 0 || Imm.isAllOnesValue())
10989       return SDValue();
10990     unsigned ShAmt = Imm.countTrailingZeros();
10991     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10992     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10993     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10994     // The narrowing should be profitable, the load/store operation should be
10995     // legal (or custom) and the store size should be equal to the NewVT width.
10996     while (NewBW < BitWidth &&
10997            (NewVT.getStoreSizeInBits() != NewBW ||
10998             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10999             !TLI.isNarrowingProfitable(VT, NewVT))) {
11000       NewBW = NextPowerOf2(NewBW);
11001       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11002     }
11003     if (NewBW >= BitWidth)
11004       return SDValue();
11005 
11006     // If the lsb changed does not start at the type bitwidth boundary,
11007     // start at the previous one.
11008     if (ShAmt % NewBW)
11009       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11010     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11011                                    std::min(BitWidth, ShAmt + NewBW));
11012     if ((Imm & Mask) == Imm) {
11013       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11014       if (Opc == ISD::AND)
11015         NewImm ^= APInt::getAllOnesValue(NewBW);
11016       uint64_t PtrOff = ShAmt / 8;
11017       // For big endian targets, we need to adjust the offset to the pointer to
11018       // load the correct bytes.
11019       if (DAG.getDataLayout().isBigEndian())
11020         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11021 
11022       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11023       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11024       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11025         return SDValue();
11026 
11027       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11028                                    Ptr.getValueType(), Ptr,
11029                                    DAG.getConstant(PtrOff, SDLoc(LD),
11030                                                    Ptr.getValueType()));
11031       SDValue NewLD =
11032           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11033                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11034                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
11035       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11036                                    DAG.getConstant(NewImm, SDLoc(Value),
11037                                                    NewVT));
11038       SDValue NewST =
11039           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11040                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11041 
11042       AddToWorklist(NewPtr.getNode());
11043       AddToWorklist(NewLD.getNode());
11044       AddToWorklist(NewVal.getNode());
11045       WorklistRemover DeadNodes(*this);
11046       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11047       ++OpsNarrowed;
11048       return NewST;
11049     }
11050   }
11051 
11052   return SDValue();
11053 }
11054 
11055 /// For a given floating point load / store pair, if the load value isn't used
11056 /// by any other operations, then consider transforming the pair to integer
11057 /// load / store operations if the target deems the transformation profitable.
11058 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11059   StoreSDNode *ST  = cast<StoreSDNode>(N);
11060   SDValue Chain = ST->getChain();
11061   SDValue Value = ST->getValue();
11062   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11063       Value.hasOneUse() &&
11064       Chain == SDValue(Value.getNode(), 1)) {
11065     LoadSDNode *LD = cast<LoadSDNode>(Value);
11066     EVT VT = LD->getMemoryVT();
11067     if (!VT.isFloatingPoint() ||
11068         VT != ST->getMemoryVT() ||
11069         LD->isNonTemporal() ||
11070         ST->isNonTemporal() ||
11071         LD->getPointerInfo().getAddrSpace() != 0 ||
11072         ST->getPointerInfo().getAddrSpace() != 0)
11073       return SDValue();
11074 
11075     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11076     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11077         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11078         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11079         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11080       return SDValue();
11081 
11082     unsigned LDAlign = LD->getAlignment();
11083     unsigned STAlign = ST->getAlignment();
11084     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11085     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11086     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11087       return SDValue();
11088 
11089     SDValue NewLD =
11090         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
11091                     LD->getPointerInfo(), LDAlign);
11092 
11093     SDValue NewST =
11094         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
11095                      ST->getPointerInfo(), STAlign);
11096 
11097     AddToWorklist(NewLD.getNode());
11098     AddToWorklist(NewST.getNode());
11099     WorklistRemover DeadNodes(*this);
11100     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11101     ++LdStFP2Int;
11102     return NewST;
11103   }
11104 
11105   return SDValue();
11106 }
11107 
11108 namespace {
11109 /// Helper struct to parse and store a memory address as base + index + offset.
11110 /// We ignore sign extensions when it is safe to do so.
11111 /// The following two expressions are not equivalent. To differentiate we need
11112 /// to store whether there was a sign extension involved in the index
11113 /// computation.
11114 ///  (load (i64 add (i64 copyfromreg %c)
11115 ///                 (i64 signextend (add (i8 load %index)
11116 ///                                      (i8 1))))
11117 /// vs
11118 ///
11119 /// (load (i64 add (i64 copyfromreg %c)
11120 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11121 ///                                         (i32 1)))))
11122 struct BaseIndexOffset {
11123   SDValue Base;
11124   SDValue Index;
11125   int64_t Offset;
11126   bool IsIndexSignExt;
11127 
11128   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11129 
11130   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11131                   bool IsIndexSignExt) :
11132     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11133 
11134   bool equalBaseIndex(const BaseIndexOffset &Other) {
11135     return Other.Base == Base && Other.Index == Index &&
11136       Other.IsIndexSignExt == IsIndexSignExt;
11137   }
11138 
11139   /// Parses tree in Ptr for base, index, offset addresses.
11140   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11141     bool IsIndexSignExt = false;
11142 
11143     // Split up a folded GlobalAddress+Offset into its component parts.
11144     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11145       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11146         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11147                                                     SDLoc(GA),
11148                                                     GA->getValueType(0),
11149                                                     /*Offset=*/0,
11150                                                     /*isTargetGA=*/false,
11151                                                     GA->getTargetFlags()),
11152                                SDValue(),
11153                                GA->getOffset(),
11154                                IsIndexSignExt);
11155       }
11156 
11157     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11158     // instruction, then it could be just the BASE or everything else we don't
11159     // know how to handle. Just use Ptr as BASE and give up.
11160     if (Ptr->getOpcode() != ISD::ADD)
11161       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11162 
11163     // We know that we have at least an ADD instruction. Try to pattern match
11164     // the simple case of BASE + OFFSET.
11165     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11166       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11167       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11168                               IsIndexSignExt);
11169     }
11170 
11171     // Inside a loop the current BASE pointer is calculated using an ADD and a
11172     // MUL instruction. In this case Ptr is the actual BASE pointer.
11173     // (i64 add (i64 %array_ptr)
11174     //          (i64 mul (i64 %induction_var)
11175     //                   (i64 %element_size)))
11176     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11177       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11178 
11179     // Look at Base + Index + Offset cases.
11180     SDValue Base = Ptr->getOperand(0);
11181     SDValue IndexOffset = Ptr->getOperand(1);
11182 
11183     // Skip signextends.
11184     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11185       IndexOffset = IndexOffset->getOperand(0);
11186       IsIndexSignExt = true;
11187     }
11188 
11189     // Either the case of Base + Index (no offset) or something else.
11190     if (IndexOffset->getOpcode() != ISD::ADD)
11191       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11192 
11193     // Now we have the case of Base + Index + offset.
11194     SDValue Index = IndexOffset->getOperand(0);
11195     SDValue Offset = IndexOffset->getOperand(1);
11196 
11197     if (!isa<ConstantSDNode>(Offset))
11198       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11199 
11200     // Ignore signextends.
11201     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11202       Index = Index->getOperand(0);
11203       IsIndexSignExt = true;
11204     } else IsIndexSignExt = false;
11205 
11206     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11207     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11208   }
11209 };
11210 } // namespace
11211 
11212 // This is a helper function for visitMUL to check the profitability
11213 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11214 // MulNode is the original multiply, AddNode is (add x, c1),
11215 // and ConstNode is c2.
11216 //
11217 // If the (add x, c1) has multiple uses, we could increase
11218 // the number of adds if we make this transformation.
11219 // It would only be worth doing this if we can remove a
11220 // multiply in the process. Check for that here.
11221 // To illustrate:
11222 //     (A + c1) * c3
11223 //     (A + c2) * c3
11224 // We're checking for cases where we have common "c3 * A" expressions.
11225 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11226                                               SDValue &AddNode,
11227                                               SDValue &ConstNode) {
11228   APInt Val;
11229 
11230   // If the add only has one use, this would be OK to do.
11231   if (AddNode.getNode()->hasOneUse())
11232     return true;
11233 
11234   // Walk all the users of the constant with which we're multiplying.
11235   for (SDNode *Use : ConstNode->uses()) {
11236 
11237     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11238       continue;
11239 
11240     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11241       SDNode *OtherOp;
11242       SDNode *MulVar = AddNode.getOperand(0).getNode();
11243 
11244       // OtherOp is what we're multiplying against the constant.
11245       if (Use->getOperand(0) == ConstNode)
11246         OtherOp = Use->getOperand(1).getNode();
11247       else
11248         OtherOp = Use->getOperand(0).getNode();
11249 
11250       // Check to see if multiply is with the same operand of our "add".
11251       //
11252       //     ConstNode  = CONST
11253       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11254       //     ...
11255       //     AddNode  = (A + c1)  <-- MulVar is A.
11256       //         = AddNode * ConstNode   <-- current visiting instruction.
11257       //
11258       // If we make this transformation, we will have a common
11259       // multiply (ConstNode * A) that we can save.
11260       if (OtherOp == MulVar)
11261         return true;
11262 
11263       // Now check to see if a future expansion will give us a common
11264       // multiply.
11265       //
11266       //     ConstNode  = CONST
11267       //     AddNode    = (A + c1)
11268       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11269       //     ...
11270       //     OtherOp = (A + c2)
11271       //     Use     = OtherOp * ConstNode <-- visiting Use.
11272       //
11273       // If we make this transformation, we will have a common
11274       // multiply (CONST * A) after we also do the same transformation
11275       // to the "t2" instruction.
11276       if (OtherOp->getOpcode() == ISD::ADD &&
11277           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11278           OtherOp->getOperand(0).getNode() == MulVar)
11279         return true;
11280     }
11281   }
11282 
11283   // Didn't find a case where this would be profitable.
11284   return false;
11285 }
11286 
11287 SDValue DAGCombiner::getMergedConstantVectorStore(
11288     SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores,
11289     SmallVectorImpl<SDValue> &Chains, EVT Ty) const {
11290   SmallVector<SDValue, 8> BuildVector;
11291 
11292   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11293     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11294     Chains.push_back(St->getChain());
11295     BuildVector.push_back(St->getValue());
11296   }
11297 
11298   return DAG.getBuildVector(Ty, SL, BuildVector);
11299 }
11300 
11301 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11302                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11303                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11304   // Make sure we have something to merge.
11305   if (NumStores < 2)
11306     return false;
11307 
11308   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11309   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11310   unsigned LatestNodeUsed = 0;
11311 
11312   for (unsigned i=0; i < NumStores; ++i) {
11313     // Find a chain for the new wide-store operand. Notice that some
11314     // of the store nodes that we found may not be selected for inclusion
11315     // in the wide store. The chain we use needs to be the chain of the
11316     // latest store node which is *used* and replaced by the wide store.
11317     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11318       LatestNodeUsed = i;
11319   }
11320 
11321   SmallVector<SDValue, 8> Chains;
11322 
11323   // The latest Node in the DAG.
11324   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11325   SDLoc DL(StoreNodes[0].MemNode);
11326 
11327   SDValue StoredVal;
11328   if (UseVector) {
11329     bool IsVec = MemVT.isVector();
11330     unsigned Elts = NumStores;
11331     if (IsVec) {
11332       // When merging vector stores, get the total number of elements.
11333       Elts *= MemVT.getVectorNumElements();
11334     }
11335     // Get the type for the merged vector store.
11336     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11337     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11338 
11339     if (IsConstantSrc) {
11340       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11341     } else {
11342       SmallVector<SDValue, 8> Ops;
11343       for (unsigned i = 0; i < NumStores; ++i) {
11344         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11345         SDValue Val = St->getValue();
11346         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11347         if (Val.getValueType() != MemVT)
11348           return false;
11349         Ops.push_back(Val);
11350         Chains.push_back(St->getChain());
11351       }
11352 
11353       // Build the extracted vector elements back into a vector.
11354       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11355                               DL, Ty, Ops);    }
11356   } else {
11357     // We should always use a vector store when merging extracted vector
11358     // elements, so this path implies a store of constants.
11359     assert(IsConstantSrc && "Merged vector elements should use vector store");
11360 
11361     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11362     APInt StoreInt(SizeInBits, 0);
11363 
11364     // Construct a single integer constant which is made of the smaller
11365     // constant inputs.
11366     bool IsLE = DAG.getDataLayout().isLittleEndian();
11367     for (unsigned i = 0; i < NumStores; ++i) {
11368       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11369       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11370       Chains.push_back(St->getChain());
11371 
11372       SDValue Val = St->getValue();
11373       StoreInt <<= ElementSizeBytes * 8;
11374       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11375         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11376       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11377         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11378       } else {
11379         llvm_unreachable("Invalid constant element type");
11380       }
11381     }
11382 
11383     // Create the new Load and Store operations.
11384     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11385     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11386   }
11387 
11388   assert(!Chains.empty());
11389 
11390   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11391   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11392                                   FirstInChain->getBasePtr(),
11393                                   FirstInChain->getPointerInfo(),
11394                                   FirstInChain->getAlignment());
11395 
11396   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11397                                                   : DAG.getSubtarget().useAA();
11398   if (UseAA) {
11399     // Replace all merged stores with the new store.
11400     for (unsigned i = 0; i < NumStores; ++i)
11401       CombineTo(StoreNodes[i].MemNode, NewStore);
11402   } else {
11403     // Replace the last store with the new store.
11404     CombineTo(LatestOp, NewStore);
11405     // Erase all other stores.
11406     for (unsigned i = 0; i < NumStores; ++i) {
11407       if (StoreNodes[i].MemNode == LatestOp)
11408         continue;
11409       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11410       // ReplaceAllUsesWith will replace all uses that existed when it was
11411       // called, but graph optimizations may cause new ones to appear. For
11412       // example, the case in pr14333 looks like
11413       //
11414       //  St's chain -> St -> another store -> X
11415       //
11416       // And the only difference from St to the other store is the chain.
11417       // When we change it's chain to be St's chain they become identical,
11418       // get CSEed and the net result is that X is now a use of St.
11419       // Since we know that St is redundant, just iterate.
11420       while (!St->use_empty())
11421         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11422       deleteAndRecombine(St);
11423     }
11424   }
11425 
11426   return true;
11427 }
11428 
11429 void DAGCombiner::getStoreMergeAndAliasCandidates(
11430     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11431     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11432   // This holds the base pointer, index, and the offset in bytes from the base
11433   // pointer.
11434   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11435 
11436   // We must have a base and an offset.
11437   if (!BasePtr.Base.getNode())
11438     return;
11439 
11440   // Do not handle stores to undef base pointers.
11441   if (BasePtr.Base.isUndef())
11442     return;
11443 
11444   // Walk up the chain and look for nodes with offsets from the same
11445   // base pointer. Stop when reaching an instruction with a different kind
11446   // or instruction which has a different base pointer.
11447   EVT MemVT = St->getMemoryVT();
11448   unsigned Seq = 0;
11449   StoreSDNode *Index = St;
11450 
11451 
11452   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11453                                                   : DAG.getSubtarget().useAA();
11454 
11455   if (UseAA) {
11456     // Look at other users of the same chain. Stores on the same chain do not
11457     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11458     // to be on the same chain, so don't bother looking at adjacent chains.
11459 
11460     SDValue Chain = St->getChain();
11461     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11462       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11463         if (I.getOperandNo() != 0)
11464           continue;
11465 
11466         if (OtherST->isVolatile() || OtherST->isIndexed())
11467           continue;
11468 
11469         if (OtherST->getMemoryVT() != MemVT)
11470           continue;
11471 
11472         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11473 
11474         if (Ptr.equalBaseIndex(BasePtr))
11475           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11476       }
11477     }
11478 
11479     return;
11480   }
11481 
11482   while (Index) {
11483     // If the chain has more than one use, then we can't reorder the mem ops.
11484     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11485       break;
11486 
11487     // Find the base pointer and offset for this memory node.
11488     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11489 
11490     // Check that the base pointer is the same as the original one.
11491     if (!Ptr.equalBaseIndex(BasePtr))
11492       break;
11493 
11494     // The memory operands must not be volatile.
11495     if (Index->isVolatile() || Index->isIndexed())
11496       break;
11497 
11498     // No truncation.
11499     if (Index->isTruncatingStore())
11500       break;
11501 
11502     // The stored memory type must be the same.
11503     if (Index->getMemoryVT() != MemVT)
11504       break;
11505 
11506     // We do not allow under-aligned stores in order to prevent
11507     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11508     // be irrelevant here; what MATTERS is that we not move memory
11509     // operations that potentially overlap past each-other.
11510     if (Index->getAlignment() < MemVT.getStoreSize())
11511       break;
11512 
11513     // We found a potential memory operand to merge.
11514     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11515 
11516     // Find the next memory operand in the chain. If the next operand in the
11517     // chain is a store then move up and continue the scan with the next
11518     // memory operand. If the next operand is a load save it and use alias
11519     // information to check if it interferes with anything.
11520     SDNode *NextInChain = Index->getChain().getNode();
11521     while (1) {
11522       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11523         // We found a store node. Use it for the next iteration.
11524         Index = STn;
11525         break;
11526       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11527         if (Ldn->isVolatile()) {
11528           Index = nullptr;
11529           break;
11530         }
11531 
11532         // Save the load node for later. Continue the scan.
11533         AliasLoadNodes.push_back(Ldn);
11534         NextInChain = Ldn->getChain().getNode();
11535         continue;
11536       } else {
11537         Index = nullptr;
11538         break;
11539       }
11540     }
11541   }
11542 }
11543 
11544 // We need to check that merging these stores does not cause a loop
11545 // in the DAG. Any store candidate may depend on another candidate
11546 // indirectly through its operand (we already consider dependencies
11547 // through the chain). Check in parallel by searching up from
11548 // non-chain operands of candidates.
11549 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11550     SmallVectorImpl<MemOpLink> &StoreNodes) {
11551   SmallPtrSet<const SDNode *, 16> Visited;
11552   SmallVector<const SDNode *, 8> Worklist;
11553   // search ops of store candidates
11554   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11555     SDNode *n = StoreNodes[i].MemNode;
11556     // Potential loops may happen only through non-chain operands
11557     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11558       Worklist.push_back(n->getOperand(j).getNode());
11559   }
11560   // search through DAG. We can stop early if we find a storenode
11561   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11562     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11563       return false;
11564   }
11565   return true;
11566 }
11567 
11568 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11569   if (OptLevel == CodeGenOpt::None)
11570     return false;
11571 
11572   EVT MemVT = St->getMemoryVT();
11573   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11574   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11575       Attribute::NoImplicitFloat);
11576 
11577   // This function cannot currently deal with non-byte-sized memory sizes.
11578   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11579     return false;
11580 
11581   if (!MemVT.isSimple())
11582     return false;
11583 
11584   // Perform an early exit check. Do not bother looking at stored values that
11585   // are not constants, loads, or extracted vector elements.
11586   SDValue StoredVal = St->getValue();
11587   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11588   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11589                        isa<ConstantFPSDNode>(StoredVal);
11590   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11591                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11592 
11593   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11594     return false;
11595 
11596   // Don't merge vectors into wider vectors if the source data comes from loads.
11597   // TODO: This restriction can be lifted by using logic similar to the
11598   // ExtractVecSrc case.
11599   if (MemVT.isVector() && IsLoadSrc)
11600     return false;
11601 
11602   // Only look at ends of store sequences.
11603   SDValue Chain = SDValue(St, 0);
11604   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11605     return false;
11606 
11607   // Save the LoadSDNodes that we find in the chain.
11608   // We need to make sure that these nodes do not interfere with
11609   // any of the store nodes.
11610   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11611 
11612   // Save the StoreSDNodes that we find in the chain.
11613   SmallVector<MemOpLink, 8> StoreNodes;
11614 
11615   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11616 
11617   // Check if there is anything to merge.
11618   if (StoreNodes.size() < 2)
11619     return false;
11620 
11621   // only do dependence check in AA case
11622   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11623                                                   : DAG.getSubtarget().useAA();
11624   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11625     return false;
11626 
11627   // Sort the memory operands according to their distance from the
11628   // base pointer.  As a secondary criteria: make sure stores coming
11629   // later in the code come first in the list. This is important for
11630   // the non-UseAA case, because we're merging stores into the FINAL
11631   // store along a chain which potentially contains aliasing stores.
11632   // Thus, if there are multiple stores to the same address, the last
11633   // one can be considered for merging but not the others.
11634   std::sort(StoreNodes.begin(), StoreNodes.end(),
11635             [](MemOpLink LHS, MemOpLink RHS) {
11636     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11637            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11638             LHS.SequenceNum < RHS.SequenceNum);
11639   });
11640 
11641   // Scan the memory operations on the chain and find the first non-consecutive
11642   // store memory address.
11643   unsigned LastConsecutiveStore = 0;
11644   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11645   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11646 
11647     // Check that the addresses are consecutive starting from the second
11648     // element in the list of stores.
11649     if (i > 0) {
11650       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11651       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11652         break;
11653     }
11654 
11655     // Check if this store interferes with any of the loads that we found.
11656     // If we find a load that alias with this store. Stop the sequence.
11657     if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) {
11658           return isAlias(Ldn, StoreNodes[i].MemNode);
11659         }))
11660       break;
11661 
11662     // Mark this node as useful.
11663     LastConsecutiveStore = i;
11664   }
11665 
11666   // The node with the lowest store address.
11667   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11668   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11669   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11670   LLVMContext &Context = *DAG.getContext();
11671   const DataLayout &DL = DAG.getDataLayout();
11672 
11673   // Store the constants into memory as one consecutive store.
11674   if (IsConstantSrc) {
11675     unsigned LastLegalType = 0;
11676     unsigned LastLegalVectorType = 0;
11677     bool NonZero = false;
11678     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11679       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11680       SDValue StoredVal = St->getValue();
11681 
11682       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11683         NonZero |= !C->isNullValue();
11684       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11685         NonZero |= !C->getConstantFPValue()->isNullValue();
11686       } else {
11687         // Non-constant.
11688         break;
11689       }
11690 
11691       // Find a legal type for the constant store.
11692       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11693       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11694       bool IsFast;
11695       if (TLI.isTypeLegal(StoreTy) &&
11696           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11697                                  FirstStoreAlign, &IsFast) && IsFast) {
11698         LastLegalType = i+1;
11699       // Or check whether a truncstore is legal.
11700       } else if (TLI.getTypeAction(Context, StoreTy) ==
11701                  TargetLowering::TypePromoteInteger) {
11702         EVT LegalizedStoredValueTy =
11703           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11704         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11705             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11706                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11707             IsFast) {
11708           LastLegalType = i + 1;
11709         }
11710       }
11711 
11712       // We only use vectors if the constant is known to be zero or the target
11713       // allows it and the function is not marked with the noimplicitfloat
11714       // attribute.
11715       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11716                                                         FirstStoreAS)) &&
11717           !NoVectors) {
11718         // Find a legal type for the vector store.
11719         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11720         if (TLI.isTypeLegal(Ty) &&
11721             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11722                                    FirstStoreAlign, &IsFast) && IsFast)
11723           LastLegalVectorType = i + 1;
11724       }
11725     }
11726 
11727     // Check if we found a legal integer type to store.
11728     if (LastLegalType == 0 && LastLegalVectorType == 0)
11729       return false;
11730 
11731     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11732     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11733 
11734     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11735                                            true, UseVector);
11736   }
11737 
11738   // When extracting multiple vector elements, try to store them
11739   // in one vector store rather than a sequence of scalar stores.
11740   if (IsExtractVecSrc) {
11741     unsigned NumStoresToMerge = 0;
11742     bool IsVec = MemVT.isVector();
11743     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11744       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11745       unsigned StoreValOpcode = St->getValue().getOpcode();
11746       // This restriction could be loosened.
11747       // Bail out if any stored values are not elements extracted from a vector.
11748       // It should be possible to handle mixed sources, but load sources need
11749       // more careful handling (see the block of code below that handles
11750       // consecutive loads).
11751       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11752           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11753         return false;
11754 
11755       // Find a legal type for the vector store.
11756       unsigned Elts = i + 1;
11757       if (IsVec) {
11758         // When merging vector stores, get the total number of elements.
11759         Elts *= MemVT.getVectorNumElements();
11760       }
11761       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11762       bool IsFast;
11763       if (TLI.isTypeLegal(Ty) &&
11764           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11765                                  FirstStoreAlign, &IsFast) && IsFast)
11766         NumStoresToMerge = i + 1;
11767     }
11768 
11769     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11770                                            false, true);
11771   }
11772 
11773   // Below we handle the case of multiple consecutive stores that
11774   // come from multiple consecutive loads. We merge them into a single
11775   // wide load and a single wide store.
11776 
11777   // Look for load nodes which are used by the stored values.
11778   SmallVector<MemOpLink, 8> LoadNodes;
11779 
11780   // Find acceptable loads. Loads need to have the same chain (token factor),
11781   // must not be zext, volatile, indexed, and they must be consecutive.
11782   BaseIndexOffset LdBasePtr;
11783   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11784     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11785     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11786     if (!Ld) break;
11787 
11788     // Loads must only have one use.
11789     if (!Ld->hasNUsesOfValue(1, 0))
11790       break;
11791 
11792     // The memory operands must not be volatile.
11793     if (Ld->isVolatile() || Ld->isIndexed())
11794       break;
11795 
11796     // We do not accept ext loads.
11797     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11798       break;
11799 
11800     // The stored memory type must be the same.
11801     if (Ld->getMemoryVT() != MemVT)
11802       break;
11803 
11804     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11805     // If this is not the first ptr that we check.
11806     if (LdBasePtr.Base.getNode()) {
11807       // The base ptr must be the same.
11808       if (!LdPtr.equalBaseIndex(LdBasePtr))
11809         break;
11810     } else {
11811       // Check that all other base pointers are the same as this one.
11812       LdBasePtr = LdPtr;
11813     }
11814 
11815     // We found a potential memory operand to merge.
11816     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11817   }
11818 
11819   if (LoadNodes.size() < 2)
11820     return false;
11821 
11822   // If we have load/store pair instructions and we only have two values,
11823   // don't bother.
11824   unsigned RequiredAlignment;
11825   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11826       St->getAlignment() >= RequiredAlignment)
11827     return false;
11828 
11829   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11830   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11831   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11832 
11833   // Scan the memory operations on the chain and find the first non-consecutive
11834   // load memory address. These variables hold the index in the store node
11835   // array.
11836   unsigned LastConsecutiveLoad = 0;
11837   // This variable refers to the size and not index in the array.
11838   unsigned LastLegalVectorType = 0;
11839   unsigned LastLegalIntegerType = 0;
11840   StartAddress = LoadNodes[0].OffsetFromBase;
11841   SDValue FirstChain = FirstLoad->getChain();
11842   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11843     // All loads must share the same chain.
11844     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11845       break;
11846 
11847     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11848     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11849       break;
11850     LastConsecutiveLoad = i;
11851     // Find a legal type for the vector store.
11852     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11853     bool IsFastSt, IsFastLd;
11854     if (TLI.isTypeLegal(StoreTy) &&
11855         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11856                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11857         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11858                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11859       LastLegalVectorType = i + 1;
11860     }
11861 
11862     // Find a legal type for the integer store.
11863     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11864     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11865     if (TLI.isTypeLegal(StoreTy) &&
11866         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11867                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11868         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11869                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11870       LastLegalIntegerType = i + 1;
11871     // Or check whether a truncstore and extload is legal.
11872     else if (TLI.getTypeAction(Context, StoreTy) ==
11873              TargetLowering::TypePromoteInteger) {
11874       EVT LegalizedStoredValueTy =
11875         TLI.getTypeToTransformTo(Context, StoreTy);
11876       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11877           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11878           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11879           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11880           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11881                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11882           IsFastSt &&
11883           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11884                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11885           IsFastLd)
11886         LastLegalIntegerType = i+1;
11887     }
11888   }
11889 
11890   // Only use vector types if the vector type is larger than the integer type.
11891   // If they are the same, use integers.
11892   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11893   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11894 
11895   // We add +1 here because the LastXXX variables refer to location while
11896   // the NumElem refers to array/index size.
11897   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11898   NumElem = std::min(LastLegalType, NumElem);
11899 
11900   if (NumElem < 2)
11901     return false;
11902 
11903   // Collect the chains from all merged stores.
11904   SmallVector<SDValue, 8> MergeStoreChains;
11905   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11906 
11907   // The latest Node in the DAG.
11908   unsigned LatestNodeUsed = 0;
11909   for (unsigned i=1; i<NumElem; ++i) {
11910     // Find a chain for the new wide-store operand. Notice that some
11911     // of the store nodes that we found may not be selected for inclusion
11912     // in the wide store. The chain we use needs to be the chain of the
11913     // latest store node which is *used* and replaced by the wide store.
11914     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11915       LatestNodeUsed = i;
11916 
11917     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11918   }
11919 
11920   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11921 
11922   // Find if it is better to use vectors or integers to load and store
11923   // to memory.
11924   EVT JointMemOpVT;
11925   if (UseVectorTy) {
11926     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11927   } else {
11928     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11929     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11930   }
11931 
11932   SDLoc LoadDL(LoadNodes[0].MemNode);
11933   SDLoc StoreDL(StoreNodes[0].MemNode);
11934 
11935   // The merged loads are required to have the same incoming chain, so
11936   // using the first's chain is acceptable.
11937   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
11938                                 FirstLoad->getBasePtr(),
11939                                 FirstLoad->getPointerInfo(), FirstLoadAlign);
11940 
11941   SDValue NewStoreChain =
11942     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11943 
11944   SDValue NewStore =
11945       DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11946                    FirstInChain->getPointerInfo(), FirstStoreAlign);
11947 
11948   // Transfer chain users from old loads to the new load.
11949   for (unsigned i = 0; i < NumElem; ++i) {
11950     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11951     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11952                                   SDValue(NewLoad.getNode(), 1));
11953   }
11954 
11955   if (UseAA) {
11956     // Replace the all stores with the new store.
11957     for (unsigned i = 0; i < NumElem; ++i)
11958       CombineTo(StoreNodes[i].MemNode, NewStore);
11959   } else {
11960     // Replace the last store with the new store.
11961     CombineTo(LatestOp, NewStore);
11962     // Erase all other stores.
11963     for (unsigned i = 0; i < NumElem; ++i) {
11964       // Remove all Store nodes.
11965       if (StoreNodes[i].MemNode == LatestOp)
11966         continue;
11967       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11968       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11969       deleteAndRecombine(St);
11970     }
11971   }
11972 
11973   return true;
11974 }
11975 
11976 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11977   SDLoc SL(ST);
11978   SDValue ReplStore;
11979 
11980   // Replace the chain to avoid dependency.
11981   if (ST->isTruncatingStore()) {
11982     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11983                                   ST->getBasePtr(), ST->getMemoryVT(),
11984                                   ST->getMemOperand());
11985   } else {
11986     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11987                              ST->getMemOperand());
11988   }
11989 
11990   // Create token to keep both nodes around.
11991   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11992                               MVT::Other, ST->getChain(), ReplStore);
11993 
11994   // Make sure the new and old chains are cleaned up.
11995   AddToWorklist(Token.getNode());
11996 
11997   // Don't add users to work list.
11998   return CombineTo(ST, Token, false);
11999 }
12000 
12001 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12002   SDValue Value = ST->getValue();
12003   if (Value.getOpcode() == ISD::TargetConstantFP)
12004     return SDValue();
12005 
12006   SDLoc DL(ST);
12007 
12008   SDValue Chain = ST->getChain();
12009   SDValue Ptr = ST->getBasePtr();
12010 
12011   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12012 
12013   // NOTE: If the original store is volatile, this transform must not increase
12014   // the number of stores.  For example, on x86-32 an f64 can be stored in one
12015   // processor operation but an i64 (which is not legal) requires two.  So the
12016   // transform should not be done in this case.
12017 
12018   SDValue Tmp;
12019   switch (CFP->getSimpleValueType(0).SimpleTy) {
12020   default:
12021     llvm_unreachable("Unknown FP type");
12022   case MVT::f16:    // We don't do this for these yet.
12023   case MVT::f80:
12024   case MVT::f128:
12025   case MVT::ppcf128:
12026     return SDValue();
12027   case MVT::f32:
12028     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12029         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12030       ;
12031       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12032                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12033                             MVT::i32);
12034       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12035     }
12036 
12037     return SDValue();
12038   case MVT::f64:
12039     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12040          !ST->isVolatile()) ||
12041         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12042       ;
12043       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12044                             getZExtValue(), SDLoc(CFP), MVT::i64);
12045       return DAG.getStore(Chain, DL, Tmp,
12046                           Ptr, ST->getMemOperand());
12047     }
12048 
12049     if (!ST->isVolatile() &&
12050         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12051       // Many FP stores are not made apparent until after legalize, e.g. for
12052       // argument passing.  Since this is so common, custom legalize the
12053       // 64-bit integer store into two 32-bit stores.
12054       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12055       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12056       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12057       if (DAG.getDataLayout().isBigEndian())
12058         std::swap(Lo, Hi);
12059 
12060       unsigned Alignment = ST->getAlignment();
12061       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12062       AAMDNodes AAInfo = ST->getAAInfo();
12063 
12064       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12065                                  ST->getAlignment(), MMOFlags, AAInfo);
12066       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12067                         DAG.getConstant(4, DL, Ptr.getValueType()));
12068       Alignment = MinAlign(Alignment, 4U);
12069       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12070                                  ST->getPointerInfo().getWithOffset(4),
12071                                  Alignment, MMOFlags, AAInfo);
12072       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12073                          St0, St1);
12074     }
12075 
12076     return SDValue();
12077   }
12078 }
12079 
12080 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12081   StoreSDNode *ST  = cast<StoreSDNode>(N);
12082   SDValue Chain = ST->getChain();
12083   SDValue Value = ST->getValue();
12084   SDValue Ptr   = ST->getBasePtr();
12085 
12086   // If this is a store of a bit convert, store the input value if the
12087   // resultant store does not need a higher alignment than the original.
12088   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12089       ST->isUnindexed()) {
12090     EVT SVT = Value.getOperand(0).getValueType();
12091     if (((!LegalOperations && !ST->isVolatile()) ||
12092          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12093         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12094       unsigned OrigAlign = ST->getAlignment();
12095       bool Fast = false;
12096       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12097                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12098           Fast) {
12099         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12100                             ST->getPointerInfo(), OrigAlign,
12101                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
12102       }
12103     }
12104   }
12105 
12106   // Turn 'store undef, Ptr' -> nothing.
12107   if (Value.isUndef() && ST->isUnindexed())
12108     return Chain;
12109 
12110   // Try to infer better alignment information than the store already has.
12111   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12112     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12113       if (Align > ST->getAlignment()) {
12114         SDValue NewStore =
12115             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12116                               ST->getMemoryVT(), Align,
12117                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
12118         if (NewStore.getNode() != N)
12119           return CombineTo(ST, NewStore, true);
12120       }
12121     }
12122   }
12123 
12124   // Try transforming a pair floating point load / store ops to integer
12125   // load / store ops.
12126   if (SDValue NewST = TransformFPLoadStorePair(N))
12127     return NewST;
12128 
12129   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12130                                                   : DAG.getSubtarget().useAA();
12131 #ifndef NDEBUG
12132   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12133       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12134     UseAA = false;
12135 #endif
12136   if (UseAA && ST->isUnindexed()) {
12137     // FIXME: We should do this even without AA enabled. AA will just allow
12138     // FindBetterChain to work in more situations. The problem with this is that
12139     // any combine that expects memory operations to be on consecutive chains
12140     // first needs to be updated to look for users of the same chain.
12141 
12142     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12143     // adjacent stores.
12144     if (findBetterNeighborChains(ST)) {
12145       // replaceStoreChain uses CombineTo, which handled all of the worklist
12146       // manipulation. Return the original node to not do anything else.
12147       return SDValue(ST, 0);
12148     }
12149     Chain = ST->getChain();
12150   }
12151 
12152   // Try transforming N to an indexed store.
12153   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12154     return SDValue(N, 0);
12155 
12156   // FIXME: is there such a thing as a truncating indexed store?
12157   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12158       Value.getValueType().isInteger()) {
12159     // See if we can simplify the input to this truncstore with knowledge that
12160     // only the low bits are being used.  For example:
12161     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12162     SDValue Shorter =
12163       GetDemandedBits(Value,
12164                       APInt::getLowBitsSet(
12165                         Value.getValueType().getScalarType().getSizeInBits(),
12166                         ST->getMemoryVT().getScalarType().getSizeInBits()));
12167     AddToWorklist(Value.getNode());
12168     if (Shorter.getNode())
12169       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12170                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12171 
12172     // Otherwise, see if we can simplify the operation with
12173     // SimplifyDemandedBits, which only works if the value has a single use.
12174     if (SimplifyDemandedBits(Value,
12175                         APInt::getLowBitsSet(
12176                           Value.getValueType().getScalarType().getSizeInBits(),
12177                           ST->getMemoryVT().getScalarType().getSizeInBits())))
12178       return SDValue(N, 0);
12179   }
12180 
12181   // If this is a load followed by a store to the same location, then the store
12182   // is dead/noop.
12183   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12184     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12185         ST->isUnindexed() && !ST->isVolatile() &&
12186         // There can't be any side effects between the load and store, such as
12187         // a call or store.
12188         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12189       // The store is dead, remove it.
12190       return Chain;
12191     }
12192   }
12193 
12194   // If this is a store followed by a store with the same value to the same
12195   // location, then the store is dead/noop.
12196   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12197     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12198         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12199         ST1->isUnindexed() && !ST1->isVolatile()) {
12200       // The store is dead, remove it.
12201       return Chain;
12202     }
12203   }
12204 
12205   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12206   // truncating store.  We can do this even if this is already a truncstore.
12207   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12208       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12209       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12210                             ST->getMemoryVT())) {
12211     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12212                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12213   }
12214 
12215   // Only perform this optimization before the types are legal, because we
12216   // don't want to perform this optimization on every DAGCombine invocation.
12217   if (!LegalTypes) {
12218     bool EverChanged = false;
12219 
12220     do {
12221       // There can be multiple store sequences on the same chain.
12222       // Keep trying to merge store sequences until we are unable to do so
12223       // or until we merge the last store on the chain.
12224       bool Changed = MergeConsecutiveStores(ST);
12225       EverChanged |= Changed;
12226       if (!Changed) break;
12227     } while (ST->getOpcode() != ISD::DELETED_NODE);
12228 
12229     if (EverChanged)
12230       return SDValue(N, 0);
12231   }
12232 
12233   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12234   //
12235   // Make sure to do this only after attempting to merge stores in order to
12236   //  avoid changing the types of some subset of stores due to visit order,
12237   //  preventing their merging.
12238   if (isa<ConstantFPSDNode>(Value)) {
12239     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12240       return NewSt;
12241   }
12242 
12243   if (SDValue NewSt = splitMergedValStore(ST))
12244     return NewSt;
12245 
12246   return ReduceLoadOpStoreWidth(N);
12247 }
12248 
12249 /// For the instruction sequence of store below, F and I values
12250 /// are bundled together as an i64 value before being stored into memory.
12251 /// Sometimes it is more efficent to generate separate stores for F and I,
12252 /// which can remove the bitwise instructions or sink them to colder places.
12253 ///
12254 ///   (store (or (zext (bitcast F to i32) to i64),
12255 ///              (shl (zext I to i64), 32)), addr)  -->
12256 ///   (store F, addr) and (store I, addr+4)
12257 ///
12258 /// Similarly, splitting for other merged store can also be beneficial, like:
12259 /// For pair of {i32, i32}, i64 store --> two i32 stores.
12260 /// For pair of {i32, i16}, i64 store --> two i32 stores.
12261 /// For pair of {i16, i16}, i32 store --> two i16 stores.
12262 /// For pair of {i16, i8},  i32 store --> two i16 stores.
12263 /// For pair of {i8, i8},   i16 store --> two i8 stores.
12264 ///
12265 /// We allow each target to determine specifically which kind of splitting is
12266 /// supported.
12267 ///
12268 /// The store patterns are commonly seen from the simple code snippet below
12269 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
12270 ///   void goo(const std::pair<int, float> &);
12271 ///   hoo() {
12272 ///     ...
12273 ///     goo(std::make_pair(tmp, ftmp));
12274 ///     ...
12275 ///   }
12276 ///
12277 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
12278   if (OptLevel == CodeGenOpt::None)
12279     return SDValue();
12280 
12281   SDValue Val = ST->getValue();
12282   SDLoc DL(ST);
12283 
12284   // Match OR operand.
12285   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
12286     return SDValue();
12287 
12288   // Match SHL operand and get Lower and Higher parts of Val.
12289   SDValue Op1 = Val.getOperand(0);
12290   SDValue Op2 = Val.getOperand(1);
12291   SDValue Lo, Hi;
12292   if (Op1.getOpcode() != ISD::SHL) {
12293     std::swap(Op1, Op2);
12294     if (Op1.getOpcode() != ISD::SHL)
12295       return SDValue();
12296   }
12297   Lo = Op2;
12298   Hi = Op1.getOperand(0);
12299   if (!Op1.hasOneUse())
12300     return SDValue();
12301 
12302   // Match shift amount to HalfValBitSize.
12303   unsigned HalfValBitSize = Val.getValueType().getSizeInBits() / 2;
12304   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
12305   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
12306     return SDValue();
12307 
12308   // Lo and Hi are zero-extended from int with size less equal than 32
12309   // to i64.
12310   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
12311       !Lo.getOperand(0).getValueType().isScalarInteger() ||
12312       Lo.getOperand(0).getValueType().getSizeInBits() > HalfValBitSize ||
12313       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
12314       !Hi.getOperand(0).getValueType().isScalarInteger() ||
12315       Hi.getOperand(0).getValueType().getSizeInBits() > HalfValBitSize)
12316     return SDValue();
12317 
12318   if (!TLI.isMultiStoresCheaperThanBitsMerge(Lo.getOperand(0),
12319                                              Hi.getOperand(0)))
12320     return SDValue();
12321 
12322   // Start to split store.
12323   unsigned Alignment = ST->getAlignment();
12324   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12325   AAMDNodes AAInfo = ST->getAAInfo();
12326 
12327   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
12328   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
12329   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
12330   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
12331 
12332   SDValue Chain = ST->getChain();
12333   SDValue Ptr = ST->getBasePtr();
12334   // Lower value store.
12335   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12336                              ST->getAlignment(), MMOFlags, AAInfo);
12337   Ptr =
12338       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12339                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
12340   // Higher value store.
12341   SDValue St1 =
12342       DAG.getStore(Chain, DL, Hi, Ptr,
12343                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
12344                    Alignment / 2, MMOFlags, AAInfo);
12345   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, St0, St1);
12346 }
12347 
12348 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12349   SDValue InVec = N->getOperand(0);
12350   SDValue InVal = N->getOperand(1);
12351   SDValue EltNo = N->getOperand(2);
12352   SDLoc dl(N);
12353 
12354   // If the inserted element is an UNDEF, just use the input vector.
12355   if (InVal.isUndef())
12356     return InVec;
12357 
12358   EVT VT = InVec.getValueType();
12359 
12360   // If we can't generate a legal BUILD_VECTOR, exit
12361   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12362     return SDValue();
12363 
12364   // Check that we know which element is being inserted
12365   if (!isa<ConstantSDNode>(EltNo))
12366     return SDValue();
12367   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12368 
12369   // Canonicalize insert_vector_elt dag nodes.
12370   // Example:
12371   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12372   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12373   //
12374   // Do this only if the child insert_vector node has one use; also
12375   // do this only if indices are both constants and Idx1 < Idx0.
12376   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12377       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12378     unsigned OtherElt =
12379       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12380     if (Elt < OtherElt) {
12381       // Swap nodes.
12382       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
12383                                   InVec.getOperand(0), InVal, EltNo);
12384       AddToWorklist(NewOp.getNode());
12385       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12386                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12387     }
12388   }
12389 
12390   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12391   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12392   // vector elements.
12393   SmallVector<SDValue, 8> Ops;
12394   // Do not combine these two vectors if the output vector will not replace
12395   // the input vector.
12396   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12397     Ops.append(InVec.getNode()->op_begin(),
12398                InVec.getNode()->op_end());
12399   } else if (InVec.isUndef()) {
12400     unsigned NElts = VT.getVectorNumElements();
12401     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12402   } else {
12403     return SDValue();
12404   }
12405 
12406   // Insert the element
12407   if (Elt < Ops.size()) {
12408     // All the operands of BUILD_VECTOR must have the same type;
12409     // we enforce that here.
12410     EVT OpVT = Ops[0].getValueType();
12411     if (InVal.getValueType() != OpVT)
12412       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12413                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
12414                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
12415     Ops[Elt] = InVal;
12416   }
12417 
12418   // Return the new vector
12419   return DAG.getBuildVector(VT, dl, Ops);
12420 }
12421 
12422 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12423     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12424   assert(!OriginalLoad->isVolatile());
12425 
12426   EVT ResultVT = EVE->getValueType(0);
12427   EVT VecEltVT = InVecVT.getVectorElementType();
12428   unsigned Align = OriginalLoad->getAlignment();
12429   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12430       VecEltVT.getTypeForEVT(*DAG.getContext()));
12431 
12432   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12433     return SDValue();
12434 
12435   Align = NewAlign;
12436 
12437   SDValue NewPtr = OriginalLoad->getBasePtr();
12438   SDValue Offset;
12439   EVT PtrType = NewPtr.getValueType();
12440   MachinePointerInfo MPI;
12441   SDLoc DL(EVE);
12442   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12443     int Elt = ConstEltNo->getZExtValue();
12444     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12445     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12446     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12447   } else {
12448     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12449     Offset = DAG.getNode(
12450         ISD::MUL, DL, PtrType, Offset,
12451         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12452     MPI = OriginalLoad->getPointerInfo();
12453   }
12454   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12455 
12456   // The replacement we need to do here is a little tricky: we need to
12457   // replace an extractelement of a load with a load.
12458   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12459   // Note that this replacement assumes that the extractvalue is the only
12460   // use of the load; that's okay because we don't want to perform this
12461   // transformation in other cases anyway.
12462   SDValue Load;
12463   SDValue Chain;
12464   if (ResultVT.bitsGT(VecEltVT)) {
12465     // If the result type of vextract is wider than the load, then issue an
12466     // extending load instead.
12467     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12468                                                   VecEltVT)
12469                                    ? ISD::ZEXTLOAD
12470                                    : ISD::EXTLOAD;
12471     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
12472                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
12473                           Align, OriginalLoad->getMemOperand()->getFlags(),
12474                           OriginalLoad->getAAInfo());
12475     Chain = Load.getValue(1);
12476   } else {
12477     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
12478                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
12479                        OriginalLoad->getAAInfo());
12480     Chain = Load.getValue(1);
12481     if (ResultVT.bitsLT(VecEltVT))
12482       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12483     else
12484       Load = DAG.getBitcast(ResultVT, Load);
12485   }
12486   WorklistRemover DeadNodes(*this);
12487   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12488   SDValue To[] = { Load, Chain };
12489   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12490   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12491   // worklist explicitly as well.
12492   AddToWorklist(Load.getNode());
12493   AddUsersToWorklist(Load.getNode()); // Add users too
12494   // Make sure to revisit this node to clean it up; it will usually be dead.
12495   AddToWorklist(EVE);
12496   ++OpsNarrowed;
12497   return SDValue(EVE, 0);
12498 }
12499 
12500 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12501   // (vextract (scalar_to_vector val, 0) -> val
12502   SDValue InVec = N->getOperand(0);
12503   EVT VT = InVec.getValueType();
12504   EVT NVT = N->getValueType(0);
12505 
12506   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12507     // Check if the result type doesn't match the inserted element type. A
12508     // SCALAR_TO_VECTOR may truncate the inserted element and the
12509     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12510     SDValue InOp = InVec.getOperand(0);
12511     if (InOp.getValueType() != NVT) {
12512       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12513       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12514     }
12515     return InOp;
12516   }
12517 
12518   SDValue EltNo = N->getOperand(1);
12519   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12520 
12521   // extract_vector_elt (build_vector x, y), 1 -> y
12522   if (ConstEltNo &&
12523       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12524       TLI.isTypeLegal(VT) &&
12525       (InVec.hasOneUse() ||
12526        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12527     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12528     EVT InEltVT = Elt.getValueType();
12529 
12530     // Sometimes build_vector's scalar input types do not match result type.
12531     if (NVT == InEltVT)
12532       return Elt;
12533 
12534     // TODO: It may be useful to truncate if free if the build_vector implicitly
12535     // converts.
12536   }
12537 
12538   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12539   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12540       ConstEltNo->isNullValue() && VT.isInteger()) {
12541     SDValue BCSrc = InVec.getOperand(0);
12542     if (BCSrc.getValueType().isScalarInteger())
12543       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12544   }
12545 
12546   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
12547   //
12548   // This only really matters if the index is non-constant since other combines
12549   // on the constant elements already work.
12550   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12551       EltNo == InVec.getOperand(2)) {
12552     SDValue Elt = InVec.getOperand(1);
12553     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
12554   }
12555 
12556   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12557   // We only perform this optimization before the op legalization phase because
12558   // we may introduce new vector instructions which are not backed by TD
12559   // patterns. For example on AVX, extracting elements from a wide vector
12560   // without using extract_subvector. However, if we can find an underlying
12561   // scalar value, then we can always use that.
12562   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12563     int NumElem = VT.getVectorNumElements();
12564     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12565     // Find the new index to extract from.
12566     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12567 
12568     // Extracting an undef index is undef.
12569     if (OrigElt == -1)
12570       return DAG.getUNDEF(NVT);
12571 
12572     // Select the right vector half to extract from.
12573     SDValue SVInVec;
12574     if (OrigElt < NumElem) {
12575       SVInVec = InVec->getOperand(0);
12576     } else {
12577       SVInVec = InVec->getOperand(1);
12578       OrigElt -= NumElem;
12579     }
12580 
12581     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12582       SDValue InOp = SVInVec.getOperand(OrigElt);
12583       if (InOp.getValueType() != NVT) {
12584         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12585         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12586       }
12587 
12588       return InOp;
12589     }
12590 
12591     // FIXME: We should handle recursing on other vector shuffles and
12592     // scalar_to_vector here as well.
12593 
12594     if (!LegalOperations) {
12595       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12596       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12597                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12598     }
12599   }
12600 
12601   bool BCNumEltsChanged = false;
12602   EVT ExtVT = VT.getVectorElementType();
12603   EVT LVT = ExtVT;
12604 
12605   // If the result of load has to be truncated, then it's not necessarily
12606   // profitable.
12607   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12608     return SDValue();
12609 
12610   if (InVec.getOpcode() == ISD::BITCAST) {
12611     // Don't duplicate a load with other uses.
12612     if (!InVec.hasOneUse())
12613       return SDValue();
12614 
12615     EVT BCVT = InVec.getOperand(0).getValueType();
12616     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12617       return SDValue();
12618     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12619       BCNumEltsChanged = true;
12620     InVec = InVec.getOperand(0);
12621     ExtVT = BCVT.getVectorElementType();
12622   }
12623 
12624   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12625   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12626       ISD::isNormalLoad(InVec.getNode()) &&
12627       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12628     SDValue Index = N->getOperand(1);
12629     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
12630       if (!OrigLoad->isVolatile()) {
12631         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12632                                                              OrigLoad);
12633       }
12634     }
12635   }
12636 
12637   // Perform only after legalization to ensure build_vector / vector_shuffle
12638   // optimizations have already been done.
12639   if (!LegalOperations) return SDValue();
12640 
12641   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12642   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12643   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12644 
12645   if (ConstEltNo) {
12646     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12647 
12648     LoadSDNode *LN0 = nullptr;
12649     const ShuffleVectorSDNode *SVN = nullptr;
12650     if (ISD::isNormalLoad(InVec.getNode())) {
12651       LN0 = cast<LoadSDNode>(InVec);
12652     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12653                InVec.getOperand(0).getValueType() == ExtVT &&
12654                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12655       // Don't duplicate a load with other uses.
12656       if (!InVec.hasOneUse())
12657         return SDValue();
12658 
12659       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12660     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12661       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12662       // =>
12663       // (load $addr+1*size)
12664 
12665       // Don't duplicate a load with other uses.
12666       if (!InVec.hasOneUse())
12667         return SDValue();
12668 
12669       // If the bit convert changed the number of elements, it is unsafe
12670       // to examine the mask.
12671       if (BCNumEltsChanged)
12672         return SDValue();
12673 
12674       // Select the input vector, guarding against out of range extract vector.
12675       unsigned NumElems = VT.getVectorNumElements();
12676       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12677       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12678 
12679       if (InVec.getOpcode() == ISD::BITCAST) {
12680         // Don't duplicate a load with other uses.
12681         if (!InVec.hasOneUse())
12682           return SDValue();
12683 
12684         InVec = InVec.getOperand(0);
12685       }
12686       if (ISD::isNormalLoad(InVec.getNode())) {
12687         LN0 = cast<LoadSDNode>(InVec);
12688         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12689         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12690       }
12691     }
12692 
12693     // Make sure we found a non-volatile load and the extractelement is
12694     // the only use.
12695     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12696       return SDValue();
12697 
12698     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12699     if (Elt == -1)
12700       return DAG.getUNDEF(LVT);
12701 
12702     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12703   }
12704 
12705   return SDValue();
12706 }
12707 
12708 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12709 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12710   // We perform this optimization post type-legalization because
12711   // the type-legalizer often scalarizes integer-promoted vectors.
12712   // Performing this optimization before may create bit-casts which
12713   // will be type-legalized to complex code sequences.
12714   // We perform this optimization only before the operation legalizer because we
12715   // may introduce illegal operations.
12716   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12717     return SDValue();
12718 
12719   unsigned NumInScalars = N->getNumOperands();
12720   SDLoc dl(N);
12721   EVT VT = N->getValueType(0);
12722 
12723   // Check to see if this is a BUILD_VECTOR of a bunch of values
12724   // which come from any_extend or zero_extend nodes. If so, we can create
12725   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12726   // optimizations. We do not handle sign-extend because we can't fill the sign
12727   // using shuffles.
12728   EVT SourceType = MVT::Other;
12729   bool AllAnyExt = true;
12730 
12731   for (unsigned i = 0; i != NumInScalars; ++i) {
12732     SDValue In = N->getOperand(i);
12733     // Ignore undef inputs.
12734     if (In.isUndef()) continue;
12735 
12736     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12737     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12738 
12739     // Abort if the element is not an extension.
12740     if (!ZeroExt && !AnyExt) {
12741       SourceType = MVT::Other;
12742       break;
12743     }
12744 
12745     // The input is a ZeroExt or AnyExt. Check the original type.
12746     EVT InTy = In.getOperand(0).getValueType();
12747 
12748     // Check that all of the widened source types are the same.
12749     if (SourceType == MVT::Other)
12750       // First time.
12751       SourceType = InTy;
12752     else if (InTy != SourceType) {
12753       // Multiple income types. Abort.
12754       SourceType = MVT::Other;
12755       break;
12756     }
12757 
12758     // Check if all of the extends are ANY_EXTENDs.
12759     AllAnyExt &= AnyExt;
12760   }
12761 
12762   // In order to have valid types, all of the inputs must be extended from the
12763   // same source type and all of the inputs must be any or zero extend.
12764   // Scalar sizes must be a power of two.
12765   EVT OutScalarTy = VT.getScalarType();
12766   bool ValidTypes = SourceType != MVT::Other &&
12767                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12768                  isPowerOf2_32(SourceType.getSizeInBits());
12769 
12770   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12771   // turn into a single shuffle instruction.
12772   if (!ValidTypes)
12773     return SDValue();
12774 
12775   bool isLE = DAG.getDataLayout().isLittleEndian();
12776   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12777   assert(ElemRatio > 1 && "Invalid element size ratio");
12778   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12779                                DAG.getConstant(0, SDLoc(N), SourceType);
12780 
12781   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12782   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12783 
12784   // Populate the new build_vector
12785   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12786     SDValue Cast = N->getOperand(i);
12787     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12788             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12789             Cast.isUndef()) && "Invalid cast opcode");
12790     SDValue In;
12791     if (Cast.isUndef())
12792       In = DAG.getUNDEF(SourceType);
12793     else
12794       In = Cast->getOperand(0);
12795     unsigned Index = isLE ? (i * ElemRatio) :
12796                             (i * ElemRatio + (ElemRatio - 1));
12797 
12798     assert(Index < Ops.size() && "Invalid index");
12799     Ops[Index] = In;
12800   }
12801 
12802   // The type of the new BUILD_VECTOR node.
12803   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12804   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12805          "Invalid vector size");
12806   // Check if the new vector type is legal.
12807   if (!isTypeLegal(VecVT)) return SDValue();
12808 
12809   // Make the new BUILD_VECTOR.
12810   SDValue BV = DAG.getBuildVector(VecVT, dl, Ops);
12811 
12812   // The new BUILD_VECTOR node has the potential to be further optimized.
12813   AddToWorklist(BV.getNode());
12814   // Bitcast to the desired type.
12815   return DAG.getBitcast(VT, BV);
12816 }
12817 
12818 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12819   EVT VT = N->getValueType(0);
12820 
12821   unsigned NumInScalars = N->getNumOperands();
12822   SDLoc dl(N);
12823 
12824   EVT SrcVT = MVT::Other;
12825   unsigned Opcode = ISD::DELETED_NODE;
12826   unsigned NumDefs = 0;
12827 
12828   for (unsigned i = 0; i != NumInScalars; ++i) {
12829     SDValue In = N->getOperand(i);
12830     unsigned Opc = In.getOpcode();
12831 
12832     if (Opc == ISD::UNDEF)
12833       continue;
12834 
12835     // If all scalar values are floats and converted from integers.
12836     if (Opcode == ISD::DELETED_NODE &&
12837         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12838       Opcode = Opc;
12839     }
12840 
12841     if (Opc != Opcode)
12842       return SDValue();
12843 
12844     EVT InVT = In.getOperand(0).getValueType();
12845 
12846     // If all scalar values are typed differently, bail out. It's chosen to
12847     // simplify BUILD_VECTOR of integer types.
12848     if (SrcVT == MVT::Other)
12849       SrcVT = InVT;
12850     if (SrcVT != InVT)
12851       return SDValue();
12852     NumDefs++;
12853   }
12854 
12855   // If the vector has just one element defined, it's not worth to fold it into
12856   // a vectorized one.
12857   if (NumDefs < 2)
12858     return SDValue();
12859 
12860   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12861          && "Should only handle conversion from integer to float.");
12862   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12863 
12864   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12865 
12866   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12867     return SDValue();
12868 
12869   // Just because the floating-point vector type is legal does not necessarily
12870   // mean that the corresponding integer vector type is.
12871   if (!isTypeLegal(NVT))
12872     return SDValue();
12873 
12874   SmallVector<SDValue, 8> Opnds;
12875   for (unsigned i = 0; i != NumInScalars; ++i) {
12876     SDValue In = N->getOperand(i);
12877 
12878     if (In.isUndef())
12879       Opnds.push_back(DAG.getUNDEF(SrcVT));
12880     else
12881       Opnds.push_back(In.getOperand(0));
12882   }
12883   SDValue BV = DAG.getBuildVector(NVT, dl, Opnds);
12884   AddToWorklist(BV.getNode());
12885 
12886   return DAG.getNode(Opcode, dl, VT, BV);
12887 }
12888 
12889 // If Vec holds a reference to a non-null node, return Vec.
12890 // Otherwise, return either a zero or an undef node of the appropriate type.
12891 static SDValue getRightHandValue(SelectionDAG &DAG, SDLoc DL, SDValue Vec,
12892                                  EVT VT, bool Zero) {
12893   if (Vec.getNode())
12894     return Vec;
12895 
12896   if (Zero)
12897     return VT.isInteger() ? DAG.getConstant(0, DL, VT)
12898                           : DAG.getConstantFP(0.0, DL, VT);
12899 
12900   return DAG.getUNDEF(VT);
12901 }
12902 
12903 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12904 // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12905 // at most two distinct vectors, turn this into a shuffle node.
12906 // TODO: Support more than two inputs by constructing a tree of shuffles.
12907 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
12908   SDLoc dl(N);
12909   EVT VT = N->getValueType(0);
12910 
12911   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12912   if (!isTypeLegal(VT))
12913     return SDValue();
12914 
12915   // May only combine to shuffle after legalize if shuffle is legal.
12916   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12917     return SDValue();
12918 
12919   SDValue VecIn1, VecIn2;
12920   bool UsesZeroVector = false;
12921   unsigned NumElems = N->getNumOperands();
12922 
12923   // Record, for each element of newly built vector, which input it uses.
12924   // 0 stands for the zero vector, 1 and 2 for the two input vectors, and -1
12925   // for undef.
12926   SmallVector<int, 8> VectorMask;
12927   for (unsigned i = 0; i != NumElems; ++i) {
12928     SDValue Op = N->getOperand(i);
12929 
12930     if (Op.isUndef()) {
12931       VectorMask.push_back(-1);
12932       continue;
12933     }
12934 
12935     // See if we can combine this into a blend with a zero vector.
12936     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12937       UsesZeroVector = true;
12938       VectorMask.push_back(0);
12939       continue;
12940     }
12941 
12942     // Not an undef or zero. If the input is something other than an
12943     // EXTRACT_VECTOR_ELT with a constant index, bail out.
12944     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12945         !isa<ConstantSDNode>(Op.getOperand(1)))
12946       return SDValue();
12947 
12948     // We only allow up to two distinct input vectors.
12949     SDValue ExtractedFromVec = Op.getOperand(0);
12950     if (ExtractedFromVec == VecIn1) {
12951       VectorMask.push_back(1);
12952       continue;
12953     }
12954     if (ExtractedFromVec == VecIn2) {
12955       VectorMask.push_back(2);
12956       continue;
12957     }
12958 
12959     if (!VecIn1.getNode()) {
12960       VecIn1 = ExtractedFromVec;
12961       VectorMask.push_back(1);
12962     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12963       VecIn2 = ExtractedFromVec;
12964       VectorMask.push_back(2);
12965     } else {
12966       return SDValue();
12967     }
12968   }
12969 
12970   // If we didn't find at least one input vector, bail out.
12971   if (!VecIn1.getNode())
12972     return SDValue();
12973 
12974   EVT InVT1 = VecIn1.getValueType();
12975   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
12976   unsigned Vec2Offset = InVT1.getVectorNumElements();
12977   unsigned ShuffleNumElems = NumElems;
12978 
12979   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12980   SDValue ZeroIdx = DAG.getConstant(0, dl, IdxTy);
12981 
12982   // We can't generate a shuffle node with mismatched input and output types.
12983   // Try to make the types match.
12984   // TODO: Should this fire if InVT1/InVT2 are not legal types, or should
12985   // we let legalization run its course first?
12986   if (InVT1 != VT || InVT2 != VT) {
12987     // Both inputs and the output must have the same base element type.
12988     EVT ElemType = VT.getVectorElementType();
12989     if (ElemType != InVT1.getVectorElementType() ||
12990         ElemType != InVT2.getVectorElementType())
12991       return SDValue();
12992 
12993     // TODO: Canonicalize this so that if the vectors have different lengths,
12994     // VecIn1 is always longer.
12995 
12996     // The element types match, now figure out the lengths.
12997     if (InVT1.getSizeInBits() * 2 == VT.getSizeInBits() && InVT1 == InVT2) {
12998       // If both input vectors are exactly half the size of the output, concat
12999       // them. If we have only one (non-zero) input, concat it with undef.
13000       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
13001                            getRightHandValue(DAG, dl, VecIn2, InVT1, false));
13002       VecIn2 = SDValue();
13003       // If we have one "real" input and are blending with zero, we need the
13004       // zero elements to come from the second input, not the undef part of the
13005       // first input.
13006       if (UsesZeroVector)
13007         Vec2Offset = NumElems;
13008     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13009       if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13010         return SDValue();
13011 
13012       if (UsesZeroVector)
13013         return SDValue();
13014 
13015       if (!VecIn2.getNode()) {
13016         // If we only have one input vector, and it's twice the size of the
13017         // output, split it in two.
13018         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
13019                              DAG.getConstant(NumElems, dl, IdxTy));
13020         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, ZeroIdx);
13021         // Since we now have shorter input vectors, adjust the offset of the
13022         // second vector's start.
13023         Vec2Offset = NumElems;
13024       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13025         // VecIn1 is wider than the output, and we have another, possibly
13026         // smaller input. Pad the smaller input with undefs, shuffle at the
13027         // input vector width, and extract the output.
13028 
13029         // The shuffle type is different than VT, so check legality again.
13030         if (LegalOperations &&
13031             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13032           return SDValue();
13033 
13034         if (InVT1 != InVT2)
13035           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, InVT1,
13036                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13037         ShuffleNumElems = NumElems * 2;
13038       }
13039     } else {
13040       // TODO: Support cases where the length mismatch isn't exactly by a
13041       // factor of 2.
13042       return SDValue();
13043     }
13044   }
13045 
13046   // Initialize mask to undef.
13047   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13048 
13049   // Only need to run up to the number of elements actually used, not the
13050   // total number of elements in the shuffle - if we are shuffling a wider
13051   // vector, the high lanes should be set to undef.
13052   for (unsigned i = 0; i != NumElems; ++i) {
13053     if (VectorMask[i] == -1)
13054       continue;
13055 
13056     // If we are trying to blend with zero, we need to take a zero from the
13057     // correct position in the second input.
13058     if (VectorMask[i] == 0) {
13059       Mask[i] = Vec2Offset + i;
13060       continue;
13061     }
13062 
13063     SDValue Extract = N->getOperand(i);
13064     unsigned ExtIndex =
13065         cast<ConstantSDNode>(Extract.getOperand(1))->getZExtValue();
13066 
13067     if (VectorMask[i] == 1) {
13068       Mask[i] = ExtIndex;
13069       continue;
13070     }
13071 
13072     assert(VectorMask[i] == 2 && "Expected input to be from second vector");
13073     Mask[i] = Vec2Offset + ExtIndex;
13074   }
13075 
13076   // Avoid introducing illegal shuffles with zero.
13077   // TODO: This doesn't actually do anything smart at the moment.
13078   // We should either delete this, or check legality for all the shuffles
13079   // we create.
13080   if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
13081     return SDValue();
13082 
13083   // The type the input vectors may have changed above.
13084   InVT1 = VecIn1.getValueType();
13085 
13086   // If we already have a VecIn2, it should have the same type as VecIn1.
13087   // If we don't, get an undef/zero vector of the appropriate type.
13088   VecIn2 = getRightHandValue(DAG, dl, VecIn2, InVT1, UsesZeroVector);
13089   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13090 
13091   // Return the new VECTOR_SHUFFLE node.
13092   SDValue Ops[2];
13093   Ops[0] = VecIn1;
13094   Ops[1] = VecIn2;
13095   SDValue Shuffle = DAG.getVectorShuffle(InVT1, dl, Ops[0], Ops[1], Mask);
13096   if (ShuffleNumElems > NumElems)
13097     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Shuffle, ZeroIdx);
13098 
13099   return Shuffle;
13100 }
13101 
13102 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13103   EVT VT = N->getValueType(0);
13104 
13105   // A vector built entirely of undefs is undef.
13106   if (ISD::allOperandsUndef(N))
13107     return DAG.getUNDEF(VT);
13108 
13109   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13110     return V;
13111 
13112   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13113     return V;
13114 
13115   if (SDValue V = reduceBuildVecToShuffle(N))
13116     return V;
13117 
13118   return SDValue();
13119 }
13120 
13121 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13122   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13123   EVT OpVT = N->getOperand(0).getValueType();
13124 
13125   // If the operands are legal vectors, leave them alone.
13126   if (TLI.isTypeLegal(OpVT))
13127     return SDValue();
13128 
13129   SDLoc DL(N);
13130   EVT VT = N->getValueType(0);
13131   SmallVector<SDValue, 8> Ops;
13132 
13133   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13134   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13135 
13136   // Keep track of what we encounter.
13137   bool AnyInteger = false;
13138   bool AnyFP = false;
13139   for (const SDValue &Op : N->ops()) {
13140     if (ISD::BITCAST == Op.getOpcode() &&
13141         !Op.getOperand(0).getValueType().isVector())
13142       Ops.push_back(Op.getOperand(0));
13143     else if (ISD::UNDEF == Op.getOpcode())
13144       Ops.push_back(ScalarUndef);
13145     else
13146       return SDValue();
13147 
13148     // Note whether we encounter an integer or floating point scalar.
13149     // If it's neither, bail out, it could be something weird like x86mmx.
13150     EVT LastOpVT = Ops.back().getValueType();
13151     if (LastOpVT.isFloatingPoint())
13152       AnyFP = true;
13153     else if (LastOpVT.isInteger())
13154       AnyInteger = true;
13155     else
13156       return SDValue();
13157   }
13158 
13159   // If any of the operands is a floating point scalar bitcast to a vector,
13160   // use floating point types throughout, and bitcast everything.
13161   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
13162   if (AnyFP) {
13163     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
13164     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13165     if (AnyInteger) {
13166       for (SDValue &Op : Ops) {
13167         if (Op.getValueType() == SVT)
13168           continue;
13169         if (Op.isUndef())
13170           Op = ScalarUndef;
13171         else
13172           Op = DAG.getBitcast(SVT, Op);
13173       }
13174     }
13175   }
13176 
13177   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
13178                                VT.getSizeInBits() / SVT.getSizeInBits());
13179   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
13180 }
13181 
13182 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
13183 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
13184 // most two distinct vectors the same size as the result, attempt to turn this
13185 // into a legal shuffle.
13186 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
13187   EVT VT = N->getValueType(0);
13188   EVT OpVT = N->getOperand(0).getValueType();
13189   int NumElts = VT.getVectorNumElements();
13190   int NumOpElts = OpVT.getVectorNumElements();
13191 
13192   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
13193   SmallVector<int, 8> Mask;
13194 
13195   for (SDValue Op : N->ops()) {
13196     // Peek through any bitcast.
13197     while (Op.getOpcode() == ISD::BITCAST)
13198       Op = Op.getOperand(0);
13199 
13200     // UNDEF nodes convert to UNDEF shuffle mask values.
13201     if (Op.isUndef()) {
13202       Mask.append((unsigned)NumOpElts, -1);
13203       continue;
13204     }
13205 
13206     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13207       return SDValue();
13208 
13209     // What vector are we extracting the subvector from and at what index?
13210     SDValue ExtVec = Op.getOperand(0);
13211 
13212     // We want the EVT of the original extraction to correctly scale the
13213     // extraction index.
13214     EVT ExtVT = ExtVec.getValueType();
13215 
13216     // Peek through any bitcast.
13217     while (ExtVec.getOpcode() == ISD::BITCAST)
13218       ExtVec = ExtVec.getOperand(0);
13219 
13220     // UNDEF nodes convert to UNDEF shuffle mask values.
13221     if (ExtVec.isUndef()) {
13222       Mask.append((unsigned)NumOpElts, -1);
13223       continue;
13224     }
13225 
13226     if (!isa<ConstantSDNode>(Op.getOperand(1)))
13227       return SDValue();
13228     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13229 
13230     // Ensure that we are extracting a subvector from a vector the same
13231     // size as the result.
13232     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13233       return SDValue();
13234 
13235     // Scale the subvector index to account for any bitcast.
13236     int NumExtElts = ExtVT.getVectorNumElements();
13237     if (0 == (NumExtElts % NumElts))
13238       ExtIdx /= (NumExtElts / NumElts);
13239     else if (0 == (NumElts % NumExtElts))
13240       ExtIdx *= (NumElts / NumExtElts);
13241     else
13242       return SDValue();
13243 
13244     // At most we can reference 2 inputs in the final shuffle.
13245     if (SV0.isUndef() || SV0 == ExtVec) {
13246       SV0 = ExtVec;
13247       for (int i = 0; i != NumOpElts; ++i)
13248         Mask.push_back(i + ExtIdx);
13249     } else if (SV1.isUndef() || SV1 == ExtVec) {
13250       SV1 = ExtVec;
13251       for (int i = 0; i != NumOpElts; ++i)
13252         Mask.push_back(i + ExtIdx + NumElts);
13253     } else {
13254       return SDValue();
13255     }
13256   }
13257 
13258   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13259     return SDValue();
13260 
13261   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13262                               DAG.getBitcast(VT, SV1), Mask);
13263 }
13264 
13265 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13266   // If we only have one input vector, we don't need to do any concatenation.
13267   if (N->getNumOperands() == 1)
13268     return N->getOperand(0);
13269 
13270   // Check if all of the operands are undefs.
13271   EVT VT = N->getValueType(0);
13272   if (ISD::allOperandsUndef(N))
13273     return DAG.getUNDEF(VT);
13274 
13275   // Optimize concat_vectors where all but the first of the vectors are undef.
13276   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13277         return Op.isUndef();
13278       })) {
13279     SDValue In = N->getOperand(0);
13280     assert(In.getValueType().isVector() && "Must concat vectors");
13281 
13282     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13283     if (In->getOpcode() == ISD::BITCAST &&
13284         !In->getOperand(0)->getValueType(0).isVector()) {
13285       SDValue Scalar = In->getOperand(0);
13286 
13287       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13288       // look through the trunc so we can still do the transform:
13289       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13290       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13291           !TLI.isTypeLegal(Scalar.getValueType()) &&
13292           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13293         Scalar = Scalar->getOperand(0);
13294 
13295       EVT SclTy = Scalar->getValueType(0);
13296 
13297       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13298         return SDValue();
13299 
13300       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13301                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13302       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13303         return SDValue();
13304 
13305       SDLoc dl = SDLoc(N);
13306       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
13307       return DAG.getBitcast(VT, Res);
13308     }
13309   }
13310 
13311   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13312   // We have already tested above for an UNDEF only concatenation.
13313   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13314   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13315   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13316     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13317   };
13318   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13319     SmallVector<SDValue, 8> Opnds;
13320     EVT SVT = VT.getScalarType();
13321 
13322     EVT MinVT = SVT;
13323     if (!SVT.isFloatingPoint()) {
13324       // If BUILD_VECTOR are from built from integer, they may have different
13325       // operand types. Get the smallest type and truncate all operands to it.
13326       bool FoundMinVT = false;
13327       for (const SDValue &Op : N->ops())
13328         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13329           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13330           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13331           FoundMinVT = true;
13332         }
13333       assert(FoundMinVT && "Concat vector type mismatch");
13334     }
13335 
13336     for (const SDValue &Op : N->ops()) {
13337       EVT OpVT = Op.getValueType();
13338       unsigned NumElts = OpVT.getVectorNumElements();
13339 
13340       if (ISD::UNDEF == Op.getOpcode())
13341         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13342 
13343       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13344         if (SVT.isFloatingPoint()) {
13345           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13346           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13347         } else {
13348           for (unsigned i = 0; i != NumElts; ++i)
13349             Opnds.push_back(
13350                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13351         }
13352       }
13353     }
13354 
13355     assert(VT.getVectorNumElements() == Opnds.size() &&
13356            "Concat vector type mismatch");
13357     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13358   }
13359 
13360   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13361   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13362     return V;
13363 
13364   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13365   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13366     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13367       return V;
13368 
13369   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13370   // nodes often generate nop CONCAT_VECTOR nodes.
13371   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13372   // place the incoming vectors at the exact same location.
13373   SDValue SingleSource = SDValue();
13374   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13375 
13376   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13377     SDValue Op = N->getOperand(i);
13378 
13379     if (Op.isUndef())
13380       continue;
13381 
13382     // Check if this is the identity extract:
13383     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13384       return SDValue();
13385 
13386     // Find the single incoming vector for the extract_subvector.
13387     if (SingleSource.getNode()) {
13388       if (Op.getOperand(0) != SingleSource)
13389         return SDValue();
13390     } else {
13391       SingleSource = Op.getOperand(0);
13392 
13393       // Check the source type is the same as the type of the result.
13394       // If not, this concat may extend the vector, so we can not
13395       // optimize it away.
13396       if (SingleSource.getValueType() != N->getValueType(0))
13397         return SDValue();
13398     }
13399 
13400     unsigned IdentityIndex = i * PartNumElem;
13401     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13402     // The extract index must be constant.
13403     if (!CS)
13404       return SDValue();
13405 
13406     // Check that we are reading from the identity index.
13407     if (CS->getZExtValue() != IdentityIndex)
13408       return SDValue();
13409   }
13410 
13411   if (SingleSource.getNode())
13412     return SingleSource;
13413 
13414   return SDValue();
13415 }
13416 
13417 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13418   EVT NVT = N->getValueType(0);
13419   SDValue V = N->getOperand(0);
13420 
13421   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13422     // Combine:
13423     //    (extract_subvec (concat V1, V2, ...), i)
13424     // Into:
13425     //    Vi if possible
13426     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13427     // type.
13428     if (V->getOperand(0).getValueType() != NVT)
13429       return SDValue();
13430     unsigned Idx = N->getConstantOperandVal(1);
13431     unsigned NumElems = NVT.getVectorNumElements();
13432     assert((Idx % NumElems) == 0 &&
13433            "IDX in concat is not a multiple of the result vector length.");
13434     return V->getOperand(Idx / NumElems);
13435   }
13436 
13437   // Skip bitcasting
13438   if (V->getOpcode() == ISD::BITCAST)
13439     V = V.getOperand(0);
13440 
13441   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13442     SDLoc dl(N);
13443     // Handle only simple case where vector being inserted and vector
13444     // being extracted are of same type, and are half size of larger vectors.
13445     EVT BigVT = V->getOperand(0).getValueType();
13446     EVT SmallVT = V->getOperand(1).getValueType();
13447     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13448       return SDValue();
13449 
13450     // Only handle cases where both indexes are constants with the same type.
13451     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13452     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13453 
13454     if (InsIdx && ExtIdx &&
13455         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13456         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13457       // Combine:
13458       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13459       // Into:
13460       //    indices are equal or bit offsets are equal => V1
13461       //    otherwise => (extract_subvec V1, ExtIdx)
13462       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
13463           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
13464         return DAG.getBitcast(NVT, V->getOperand(1));
13465       return DAG.getNode(
13466           ISD::EXTRACT_SUBVECTOR, dl, NVT,
13467           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13468           N->getOperand(1));
13469     }
13470   }
13471 
13472   return SDValue();
13473 }
13474 
13475 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13476                                                  SDValue V, SelectionDAG &DAG) {
13477   SDLoc DL(V);
13478   EVT VT = V.getValueType();
13479 
13480   switch (V.getOpcode()) {
13481   default:
13482     return V;
13483 
13484   case ISD::CONCAT_VECTORS: {
13485     EVT OpVT = V->getOperand(0).getValueType();
13486     int OpSize = OpVT.getVectorNumElements();
13487     SmallBitVector OpUsedElements(OpSize, false);
13488     bool FoundSimplification = false;
13489     SmallVector<SDValue, 4> NewOps;
13490     NewOps.reserve(V->getNumOperands());
13491     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13492       SDValue Op = V->getOperand(i);
13493       bool OpUsed = false;
13494       for (int j = 0; j < OpSize; ++j)
13495         if (UsedElements[i * OpSize + j]) {
13496           OpUsedElements[j] = true;
13497           OpUsed = true;
13498         }
13499       NewOps.push_back(
13500           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13501                  : DAG.getUNDEF(OpVT));
13502       FoundSimplification |= Op == NewOps.back();
13503       OpUsedElements.reset();
13504     }
13505     if (FoundSimplification)
13506       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13507     return V;
13508   }
13509 
13510   case ISD::INSERT_SUBVECTOR: {
13511     SDValue BaseV = V->getOperand(0);
13512     SDValue SubV = V->getOperand(1);
13513     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13514     if (!IdxN)
13515       return V;
13516 
13517     int SubSize = SubV.getValueType().getVectorNumElements();
13518     int Idx = IdxN->getZExtValue();
13519     bool SubVectorUsed = false;
13520     SmallBitVector SubUsedElements(SubSize, false);
13521     for (int i = 0; i < SubSize; ++i)
13522       if (UsedElements[i + Idx]) {
13523         SubVectorUsed = true;
13524         SubUsedElements[i] = true;
13525         UsedElements[i + Idx] = false;
13526       }
13527 
13528     // Now recurse on both the base and sub vectors.
13529     SDValue SimplifiedSubV =
13530         SubVectorUsed
13531             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13532             : DAG.getUNDEF(SubV.getValueType());
13533     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13534     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13535       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13536                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13537     return V;
13538   }
13539   }
13540 }
13541 
13542 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13543                                        SDValue N1, SelectionDAG &DAG) {
13544   EVT VT = SVN->getValueType(0);
13545   int NumElts = VT.getVectorNumElements();
13546   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13547   for (int M : SVN->getMask())
13548     if (M >= 0 && M < NumElts)
13549       N0UsedElements[M] = true;
13550     else if (M >= NumElts)
13551       N1UsedElements[M - NumElts] = true;
13552 
13553   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13554   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13555   if (S0 == N0 && S1 == N1)
13556     return SDValue();
13557 
13558   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13559 }
13560 
13561 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13562 // or turn a shuffle of a single concat into simpler shuffle then concat.
13563 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13564   EVT VT = N->getValueType(0);
13565   unsigned NumElts = VT.getVectorNumElements();
13566 
13567   SDValue N0 = N->getOperand(0);
13568   SDValue N1 = N->getOperand(1);
13569   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13570 
13571   SmallVector<SDValue, 4> Ops;
13572   EVT ConcatVT = N0.getOperand(0).getValueType();
13573   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13574   unsigned NumConcats = NumElts / NumElemsPerConcat;
13575 
13576   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13577   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13578   // half vector elements.
13579   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13580       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13581                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13582     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13583                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13584     N1 = DAG.getUNDEF(ConcatVT);
13585     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13586   }
13587 
13588   // Look at every vector that's inserted. We're looking for exact
13589   // subvector-sized copies from a concatenated vector
13590   for (unsigned I = 0; I != NumConcats; ++I) {
13591     // Make sure we're dealing with a copy.
13592     unsigned Begin = I * NumElemsPerConcat;
13593     bool AllUndef = true, NoUndef = true;
13594     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13595       if (SVN->getMaskElt(J) >= 0)
13596         AllUndef = false;
13597       else
13598         NoUndef = false;
13599     }
13600 
13601     if (NoUndef) {
13602       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13603         return SDValue();
13604 
13605       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13606         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13607           return SDValue();
13608 
13609       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13610       if (FirstElt < N0.getNumOperands())
13611         Ops.push_back(N0.getOperand(FirstElt));
13612       else
13613         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13614 
13615     } else if (AllUndef) {
13616       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13617     } else { // Mixed with general masks and undefs, can't do optimization.
13618       return SDValue();
13619     }
13620   }
13621 
13622   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13623 }
13624 
13625 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13626   EVT VT = N->getValueType(0);
13627   unsigned NumElts = VT.getVectorNumElements();
13628 
13629   SDValue N0 = N->getOperand(0);
13630   SDValue N1 = N->getOperand(1);
13631 
13632   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13633 
13634   // Canonicalize shuffle undef, undef -> undef
13635   if (N0.isUndef() && N1.isUndef())
13636     return DAG.getUNDEF(VT);
13637 
13638   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13639 
13640   // Canonicalize shuffle v, v -> v, undef
13641   if (N0 == N1) {
13642     SmallVector<int, 8> NewMask;
13643     for (unsigned i = 0; i != NumElts; ++i) {
13644       int Idx = SVN->getMaskElt(i);
13645       if (Idx >= (int)NumElts) Idx -= NumElts;
13646       NewMask.push_back(Idx);
13647     }
13648     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
13649   }
13650 
13651   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13652   if (N0.isUndef())
13653     return DAG.getCommutedVectorShuffle(*SVN);
13654 
13655   // Remove references to rhs if it is undef
13656   if (N1.isUndef()) {
13657     bool Changed = false;
13658     SmallVector<int, 8> NewMask;
13659     for (unsigned i = 0; i != NumElts; ++i) {
13660       int Idx = SVN->getMaskElt(i);
13661       if (Idx >= (int)NumElts) {
13662         Idx = -1;
13663         Changed = true;
13664       }
13665       NewMask.push_back(Idx);
13666     }
13667     if (Changed)
13668       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
13669   }
13670 
13671   // If it is a splat, check if the argument vector is another splat or a
13672   // build_vector.
13673   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13674     SDNode *V = N0.getNode();
13675 
13676     // If this is a bit convert that changes the element type of the vector but
13677     // not the number of vector elements, look through it.  Be careful not to
13678     // look though conversions that change things like v4f32 to v2f64.
13679     if (V->getOpcode() == ISD::BITCAST) {
13680       SDValue ConvInput = V->getOperand(0);
13681       if (ConvInput.getValueType().isVector() &&
13682           ConvInput.getValueType().getVectorNumElements() == NumElts)
13683         V = ConvInput.getNode();
13684     }
13685 
13686     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13687       assert(V->getNumOperands() == NumElts &&
13688              "BUILD_VECTOR has wrong number of operands");
13689       SDValue Base;
13690       bool AllSame = true;
13691       for (unsigned i = 0; i != NumElts; ++i) {
13692         if (!V->getOperand(i).isUndef()) {
13693           Base = V->getOperand(i);
13694           break;
13695         }
13696       }
13697       // Splat of <u, u, u, u>, return <u, u, u, u>
13698       if (!Base.getNode())
13699         return N0;
13700       for (unsigned i = 0; i != NumElts; ++i) {
13701         if (V->getOperand(i) != Base) {
13702           AllSame = false;
13703           break;
13704         }
13705       }
13706       // Splat of <x, x, x, x>, return <x, x, x, x>
13707       if (AllSame)
13708         return N0;
13709 
13710       // Canonicalize any other splat as a build_vector.
13711       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13712       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13713       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13714 
13715       // We may have jumped through bitcasts, so the type of the
13716       // BUILD_VECTOR may not match the type of the shuffle.
13717       if (V->getValueType(0) != VT)
13718         NewBV = DAG.getBitcast(VT, NewBV);
13719       return NewBV;
13720     }
13721   }
13722 
13723   // There are various patterns used to build up a vector from smaller vectors,
13724   // subvectors, or elements. Scan chains of these and replace unused insertions
13725   // or components with undef.
13726   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13727     return S;
13728 
13729   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13730       Level < AfterLegalizeVectorOps &&
13731       (N1.isUndef() ||
13732       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13733        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13734     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13735       return V;
13736   }
13737 
13738   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13739   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13740   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13741     SmallVector<SDValue, 8> Ops;
13742     for (int M : SVN->getMask()) {
13743       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13744       if (M >= 0) {
13745         int Idx = M % NumElts;
13746         SDValue &S = (M < (int)NumElts ? N0 : N1);
13747         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13748           Op = S.getOperand(Idx);
13749         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13750           if (Idx == 0)
13751             Op = S.getOperand(0);
13752         } else {
13753           // Operand can't be combined - bail out.
13754           break;
13755         }
13756       }
13757       Ops.push_back(Op);
13758     }
13759     if (Ops.size() == VT.getVectorNumElements()) {
13760       // BUILD_VECTOR requires all inputs to be of the same type, find the
13761       // maximum type and extend them all.
13762       EVT SVT = VT.getScalarType();
13763       if (SVT.isInteger())
13764         for (SDValue &Op : Ops)
13765           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13766       if (SVT != VT.getScalarType())
13767         for (SDValue &Op : Ops)
13768           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13769                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13770                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13771       return DAG.getBuildVector(VT, SDLoc(N), Ops);
13772     }
13773   }
13774 
13775   // If this shuffle only has a single input that is a bitcasted shuffle,
13776   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13777   // back to their original types.
13778   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13779       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13780       TLI.isTypeLegal(VT)) {
13781 
13782     // Peek through the bitcast only if there is one user.
13783     SDValue BC0 = N0;
13784     while (BC0.getOpcode() == ISD::BITCAST) {
13785       if (!BC0.hasOneUse())
13786         break;
13787       BC0 = BC0.getOperand(0);
13788     }
13789 
13790     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13791       if (Scale == 1)
13792         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13793 
13794       SmallVector<int, 8> NewMask;
13795       for (int M : Mask)
13796         for (int s = 0; s != Scale; ++s)
13797           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13798       return NewMask;
13799     };
13800 
13801     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13802       EVT SVT = VT.getScalarType();
13803       EVT InnerVT = BC0->getValueType(0);
13804       EVT InnerSVT = InnerVT.getScalarType();
13805 
13806       // Determine which shuffle works with the smaller scalar type.
13807       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13808       EVT ScaleSVT = ScaleVT.getScalarType();
13809 
13810       if (TLI.isTypeLegal(ScaleVT) &&
13811           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13812           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13813 
13814         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13815         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13816 
13817         // Scale the shuffle masks to the smaller scalar type.
13818         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13819         SmallVector<int, 8> InnerMask =
13820             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13821         SmallVector<int, 8> OuterMask =
13822             ScaleShuffleMask(SVN->getMask(), OuterScale);
13823 
13824         // Merge the shuffle masks.
13825         SmallVector<int, 8> NewMask;
13826         for (int M : OuterMask)
13827           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13828 
13829         // Test for shuffle mask legality over both commutations.
13830         SDValue SV0 = BC0->getOperand(0);
13831         SDValue SV1 = BC0->getOperand(1);
13832         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13833         if (!LegalMask) {
13834           std::swap(SV0, SV1);
13835           ShuffleVectorSDNode::commuteMask(NewMask);
13836           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13837         }
13838 
13839         if (LegalMask) {
13840           SV0 = DAG.getBitcast(ScaleVT, SV0);
13841           SV1 = DAG.getBitcast(ScaleVT, SV1);
13842           return DAG.getBitcast(
13843               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13844         }
13845       }
13846     }
13847   }
13848 
13849   // Canonicalize shuffles according to rules:
13850   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13851   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13852   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13853   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13854       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13855       TLI.isTypeLegal(VT)) {
13856     // The incoming shuffle must be of the same type as the result of the
13857     // current shuffle.
13858     assert(N1->getOperand(0).getValueType() == VT &&
13859            "Shuffle types don't match");
13860 
13861     SDValue SV0 = N1->getOperand(0);
13862     SDValue SV1 = N1->getOperand(1);
13863     bool HasSameOp0 = N0 == SV0;
13864     bool IsSV1Undef = SV1.isUndef();
13865     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13866       // Commute the operands of this shuffle so that next rule
13867       // will trigger.
13868       return DAG.getCommutedVectorShuffle(*SVN);
13869   }
13870 
13871   // Try to fold according to rules:
13872   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13873   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13874   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13875   // Don't try to fold shuffles with illegal type.
13876   // Only fold if this shuffle is the only user of the other shuffle.
13877   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13878       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13879     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13880 
13881     // The incoming shuffle must be of the same type as the result of the
13882     // current shuffle.
13883     assert(OtherSV->getOperand(0).getValueType() == VT &&
13884            "Shuffle types don't match");
13885 
13886     SDValue SV0, SV1;
13887     SmallVector<int, 4> Mask;
13888     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13889     // operand, and SV1 as the second operand.
13890     for (unsigned i = 0; i != NumElts; ++i) {
13891       int Idx = SVN->getMaskElt(i);
13892       if (Idx < 0) {
13893         // Propagate Undef.
13894         Mask.push_back(Idx);
13895         continue;
13896       }
13897 
13898       SDValue CurrentVec;
13899       if (Idx < (int)NumElts) {
13900         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13901         // shuffle mask to identify which vector is actually referenced.
13902         Idx = OtherSV->getMaskElt(Idx);
13903         if (Idx < 0) {
13904           // Propagate Undef.
13905           Mask.push_back(Idx);
13906           continue;
13907         }
13908 
13909         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13910                                            : OtherSV->getOperand(1);
13911       } else {
13912         // This shuffle index references an element within N1.
13913         CurrentVec = N1;
13914       }
13915 
13916       // Simple case where 'CurrentVec' is UNDEF.
13917       if (CurrentVec.isUndef()) {
13918         Mask.push_back(-1);
13919         continue;
13920       }
13921 
13922       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13923       // will be the first or second operand of the combined shuffle.
13924       Idx = Idx % NumElts;
13925       if (!SV0.getNode() || SV0 == CurrentVec) {
13926         // Ok. CurrentVec is the left hand side.
13927         // Update the mask accordingly.
13928         SV0 = CurrentVec;
13929         Mask.push_back(Idx);
13930         continue;
13931       }
13932 
13933       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13934       if (SV1.getNode() && SV1 != CurrentVec)
13935         return SDValue();
13936 
13937       // Ok. CurrentVec is the right hand side.
13938       // Update the mask accordingly.
13939       SV1 = CurrentVec;
13940       Mask.push_back(Idx + NumElts);
13941     }
13942 
13943     // Check if all indices in Mask are Undef. In case, propagate Undef.
13944     bool isUndefMask = true;
13945     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13946       isUndefMask &= Mask[i] < 0;
13947 
13948     if (isUndefMask)
13949       return DAG.getUNDEF(VT);
13950 
13951     if (!SV0.getNode())
13952       SV0 = DAG.getUNDEF(VT);
13953     if (!SV1.getNode())
13954       SV1 = DAG.getUNDEF(VT);
13955 
13956     // Avoid introducing shuffles with illegal mask.
13957     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13958       ShuffleVectorSDNode::commuteMask(Mask);
13959 
13960       if (!TLI.isShuffleMaskLegal(Mask, VT))
13961         return SDValue();
13962 
13963       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13964       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13965       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13966       std::swap(SV0, SV1);
13967     }
13968 
13969     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13970     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13971     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13972     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
13973   }
13974 
13975   return SDValue();
13976 }
13977 
13978 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13979   SDValue InVal = N->getOperand(0);
13980   EVT VT = N->getValueType(0);
13981 
13982   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13983   // with a VECTOR_SHUFFLE.
13984   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13985     SDValue InVec = InVal->getOperand(0);
13986     SDValue EltNo = InVal->getOperand(1);
13987 
13988     // FIXME: We could support implicit truncation if the shuffle can be
13989     // scaled to a smaller vector scalar type.
13990     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13991     if (C0 && VT == InVec.getValueType() &&
13992         VT.getScalarType() == InVal.getValueType()) {
13993       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13994       int Elt = C0->getZExtValue();
13995       NewMask[0] = Elt;
13996 
13997       if (TLI.isShuffleMaskLegal(NewMask, VT))
13998         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13999                                     NewMask);
14000     }
14001   }
14002 
14003   return SDValue();
14004 }
14005 
14006 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
14007   EVT VT = N->getValueType(0);
14008   SDValue N0 = N->getOperand(0);
14009   SDValue N1 = N->getOperand(1);
14010   SDValue N2 = N->getOperand(2);
14011 
14012   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
14013   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
14014   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
14015   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
14016       N0.getOperand(1).getValueType() == N1.getValueType() &&
14017       N0.getOperand(2) == N2)
14018     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
14019                        N1, N2);
14020 
14021   if (N0.getValueType() != N1.getValueType())
14022     return SDValue();
14023 
14024   // If the input vector is a concatenation, and the insert replaces
14025   // one of the halves, we can optimize into a single concat_vectors.
14026   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
14027       N2.getOpcode() == ISD::Constant) {
14028     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
14029 
14030     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14031     // (concat_vectors Z, Y)
14032     if (InsIdx == 0)
14033       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
14034                          N0.getOperand(1));
14035 
14036     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
14037     // (concat_vectors X, Z)
14038     if (InsIdx == VT.getVectorNumElements() / 2)
14039       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
14040                          N1);
14041   }
14042 
14043   return SDValue();
14044 }
14045 
14046 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
14047   SDValue N0 = N->getOperand(0);
14048 
14049   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
14050   if (N0->getOpcode() == ISD::FP16_TO_FP)
14051     return N0->getOperand(0);
14052 
14053   return SDValue();
14054 }
14055 
14056 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
14057   SDValue N0 = N->getOperand(0);
14058 
14059   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
14060   if (N0->getOpcode() == ISD::AND) {
14061     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
14062     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
14063       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
14064                          N0.getOperand(0));
14065     }
14066   }
14067 
14068   return SDValue();
14069 }
14070 
14071 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
14072 /// with the destination vector and a zero vector.
14073 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
14074 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
14075 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
14076   EVT VT = N->getValueType(0);
14077   SDValue LHS = N->getOperand(0);
14078   SDValue RHS = N->getOperand(1);
14079   SDLoc dl(N);
14080 
14081   // Make sure we're not running after operation legalization where it
14082   // may have custom lowered the vector shuffles.
14083   if (LegalOperations)
14084     return SDValue();
14085 
14086   if (N->getOpcode() != ISD::AND)
14087     return SDValue();
14088 
14089   if (RHS.getOpcode() == ISD::BITCAST)
14090     RHS = RHS.getOperand(0);
14091 
14092   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
14093     return SDValue();
14094 
14095   EVT RVT = RHS.getValueType();
14096   unsigned NumElts = RHS.getNumOperands();
14097 
14098   // Attempt to create a valid clear mask, splitting the mask into
14099   // sub elements and checking to see if each is
14100   // all zeros or all ones - suitable for shuffle masking.
14101   auto BuildClearMask = [&](int Split) {
14102     int NumSubElts = NumElts * Split;
14103     int NumSubBits = RVT.getScalarSizeInBits() / Split;
14104 
14105     SmallVector<int, 8> Indices;
14106     for (int i = 0; i != NumSubElts; ++i) {
14107       int EltIdx = i / Split;
14108       int SubIdx = i % Split;
14109       SDValue Elt = RHS.getOperand(EltIdx);
14110       if (Elt.isUndef()) {
14111         Indices.push_back(-1);
14112         continue;
14113       }
14114 
14115       APInt Bits;
14116       if (isa<ConstantSDNode>(Elt))
14117         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
14118       else if (isa<ConstantFPSDNode>(Elt))
14119         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
14120       else
14121         return SDValue();
14122 
14123       // Extract the sub element from the constant bit mask.
14124       if (DAG.getDataLayout().isBigEndian()) {
14125         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
14126       } else {
14127         Bits = Bits.lshr(SubIdx * NumSubBits);
14128       }
14129 
14130       if (Split > 1)
14131         Bits = Bits.trunc(NumSubBits);
14132 
14133       if (Bits.isAllOnesValue())
14134         Indices.push_back(i);
14135       else if (Bits == 0)
14136         Indices.push_back(i + NumSubElts);
14137       else
14138         return SDValue();
14139     }
14140 
14141     // Let's see if the target supports this vector_shuffle.
14142     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
14143     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
14144     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
14145       return SDValue();
14146 
14147     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
14148     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
14149                                                    DAG.getBitcast(ClearVT, LHS),
14150                                                    Zero, Indices));
14151   };
14152 
14153   // Determine maximum split level (byte level masking).
14154   int MaxSplit = 1;
14155   if (RVT.getScalarSizeInBits() % 8 == 0)
14156     MaxSplit = RVT.getScalarSizeInBits() / 8;
14157 
14158   for (int Split = 1; Split <= MaxSplit; ++Split)
14159     if (RVT.getScalarSizeInBits() % Split == 0)
14160       if (SDValue S = BuildClearMask(Split))
14161         return S;
14162 
14163   return SDValue();
14164 }
14165 
14166 /// Visit a binary vector operation, like ADD.
14167 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
14168   assert(N->getValueType(0).isVector() &&
14169          "SimplifyVBinOp only works on vectors!");
14170 
14171   SDValue LHS = N->getOperand(0);
14172   SDValue RHS = N->getOperand(1);
14173   SDValue Ops[] = {LHS, RHS};
14174 
14175   // See if we can constant fold the vector operation.
14176   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
14177           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
14178     return Fold;
14179 
14180   // Try to convert a constant mask AND into a shuffle clear mask.
14181   if (SDValue Shuffle = XformToShuffleWithZero(N))
14182     return Shuffle;
14183 
14184   // Type legalization might introduce new shuffles in the DAG.
14185   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
14186   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
14187   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
14188       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
14189       LHS.getOperand(1).isUndef() &&
14190       RHS.getOperand(1).isUndef()) {
14191     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
14192     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
14193 
14194     if (SVN0->getMask().equals(SVN1->getMask())) {
14195       EVT VT = N->getValueType(0);
14196       SDValue UndefVector = LHS.getOperand(1);
14197       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
14198                                      LHS.getOperand(0), RHS.getOperand(0),
14199                                      N->getFlags());
14200       AddUsersToWorklist(N);
14201       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
14202                                   SVN0->getMask());
14203     }
14204   }
14205 
14206   return SDValue();
14207 }
14208 
14209 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
14210                                     SDValue N2) {
14211   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
14212 
14213   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
14214                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
14215 
14216   // If we got a simplified select_cc node back from SimplifySelectCC, then
14217   // break it down into a new SETCC node, and a new SELECT node, and then return
14218   // the SELECT node, since we were called with a SELECT node.
14219   if (SCC.getNode()) {
14220     // Check to see if we got a select_cc back (to turn into setcc/select).
14221     // Otherwise, just return whatever node we got back, like fabs.
14222     if (SCC.getOpcode() == ISD::SELECT_CC) {
14223       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
14224                                   N0.getValueType(),
14225                                   SCC.getOperand(0), SCC.getOperand(1),
14226                                   SCC.getOperand(4));
14227       AddToWorklist(SETCC.getNode());
14228       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14229                            SCC.getOperand(2), SCC.getOperand(3));
14230     }
14231 
14232     return SCC;
14233   }
14234   return SDValue();
14235 }
14236 
14237 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14238 /// being selected between, see if we can simplify the select.  Callers of this
14239 /// should assume that TheSelect is deleted if this returns true.  As such, they
14240 /// should return the appropriate thing (e.g. the node) back to the top-level of
14241 /// the DAG combiner loop to avoid it being looked at.
14242 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14243                                     SDValue RHS) {
14244 
14245   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14246   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14247   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14248     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14249       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14250       SDValue Sqrt = RHS;
14251       ISD::CondCode CC;
14252       SDValue CmpLHS;
14253       const ConstantFPSDNode *Zero = nullptr;
14254 
14255       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14256         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14257         CmpLHS = TheSelect->getOperand(0);
14258         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14259       } else {
14260         // SELECT or VSELECT
14261         SDValue Cmp = TheSelect->getOperand(0);
14262         if (Cmp.getOpcode() == ISD::SETCC) {
14263           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14264           CmpLHS = Cmp.getOperand(0);
14265           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14266         }
14267       }
14268       if (Zero && Zero->isZero() &&
14269           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14270           CC == ISD::SETULT || CC == ISD::SETLT)) {
14271         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14272         CombineTo(TheSelect, Sqrt);
14273         return true;
14274       }
14275     }
14276   }
14277   // Cannot simplify select with vector condition
14278   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14279 
14280   // If this is a select from two identical things, try to pull the operation
14281   // through the select.
14282   if (LHS.getOpcode() != RHS.getOpcode() ||
14283       !LHS.hasOneUse() || !RHS.hasOneUse())
14284     return false;
14285 
14286   // If this is a load and the token chain is identical, replace the select
14287   // of two loads with a load through a select of the address to load from.
14288   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14289   // constants have been dropped into the constant pool.
14290   if (LHS.getOpcode() == ISD::LOAD) {
14291     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14292     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14293 
14294     // Token chains must be identical.
14295     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14296         // Do not let this transformation reduce the number of volatile loads.
14297         LLD->isVolatile() || RLD->isVolatile() ||
14298         // FIXME: If either is a pre/post inc/dec load,
14299         // we'd need to split out the address adjustment.
14300         LLD->isIndexed() || RLD->isIndexed() ||
14301         // If this is an EXTLOAD, the VT's must match.
14302         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14303         // If this is an EXTLOAD, the kind of extension must match.
14304         (LLD->getExtensionType() != RLD->getExtensionType() &&
14305          // The only exception is if one of the extensions is anyext.
14306          LLD->getExtensionType() != ISD::EXTLOAD &&
14307          RLD->getExtensionType() != ISD::EXTLOAD) ||
14308         // FIXME: this discards src value information.  This is
14309         // over-conservative. It would be beneficial to be able to remember
14310         // both potential memory locations.  Since we are discarding
14311         // src value info, don't do the transformation if the memory
14312         // locations are not in the default address space.
14313         LLD->getPointerInfo().getAddrSpace() != 0 ||
14314         RLD->getPointerInfo().getAddrSpace() != 0 ||
14315         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14316                                       LLD->getBasePtr().getValueType()))
14317       return false;
14318 
14319     // Check that the select condition doesn't reach either load.  If so,
14320     // folding this will induce a cycle into the DAG.  If not, this is safe to
14321     // xform, so create a select of the addresses.
14322     SDValue Addr;
14323     if (TheSelect->getOpcode() == ISD::SELECT) {
14324       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14325       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14326           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14327         return false;
14328       // The loads must not depend on one another.
14329       if (LLD->isPredecessorOf(RLD) ||
14330           RLD->isPredecessorOf(LLD))
14331         return false;
14332       Addr = DAG.getSelect(SDLoc(TheSelect),
14333                            LLD->getBasePtr().getValueType(),
14334                            TheSelect->getOperand(0), LLD->getBasePtr(),
14335                            RLD->getBasePtr());
14336     } else {  // Otherwise SELECT_CC
14337       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14338       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14339 
14340       if ((LLD->hasAnyUseOfValue(1) &&
14341            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14342           (RLD->hasAnyUseOfValue(1) &&
14343            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14344         return false;
14345 
14346       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14347                          LLD->getBasePtr().getValueType(),
14348                          TheSelect->getOperand(0),
14349                          TheSelect->getOperand(1),
14350                          LLD->getBasePtr(), RLD->getBasePtr(),
14351                          TheSelect->getOperand(4));
14352     }
14353 
14354     SDValue Load;
14355     // It is safe to replace the two loads if they have different alignments,
14356     // but the new load must be the minimum (most restrictive) alignment of the
14357     // inputs.
14358     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14359     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
14360     if (!RLD->isInvariant())
14361       MMOFlags &= ~MachineMemOperand::MOInvariant;
14362     if (!RLD->isDereferenceable())
14363       MMOFlags &= ~MachineMemOperand::MODereferenceable;
14364     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14365       // FIXME: Discards pointer and AA info.
14366       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
14367                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
14368                          MMOFlags);
14369     } else {
14370       // FIXME: Discards pointer and AA info.
14371       Load = DAG.getExtLoad(
14372           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
14373                                                   : LLD->getExtensionType(),
14374           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
14375           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
14376     }
14377 
14378     // Users of the select now use the result of the load.
14379     CombineTo(TheSelect, Load);
14380 
14381     // Users of the old loads now use the new load's chain.  We know the
14382     // old-load value is dead now.
14383     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14384     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14385     return true;
14386   }
14387 
14388   return false;
14389 }
14390 
14391 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14392 /// where 'cond' is the comparison specified by CC.
14393 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
14394                                       SDValue N2, SDValue N3, ISD::CondCode CC,
14395                                       bool NotExtCompare) {
14396   // (x ? y : y) -> y.
14397   if (N2 == N3) return N2;
14398 
14399   EVT VT = N2.getValueType();
14400   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14401   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14402 
14403   // Determine if the condition we're dealing with is constant
14404   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14405                               N0, N1, CC, DL, false);
14406   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14407 
14408   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14409     // fold select_cc true, x, y -> x
14410     // fold select_cc false, x, y -> y
14411     return !SCCC->isNullValue() ? N2 : N3;
14412   }
14413 
14414   // Check to see if we can simplify the select into an fabs node
14415   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14416     // Allow either -0.0 or 0.0
14417     if (CFP->isZero()) {
14418       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14419       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14420           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14421           N2 == N3.getOperand(0))
14422         return DAG.getNode(ISD::FABS, DL, VT, N0);
14423 
14424       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14425       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14426           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14427           N2.getOperand(0) == N3)
14428         return DAG.getNode(ISD::FABS, DL, VT, N3);
14429     }
14430   }
14431 
14432   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14433   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14434   // in it.  This is a win when the constant is not otherwise available because
14435   // it replaces two constant pool loads with one.  We only do this if the FP
14436   // type is known to be legal, because if it isn't, then we are before legalize
14437   // types an we want the other legalization to happen first (e.g. to avoid
14438   // messing with soft float) and if the ConstantFP is not legal, because if
14439   // it is legal, we may not need to store the FP constant in a constant pool.
14440   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14441     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14442       if (TLI.isTypeLegal(N2.getValueType()) &&
14443           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14444                TargetLowering::Legal &&
14445            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14446            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14447           // If both constants have multiple uses, then we won't need to do an
14448           // extra load, they are likely around in registers for other users.
14449           (TV->hasOneUse() || FV->hasOneUse())) {
14450         Constant *Elts[] = {
14451           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14452           const_cast<ConstantFP*>(TV->getConstantFPValue())
14453         };
14454         Type *FPTy = Elts[0]->getType();
14455         const DataLayout &TD = DAG.getDataLayout();
14456 
14457         // Create a ConstantArray of the two constants.
14458         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14459         SDValue CPIdx =
14460             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14461                                 TD.getPrefTypeAlignment(FPTy));
14462         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14463 
14464         // Get the offsets to the 0 and 1 element of the array so that we can
14465         // select between them.
14466         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14467         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14468         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14469 
14470         SDValue Cond = DAG.getSetCC(DL,
14471                                     getSetCCResultType(N0.getValueType()),
14472                                     N0, N1, CC);
14473         AddToWorklist(Cond.getNode());
14474         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14475                                           Cond, One, Zero);
14476         AddToWorklist(CstOffset.getNode());
14477         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14478                             CstOffset);
14479         AddToWorklist(CPIdx.getNode());
14480         return DAG.getLoad(
14481             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14482             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14483             Alignment);
14484       }
14485     }
14486 
14487   // Check to see if we can perform the "gzip trick", transforming
14488   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14489   if (isNullConstant(N3) && CC == ISD::SETLT &&
14490       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14491        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14492     EVT XType = N0.getValueType();
14493     EVT AType = N2.getValueType();
14494     if (XType.bitsGE(AType)) {
14495       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14496       // single-bit constant.
14497       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14498         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14499         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14500         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14501                                        getShiftAmountTy(N0.getValueType()));
14502         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14503                                     XType, N0, ShCt);
14504         AddToWorklist(Shift.getNode());
14505 
14506         if (XType.bitsGT(AType)) {
14507           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14508           AddToWorklist(Shift.getNode());
14509         }
14510 
14511         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14512       }
14513 
14514       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14515                                   XType, N0,
14516                                   DAG.getConstant(XType.getSizeInBits() - 1,
14517                                                   SDLoc(N0),
14518                                          getShiftAmountTy(N0.getValueType())));
14519       AddToWorklist(Shift.getNode());
14520 
14521       if (XType.bitsGT(AType)) {
14522         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14523         AddToWorklist(Shift.getNode());
14524       }
14525 
14526       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14527     }
14528   }
14529 
14530   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14531   // where y is has a single bit set.
14532   // A plaintext description would be, we can turn the SELECT_CC into an AND
14533   // when the condition can be materialized as an all-ones register.  Any
14534   // single bit-test can be materialized as an all-ones register with
14535   // shift-left and shift-right-arith.
14536   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14537       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14538     SDValue AndLHS = N0->getOperand(0);
14539     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14540     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14541       // Shift the tested bit over the sign bit.
14542       const APInt &AndMask = ConstAndRHS->getAPIntValue();
14543       SDValue ShlAmt =
14544         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14545                         getShiftAmountTy(AndLHS.getValueType()));
14546       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14547 
14548       // Now arithmetic right shift it all the way over, so the result is either
14549       // all-ones, or zero.
14550       SDValue ShrAmt =
14551         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14552                         getShiftAmountTy(Shl.getValueType()));
14553       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14554 
14555       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14556     }
14557   }
14558 
14559   // fold select C, 16, 0 -> shl C, 4
14560   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14561       TLI.getBooleanContents(N0.getValueType()) ==
14562           TargetLowering::ZeroOrOneBooleanContent) {
14563 
14564     // If the caller doesn't want us to simplify this into a zext of a compare,
14565     // don't do it.
14566     if (NotExtCompare && N2C->isOne())
14567       return SDValue();
14568 
14569     // Get a SetCC of the condition
14570     // NOTE: Don't create a SETCC if it's not legal on this target.
14571     if (!LegalOperations ||
14572         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14573       SDValue Temp, SCC;
14574       // cast from setcc result type to select result type
14575       if (LegalTypes) {
14576         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14577                             N0, N1, CC);
14578         if (N2.getValueType().bitsLT(SCC.getValueType()))
14579           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14580                                         N2.getValueType());
14581         else
14582           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14583                              N2.getValueType(), SCC);
14584       } else {
14585         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14586         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14587                            N2.getValueType(), SCC);
14588       }
14589 
14590       AddToWorklist(SCC.getNode());
14591       AddToWorklist(Temp.getNode());
14592 
14593       if (N2C->isOne())
14594         return Temp;
14595 
14596       // shl setcc result by log2 n2c
14597       return DAG.getNode(
14598           ISD::SHL, DL, N2.getValueType(), Temp,
14599           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14600                           getShiftAmountTy(Temp.getValueType())));
14601     }
14602   }
14603 
14604   // Check to see if this is an integer abs.
14605   // select_cc setg[te] X,  0,  X, -X ->
14606   // select_cc setgt    X, -1,  X, -X ->
14607   // select_cc setl[te] X,  0, -X,  X ->
14608   // select_cc setlt    X,  1, -X,  X ->
14609   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14610   if (N1C) {
14611     ConstantSDNode *SubC = nullptr;
14612     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14613          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14614         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14615       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14616     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14617               (N1C->isOne() && CC == ISD::SETLT)) &&
14618              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14619       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14620 
14621     EVT XType = N0.getValueType();
14622     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14623       SDLoc DL(N0);
14624       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14625                                   N0,
14626                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14627                                          getShiftAmountTy(N0.getValueType())));
14628       SDValue Add = DAG.getNode(ISD::ADD, DL,
14629                                 XType, N0, Shift);
14630       AddToWorklist(Shift.getNode());
14631       AddToWorklist(Add.getNode());
14632       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14633     }
14634   }
14635 
14636   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14637   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14638   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14639   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14640   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14641   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14642   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14643   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14644   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14645     SDValue ValueOnZero = N2;
14646     SDValue Count = N3;
14647     // If the condition is NE instead of E, swap the operands.
14648     if (CC == ISD::SETNE)
14649       std::swap(ValueOnZero, Count);
14650     // Check if the value on zero is a constant equal to the bits in the type.
14651     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14652       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14653         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14654         // legal, combine to just cttz.
14655         if ((Count.getOpcode() == ISD::CTTZ ||
14656              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14657             N0 == Count.getOperand(0) &&
14658             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14659           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14660         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14661         // legal, combine to just ctlz.
14662         if ((Count.getOpcode() == ISD::CTLZ ||
14663              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14664             N0 == Count.getOperand(0) &&
14665             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14666           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14667       }
14668     }
14669   }
14670 
14671   return SDValue();
14672 }
14673 
14674 /// This is a stub for TargetLowering::SimplifySetCC.
14675 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
14676                                    ISD::CondCode Cond, const SDLoc &DL,
14677                                    bool foldBooleans) {
14678   TargetLowering::DAGCombinerInfo
14679     DagCombineInfo(DAG, Level, false, this);
14680   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14681 }
14682 
14683 /// Given an ISD::SDIV node expressing a divide by constant, return
14684 /// a DAG expression to select that will generate the same value by multiplying
14685 /// by a magic number.
14686 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14687 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14688   // when optimising for minimum size, we don't want to expand a div to a mul
14689   // and a shift.
14690   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14691     return SDValue();
14692 
14693   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14694   if (!C)
14695     return SDValue();
14696 
14697   // Avoid division by zero.
14698   if (C->isNullValue())
14699     return SDValue();
14700 
14701   std::vector<SDNode*> Built;
14702   SDValue S =
14703       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14704 
14705   for (SDNode *N : Built)
14706     AddToWorklist(N);
14707   return S;
14708 }
14709 
14710 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14711 /// DAG expression that will generate the same value by right shifting.
14712 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14713   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14714   if (!C)
14715     return SDValue();
14716 
14717   // Avoid division by zero.
14718   if (C->isNullValue())
14719     return SDValue();
14720 
14721   std::vector<SDNode *> Built;
14722   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14723 
14724   for (SDNode *N : Built)
14725     AddToWorklist(N);
14726   return S;
14727 }
14728 
14729 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14730 /// expression that will generate the same value by multiplying by a magic
14731 /// number.
14732 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14733 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14734   // when optimising for minimum size, we don't want to expand a div to a mul
14735   // and a shift.
14736   if (DAG.getMachineFunction().getFunction()->optForMinSize())
14737     return SDValue();
14738 
14739   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14740   if (!C)
14741     return SDValue();
14742 
14743   // Avoid division by zero.
14744   if (C->isNullValue())
14745     return SDValue();
14746 
14747   std::vector<SDNode*> Built;
14748   SDValue S =
14749       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14750 
14751   for (SDNode *N : Built)
14752     AddToWorklist(N);
14753   return S;
14754 }
14755 
14756 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14757   if (Level >= AfterLegalizeDAG)
14758     return SDValue();
14759 
14760   // Expose the DAG combiner to the target combiner implementations.
14761   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14762 
14763   unsigned Iterations = 0;
14764   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14765     if (Iterations) {
14766       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14767       // For the reciprocal, we need to find the zero of the function:
14768       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14769       //     =>
14770       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14771       //     does not require additional intermediate precision]
14772       EVT VT = Op.getValueType();
14773       SDLoc DL(Op);
14774       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14775 
14776       AddToWorklist(Est.getNode());
14777 
14778       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14779       for (unsigned i = 0; i < Iterations; ++i) {
14780         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14781         AddToWorklist(NewEst.getNode());
14782 
14783         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14784         AddToWorklist(NewEst.getNode());
14785 
14786         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14787         AddToWorklist(NewEst.getNode());
14788 
14789         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14790         AddToWorklist(Est.getNode());
14791       }
14792     }
14793     return Est;
14794   }
14795 
14796   return SDValue();
14797 }
14798 
14799 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14800 /// For the reciprocal sqrt, we need to find the zero of the function:
14801 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14802 ///     =>
14803 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14804 /// As a result, we precompute A/2 prior to the iteration loop.
14805 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
14806                                          unsigned Iterations,
14807                                          SDNodeFlags *Flags, bool Reciprocal) {
14808   EVT VT = Arg.getValueType();
14809   SDLoc DL(Arg);
14810   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14811 
14812   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14813   // this entire sequence requires only one FP constant.
14814   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14815   AddToWorklist(HalfArg.getNode());
14816 
14817   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14818   AddToWorklist(HalfArg.getNode());
14819 
14820   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14821   for (unsigned i = 0; i < Iterations; ++i) {
14822     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14823     AddToWorklist(NewEst.getNode());
14824 
14825     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14826     AddToWorklist(NewEst.getNode());
14827 
14828     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14829     AddToWorklist(NewEst.getNode());
14830 
14831     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14832     AddToWorklist(Est.getNode());
14833   }
14834 
14835   // If non-reciprocal square root is requested, multiply the result by Arg.
14836   if (!Reciprocal) {
14837     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14838     AddToWorklist(Est.getNode());
14839   }
14840 
14841   return Est;
14842 }
14843 
14844 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14845 /// For the reciprocal sqrt, we need to find the zero of the function:
14846 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14847 ///     =>
14848 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14849 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
14850                                          unsigned Iterations,
14851                                          SDNodeFlags *Flags, bool Reciprocal) {
14852   EVT VT = Arg.getValueType();
14853   SDLoc DL(Arg);
14854   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14855   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14856 
14857   // This routine must enter the loop below to work correctly
14858   // when (Reciprocal == false).
14859   assert(Iterations > 0);
14860 
14861   // Newton iterations for reciprocal square root:
14862   // E = (E * -0.5) * ((A * E) * E + -3.0)
14863   for (unsigned i = 0; i < Iterations; ++i) {
14864     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
14865     AddToWorklist(AE.getNode());
14866 
14867     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
14868     AddToWorklist(AEE.getNode());
14869 
14870     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
14871     AddToWorklist(RHS.getNode());
14872 
14873     // When calculating a square root at the last iteration build:
14874     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
14875     // (notice a common subexpression)
14876     SDValue LHS;
14877     if (Reciprocal || (i + 1) < Iterations) {
14878       // RSQRT: LHS = (E * -0.5)
14879       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14880     } else {
14881       // SQRT: LHS = (A * E) * -0.5
14882       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
14883     }
14884     AddToWorklist(LHS.getNode());
14885 
14886     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
14887     AddToWorklist(Est.getNode());
14888   }
14889 
14890   return Est;
14891 }
14892 
14893 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
14894 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
14895 /// Op can be zero.
14896 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
14897                                            bool Reciprocal) {
14898   if (Level >= AfterLegalizeDAG)
14899     return SDValue();
14900 
14901   // Expose the DAG combiner to the target combiner implementations.
14902   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14903   unsigned Iterations = 0;
14904   bool UseOneConstNR = false;
14905   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14906     AddToWorklist(Est.getNode());
14907     if (Iterations) {
14908       Est = UseOneConstNR
14909                 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
14910                 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
14911     }
14912     return Est;
14913   }
14914 
14915   return SDValue();
14916 }
14917 
14918 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14919   return buildSqrtEstimateImpl(Op, Flags, true);
14920 }
14921 
14922 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14923   SDValue Est = buildSqrtEstimateImpl(Op, Flags, false);
14924   if (!Est)
14925     return SDValue();
14926 
14927   // Unfortunately, Est is now NaN if the input was exactly 0.
14928   // Select out this case and force the answer to 0.
14929   EVT VT = Est.getValueType();
14930   SDLoc DL(Op);
14931   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
14932   EVT CCVT = getSetCCResultType(VT);
14933   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, Zero, ISD::SETEQ);
14934   AddToWorklist(ZeroCmp.getNode());
14935 
14936   Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, ZeroCmp,
14937                     Zero, Est);
14938   AddToWorklist(Est.getNode());
14939   return Est;
14940 }
14941 
14942 /// Return true if base is a frame index, which is known not to alias with
14943 /// anything but itself.  Provides base object and offset as results.
14944 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14945                            const GlobalValue *&GV, const void *&CV) {
14946   // Assume it is a primitive operation.
14947   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14948 
14949   // If it's an adding a simple constant then integrate the offset.
14950   if (Base.getOpcode() == ISD::ADD) {
14951     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14952       Base = Base.getOperand(0);
14953       Offset += C->getZExtValue();
14954     }
14955   }
14956 
14957   // Return the underlying GlobalValue, and update the Offset.  Return false
14958   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14959   // by multiple nodes with different offsets.
14960   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14961     GV = G->getGlobal();
14962     Offset += G->getOffset();
14963     return false;
14964   }
14965 
14966   // Return the underlying Constant value, and update the Offset.  Return false
14967   // for ConstantSDNodes since the same constant pool entry may be represented
14968   // by multiple nodes with different offsets.
14969   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14970     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14971                                          : (const void *)C->getConstVal();
14972     Offset += C->getOffset();
14973     return false;
14974   }
14975   // If it's any of the following then it can't alias with anything but itself.
14976   return isa<FrameIndexSDNode>(Base);
14977 }
14978 
14979 /// Return true if there is any possibility that the two addresses overlap.
14980 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14981   // If they are the same then they must be aliases.
14982   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14983 
14984   // If they are both volatile then they cannot be reordered.
14985   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14986 
14987   // If one operation reads from invariant memory, and the other may store, they
14988   // cannot alias. These should really be checking the equivalent of mayWrite,
14989   // but it only matters for memory nodes other than load /store.
14990   if (Op0->isInvariant() && Op1->writeMem())
14991     return false;
14992 
14993   if (Op1->isInvariant() && Op0->writeMem())
14994     return false;
14995 
14996   // Gather base node and offset information.
14997   SDValue Base1, Base2;
14998   int64_t Offset1, Offset2;
14999   const GlobalValue *GV1, *GV2;
15000   const void *CV1, *CV2;
15001   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
15002                                       Base1, Offset1, GV1, CV1);
15003   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
15004                                       Base2, Offset2, GV2, CV2);
15005 
15006   // If they have a same base address then check to see if they overlap.
15007   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
15008     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15009              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15010 
15011   // It is possible for different frame indices to alias each other, mostly
15012   // when tail call optimization reuses return address slots for arguments.
15013   // To catch this case, look up the actual index of frame indices to compute
15014   // the real alias relationship.
15015   if (isFrameIndex1 && isFrameIndex2) {
15016     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
15017     Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
15018     Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
15019     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
15020              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
15021   }
15022 
15023   // Otherwise, if we know what the bases are, and they aren't identical, then
15024   // we know they cannot alias.
15025   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
15026     return false;
15027 
15028   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
15029   // compared to the size and offset of the access, we may be able to prove they
15030   // do not alias.  This check is conservative for now to catch cases created by
15031   // splitting vector types.
15032   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
15033       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
15034       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
15035        Op1->getMemoryVT().getSizeInBits() >> 3) &&
15036       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
15037     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
15038     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
15039 
15040     // There is no overlap between these relatively aligned accesses of similar
15041     // size, return no alias.
15042     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
15043         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
15044       return false;
15045   }
15046 
15047   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
15048                    ? CombinerGlobalAA
15049                    : DAG.getSubtarget().useAA();
15050 #ifndef NDEBUG
15051   if (CombinerAAOnlyFunc.getNumOccurrences() &&
15052       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
15053     UseAA = false;
15054 #endif
15055   if (UseAA &&
15056       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
15057     // Use alias analysis information.
15058     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
15059                                  Op1->getSrcValueOffset());
15060     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
15061         Op0->getSrcValueOffset() - MinOffset;
15062     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
15063         Op1->getSrcValueOffset() - MinOffset;
15064     AliasResult AAResult =
15065         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
15066                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
15067                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
15068                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
15069     if (AAResult == NoAlias)
15070       return false;
15071   }
15072 
15073   // Otherwise we have to assume they alias.
15074   return true;
15075 }
15076 
15077 /// Walk up chain skipping non-aliasing memory nodes,
15078 /// looking for aliasing nodes and adding them to the Aliases vector.
15079 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
15080                                    SmallVectorImpl<SDValue> &Aliases) {
15081   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
15082   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
15083 
15084   // Get alias information for node.
15085   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
15086 
15087   // Starting off.
15088   Chains.push_back(OriginalChain);
15089   unsigned Depth = 0;
15090 
15091   // Look at each chain and determine if it is an alias.  If so, add it to the
15092   // aliases list.  If not, then continue up the chain looking for the next
15093   // candidate.
15094   while (!Chains.empty()) {
15095     SDValue Chain = Chains.pop_back_val();
15096 
15097     // For TokenFactor nodes, look at each operand and only continue up the
15098     // chain until we reach the depth limit.
15099     //
15100     // FIXME: The depth check could be made to return the last non-aliasing
15101     // chain we found before we hit a tokenfactor rather than the original
15102     // chain.
15103     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
15104       Aliases.clear();
15105       Aliases.push_back(OriginalChain);
15106       return;
15107     }
15108 
15109     // Don't bother if we've been before.
15110     if (!Visited.insert(Chain.getNode()).second)
15111       continue;
15112 
15113     switch (Chain.getOpcode()) {
15114     case ISD::EntryToken:
15115       // Entry token is ideal chain operand, but handled in FindBetterChain.
15116       break;
15117 
15118     case ISD::LOAD:
15119     case ISD::STORE: {
15120       // Get alias information for Chain.
15121       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
15122           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
15123 
15124       // If chain is alias then stop here.
15125       if (!(IsLoad && IsOpLoad) &&
15126           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
15127         Aliases.push_back(Chain);
15128       } else {
15129         // Look further up the chain.
15130         Chains.push_back(Chain.getOperand(0));
15131         ++Depth;
15132       }
15133       break;
15134     }
15135 
15136     case ISD::TokenFactor:
15137       // We have to check each of the operands of the token factor for "small"
15138       // token factors, so we queue them up.  Adding the operands to the queue
15139       // (stack) in reverse order maintains the original order and increases the
15140       // likelihood that getNode will find a matching token factor (CSE.)
15141       if (Chain.getNumOperands() > 16) {
15142         Aliases.push_back(Chain);
15143         break;
15144       }
15145       for (unsigned n = Chain.getNumOperands(); n;)
15146         Chains.push_back(Chain.getOperand(--n));
15147       ++Depth;
15148       break;
15149 
15150     default:
15151       // For all other instructions we will just have to take what we can get.
15152       Aliases.push_back(Chain);
15153       break;
15154     }
15155   }
15156 }
15157 
15158 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
15159 /// (aliasing node.)
15160 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
15161   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
15162 
15163   // Accumulate all the aliases to this node.
15164   GatherAllAliases(N, OldChain, Aliases);
15165 
15166   // If no operands then chain to entry token.
15167   if (Aliases.size() == 0)
15168     return DAG.getEntryNode();
15169 
15170   // If a single operand then chain to it.  We don't need to revisit it.
15171   if (Aliases.size() == 1)
15172     return Aliases[0];
15173 
15174   // Construct a custom tailored token factor.
15175   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
15176 }
15177 
15178 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
15179   // This holds the base pointer, index, and the offset in bytes from the base
15180   // pointer.
15181   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
15182 
15183   // We must have a base and an offset.
15184   if (!BasePtr.Base.getNode())
15185     return false;
15186 
15187   // Do not handle stores to undef base pointers.
15188   if (BasePtr.Base.isUndef())
15189     return false;
15190 
15191   SmallVector<StoreSDNode *, 8> ChainedStores;
15192   ChainedStores.push_back(St);
15193 
15194   // Walk up the chain and look for nodes with offsets from the same
15195   // base pointer. Stop when reaching an instruction with a different kind
15196   // or instruction which has a different base pointer.
15197   StoreSDNode *Index = St;
15198   while (Index) {
15199     // If the chain has more than one use, then we can't reorder the mem ops.
15200     if (Index != St && !SDValue(Index, 0)->hasOneUse())
15201       break;
15202 
15203     if (Index->isVolatile() || Index->isIndexed())
15204       break;
15205 
15206     // Find the base pointer and offset for this memory node.
15207     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
15208 
15209     // Check that the base pointer is the same as the original one.
15210     if (!Ptr.equalBaseIndex(BasePtr))
15211       break;
15212 
15213     // Find the next memory operand in the chain. If the next operand in the
15214     // chain is a store then move up and continue the scan with the next
15215     // memory operand. If the next operand is a load save it and use alias
15216     // information to check if it interferes with anything.
15217     SDNode *NextInChain = Index->getChain().getNode();
15218     while (true) {
15219       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
15220         // We found a store node. Use it for the next iteration.
15221         if (STn->isVolatile() || STn->isIndexed()) {
15222           Index = nullptr;
15223           break;
15224         }
15225         ChainedStores.push_back(STn);
15226         Index = STn;
15227         break;
15228       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
15229         NextInChain = Ldn->getChain().getNode();
15230         continue;
15231       } else {
15232         Index = nullptr;
15233         break;
15234       }
15235     }
15236   }
15237 
15238   bool MadeChangeToSt = false;
15239   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
15240 
15241   for (StoreSDNode *ChainedStore : ChainedStores) {
15242     SDValue Chain = ChainedStore->getChain();
15243     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
15244 
15245     if (Chain != BetterChain) {
15246       if (ChainedStore == St)
15247         MadeChangeToSt = true;
15248       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
15249     }
15250   }
15251 
15252   // Do all replacements after finding the replacements to make to avoid making
15253   // the chains more complicated by introducing new TokenFactors.
15254   for (auto Replacement : BetterChains)
15255     replaceStoreChain(Replacement.first, Replacement.second);
15256 
15257   return MadeChangeToSt;
15258 }
15259 
15260 /// This is the entry point for the file.
15261 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
15262                            CodeGenOpt::Level OptLevel) {
15263   /// This is the main entry point to this class.
15264   DAGCombiner(*this, AA, OptLevel).Run(Level);
15265 }
15266